text stringlengths 54 60.6k |
|---|
<commit_before>#include <PluginFactory/PluginFactory.hpp>
#include <PluginFactory/details/PolicyProperties.hpp>
#include <load_plugins/PluginInterface.hpp>
#include <load_plugins/PluginServiceInterface.hpp>
#include "ConcreteService.hpp"
#include <iostream>
#include <memory>
using MyPlugin = std::unique_ptr<load_plugins::MyPlugin, PluginFactory::PluginDeleter<load_plugins::MyPlugin>>;
using MyPluginFactory = PluginFactory::PluginFactory<load_plugins::MyPlugin, load_plugins::PluginServiceInterface, PluginFactory::details::PolicyIsExternal>;
int usage(char const * const programName);
int run(int argc, char** argv);
void printPluginNames(const std::vector<std::string>& plugins);
void createPlugins(MyPluginFactory& factory, const std::vector<std::string>& availablePlugins, std::deque<MyPlugin>& plugins);
void callPlugins(const std::deque<MyPlugin>& plugins);
int main(int argc, char** argv)
{
if(argc < 2)
{
return usage(argv[0]);
}
try
{
return run(argc, argv);
}
catch(const std::exception& e )
{
std::cerr << e.what() << std::endl;
}
return -1;
}
int usage(char const * const programName)
{
std::cerr << "Usage: " << programName << " <plugin_path>" << std::endl;
return -1;
}
int run(int /*argc*/, char** argv)
{
std::string pluginPath(argv[1]);
std::deque<MyPlugin> plugins;
std::unique_ptr<load_plugins::PluginServiceInterface> service(new load_plugins::ConcreteService());
MyPluginFactory factory(pluginPath, *service);
factory.load();
auto availablePlugins = factory.availablePlugins();
printPluginNames(availablePlugins);
createPlugins(factory, availablePlugins, plugins);
callPlugins(plugins);
service->report();
return 0;
}
void printPluginNames(const std::vector<std::string>& plugins)
{
std::cout << "loaded: ";
for(const auto& pluginName : plugins)
{
std::cout << pluginName << " ";
}
std::cout << std::endl;
}
void createPlugins(MyPluginFactory& factory, const std::vector<std::string>& availablePlugins, std::deque<MyPlugin>& plugins)
{
for(const auto& pluginName : availablePlugins)
{
plugins.emplace_back(factory.instance(pluginName));
}
}
void callPlugins(const std::deque<MyPlugin>& plugins)
{
for(auto& plugin : plugins)
{
plugin->do_stuff();
}
}
<commit_msg>Change the plugin handle to a raw pointer, we won't be responsible for cleaning up the memory - the plugin shared library must do that.<commit_after>#include <PluginFactory/PluginFactory.hpp>
#include <PluginFactory/details/PolicyProperties.hpp>
#include <load_plugins/PluginInterface.hpp>
#include <load_plugins/PluginServiceInterface.hpp>
#include "ConcreteService.hpp"
#include <iostream>
#include <memory>
using MyPlugin = load_plugins::MyPlugin*;
using MyPluginFactory = PluginFactory::PluginFactory<load_plugins::MyPlugin, load_plugins::PluginServiceInterface, PluginFactory::details::PolicyIsExternal>;
int usage(char const * const programName);
int run(int argc, char** argv);
void printPluginNames(const std::vector<std::string>& plugins);
void createPlugins(MyPluginFactory& factory, const std::vector<std::string>& availablePlugins, std::deque<MyPlugin>& plugins);
void callPlugins(const std::deque<MyPlugin>& plugins);
int main(int argc, char** argv)
{
if(argc < 2)
{
return usage(argv[0]);
}
try
{
return run(argc, argv);
}
catch(const std::exception& e )
{
std::cerr << e.what() << std::endl;
}
return -1;
}
int usage(char const * const programName)
{
std::cerr << "Usage: " << programName << " <plugin_path>" << std::endl;
return -1;
}
int run(int /*argc*/, char** argv)
{
std::string pluginPath(argv[1]);
std::deque<MyPlugin> plugins;
std::unique_ptr<load_plugins::PluginServiceInterface> service(new load_plugins::ConcreteService());
MyPluginFactory factory(pluginPath, *service);
factory.load();
auto availablePlugins = factory.availablePlugins();
printPluginNames(availablePlugins);
createPlugins(factory, availablePlugins, plugins);
callPlugins(plugins);
service->report();
return 0;
}
void printPluginNames(const std::vector<std::string>& plugins)
{
std::cout << "loaded: ";
for(const auto& pluginName : plugins)
{
std::cout << pluginName << " ";
}
std::cout << std::endl;
}
void createPlugins(MyPluginFactory& factory, const std::vector<std::string>& availablePlugins, std::deque<MyPlugin>& plugins)
{
for(const auto& pluginName : availablePlugins)
{
plugins.emplace_back(factory.instance(pluginName));
}
}
void callPlugins(const std::deque<MyPlugin>& plugins)
{
for(auto& plugin : plugins)
{
plugin->do_stuff();
}
}
<|endoftext|> |
<commit_before>#pragma once
#pragma message("NETClassBase.hpp - 1")
#include "NETClassBase.inl"
#pragma message("NETClassBase.hpp - 2")
#include "NETClass.hpp"
#pragma message("NETClassBase.hpp - 3")
#pragma message("NETClassBase.hpp - 4")
#include "../NETDerivedClassChecker/NETDerivedClassChecker.hpp"
#pragma message("NETClassBase.hpp - 5")
#include "../NETTemplateChecker/NETTemplateChecker.hpp"
#pragma message("NETClassBase.hpp - 6")
// We must include ADTChecker after loaded TClass declarations and its
// implementations(= TClass.hpp).
// Why do we have to keep this sequence:
// in order to use ADTChecker including TClass must be predeterminded first.
// because ADTChecker can checks whether T is kind of Interface Class by
// applying SFINAE with TInterfaceClass(is part of TClass.hpp)
#pragma message("NETClassBase.hpp - 7")
#include "../NETADTChecker/NETADTChecker.hpp"
#pragma message("NETClassBase.hpp - 8")
// Following one is just same as above.
#include "../NETUnknownMetaClass/NETUnknownMetaClass.hpp"
#pragma message("NETClassBase.hpp - 9")
namespace NE
{
template <typename T>
const NEClassBase& NETClassBase<T>::getClassStatically()
{
// What is this:
// When NETClass is templated with some parameter type T,
// it's a problem to provide metaclass of NETClass. (of course,
// because NETClass is a kind of metaclass, giving metaclass of
// metaclass is the problem mentioned above)
// The reason which this going to be a problem is templating reculsively.
// Just imagine NETClass<T> that is returning NETClassMetaClass as
// its metaclass.
// so, this get crack the codes. to prevent this, we replace metaclass
// to NETMetaClass. Dummy.
// All NETClass<T> will return NETClassMetaClass at getClass()
// method.
static NETClassMetaClass inner;
return inner;
}
template <typename T>
const NEClassBase& NETClassBase<T>::getClass() const
{
return getClassStatically();
}
template <typename T>
NEObject& NETClassBase<T>::clone() const
{
return *(new This(*this));
}
template <typename T>
const NETString& NETClassBase<T>::getName() const
{
return getNameStatically();
}
template <typename T>
const type_bool& NETClassBase<T>::isRegistered() const
{
return isRegisteredStatically();
}
template <typename T>
const NEClassBaseList& NETClassBase<T>::getSuperClasses() const
{
return getSuperClassesStatically();
}
template <typename T>
const NEClassBaseList& NETClassBase<T>::getChildrenClasses() const
{
return getChildrenClassesStatically();
}
template <typename T>
type_bool NETClassBase<T>::isMetaClassDefined() const
{
return isMetaClassDefinedStatically();
}
template <typename T>
type_bool NETClassBase<T>::isInstantiable() const
{
return isInstantiableStatically();
}
template <typename T>
type_bool NETClassBase<T>::isTemplate() const
{
return isTemplateStatically();
}
template <typename T>
type_bool NETClassBase<T>::isBuiltInClass() const
{
return isBuiltInClassStatically();
}
template <typename T>
const NEClassBase& NETClassBase<T>::getTraitClass() const
{
return getTraitClassStatically();
}
template <typename T>
const NETString& NETClassBase<T>::getNameStatically()
{
static NETString _inner;
if (_inner.getLength() <= 0)
_inner = typeid(T).name();
return _inner;
}
template <typename T>
const NEHeader& NETClassBase<T>::getHeader() const
{
return getHeaderStatically();
}
template <typename T>
const NEHeader& NETClassBase<T>::getHeaderStatically()
{
static NEHeader _inner;
return _inner;
}
template <typename T>
const type_bool& NETClassBase<T>::isRegisteredStatically()
{
static type_bool _inner;
return _inner;
}
template <typename T>
const NEClassBaseList& NETClassBase<T>::getSuperClassesStatically()
{
static NEClassBaseList _inner;
return _inner;
}
template <typename T>
const NEClassBaseList& NETClassBase<T>::getChildrenClassesStatically()
{
static NEClassBaseList _inner;
return _inner;
}
template <typename T>
const type_id& NETClassBase<T>::getId() const
{
return getIdStatically();
}
template <typename T>
const type_id& NETClassBase<T>::getIdStatically()
{
static type_id _inner;
return _inner;
}
template <typename T>
const NEClassBase& NETClassBase<T>::getTraitClassStatically()
{
static NETClass<Trait> _inner;
return _inner;
}
template <typename T>
type_bool NETClassBase<T>::isBuiltInClassStatically()
{
return NETDerivedClassChecker<T, NEObject>::IS_DERIVED_OF;
}
template <typename T>
type_bool NETClassBase<T>::isTemplateStatically()
{
return NETTemplateChecker<T>::IS_TEMPLATE;
}
template <typename T>
type_bool NETClassBase<T>::isInstantiableStatically()
{
return NETADTChecker<T>::IS_ADT;
}
template <typename T>
type_bool NETClassBase<T>::isMetaClassDefinedStatically()
{
return NETMetaClassChecker<T>::IS_METACLASS_DEFINED;
}
template <typename T>
const NEPackagePtr& NETClassBase<T>::_getPackage() const
{
static NEPackagePtr _inner = NE_NULL;
return _inner;
}
}<commit_msg>- NETClassBase misses header file "NEHeader.hpp"<commit_after>#pragma once
#pragma message("NETClassBase.hpp - 1")
#include "NETClassBase.inl"
#pragma message("NETClassBase.hpp - 2")
#include "NETClass.hpp"
#pragma message("NETClassBase.hpp - 3")
#include "../NEHeader/NEHeader.hpp"
#pragma message("NETClassBase.hpp - 4")
#include "../NETDerivedClassChecker/NETDerivedClassChecker.hpp"
#pragma message("NETClassBase.hpp - 5")
#include "../NETTemplateChecker/NETTemplateChecker.hpp"
#pragma message("NETClassBase.hpp - 6")
// We must include ADTChecker after loaded TClass declarations and its
// implementations(= TClass.hpp).
// Why do we have to keep this sequence:
// in order to use ADTChecker including TClass must be predeterminded first.
// because ADTChecker can checks whether T is kind of Interface Class by
// applying SFINAE with TInterfaceClass(is part of TClass.hpp)
#pragma message("NETClassBase.hpp - 7")
#include "../NETADTChecker/NETADTChecker.hpp"
#pragma message("NETClassBase.hpp - 8")
// Following one is just same as above.
#include "../NETUnknownMetaClass/NETUnknownMetaClass.hpp"
#pragma message("NETClassBase.hpp - 9")
namespace NE
{
template <typename T>
const NEClassBase& NETClassBase<T>::getClassStatically()
{
// What is this:
// When NETClass is templated with some parameter type T,
// it's a problem to provide metaclass of NETClass. (of course,
// because NETClass is a kind of metaclass, giving metaclass of
// metaclass is the problem mentioned above)
// The reason which this going to be a problem is templating reculsively.
// Just imagine NETClass<T> that is returning NETClassMetaClass as
// its metaclass.
// so, this get crack the codes. to prevent this, we replace metaclass
// to NETMetaClass. Dummy.
// All NETClass<T> will return NETClassMetaClass at getClass()
// method.
static NETClassMetaClass inner;
return inner;
}
template <typename T>
const NEClassBase& NETClassBase<T>::getClass() const
{
return getClassStatically();
}
template <typename T>
NEObject& NETClassBase<T>::clone() const
{
return *(new This(*this));
}
template <typename T>
const NETString& NETClassBase<T>::getName() const
{
return getNameStatically();
}
template <typename T>
const type_bool& NETClassBase<T>::isRegistered() const
{
return isRegisteredStatically();
}
template <typename T>
const NEClassBaseList& NETClassBase<T>::getSuperClasses() const
{
return getSuperClassesStatically();
}
template <typename T>
const NEClassBaseList& NETClassBase<T>::getChildrenClasses() const
{
return getChildrenClassesStatically();
}
template <typename T>
type_bool NETClassBase<T>::isMetaClassDefined() const
{
return isMetaClassDefinedStatically();
}
template <typename T>
type_bool NETClassBase<T>::isInstantiable() const
{
return isInstantiableStatically();
}
template <typename T>
type_bool NETClassBase<T>::isTemplate() const
{
return isTemplateStatically();
}
template <typename T>
type_bool NETClassBase<T>::isBuiltInClass() const
{
return isBuiltInClassStatically();
}
template <typename T>
const NEClassBase& NETClassBase<T>::getTraitClass() const
{
return getTraitClassStatically();
}
template <typename T>
const NETString& NETClassBase<T>::getNameStatically()
{
static NETString _inner;
if (_inner.getLength() <= 0)
_inner = typeid(T).name();
return _inner;
}
template <typename T>
const NEHeader& NETClassBase<T>::getHeader() const
{
return getHeaderStatically();
}
template <typename T>
const NEHeader& NETClassBase<T>::getHeaderStatically()
{
static NEHeader _inner;
return _inner;
}
template <typename T>
const type_bool& NETClassBase<T>::isRegisteredStatically()
{
static type_bool _inner;
return _inner;
}
template <typename T>
const NEClassBaseList& NETClassBase<T>::getSuperClassesStatically()
{
static NEClassBaseList _inner;
return _inner;
}
template <typename T>
const NEClassBaseList& NETClassBase<T>::getChildrenClassesStatically()
{
static NEClassBaseList _inner;
return _inner;
}
template <typename T>
const type_id& NETClassBase<T>::getId() const
{
return getIdStatically();
}
template <typename T>
const type_id& NETClassBase<T>::getIdStatically()
{
static type_id _inner;
return _inner;
}
template <typename T>
const NEClassBase& NETClassBase<T>::getTraitClassStatically()
{
static NETClass<Trait> _inner;
return _inner;
}
template <typename T>
type_bool NETClassBase<T>::isBuiltInClassStatically()
{
return NETDerivedClassChecker<T, NEObject>::IS_DERIVED_OF;
}
template <typename T>
type_bool NETClassBase<T>::isTemplateStatically()
{
return NETTemplateChecker<T>::IS_TEMPLATE;
}
template <typename T>
type_bool NETClassBase<T>::isInstantiableStatically()
{
return NETADTChecker<T>::IS_ADT;
}
template <typename T>
type_bool NETClassBase<T>::isMetaClassDefinedStatically()
{
return NETMetaClassChecker<T>::IS_METACLASS_DEFINED;
}
template <typename T>
const NEPackagePtr& NETClassBase<T>::_getPackage() const
{
static NEPackagePtr _inner = NE_NULL;
return _inner;
}
}<|endoftext|> |
<commit_before>// $Id: OoiEnergy_test.C,v 1.1 2000/05/30 10:28:50 oliver Exp $
#include <BALL/CONCEPT/classTest.h>
///////////////////////////
#include <BALL/SOLVATION/ooiEnergy.h>
#include <BALL/FORMAT/PDBFile.h>
#include <BALL/FORMAT/HINFile.h>
#include <BALL/KERNEL/system.h>
#include <BALL/STRUCTURE/fragmentDB.h>
///////////////////////////
START_TEST(OOiEnergy, "$Id: OoiEnergy_test.C,v 1.1 2000/05/30 10:28:50 oliver Exp $")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
using namespace BALL;
/// insert tests for each member function here
///
PRECISION(1.0) // it's not THAT precise
CHECK(calculateOoiEnergy() / BPTI)
System S;
PDBFile f("data/OoiEnergy_test.pdb");
f >> S;
f.close();
FragmentDB frag_db;
S.apply(frag_db.normalize_names);
S.apply(frag_db.build_bonds);
TEST_EQUAL(S.countAtoms(), 892)
float energy = calculateOoiEnergy(S);
TEST_REAL_EQUAL(energy, -2589.7)
RESULT
CHECK(calculateOoiEnergy() / ethanol)
System S;
HINFile f("data/OoiEnergy_test1.hin");
f >> S;
f.close();
TEST_EQUAL(S.countAtoms(), 9)
float energy = calculateOoiEnergy(S);
TEST_REAL_EQUAL(energy, -21.09)
TEST_EQUAL(S.countAtoms(), 9)
energy = calculateOoiEnergy(S);
TEST_REAL_EQUAL(energy, -21.09)
RESULT
CHECK(calculateOoiEnergy() / acetamide)
System S;
HINFile f("data/OoiEnergy_test2.hin");
f >> S;
f.close();
TEST_EQUAL(S.countAtoms(), 9)
float energy = calculateOoiEnergy(S);
TEST_REAL_EQUAL(energy, -28.04)
RESULT
CHECK(calculateOoiEnergy() / butylamine)
System S;
HINFile f("data/OoiEnergy_test3.hin");
f >> S;
f.close();
TEST_EQUAL(S.countAtoms(), 16)
float energy = calculateOoiEnergy(S);
TEST_REAL_EQUAL(energy, -18.34)
RESULT
CHECK(calculateOoiEnergy() / methanethiol)
System S;
HINFile f("data/OoiEnergy_test4.hin");
f >> S;
f.close();
TEST_EQUAL(S.countAtoms(), 6)
float energy = calculateOoiEnergy(S);
TEST_REAL_EQUAL(energy, -4.72)
RESULT
CHECK(calculateOoiEnergy() / acetic acid)
System S;
HINFile f("data/OoiEnergy_test5.hin");
f >> S;
f.close();
TEST_EQUAL(S.countAtoms(), 8)
float energy = calculateOoiEnergy(S);
TEST_REAL_EQUAL(energy, -29.15)
RESULT
CHECK(calculateOoiEnergy() / acetate)
System S;
HINFile f("data/OoiEnergy_test6.hin");
f >> S;
f.close();
TEST_EQUAL(S.countAtoms(), 7)
float energy = calculateOoiEnergy(S);
TEST_REAL_EQUAL(energy, -337.44)
RESULT
CHECK(calculateOoiEnergy() / butylammonium)
System S;
HINFile f("data/OoiEnergy_test7.hin");
f >> S;
f.close();
TEST_EQUAL(S.countAtoms(), 17)
float energy = calculateOoiEnergy(S);
TEST_REAL_EQUAL(energy, -289.70)
RESULT
CHECK(calculateOoiEnergy() / propionate)
System S;
HINFile f("data/OoiEnergy_test8.hin");
f >> S;
f.close();
TEST_EQUAL(S.countAtoms(), 10)
float energy = calculateOoiEnergy(S);
TEST_REAL_EQUAL(energy, -311.8)
RESULT
CHECK(calculateOoiEnergy() / methylimidazolium)
System S;
HINFile f("data/OoiEnergy_test9.hin");
f >> S;
f.close();
TEST_EQUAL(S.countAtoms(), 13)
float energy = calculateOoiEnergy(S);
TEST_REAL_EQUAL(energy, -26.4)
RESULT
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
<commit_msg>fixed: examples were adapted to the modified parameter set<commit_after>// $Id: OoiEnergy_test.C,v 1.2 2000/05/31 17:37:07 oliver Exp $
#include <BALL/CONCEPT/classTest.h>
///////////////////////////
#include <BALL/SOLVATION/ooiEnergy.h>
#include <BALL/FORMAT/PDBFile.h>
#include <BALL/FORMAT/HINFile.h>
#include <BALL/KERNEL/system.h>
#include <BALL/STRUCTURE/fragmentDB.h>
///////////////////////////
START_TEST(OOiEnergy, "$Id: OoiEnergy_test.C,v 1.2 2000/05/31 17:37:07 oliver Exp $")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
using namespace BALL;
/// insert tests for each member function here
///
PRECISION(1.0) // it's not THAT precise
CHECK(calculateOoiEnergy() / BPTI)
System S;
PDBFile f("data/OoiEnergy_test.pdb");
f >> S;
f.close();
FragmentDB frag_db;
S.apply(frag_db.normalize_names);
S.apply(frag_db.build_bonds);
TEST_EQUAL(S.countAtoms(), 892)
float energy = calculateOoiEnergy(S);
TEST_REAL_EQUAL(energy, -2602.97)
RESULT
CHECK(calculateOoiEnergy() / ethanol)
System S;
HINFile f("data/OoiEnergy_test1.hin");
f >> S;
f.close();
TEST_EQUAL(S.countAtoms(), 9)
float energy = calculateOoiEnergy(S);
TEST_REAL_EQUAL(energy, -21.09)
TEST_EQUAL(S.countAtoms(), 9)
energy = calculateOoiEnergy(S);
TEST_REAL_EQUAL(energy, -21.09)
RESULT
CHECK(calculateOoiEnergy() / acetamide)
System S;
HINFile f("data/OoiEnergy_test2.hin");
f >> S;
f.close();
TEST_EQUAL(S.countAtoms(), 9)
float energy = calculateOoiEnergy(S);
TEST_REAL_EQUAL(energy, -28.04)
RESULT
CHECK(calculateOoiEnergy() / butylamine)
System S;
HINFile f("data/OoiEnergy_test3.hin");
f >> S;
f.close();
TEST_EQUAL(S.countAtoms(), 16)
float energy = calculateOoiEnergy(S);
TEST_REAL_EQUAL(energy, -18.34)
RESULT
CHECK(calculateOoiEnergy() / methanethiol)
System S;
HINFile f("data/OoiEnergy_test4.hin");
f >> S;
f.close();
TEST_EQUAL(S.countAtoms(), 6)
float energy = calculateOoiEnergy(S);
TEST_REAL_EQUAL(energy, -4.72)
RESULT
CHECK(calculateOoiEnergy() / acetic acid)
System S;
HINFile f("data/OoiEnergy_test5.hin");
f >> S;
f.close();
TEST_EQUAL(S.countAtoms(), 8)
float energy = calculateOoiEnergy(S);
TEST_REAL_EQUAL(energy, -29.15)
RESULT
CHECK(calculateOoiEnergy() / acetate)
System S;
HINFile f("data/OoiEnergy_test6.hin");
f >> S;
f.close();
TEST_EQUAL(S.countAtoms(), 7)
float energy = calculateOoiEnergy(S);
TEST_REAL_EQUAL(energy, -341.942)
RESULT
CHECK(calculateOoiEnergy() / butylammonium)
System S;
HINFile f("data/OoiEnergy_test7.hin");
f >> S;
f.close();
TEST_EQUAL(S.countAtoms(), 17)
float energy = calculateOoiEnergy(S);
TEST_REAL_EQUAL(energy, -289.70)
RESULT
CHECK(calculateOoiEnergy() / propionate)
System S;
HINFile f("data/OoiEnergy_test8.hin");
f >> S;
f.close();
TEST_EQUAL(S.countAtoms(), 10)
float energy = calculateOoiEnergy(S);
TEST_REAL_EQUAL(energy, -315.938)
RESULT
CHECK(calculateOoiEnergy() / methylimidazolium)
System S;
HINFile f("data/OoiEnergy_test9.hin");
f >> S;
f.close();
TEST_EQUAL(S.countAtoms(), 13)
float energy = calculateOoiEnergy(S);
TEST_REAL_EQUAL(energy, -268.268)
RESULT
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
<|endoftext|> |
<commit_before>#include <QCoreApplication>
#include <QSqlQuery>
#include <QSqlError>
#include <QDebug>
#include <QCache>
#include <QVector>
#include <QStringList>
#include <QSqlRecord>
#include <QUrl>
#include <QDir>
#include <cxxabi.h>
#include <QException>
#include "kernel.h"
#include "factory.h"
#include "geometries.h"
#include "connectorinterface.h"
#include "abstractfactory.h"
#include "ilwisobjectfactory.h"
#include "ilwiscontext.h"
#include "catalogconnectorfactory.h"
#include "connectorfactory.h"
#include "catalogconnector.h"
#include "featurefactory.h"
#include "georefimplementationfactory.h"
#include "catalog.h"
#include "module.h"
#include "mastercatalog.h"
#include "version.h"
#include "errorobject.h"
#include "ilwisdata.h"
#include "domain.h"
#include "domainitem.h"
#include "itemdomain.h"
#include "identifieritem.h"
#include "thematicitem.h"
#include "range.h"
#include "itemrange.h"
#include "datadefinition.h"
#include "columndefinition.h"
#include "table.h"
#include "attributerecord.h"
#include "polygon.h"
#include "geometry.h"
#include "feature.h"
#include "symboltable.h"
#include "operationmetadata.h"
#include "operationExpression.h"
#include "operation.h"
#include "commandhandler.h"
Ilwis::Kernel *Ilwis::Kernel::_kernel = 0;
using namespace Ilwis;
Catalog *createCatalog() {
return new Catalog();
}
Ilwis::Kernel* kernel() {
if (Kernel::_kernel == 0) {
Kernel::_kernel = new Kernel();
Kernel::_kernel->init();
}
return Kernel::_kernel;
}
Kernel::Kernel(QObject *parent) :
QObject(parent), _version(0)
{
}
void Kernel::init() {
if ( !_version.isNull())
return;
_version.reset(new Version());
_version->addBinaryVersion(Ilwis::Version::bvFORMAT30);
_version->addBinaryVersion(Ilwis::Version::bvFORMATFOREIGN);
_version->addBinaryVersion(Ilwis::Version::bvPOLYGONFORMAT37);
_version->addODFVersion("3.1");
_issues.reset( new IssueLogger());
_dbPublic = QSqlDatabase::addDatabase("QSQLITE");
_dbPublic.setHostName("localhost");
_dbPublic.setDatabaseName(":memory:");
_dbPublic.open();
_dbPublic.prepare();
CatalogConnectorFactory *catfactory = new CatalogConnectorFactory();
addFactory(catfactory);
ConnectorFactory *confac = new ConnectorFactory();
addFactory(confac);
FeatureFactory *featureFac = new FeatureFactory();
featureFac->addCreator("feature", createFeature);
addFactory(featureFac);
GeoRefImplementationFactory *georefFac = new GeoRefImplementationFactory();
georefFac->prepare();
addFactory(georefFac);
_modules.addModules();
mastercatalog()->addContainer(QUrl("ilwis://system"));
// ItemRange::addCreateItem("ThematicItem", ThematicItem::createRange());
}
Kernel::~Kernel() {
_dbPublic.close();
delete mastercatalog();
delete context();
}
const QVariant *Kernel::getFromTLS(const QString& key) const{
if (_caches.hasLocalData()) {
return _caches.localData()->object(key);
}
return 0;
}
void Kernel::setTLS(const QString& key, QVariant* data){
if (!_caches.hasLocalData())
_caches.setLocalData(new QCache<QString, QVariant>);
_caches.localData()->insert(key, data);
}
void Kernel::deleteTLS(const QString &key) {
if (_caches.hasLocalData())
_caches.localData()->remove(key);
}
QString Kernel::translate(const QString& s) const {
//TODO implement translator class here and load in in the application object
return s;
}
const SPVersion& Kernel::version() const{
return _version;
}
PublicDatabase &Kernel::database()
{
return _dbPublic;
}
QScopedPointer<IssueLogger>& Kernel::issues()
{
return _issues;
}
void Kernel::addFactory(FactoryInterface *fac)
{
QString key = fac->key().toLower();
if (!_masterfactory.contains(key)) {
_masterfactory[key] = fac;
}
}
QString Kernel::demangle(const char *mangled_name)
{
int status;
char *realname = abi::__cxa_demangle(mangled_name,0,0,&status);
QString type(realname);
free(realname);
return type;
}
bool Kernel::error(const QString &message, const QString p1, const QString p2, const QString p3, const QString& file, int line, const QString& func)
{
QFileInfo inf(file);
QString name = inf.fileName();
quint64 issueid;
if ( p1 == sUNDEF)
issueid =issues()->log(TR(message));
else if (p2 == sUNDEF)
issueid =issues()->log(TR(message).arg(p1));
else if ( p3 == sUNDEF)
issueid =issues()->log(TR(message).arg(p1, p2));
else
issueid =issues()->log(TR(message).arg(p1).arg(p2).arg(p3));
if ( issueid != i64UNDEF) {
issues()->addCodeInfo(issueid, line, func, name);
}
return false;
}
void Kernel::startClock(){
_start_clock = clock();
}
void Kernel::endClock(){
clock_t end = clock();
double total = (double)(end - _start_clock) / CLOCKS_PER_SEC;
qDebug() << "calc old in " << total << " seconds";
}
<commit_msg>added log message for when ilwis starts and stops<commit_after>#include <QCoreApplication>
#include <QSqlQuery>
#include <QSqlError>
#include <QDebug>
#include <QCache>
#include <QVector>
#include <QStringList>
#include <QSqlRecord>
#include <QUrl>
#include <QDir>
#include <cxxabi.h>
#include <QException>
#include "kernel.h"
#include "factory.h"
#include "geometries.h"
#include "connectorinterface.h"
#include "abstractfactory.h"
#include "ilwisobjectfactory.h"
#include "ilwiscontext.h"
#include "catalogconnectorfactory.h"
#include "connectorfactory.h"
#include "catalogconnector.h"
#include "featurefactory.h"
#include "georefimplementationfactory.h"
#include "catalog.h"
#include "module.h"
#include "mastercatalog.h"
#include "version.h"
#include "errorobject.h"
#include "ilwisdata.h"
#include "domain.h"
#include "domainitem.h"
#include "itemdomain.h"
#include "identifieritem.h"
#include "thematicitem.h"
#include "range.h"
#include "itemrange.h"
#include "datadefinition.h"
#include "columndefinition.h"
#include "table.h"
#include "attributerecord.h"
#include "polygon.h"
#include "geometry.h"
#include "feature.h"
#include "symboltable.h"
#include "operationmetadata.h"
#include "operationExpression.h"
#include "operation.h"
#include "commandhandler.h"
Ilwis::Kernel *Ilwis::Kernel::_kernel = 0;
using namespace Ilwis;
Catalog *createCatalog() {
return new Catalog();
}
Ilwis::Kernel* kernel() {
if (Kernel::_kernel == 0) {
Kernel::_kernel = new Kernel();
Kernel::_kernel->init();
}
return Kernel::_kernel;
}
Kernel::Kernel(QObject *parent) :
QObject(parent), _version(0)
{
}
void Kernel::init() {
if ( !_version.isNull())
return;
_issues.reset( new IssueLogger());
issues()->log(QString("Ilwis started at %1").arg(Time::now().toString()),IssueObject::itMessage);
_version.reset(new Version());
_version->addBinaryVersion(Ilwis::Version::bvFORMAT30);
_version->addBinaryVersion(Ilwis::Version::bvFORMATFOREIGN);
_version->addBinaryVersion(Ilwis::Version::bvPOLYGONFORMAT37);
_version->addODFVersion("3.1");
_dbPublic = QSqlDatabase::addDatabase("QSQLITE");
_dbPublic.setHostName("localhost");
_dbPublic.setDatabaseName(":memory:");
_dbPublic.open();
_dbPublic.prepare();
CatalogConnectorFactory *catfactory = new CatalogConnectorFactory();
addFactory(catfactory);
ConnectorFactory *confac = new ConnectorFactory();
addFactory(confac);
FeatureFactory *featureFac = new FeatureFactory();
featureFac->addCreator("feature", createFeature);
addFactory(featureFac);
GeoRefImplementationFactory *georefFac = new GeoRefImplementationFactory();
georefFac->prepare();
addFactory(georefFac);
_modules.addModules();
mastercatalog()->addContainer(QUrl("ilwis://system"));
// ItemRange::addCreateItem("ThematicItem", ThematicItem::createRange());
}
Kernel::~Kernel() {
issues()->log(QString("Ilwis closed at %1").arg(Time::now().toString()),IssueObject::itMessage);
_dbPublic.close();
delete mastercatalog();
delete context();
}
const QVariant *Kernel::getFromTLS(const QString& key) const{
if (_caches.hasLocalData()) {
return _caches.localData()->object(key);
}
return 0;
}
void Kernel::setTLS(const QString& key, QVariant* data){
if (!_caches.hasLocalData())
_caches.setLocalData(new QCache<QString, QVariant>);
_caches.localData()->insert(key, data);
}
void Kernel::deleteTLS(const QString &key) {
if (_caches.hasLocalData())
_caches.localData()->remove(key);
}
QString Kernel::translate(const QString& s) const {
//TODO implement translator class here and load in in the application object
return s;
}
const SPVersion& Kernel::version() const{
return _version;
}
PublicDatabase &Kernel::database()
{
return _dbPublic;
}
QScopedPointer<IssueLogger>& Kernel::issues()
{
return _issues;
}
void Kernel::addFactory(FactoryInterface *fac)
{
QString key = fac->key().toLower();
if (!_masterfactory.contains(key)) {
_masterfactory[key] = fac;
}
}
QString Kernel::demangle(const char *mangled_name)
{
int status;
char *realname = abi::__cxa_demangle(mangled_name,0,0,&status);
QString type(realname);
free(realname);
return type;
}
bool Kernel::error(const QString &message, const QString p1, const QString p2, const QString p3, const QString& file, int line, const QString& func)
{
QFileInfo inf(file);
QString name = inf.fileName();
quint64 issueid;
if ( p1 == sUNDEF)
issueid =issues()->log(TR(message));
else if (p2 == sUNDEF)
issueid =issues()->log(TR(message).arg(p1));
else if ( p3 == sUNDEF)
issueid =issues()->log(TR(message).arg(p1, p2));
else
issueid =issues()->log(TR(message).arg(p1).arg(p2).arg(p3));
if ( issueid != i64UNDEF) {
issues()->addCodeInfo(issueid, line, func, name);
}
return false;
}
void Kernel::startClock(){
_start_clock = clock();
}
void Kernel::endClock(){
clock_t end = clock();
double total = (double)(end - _start_clock) / CLOCKS_PER_SEC;
qDebug() << "calc old in " << total << " seconds";
}
<|endoftext|> |
<commit_before>#ifndef __MEDIA_ELEMENT_IMPL_HPP__
#define __MEDIA_ELEMENT_IMPL_HPP__
#include "MediaObjectImpl.hpp"
#include "MediaElement.hpp"
#include "MediaType.hpp"
#include "MediaLatencyStat.hpp"
#include <EventHandler.hpp>
#include <gst/gst.h>
#include <mutex>
#include <set>
#include <random>
#include "MediaFlowOutStateChange.hpp"
#include "MediaFlowInStateChange.hpp"
#include "MediaFlowState.hpp"
#include "commons/kmselement.h"
namespace kurento
{
class MediaType;
class MediaElementImpl;
class AudioCodec;
class VideoCodec;
class MediaFlowData;
struct MediaTypeCmp {
bool operator() (const std::shared_ptr<MediaType> &a,
const std::shared_ptr<MediaType> &b) const {
return a->getValue () < b->getValue ();
}
};
void Serialize (std::shared_ptr<MediaElementImpl> &object,
JsonSerializer &serializer);
class ElementConnectionDataInternal;
class MediaElementImpl : public MediaObjectImpl, public virtual MediaElement
{
public:
MediaElementImpl (const boost::property_tree::ptree &config,
std::shared_ptr<MediaObjectImpl> parent,
const std::string &factoryName);
virtual ~MediaElementImpl ();
GstElement *getGstreamerElement() {
return element;
};
virtual std::map <std::string, std::shared_ptr<Stats>> getStats () override;
virtual std::map <std::string, std::shared_ptr<Stats>> getStats (
std::shared_ptr<MediaType> mediaType) override;
virtual std::vector<std::shared_ptr<ElementConnectionData>>
getSourceConnections () override;
virtual std::vector<std::shared_ptr<ElementConnectionData>>
getSourceConnections (
std::shared_ptr<MediaType> mediaType) override;
virtual std::vector<std::shared_ptr<ElementConnectionData>>
getSourceConnections (
std::shared_ptr<MediaType> mediaType, const std::string &description) override;
virtual std::vector<std::shared_ptr<ElementConnectionData>>
getSinkConnections () override;
virtual std::vector<std::shared_ptr<ElementConnectionData>> getSinkConnections (
std::shared_ptr<MediaType> mediaType) override;
virtual std::vector<std::shared_ptr<ElementConnectionData>> getSinkConnections (
std::shared_ptr<MediaType> mediaType, const std::string &description) override;
virtual void connect (std::shared_ptr<MediaElement> sink) override;
virtual void connect (std::shared_ptr<MediaElement> sink,
std::shared_ptr<MediaType> mediaType) override;
virtual void connect (std::shared_ptr<MediaElement> sink,
std::shared_ptr<MediaType> mediaType,
const std::string &sourceMediaDescription) override;
virtual void connect (std::shared_ptr<MediaElement> sink,
std::shared_ptr<MediaType> mediaType,
const std::string &sourceMediaDescription,
const std::string &sinkMediaDescription) override;
virtual void disconnect (std::shared_ptr<MediaElement> sink) override;
virtual void disconnect (std::shared_ptr<MediaElement> sink,
std::shared_ptr<MediaType> mediaType) override;
virtual void disconnect (std::shared_ptr<MediaElement> sink,
std::shared_ptr<MediaType> mediaType,
const std::string &sourceMediaDescription) override;
virtual void disconnect (std::shared_ptr<MediaElement> sink,
std::shared_ptr<MediaType> mediaType,
const std::string &sourceMediaDescription,
const std::string &sinkMediaDescription) override;
void setAudioFormat (std::shared_ptr<AudioCaps> caps) override;
void setVideoFormat (std::shared_ptr<VideoCaps> caps) override;
virtual void release () override;
virtual std::string getGstreamerDot () override;
virtual std::string getGstreamerDot (std::shared_ptr<GstreamerDotDetails>
details) override;
virtual void setOutputBitrate (int bitrate) override;
bool isMediaFlowingIn (std::shared_ptr<MediaType> mediaType) override;
bool isMediaFlowingIn (std::shared_ptr<MediaType> mediaType,
const std::string &sinkMediaDescription) override;
bool isMediaFlowingOut (std::shared_ptr<MediaType> mediaType) override;
bool isMediaFlowingOut (std::shared_ptr<MediaType> mediaType,
const std::string &sourceMediaDescription) override;
virtual int getMinOuputBitrate () override;
virtual void setMinOuputBitrate (int minOuputBitrate) override;
virtual int getMinOutputBitrate () override;
virtual void setMinOutputBitrate (int minOutputBitrate) override;
virtual int getMaxOuputBitrate () override;
virtual void setMaxOuputBitrate (int maxOuputBitrate) override;
virtual int getMaxOutputBitrate () override;
virtual void setMaxOutputBitrate (int maxOutputBitrate) override;
/* Next methods are automatically implemented by code generator */
virtual bool connect (const std::string &eventType,
std::shared_ptr<EventHandler> handler) override;
sigc::signal<void, ElementConnected> signalElementConnected;
sigc::signal<void, ElementDisconnected> signalElementDisconnected;
sigc::signal<void, MediaFlowOutStateChange> signalMediaFlowOutStateChange;
sigc::signal<void, MediaFlowInStateChange> signalMediaFlowInStateChange;
virtual void invoke (std::shared_ptr<MediaObjectImpl> obj,
const std::string &methodName, const Json::Value ¶ms,
Json::Value &response) override;
virtual void Serialize (JsonSerializer &serializer) override;
protected:
GstElement *element;
GstBus *bus;
gulong handlerId;
virtual void postConstructor () override;
void collectLatencyStats (std::vector<std::shared_ptr<MediaLatencyStat>>
&latencyStats, const GstStructure *stats);
virtual void fillStatsReport (std::map <std::string, std::shared_ptr<Stats>>
&report, const GstStructure *stats, double timestamp);
private:
std::recursive_timed_mutex sourcesMutex;
std::recursive_timed_mutex sinksMutex;
std::map < std::shared_ptr <MediaType>, std::map < std::string,
std::shared_ptr<ElementConnectionDataInternal >> , MediaTypeCmp > sources;
std::map < std::shared_ptr <MediaType>, std::map < std::string,
std::set<std::shared_ptr<ElementConnectionDataInternal> >> , MediaTypeCmp >
sinks;
std::mt19937_64 rnd {std::random_device{}() };
std::uniform_int_distribution<> dist {1, 100};
gulong padAddedHandlerId;
gulong mediaFlowOutHandler;
gulong mediaFlowInHandler;
std::map <std::string, std::shared_ptr <MediaFlowData>> mediaFlowDataIn;
std::map <std::string, std::shared_ptr <MediaFlowData>> mediaFlowDataOut;
void disconnectAll();
void performConnection (std::shared_ptr <ElementConnectionDataInternal> data);
std::map <std::string, std::shared_ptr<Stats>> generateStats (
const gchar *selector);
void mediaFlowOutStateChange (gboolean isFlowing, gchar *padName,
KmsElementPadType type);
void mediaFlowInStateChange (gboolean isFlowing, gchar *padName,
KmsElementPadType type);
class StaticConstructor
{
public:
StaticConstructor();
};
static StaticConstructor staticConstructor;
friend void _media_element_impl_bus_message (GstBus *bus, GstMessage *message,
gpointer data);
friend void _media_element_pad_added (GstElement *elem, GstPad *pad,
gpointer data);
};
} /* kurento */
#endif /* __MEDIA_ELEMENT_IMPL_HPP__ */
<commit_msg>MediaElementImpl: Move mediaFlow structures from private to protected<commit_after>#ifndef __MEDIA_ELEMENT_IMPL_HPP__
#define __MEDIA_ELEMENT_IMPL_HPP__
#include "MediaObjectImpl.hpp"
#include "MediaElement.hpp"
#include "MediaType.hpp"
#include "MediaLatencyStat.hpp"
#include <EventHandler.hpp>
#include <gst/gst.h>
#include <mutex>
#include <set>
#include <random>
#include "MediaFlowOutStateChange.hpp"
#include "MediaFlowInStateChange.hpp"
#include "MediaFlowState.hpp"
#include "commons/kmselement.h"
namespace kurento
{
class MediaType;
class MediaElementImpl;
class AudioCodec;
class VideoCodec;
class MediaFlowData;
struct MediaTypeCmp {
bool operator() (const std::shared_ptr<MediaType> &a,
const std::shared_ptr<MediaType> &b) const {
return a->getValue () < b->getValue ();
}
};
void Serialize (std::shared_ptr<MediaElementImpl> &object,
JsonSerializer &serializer);
class ElementConnectionDataInternal;
class MediaElementImpl : public MediaObjectImpl, public virtual MediaElement
{
public:
MediaElementImpl (const boost::property_tree::ptree &config,
std::shared_ptr<MediaObjectImpl> parent,
const std::string &factoryName);
virtual ~MediaElementImpl ();
GstElement *getGstreamerElement() {
return element;
};
virtual std::map <std::string, std::shared_ptr<Stats>> getStats () override;
virtual std::map <std::string, std::shared_ptr<Stats>> getStats (
std::shared_ptr<MediaType> mediaType) override;
virtual std::vector<std::shared_ptr<ElementConnectionData>>
getSourceConnections () override;
virtual std::vector<std::shared_ptr<ElementConnectionData>>
getSourceConnections (
std::shared_ptr<MediaType> mediaType) override;
virtual std::vector<std::shared_ptr<ElementConnectionData>>
getSourceConnections (
std::shared_ptr<MediaType> mediaType, const std::string &description) override;
virtual std::vector<std::shared_ptr<ElementConnectionData>>
getSinkConnections () override;
virtual std::vector<std::shared_ptr<ElementConnectionData>> getSinkConnections (
std::shared_ptr<MediaType> mediaType) override;
virtual std::vector<std::shared_ptr<ElementConnectionData>> getSinkConnections (
std::shared_ptr<MediaType> mediaType, const std::string &description) override;
virtual void connect (std::shared_ptr<MediaElement> sink) override;
virtual void connect (std::shared_ptr<MediaElement> sink,
std::shared_ptr<MediaType> mediaType) override;
virtual void connect (std::shared_ptr<MediaElement> sink,
std::shared_ptr<MediaType> mediaType,
const std::string &sourceMediaDescription) override;
virtual void connect (std::shared_ptr<MediaElement> sink,
std::shared_ptr<MediaType> mediaType,
const std::string &sourceMediaDescription,
const std::string &sinkMediaDescription) override;
virtual void disconnect (std::shared_ptr<MediaElement> sink) override;
virtual void disconnect (std::shared_ptr<MediaElement> sink,
std::shared_ptr<MediaType> mediaType) override;
virtual void disconnect (std::shared_ptr<MediaElement> sink,
std::shared_ptr<MediaType> mediaType,
const std::string &sourceMediaDescription) override;
virtual void disconnect (std::shared_ptr<MediaElement> sink,
std::shared_ptr<MediaType> mediaType,
const std::string &sourceMediaDescription,
const std::string &sinkMediaDescription) override;
void setAudioFormat (std::shared_ptr<AudioCaps> caps) override;
void setVideoFormat (std::shared_ptr<VideoCaps> caps) override;
virtual void release () override;
virtual std::string getGstreamerDot () override;
virtual std::string getGstreamerDot (std::shared_ptr<GstreamerDotDetails>
details) override;
virtual void setOutputBitrate (int bitrate) override;
bool isMediaFlowingIn (std::shared_ptr<MediaType> mediaType) override;
bool isMediaFlowingIn (std::shared_ptr<MediaType> mediaType,
const std::string &sinkMediaDescription) override;
bool isMediaFlowingOut (std::shared_ptr<MediaType> mediaType) override;
bool isMediaFlowingOut (std::shared_ptr<MediaType> mediaType,
const std::string &sourceMediaDescription) override;
virtual int getMinOuputBitrate () override;
virtual void setMinOuputBitrate (int minOuputBitrate) override;
virtual int getMinOutputBitrate () override;
virtual void setMinOutputBitrate (int minOutputBitrate) override;
virtual int getMaxOuputBitrate () override;
virtual void setMaxOuputBitrate (int maxOuputBitrate) override;
virtual int getMaxOutputBitrate () override;
virtual void setMaxOutputBitrate (int maxOutputBitrate) override;
/* Next methods are automatically implemented by code generator */
virtual bool connect (const std::string &eventType,
std::shared_ptr<EventHandler> handler) override;
sigc::signal<void, ElementConnected> signalElementConnected;
sigc::signal<void, ElementDisconnected> signalElementDisconnected;
sigc::signal<void, MediaFlowOutStateChange> signalMediaFlowOutStateChange;
sigc::signal<void, MediaFlowInStateChange> signalMediaFlowInStateChange;
virtual void invoke (std::shared_ptr<MediaObjectImpl> obj,
const std::string &methodName, const Json::Value ¶ms,
Json::Value &response) override;
virtual void Serialize (JsonSerializer &serializer) override;
protected:
GstElement *element;
GstBus *bus;
gulong handlerId;
std::map <std::string, std::shared_ptr <MediaFlowData>> mediaFlowDataIn;
std::map <std::string, std::shared_ptr <MediaFlowData>> mediaFlowDataOut;
virtual void postConstructor () override;
void collectLatencyStats (std::vector<std::shared_ptr<MediaLatencyStat>>
&latencyStats, const GstStructure *stats);
virtual void fillStatsReport (std::map <std::string, std::shared_ptr<Stats>>
&report, const GstStructure *stats, double timestamp);
private:
std::recursive_timed_mutex sourcesMutex;
std::recursive_timed_mutex sinksMutex;
std::map < std::shared_ptr <MediaType>, std::map < std::string,
std::shared_ptr<ElementConnectionDataInternal >> , MediaTypeCmp > sources;
std::map < std::shared_ptr <MediaType>, std::map < std::string,
std::set<std::shared_ptr<ElementConnectionDataInternal> >> , MediaTypeCmp >
sinks;
std::mt19937_64 rnd {std::random_device{}() };
std::uniform_int_distribution<> dist {1, 100};
gulong padAddedHandlerId;
gulong mediaFlowOutHandler;
gulong mediaFlowInHandler;
void disconnectAll();
void performConnection (std::shared_ptr <ElementConnectionDataInternal> data);
std::map <std::string, std::shared_ptr<Stats>> generateStats (
const gchar *selector);
void mediaFlowOutStateChange (gboolean isFlowing, gchar *padName,
KmsElementPadType type);
void mediaFlowInStateChange (gboolean isFlowing, gchar *padName,
KmsElementPadType type);
class StaticConstructor
{
public:
StaticConstructor();
};
static StaticConstructor staticConstructor;
friend void _media_element_impl_bus_message (GstBus *bus, GstMessage *message,
gpointer data);
friend void _media_element_pad_added (GstElement *elem, GstPad *pad,
gpointer data);
};
} /* kurento */
#endif /* __MEDIA_ELEMENT_IMPL_HPP__ */
<|endoftext|> |
<commit_before>#include "Decoder_LDPC_BP_peeling.hpp"
#include "Tools/Perf/common/hard_decide.h"
#include "Tools/Noise/Erased_value.hpp"
#include "Tools/Math/utils.h"
using namespace aff3ct;
using namespace aff3ct::module;
template<typename B, typename R>
Decoder_LDPC_BP_peeling<B, R>::Decoder_LDPC_BP_peeling(const int K, const int N, const int n_ite,
const tools::Sparse_matrix &H,
const std::vector<unsigned> &info_bits_pos,
const bool enable_syndrome, const int syndrome_depth,
const int n_frames)
: Decoder (K, N, n_frames, 1),
Decoder_LDPC_BP<B,R> (K, N, n_ite, H, enable_syndrome, syndrome_depth, n_frames, 1),
info_bits_pos (info_bits_pos ),
var_nodes (n_frames, std::vector<B>(N ) ),
check_nodes (n_frames, std::vector<B>(H.get_n_cols()) )
{
const std::string name = "Decoder_LDPC_BP_peeling";
this->set_name(name);
}
template <typename B, typename R>
void Decoder_LDPC_BP_peeling<B,R>
::_load(const R *Y_N, const int frame_id)
{
tools::hard_decide(Y_N, var_nodes[frame_id].data(), this->N);
for (auto i = 0; i < this->N; i++)
if (Y_N[i] <= tools::Erased_value<R>::llr && Y_N[i] >= -tools::Erased_value<R>::llr)
var_nodes[frame_id][i] = tools::Erased_value<B>::symbol;
}
template <typename B, typename R>
void Decoder_LDPC_BP_peeling<B,R>
::_decode(const int frame_id)
{
auto links = this->H;
std::fill(this->check_nodes[frame_id].begin(), this->check_nodes[frame_id].end(), (B)0);
// std::cout << "(L) var_nodes : " << std::endl;
// for (unsigned i = 0; i < this->var_nodes[frame_id].size(); i++)
// std::cout << this->var_nodes[frame_id][i] << " ";
// std::cout << std::endl;
// std::cout << "(L) check_nodes : " << std::endl;
// for (unsigned i = 0; i < this->check_nodes[frame_id].size(); i++)
// std::cout << this->check_nodes[frame_id][i] << " ";
// std::cout << std::endl;
// std::cout << "(L) links : " << std::endl;
// links.print(true);
// first propagate known values
for (unsigned i = 0; i < links.get_n_rows(); i++)
{
auto cur_state = this->var_nodes[frame_id][i];
if (cur_state != tools::Erased_value<B>::symbol)
{
auto& cn_list = links.get_row_to_cols()[i];
while (cn_list.size())
{
auto& cn_pos = cn_list.front();
this->check_nodes[frame_id][cn_pos] ^= cur_state;
links.rm_connection(i, cn_pos);
}
}
}
// std::cout << "(I) var_nodes : " << std::endl;
// for (unsigned i = 0; i < this->var_nodes[frame_id].size(); i++)
// std::cout << this->var_nodes[frame_id][i] << " ";
// std::cout << std::endl;
// std::cout << "(I) check_nodes : " << std::endl;
// for (unsigned i = 0; i < this->check_nodes[frame_id].size(); i++)
// std::cout << this->check_nodes[frame_id][i] << " ";
// std::cout << std::endl;
// std::cout << "(I) links : " << std::endl;
// links.print(true);
for (auto ite = 0; ite < this->n_ite; ite++)
{
bool all_check_nodes_done = true;
// find degree-1 check nodes
for (unsigned i = 0; i < links.get_n_cols(); i++)
{
if (links.get_col_to_rows()[i].size() == 1)
{ // then propagate the belief
auto& vn_pos = links.get_col_to_rows()[i].front();
this->var_nodes [frame_id][vn_pos] = this->check_nodes[frame_id][i];
this->check_nodes[frame_id][ i] = 0;
links.rm_connection(vn_pos, i);
}
else
all_check_nodes_done &= links.get_col_to_rows()[i].size() == 0;
}
// std::cout << "(" << ite << ") var_nodes : " << std::endl;
// for (unsigned i = 0; i < this->var_nodes[frame_id].size(); i++)
// std::cout << this->var_nodes[frame_id][i] << " ";
// std::cout << std::endl;
// std::cout << "(" << ite << ") check_nodes : " << std::endl;
// for (unsigned i = 0; i < this->check_nodes[frame_id].size(); i++)
// std::cout << this->check_nodes[frame_id][i] << " ";
// std::cout << std::endl;
if (all_check_nodes_done)
break;
}
};
template <typename B, typename R>
void Decoder_LDPC_BP_peeling<B,R>
::_decode_hiho(const B *Y_N, B *V_K, const int frame_id)
{
// auto t_load = std::chrono::steady_clock::now(); // ---------------------------------------------------------- LOAD
std::copy(Y_N, Y_N + this->N, var_nodes[frame_id].data());
// auto d_load = std::chrono::steady_clock::now() - t_load;
// auto t_decod = std::chrono::steady_clock::now(); // -------------------------------------------------------- DECODE
this->_decode(frame_id);
// auto d_decod = std::chrono::steady_clock::now() - t_decod;
// auto t_store = std::chrono::steady_clock::now(); // --------------------------------------------------------- STORE
_store(V_K, frame_id);
// auto d_store = std::chrono::steady_clock::now() - t_store;
// (*this)[dec::tsk::decode_hiho].update_timer(dec::tm::decode_hiho::decode, d_decod);
// (*this)[dec::tsk::decode_hiho].update_timer(dec::tm::decode_hiho::store, d_store);
}
template <typename B, typename R>
void Decoder_LDPC_BP_peeling<B,R>
::_decode_hiho_cw(const B *Y_N, B *V_N, const int frame_id)
{
// auto t_load = std::chrono::steady_clock::now(); // ---------------------------------------------------------- LOAD
std::copy(Y_N, Y_N + this->N, var_nodes[frame_id].data());
// auto d_load = std::chrono::steady_clock::now() - t_load;
// auto t_decod = std::chrono::steady_clock::now(); // -------------------------------------------------------- DECODE
this->_decode(frame_id);
// auto d_decod = std::chrono::steady_clock::now() - t_decod;
// auto t_store = std::chrono::steady_clock::now(); // --------------------------------------------------------- STORE
_store_cw(V_N, frame_id);
// auto d_store = std::chrono::steady_clock::now() - t_store;
// (*this)[dec::tsk::decode_hiho_cw].update_timer(dec::tm::decode_hiho_cw::decode, d_decod);
// (*this)[dec::tsk::decode_hiho_cw].update_timer(dec::tm::decode_hiho_cw::store, d_store);
}
template <typename B, typename R>
void Decoder_LDPC_BP_peeling<B,R>
::_decode_siho(const R *Y_N, B *V_K, const int frame_id)
{
// auto t_load = std::chrono::steady_clock::now(); // ---------------------------------------------------------- LOAD
this->_load(Y_N, frame_id);
// auto d_load = std::chrono::steady_clock::now() - t_load;
// auto t_decod = std::chrono::steady_clock::now(); // -------------------------------------------------------- DECODE
this->_decode(frame_id);
// auto d_decod = std::chrono::steady_clock::now() - t_decod;
// auto t_store = std::chrono::steady_clock::now(); // --------------------------------------------------------- STORE
_store(V_K, frame_id);
// auto d_store = std::chrono::steady_clock::now() - t_store;
// (*this)[dec::tsk::decode_siho].update_timer(dec::tm::decode_siho::load, d_load);
// (*this)[dec::tsk::decode_siho].update_timer(dec::tm::decode_siho::decode, d_decod);
// (*this)[dec::tsk::decode_siho].update_timer(dec::tm::decode_siho::store, d_store);
}
template <typename B, typename R>
void Decoder_LDPC_BP_peeling<B,R>
::_decode_siho_cw(const R *Y_N, B *V_N, const int frame_id)
{
// auto t_load = std::chrono::steady_clock::now(); // ---------------------------------------------------------- LOAD
this->_load(Y_N, frame_id);
// auto d_load = std::chrono::steady_clock::now() - t_load;
// auto t_decod = std::chrono::steady_clock::now(); // -------------------------------------------------------- DECODE
this->_decode(frame_id);
// auto d_decod = std::chrono::steady_clock::now() - t_decod;
// auto t_store = std::chrono::steady_clock::now(); // --------------------------------------------------------- STORE
_store_cw(V_N, frame_id);
// auto d_store = std::chrono::steady_clock::now() - t_store;
// (*this)[dec::tsk::decode_siho_cw].update_timer(dec::tm::decode_siho_cw::load, d_load);
// (*this)[dec::tsk::decode_siho_cw].update_timer(dec::tm::decode_siho_cw::decode, d_decod);
// (*this)[dec::tsk::decode_siho_cw].update_timer(dec::tm::decode_siho_cw::store, d_store);
}
template<typename B, typename R>
void Decoder_LDPC_BP_peeling<B, R>::_store(B *V_K, const int frame_id)
{
for (auto i = 0; i < this->K; i++)
V_K[i] = this->var_nodes[frame_id][this->info_bits_pos[i]];
}
template<typename B, typename R>
void Decoder_LDPC_BP_peeling<B, R>::_store_cw(B *V_N, const int frame_id)
{
std::copy(this->var_nodes[frame_id].begin(), this->var_nodes[frame_id].end(), V_N);
}
// ==================================================================================== explicit template instantiation
#include "Tools/types.h"
#ifdef MULTI_PREC
template class aff3ct::module::Decoder_LDPC_BP_peeling<B_8,Q_8>;
template class aff3ct::module::Decoder_LDPC_BP_peeling<B_16,Q_16>;
template class aff3ct::module::Decoder_LDPC_BP_peeling<B_32,Q_32>;
template class aff3ct::module::Decoder_LDPC_BP_peeling<B_64,Q_64>;
#else
template class aff3ct::module::Decoder_LDPC_BP_peeling<B,Q>;
#endif
// ==================================================================================== explicit template instantiation
<commit_msg>Add a no modification syndrome and handle the syndrome depth<commit_after>#include "Decoder_LDPC_BP_peeling.hpp"
#include "Tools/Perf/common/hard_decide.h"
#include "Tools/Noise/Erased_value.hpp"
#include "Tools/Math/utils.h"
using namespace aff3ct;
using namespace aff3ct::module;
template<typename B, typename R>
Decoder_LDPC_BP_peeling<B, R>::Decoder_LDPC_BP_peeling(const int K, const int N, const int n_ite,
const tools::Sparse_matrix &H,
const std::vector<unsigned> &info_bits_pos,
const bool enable_syndrome, const int syndrome_depth,
const int n_frames)
: Decoder (K, N, n_frames, 1),
Decoder_LDPC_BP<B,R> (K, N, n_ite, H, enable_syndrome, syndrome_depth, n_frames, 1),
info_bits_pos (info_bits_pos ),
var_nodes (n_frames, std::vector<B>(N ) ),
check_nodes (n_frames, std::vector<B>(H.get_n_cols()) )
{
const std::string name = "Decoder_LDPC_BP_peeling";
this->set_name(name);
}
template <typename B, typename R>
void Decoder_LDPC_BP_peeling<B,R>
::_load(const R *Y_N, const int frame_id)
{
tools::hard_decide(Y_N, var_nodes[frame_id].data(), this->N);
for (auto i = 0; i < this->N; i++)
if (Y_N[i] <= tools::Erased_value<R>::llr && Y_N[i] >= -tools::Erased_value<R>::llr)
var_nodes[frame_id][i] = tools::Erased_value<B>::symbol;
}
template <typename B, typename R>
void Decoder_LDPC_BP_peeling<B,R>
::_decode(const int frame_id)
{
auto links = this->H;
std::fill(this->check_nodes[frame_id].begin(), this->check_nodes[frame_id].end(), (B)0);
// std::cout << "(L) var_nodes : " << std::endl;
// for (unsigned i = 0; i < this->var_nodes[frame_id].size(); i++)
// std::cout << this->var_nodes[frame_id][i] << " ";
// std::cout << std::endl;
// std::cout << "(L) check_nodes : " << std::endl;
// for (unsigned i = 0; i < this->check_nodes[frame_id].size(); i++)
// std::cout << this->check_nodes[frame_id][i] << " ";
// std::cout << std::endl;
// std::cout << "(L) links : " << std::endl;
// links.print(true);
// first propagate known values
for (unsigned i = 0; i < links.get_n_rows(); i++)
{
auto cur_state = this->var_nodes[frame_id][i];
if (cur_state != tools::Erased_value<B>::symbol)
{
auto& cn_list = links.get_row_to_cols()[i];
while (cn_list.size())
{
auto& cn_pos = cn_list.front();
this->check_nodes[frame_id][cn_pos] ^= cur_state;
links.rm_connection(i, cn_pos);
}
}
}
// std::cout << "(I) var_nodes : " << std::endl;
// for (unsigned i = 0; i < this->var_nodes[frame_id].size(); i++)
// std::cout << this->var_nodes[frame_id][i] << " ";
// std::cout << std::endl;
// std::cout << "(I) check_nodes : " << std::endl;
// for (unsigned i = 0; i < this->check_nodes[frame_id].size(); i++)
// std::cout << this->check_nodes[frame_id][i] << " ";
// std::cout << std::endl;
// std::cout << "(I) links : " << std::endl;
// links.print(true);
for (auto ite = 0; ite < this->n_ite; ite++)
{
bool all_check_nodes_done = true, no_modification = true;
// find degree-1 check nodes
for (unsigned i = 0; i < links.get_n_cols(); i++)
{
if (links.get_col_to_rows()[i].size() == 1)
{ // then propagate the belief
auto& vn_pos = links.get_col_to_rows()[i].front();
this->var_nodes [frame_id][vn_pos] = this->check_nodes[frame_id][i];
this->check_nodes[frame_id][ i] = 0;
links.rm_connection(vn_pos, i);
no_modification = false;
}
else
all_check_nodes_done &= links.get_col_to_rows()[i].size() == 0;
}
// std::cout << "(" << ite << ") var_nodes : " << std::endl;
// for (unsigned i = 0; i < this->var_nodes[frame_id].size(); i++)
// std::cout << this->var_nodes[frame_id][i] << " ";
// std::cout << std::endl;
// std::cout << "(" << ite << ") check_nodes : " << std::endl;
// for (unsigned i = 0; i < this->check_nodes[frame_id].size(); i++)
// std::cout << this->check_nodes[frame_id][i] << " ";
// std::cout << std::endl;
if (this->enable_syndrome && (all_check_nodes_done || no_modification))
{
this->cur_syndrome_depth++;
if (this->cur_syndrome_depth == this->syndrome_depth)
break;
}
else
this->cur_syndrome_depth = 0;
}
};
template <typename B, typename R>
void Decoder_LDPC_BP_peeling<B,R>
::_decode_hiho(const B *Y_N, B *V_K, const int frame_id)
{
// auto t_load = std::chrono::steady_clock::now(); // ---------------------------------------------------------- LOAD
std::copy(Y_N, Y_N + this->N, var_nodes[frame_id].data());
// auto d_load = std::chrono::steady_clock::now() - t_load;
// auto t_decod = std::chrono::steady_clock::now(); // -------------------------------------------------------- DECODE
this->_decode(frame_id);
// auto d_decod = std::chrono::steady_clock::now() - t_decod;
// auto t_store = std::chrono::steady_clock::now(); // --------------------------------------------------------- STORE
_store(V_K, frame_id);
// auto d_store = std::chrono::steady_clock::now() - t_store;
// (*this)[dec::tsk::decode_hiho].update_timer(dec::tm::decode_hiho::decode, d_decod);
// (*this)[dec::tsk::decode_hiho].update_timer(dec::tm::decode_hiho::store, d_store);
}
template <typename B, typename R>
void Decoder_LDPC_BP_peeling<B,R>
::_decode_hiho_cw(const B *Y_N, B *V_N, const int frame_id)
{
// auto t_load = std::chrono::steady_clock::now(); // ---------------------------------------------------------- LOAD
std::copy(Y_N, Y_N + this->N, var_nodes[frame_id].data());
// auto d_load = std::chrono::steady_clock::now() - t_load;
// auto t_decod = std::chrono::steady_clock::now(); // -------------------------------------------------------- DECODE
this->_decode(frame_id);
// auto d_decod = std::chrono::steady_clock::now() - t_decod;
// auto t_store = std::chrono::steady_clock::now(); // --------------------------------------------------------- STORE
_store_cw(V_N, frame_id);
// auto d_store = std::chrono::steady_clock::now() - t_store;
// (*this)[dec::tsk::decode_hiho_cw].update_timer(dec::tm::decode_hiho_cw::decode, d_decod);
// (*this)[dec::tsk::decode_hiho_cw].update_timer(dec::tm::decode_hiho_cw::store, d_store);
}
template <typename B, typename R>
void Decoder_LDPC_BP_peeling<B,R>
::_decode_siho(const R *Y_N, B *V_K, const int frame_id)
{
// auto t_load = std::chrono::steady_clock::now(); // ---------------------------------------------------------- LOAD
this->_load(Y_N, frame_id);
// auto d_load = std::chrono::steady_clock::now() - t_load;
// auto t_decod = std::chrono::steady_clock::now(); // -------------------------------------------------------- DECODE
this->_decode(frame_id);
// auto d_decod = std::chrono::steady_clock::now() - t_decod;
// auto t_store = std::chrono::steady_clock::now(); // --------------------------------------------------------- STORE
_store(V_K, frame_id);
// auto d_store = std::chrono::steady_clock::now() - t_store;
// (*this)[dec::tsk::decode_siho].update_timer(dec::tm::decode_siho::load, d_load);
// (*this)[dec::tsk::decode_siho].update_timer(dec::tm::decode_siho::decode, d_decod);
// (*this)[dec::tsk::decode_siho].update_timer(dec::tm::decode_siho::store, d_store);
}
template <typename B, typename R>
void Decoder_LDPC_BP_peeling<B,R>
::_decode_siho_cw(const R *Y_N, B *V_N, const int frame_id)
{
// auto t_load = std::chrono::steady_clock::now(); // ---------------------------------------------------------- LOAD
this->_load(Y_N, frame_id);
// auto d_load = std::chrono::steady_clock::now() - t_load;
// auto t_decod = std::chrono::steady_clock::now(); // -------------------------------------------------------- DECODE
this->_decode(frame_id);
// auto d_decod = std::chrono::steady_clock::now() - t_decod;
// auto t_store = std::chrono::steady_clock::now(); // --------------------------------------------------------- STORE
_store_cw(V_N, frame_id);
// auto d_store = std::chrono::steady_clock::now() - t_store;
// (*this)[dec::tsk::decode_siho_cw].update_timer(dec::tm::decode_siho_cw::load, d_load);
// (*this)[dec::tsk::decode_siho_cw].update_timer(dec::tm::decode_siho_cw::decode, d_decod);
// (*this)[dec::tsk::decode_siho_cw].update_timer(dec::tm::decode_siho_cw::store, d_store);
}
template<typename B, typename R>
void Decoder_LDPC_BP_peeling<B, R>::_store(B *V_K, const int frame_id)
{
for (auto i = 0; i < this->K; i++)
V_K[i] = this->var_nodes[frame_id][this->info_bits_pos[i]];
}
template<typename B, typename R>
void Decoder_LDPC_BP_peeling<B, R>::_store_cw(B *V_N, const int frame_id)
{
std::copy(this->var_nodes[frame_id].begin(), this->var_nodes[frame_id].end(), V_N);
}
// ==================================================================================== explicit template instantiation
#include "Tools/types.h"
#ifdef MULTI_PREC
template class aff3ct::module::Decoder_LDPC_BP_peeling<B_8,Q_8>;
template class aff3ct::module::Decoder_LDPC_BP_peeling<B_16,Q_16>;
template class aff3ct::module::Decoder_LDPC_BP_peeling<B_32,Q_32>;
template class aff3ct::module::Decoder_LDPC_BP_peeling<B_64,Q_64>;
#else
template class aff3ct::module::Decoder_LDPC_BP_peeling<B,Q>;
#endif
// ==================================================================================== explicit template instantiation
<|endoftext|> |
<commit_before>/** @file
@section license License
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "ts/RbTree.h"
namespace ts
{
namespace detail
{
/// Equality.
/// @note If @a n is @c NULL it is treated as having the color @c BLACK.
/// @return @c true if @a c and the color of @a n are the same.
inline bool
operator==(RBNode *n, RBNode::Color c)
{
return c == (n ? n->getColor() : RBNode::BLACK);
}
/// Equality.
/// @note If @a n is @c NULL it is treated as having the color @c BLACK.
/// @return @c true if @a c and the color of @a n are the same.
inline bool
operator==(RBNode::Color c, RBNode *n)
{
return n == c;
}
RBNode *
RBNode::getChild(Direction d) const
{
return d == RIGHT ? _right : d == LEFT ? _left : nullptr;
}
RBNode *
RBNode::rotate(Direction d)
{
self *parent = _parent; // Cache because it can change before we use it.
Direction child_dir = _parent ? _parent->getChildDirection(this) : NONE;
Direction other_dir = this->flip(d);
self *child = this;
if (d != NONE && this->getChild(other_dir)) {
child = this->getChild(other_dir);
this->clearChild(other_dir);
this->setChild(child->getChild(d), other_dir);
child->clearChild(d);
child->setChild(this, d);
child->structureFixup();
this->structureFixup();
if (parent) {
parent->clearChild(child_dir);
parent->setChild(child, child_dir);
} else {
child->_parent = nullptr;
}
}
return child;
}
RBNode *
RBNode::setChild(self *n, Direction d)
{
if (n) {
n->_parent = this;
}
if (d == RIGHT) {
_right = n;
} else if (d == LEFT) {
_left = n;
}
return n;
}
// Returns the root node
RBNode *
RBNode::rippleStructureFixup()
{
self *root = this; // last node seen, root node at the end
self *p = this;
while (p) {
p->structureFixup();
root = p;
p = root->_parent;
}
return root;
}
void
RBNode::replaceWith(self *n)
{
n->_color = _color;
if (_parent) {
Direction d = _parent->getChildDirection(this);
_parent->setChild(nullptr, d);
if (_parent != n) {
_parent->setChild(n, d);
}
} else {
n->_parent = nullptr;
}
n->_left = n->_right = nullptr;
if (_left && _left != n) {
n->setChild(_left, LEFT);
}
if (_right && _right != n) {
n->setChild(_right, RIGHT);
}
_left = _right = nullptr;
}
/* Rebalance the tree. This node is the unbalanced node. */
RBNode *
RBNode::rebalanceAfterInsert()
{
self *x(this); // the node with the imbalance
while (x && x->_parent == RED) {
Direction child_dir = NONE;
if (x->_parent->_parent) {
child_dir = x->_parent->_parent->getChildDirection(x->_parent);
} else {
break;
}
Direction other_dir(flip(child_dir));
self *y = x->_parent->_parent->getChild(other_dir);
if (y == RED) {
x->_parent->_color = BLACK;
y->_color = BLACK;
x = x->_parent->_parent;
x->_color = RED;
} else {
if (x->_parent->getChild(other_dir) == x) {
x = x->_parent;
x->rotate(child_dir);
}
// Note setting the parent color to BLACK causes the loop to exit.
x->_parent->_color = BLACK;
x->_parent->_parent->_color = RED;
x->_parent->_parent->rotate(other_dir);
}
}
// every node above this one has a subtree structure change,
// so notify it. serendipitously, this makes it easy to return
// the new root node.
self *root = this->rippleStructureFixup();
root->_color = BLACK;
return root;
}
// Returns new root node
RBNode *
RBNode::remove()
{
self *root = nullptr; // new root node, returned to caller
/* Handle two special cases first.
- This is the only node in the tree, return a new root of NIL
- This is the root node with only one child, return that child as new root
*/
if (!_parent && !(_left && _right)) {
if (_left) {
_left->_parent = nullptr;
root = _left;
root->_color = BLACK;
} else if (_right) {
_right->_parent = nullptr;
root = _right;
root->_color = BLACK;
} // else that was the only node, so leave @a root @c NULL.
return root;
}
/* The node to be removed from the tree.
If @c this (the target node) has both children, we remove
its successor, which cannot have a left child and
put that node in place of the target node. Otherwise this
node has at most one child, so we can remove it.
Note that the successor of a node with a right child is always
a right descendant of the node. Therefore, remove_node
is an element of the tree rooted at this node.
Because of the initial special case checks, we know
that remove_node is @b not the root node.
*/
self *remove_node(_left && _right ? _right->leftmostDescendant() : this);
// This is the color of the node physically removed from the tree.
// Normally this is the color of @a remove_node
Color remove_color = remove_node->_color;
// Need to remember the direction from @a remove_node to @a splice_node
Direction d(NONE);
// The child node that will be promoted to replace the removed node.
// The choice of left or right is irrelevant, as remove_node has at
// most one child (and splice_node may be NIL if remove_node has no
// children).
self *splice_node(remove_node->_left ? remove_node->_left : remove_node->_right);
if (splice_node) {
// @c replace_with copies color so in this case the actual color
// lost is that of the splice_node.
remove_color = splice_node->_color;
remove_node->replaceWith(splice_node);
} else {
// No children on remove node so we can just clip it off the tree
// We update splice_node to maintain the invariant that it is
// the node where the physical removal occurred.
splice_node = remove_node->_parent;
// Keep @a d up to date.
d = splice_node->getChildDirection(remove_node);
splice_node->setChild(nullptr, d);
}
// If the node to pull out of the tree isn't this one,
// then replace this node in the tree with that removed
// node in liu of copying the data over.
if (remove_node != this) {
// Don't leave @a splice_node referring to a removed node
if (splice_node == this) {
splice_node = remove_node;
}
this->replaceWith(remove_node);
}
root = splice_node->rebalanceAfterRemove(remove_color, d);
root->_color = BLACK;
return root;
}
/**
* Rebalance tree after a deletion
* Called on the spliced in node or its parent, whichever is not NIL.
* This modifies the tree structure only if @a c is @c BLACK.
*/
RBNode *
RBNode::rebalanceAfterRemove(Color c, //!< The color of the removed node
Direction d //!< Direction of removed node from its parent
)
{
self *root;
if (BLACK == c) { // only rebalance if too much black
self *n = this;
self *parent = n->_parent;
// If @a direction is set, then we need to start at a leaf pseudo-node.
// This is why we need @a parent, otherwise we could just use @a n.
if (NONE != d) {
parent = n;
n = nullptr;
}
while (parent) { // @a n is not the root
// If the current node is RED, we can just recolor and be done
if (n == RED) {
n->_color = BLACK;
break;
} else {
// Parameterizing the rebalance logic on the directions. We
// write for the left child case and flip directions for the
// right child case
Direction near(LEFT), far(RIGHT);
if ((NONE == d && parent->getChildDirection(n) == RIGHT) || RIGHT == d) {
near = RIGHT;
far = LEFT;
}
self *w = parent->getChild(far); // sibling(n)
if (w->_color == RED) {
w->_color = BLACK;
parent->_color = RED;
parent->rotate(near);
w = parent->getChild(far);
}
self *wfc = w->getChild(far);
if (w->getChild(near) == BLACK && wfc == BLACK) {
w->_color = RED;
n = parent;
parent = n->_parent;
d = NONE; // Cancel any leaf node logic
} else {
if (wfc->_color == BLACK) {
w->getChild(near)->_color = BLACK;
w->_color = RED;
w->rotate(far);
w = parent->getChild(far);
wfc = w->getChild(far); // w changed, update far child cache.
}
w->_color = parent->_color;
parent->_color = BLACK;
wfc->_color = BLACK;
parent->rotate(near);
break;
}
}
}
}
root = this->rippleStructureFixup();
return root;
}
/** Ensure that the local information associated with each node is
correct globally This should only be called on debug builds as it
breaks any efficiencies we have gained from our tree structure.
*/
int
RBNode::validate()
{
#if 0
int black_ht = 0;
int black_ht1, black_ht2;
if (_left) {
black_ht1 = _left->validate();
}
else
black_ht1 = 1;
if (black_ht1 > 0 && _right)
black_ht2 = _right->validate();
else
black_ht2 = 1;
if (black_ht1 == black_ht2) {
black_ht = black_ht1;
if (this->_color == BLACK)
++black_ht;
else { // No red-red
if (_left == RED)
black_ht = 0;
else if (_right == RED)
black_ht = 0;
if (black_ht == 0)
std::cout << "Red-red child\n";
}
} else {
std::cout << "Height mismatch " << black_ht1 << " " << black_ht2 << "\n";
}
if (black_ht > 0 && !this->structureValidate())
black_ht = 0;
return black_ht;
#else
return 0;
#endif
}
} // namespace detail
} // namespace ts
<commit_msg>Coverity 1021989<commit_after>/** @file
@section license License
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "ts/RbTree.h"
namespace ts
{
namespace detail
{
/// Equality.
/// @note If @a n is @c NULL it is treated as having the color @c BLACK.
/// @return @c true if @a c and the color of @a n are the same.
inline bool
operator==(RBNode *n, RBNode::Color c)
{
return c == (n ? n->getColor() : RBNode::BLACK);
}
/// Equality.
/// @note If @a n is @c NULL it is treated as having the color @c BLACK.
/// @return @c true if @a c and the color of @a n are the same.
inline bool
operator==(RBNode::Color c, RBNode *n)
{
return n == c;
}
RBNode *
RBNode::getChild(Direction d) const
{
return d == RIGHT ? _right : d == LEFT ? _left : nullptr;
}
RBNode *
RBNode::rotate(Direction d)
{
self *parent = _parent; // Cache because it can change before we use it.
Direction child_dir = _parent ? _parent->getChildDirection(this) : NONE;
Direction other_dir = this->flip(d);
self *child = this;
if (d != NONE && this->getChild(other_dir)) {
child = this->getChild(other_dir);
this->clearChild(other_dir);
this->setChild(child->getChild(d), other_dir);
child->clearChild(d);
child->setChild(this, d);
child->structureFixup();
this->structureFixup();
if (parent) {
parent->clearChild(child_dir);
parent->setChild(child, child_dir);
} else {
child->_parent = nullptr;
}
}
return child;
}
RBNode *
RBNode::setChild(self *n, Direction d)
{
if (n) {
n->_parent = this;
}
if (d == RIGHT) {
_right = n;
} else if (d == LEFT) {
_left = n;
}
return n;
}
// Returns the root node
RBNode *
RBNode::rippleStructureFixup()
{
self *root = this; // last node seen, root node at the end
self *p = this;
while (p) {
p->structureFixup();
root = p;
p = root->_parent;
}
return root;
}
void
RBNode::replaceWith(self *n)
{
n->_color = _color;
if (_parent) {
Direction d = _parent->getChildDirection(this);
_parent->setChild(nullptr, d);
if (_parent != n) {
_parent->setChild(n, d);
}
} else {
n->_parent = nullptr;
}
n->_left = n->_right = nullptr;
if (_left && _left != n) {
n->setChild(_left, LEFT);
}
if (_right && _right != n) {
n->setChild(_right, RIGHT);
}
_left = _right = nullptr;
}
/* Rebalance the tree. This node is the unbalanced node. */
RBNode *
RBNode::rebalanceAfterInsert()
{
self *x(this); // the node with the imbalance
while (x && x->_parent == RED) {
Direction child_dir = NONE;
if (x->_parent->_parent) {
child_dir = x->_parent->_parent->getChildDirection(x->_parent);
} else {
break;
}
Direction other_dir(flip(child_dir));
self *y = x->_parent->_parent->getChild(other_dir);
if (y == RED) {
x->_parent->_color = BLACK;
y->_color = BLACK;
x = x->_parent->_parent;
x->_color = RED;
} else {
if (x->_parent->getChild(other_dir) == x) {
x = x->_parent;
x->rotate(child_dir);
}
// Note setting the parent color to BLACK causes the loop to exit.
x->_parent->_color = BLACK;
x->_parent->_parent->_color = RED;
x->_parent->_parent->rotate(other_dir);
}
}
// every node above this one has a subtree structure change,
// so notify it. serendipitously, this makes it easy to return
// the new root node.
self *root = this->rippleStructureFixup();
root->_color = BLACK;
return root;
}
// Returns new root node
RBNode *
RBNode::remove()
{
self *root = nullptr; // new root node, returned to caller
/* Handle two special cases first.
- This is the only node in the tree, return a new root of NIL
- This is the root node with only one child, return that child as new root
*/
if (!_parent && !(_left && _right)) {
if (_left) {
_left->_parent = nullptr;
root = _left;
root->_color = BLACK;
} else if (_right) {
_right->_parent = nullptr;
root = _right;
root->_color = BLACK;
} // else that was the only node, so leave @a root @c NULL.
return root;
}
/* The node to be removed from the tree.
If @c this (the target node) has both children, we remove
its successor, which cannot have a left child and
put that node in place of the target node. Otherwise this
node has at most one child, so we can remove it.
Note that the successor of a node with a right child is always
a right descendant of the node. Therefore, remove_node
is an element of the tree rooted at this node.
Because of the initial special case checks, we know
that remove_node is @b not the root node.
*/
self *remove_node(_left && _right ? _right->leftmostDescendant() : this);
// This is the color of the node physically removed from the tree.
// Normally this is the color of @a remove_node
Color remove_color = remove_node->_color;
// Need to remember the direction from @a remove_node to @a splice_node
Direction d(NONE);
// The child node that will be promoted to replace the removed node.
// The choice of left or right is irrelevant, as remove_node has at
// most one child (and splice_node may be NIL if remove_node has no
// children).
self *splice_node(remove_node->_left ? remove_node->_left : remove_node->_right);
if (splice_node) {
// @c replace_with copies color so in this case the actual color
// lost is that of the splice_node.
remove_color = splice_node->_color;
remove_node->replaceWith(splice_node);
} else {
// No children on remove node so we can just clip it off the tree
// We update splice_node to maintain the invariant that it is
// the node where the physical removal occurred.
splice_node = remove_node->_parent;
// Keep @a d up to date.
d = splice_node->getChildDirection(remove_node);
splice_node->setChild(nullptr, d);
}
// If the node to pull out of the tree isn't this one,
// then replace this node in the tree with that removed
// node in liu of copying the data over.
if (remove_node != this) {
// Don't leave @a splice_node referring to a removed node
if (splice_node == this) {
splice_node = remove_node;
}
this->replaceWith(remove_node);
}
root = splice_node->rebalanceAfterRemove(remove_color, d);
root->_color = BLACK;
return root;
}
/**
* Rebalance tree after a deletion
* Called on the spliced in node or its parent, whichever is not NIL.
* This modifies the tree structure only if @a c is @c BLACK.
*/
RBNode *
RBNode::rebalanceAfterRemove(Color c, //!< The color of the removed node
Direction d //!< Direction of removed node from its parent
)
{
self *root;
if (BLACK == c) { // only rebalance if too much black
self *n = this;
self *parent = n->_parent;
// If @a direction is set, then we need to start at a leaf pseudo-node.
// This is why we need @a parent, otherwise we could just use @a n.
if (NONE != d) {
parent = n;
n = nullptr;
}
while (parent) { // @a n is not the root
// If the current node is RED, we can just recolor and be done
if (n && n == RED) {
n->_color = BLACK;
break;
} else {
// Parameterizing the rebalance logic on the directions. We
// write for the left child case and flip directions for the
// right child case
Direction near(LEFT), far(RIGHT);
if ((NONE == d && parent->getChildDirection(n) == RIGHT) || RIGHT == d) {
near = RIGHT;
far = LEFT;
}
self *w = parent->getChild(far); // sibling(n)
if (w->_color == RED) {
w->_color = BLACK;
parent->_color = RED;
parent->rotate(near);
w = parent->getChild(far);
}
self *wfc = w->getChild(far);
if (w->getChild(near) == BLACK && wfc == BLACK) {
w->_color = RED;
n = parent;
parent = n->_parent;
d = NONE; // Cancel any leaf node logic
} else {
if (wfc->_color == BLACK) {
w->getChild(near)->_color = BLACK;
w->_color = RED;
w->rotate(far);
w = parent->getChild(far);
wfc = w->getChild(far); // w changed, update far child cache.
}
w->_color = parent->_color;
parent->_color = BLACK;
wfc->_color = BLACK;
parent->rotate(near);
break;
}
}
}
}
root = this->rippleStructureFixup();
return root;
}
/** Ensure that the local information associated with each node is
correct globally This should only be called on debug builds as it
breaks any efficiencies we have gained from our tree structure.
*/
int
RBNode::validate()
{
#if 0
int black_ht = 0;
int black_ht1, black_ht2;
if (_left) {
black_ht1 = _left->validate();
}
else
black_ht1 = 1;
if (black_ht1 > 0 && _right)
black_ht2 = _right->validate();
else
black_ht2 = 1;
if (black_ht1 == black_ht2) {
black_ht = black_ht1;
if (this->_color == BLACK)
++black_ht;
else { // No red-red
if (_left == RED)
black_ht = 0;
else if (_right == RED)
black_ht = 0;
if (black_ht == 0)
std::cout << "Red-red child\n";
}
} else {
std::cout << "Height mismatch " << black_ht1 << " " << black_ht2 << "\n";
}
if (black_ht > 0 && !this->structureValidate())
black_ht = 0;
return black_ht;
#else
return 0;
#endif
}
} // namespace detail
} // namespace ts
<|endoftext|> |
<commit_before>/***************************************************************************
**
** This file is part of the qmlogre example on http://qt.gitorious.org.
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).*
**
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** You may use this file under the terms of the BSD license as follows:
**
** "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 Nokia Corporation and its Subsidiary(-ies) 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 <RenderSystems/GL/OgreGLTexture.h>
#include <RenderSystems/GL/OgreGLFrameBufferObject.h>
#include <RenderSystems/GL/OgreGLFBORenderTexture.h>
#include "ogrenode.h"
#include <Ogre.h>
#include <QtCore/QCoreApplication>
#include <QtCore/QDir>
#include <QSurfaceFormat>
#include <QOpenGLContext>
#include <QOpenGLFunctions>
OgreNode::OgreNode()
: QSGGeometryNode()
, m_geometry(QSGGeometry::defaultAttributes_TexturedPoint2D(), 4)
, m_texture(0)
, m_renderTexture(0)
, m_ogreFBO(0)
, m_dirtyFBO(false)
{
setMaterial(&m_material);
setOpaqueMaterial(&m_materialO);
setGeometry(&m_geometry);
setFlag(UsePreprocess);
}
OgreNode::~OgreNode()
{
if (m_renderTexture) {
m_renderTexture->removeAllViewports();
}
}
void OgreNode::setOgreEngineItem(OgreEngineItem *ogreRootItem)
{
m_ogreEngineItem = ogreRootItem;
}
void OgreNode::doneOgreContext()
{
m_ogreEngineItem->doneOgreContext();
}
void OgreNode::activateOgreContext()
{
m_ogreEngineItem->activateOgreContext();
m_ogreEngineItem->ogreContext()->functions()->glBindFramebuffer(GL_FRAMEBUFFER_EXT, m_ogreFBO);
}
GLuint OgreNode::getOgreFBO()
{
if (!m_renderTexture)
return 0;
Ogre::GLFrameBufferObject *ogreFbo = 0;
m_renderTexture->getCustomAttribute("FBO", &ogreFbo);
Ogre::GLFBOManager *manager = ogreFbo->getManager();
manager->bind(m_renderTexture);
GLint id;
glGetIntegerv(GL_FRAMEBUFFER_BINDING, &id);
return id;
}
void OgreNode::preprocess()
{
activateOgreContext();
m_renderTexture->update(true);
doneOgreContext();
}
void OgreNode::update()
{
if (m_dirtyFBO) {
activateOgreContext();
updateFBO();
m_ogreFBO = getOgreFBO();
m_dirtyFBO = false;
doneOgreContext();
}
}
void OgreNode::updateFBO()
{
if (m_renderTexture)
Ogre::TextureManager::getSingleton().remove("RttTex");
int samples = m_ogreEngineItem->ogreContext()->format().samples();
rtt_texture = Ogre::TextureManager::getSingleton().createManual("RttTex",
Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
Ogre::TEX_TYPE_2D,
m_size.width(),
m_size.height(),
0,
Ogre::PF_R8G8B8A8,
Ogre::TU_RENDERTARGET, 0, false,
samples);
m_renderTexture = rtt_texture->getBuffer()->getRenderTarget();
m_renderTexture->addViewport(m_camera);
m_renderTexture->getViewport(0)->setClearEveryFrame(true);
m_renderTexture->getViewport(0)->setBackgroundColour(Ogre::ColourValue::Black);
m_renderTexture->getViewport(0)->setOverlaysEnabled(false);
Ogre::Real aspectRatio = Ogre::Real(m_size.width()) / Ogre::Real(m_size.height());
m_camera->setAspectRatio(aspectRatio);
QSGGeometry::updateTexturedRectGeometry(&m_geometry,
QRectF(0, 0, m_size.width(), m_size.height()),
QRectF(0, 0, 1, 1));
Ogre::GLTexture *nativeTexture = static_cast<Ogre::GLTexture *>(rtt_texture.get());
delete m_texture;
m_texture = m_ogreEngineItem->createTextureFromId(nativeTexture->getGLID(), m_size);
m_material.setTexture(m_texture);
m_materialO.setTexture(m_texture);
}
void OgreNode::setSize(const QSize &size)
{
if (size == m_size)
return;
m_size = size;
m_dirtyFBO = true;
markDirty(DirtyGeometry);
}
<commit_msg>Fixed pointer initialization.<commit_after>/***************************************************************************
**
** This file is part of the qmlogre example on http://qt.gitorious.org.
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).*
**
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** You may use this file under the terms of the BSD license as follows:
**
** "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 Nokia Corporation and its Subsidiary(-ies) 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 <RenderSystems/GL/OgreGLTexture.h>
#include <RenderSystems/GL/OgreGLFrameBufferObject.h>
#include <RenderSystems/GL/OgreGLFBORenderTexture.h>
#include "ogrenode.h"
#include <Ogre.h>
#include <QtCore/QCoreApplication>
#include <QtCore/QDir>
#include <QSurfaceFormat>
#include <QOpenGLContext>
#include <QOpenGLFunctions>
OgreNode::OgreNode()
: QSGGeometryNode()
, m_geometry(QSGGeometry::defaultAttributes_TexturedPoint2D(), 4)
, m_texture(0)
, m_ogreEngineItem(0)
, m_camera(0)
, m_renderTexture(0)
, m_viewport(0)
, m_window(0)
, m_ogreFBO(0)
, m_dirtyFBO(false)
{
setMaterial(&m_material);
setOpaqueMaterial(&m_materialO);
setGeometry(&m_geometry);
setFlag(UsePreprocess);
}
OgreNode::~OgreNode()
{
if (m_renderTexture) {
m_renderTexture->removeAllViewports();
}
}
void OgreNode::setOgreEngineItem(OgreEngineItem *ogreRootItem)
{
m_ogreEngineItem = ogreRootItem;
}
void OgreNode::doneOgreContext()
{
m_ogreEngineItem->doneOgreContext();
}
void OgreNode::activateOgreContext()
{
m_ogreEngineItem->activateOgreContext();
m_ogreEngineItem->ogreContext()->functions()->glBindFramebuffer(GL_FRAMEBUFFER_EXT, m_ogreFBO);
}
GLuint OgreNode::getOgreFBO()
{
if (!m_renderTexture)
return 0;
Ogre::GLFrameBufferObject *ogreFbo = 0;
m_renderTexture->getCustomAttribute("FBO", &ogreFbo);
Ogre::GLFBOManager *manager = ogreFbo->getManager();
manager->bind(m_renderTexture);
GLint id;
glGetIntegerv(GL_FRAMEBUFFER_BINDING, &id);
return id;
}
void OgreNode::preprocess()
{
activateOgreContext();
m_renderTexture->update(true);
doneOgreContext();
}
void OgreNode::update()
{
if (m_dirtyFBO) {
activateOgreContext();
updateFBO();
m_ogreFBO = getOgreFBO();
m_dirtyFBO = false;
doneOgreContext();
}
}
void OgreNode::updateFBO()
{
if (m_renderTexture)
Ogre::TextureManager::getSingleton().remove("RttTex");
int samples = m_ogreEngineItem->ogreContext()->format().samples();
rtt_texture = Ogre::TextureManager::getSingleton().createManual("RttTex",
Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
Ogre::TEX_TYPE_2D,
m_size.width(),
m_size.height(),
0,
Ogre::PF_R8G8B8A8,
Ogre::TU_RENDERTARGET, 0, false,
samples);
m_renderTexture = rtt_texture->getBuffer()->getRenderTarget();
m_renderTexture->addViewport(m_camera);
m_renderTexture->getViewport(0)->setClearEveryFrame(true);
m_renderTexture->getViewport(0)->setBackgroundColour(Ogre::ColourValue::Black);
m_renderTexture->getViewport(0)->setOverlaysEnabled(false);
Ogre::Real aspectRatio = Ogre::Real(m_size.width()) / Ogre::Real(m_size.height());
m_camera->setAspectRatio(aspectRatio);
QSGGeometry::updateTexturedRectGeometry(&m_geometry,
QRectF(0, 0, m_size.width(), m_size.height()),
QRectF(0, 0, 1, 1));
Ogre::GLTexture *nativeTexture = static_cast<Ogre::GLTexture *>(rtt_texture.get());
delete m_texture;
m_texture = m_ogreEngineItem->createTextureFromId(nativeTexture->getGLID(), m_size);
m_material.setTexture(m_texture);
m_materialO.setTexture(m_texture);
}
void OgreNode::setSize(const QSize &size)
{
if (size == m_size)
return;
m_size = size;
m_dirtyFBO = true;
markDirty(DirtyGeometry);
}
<|endoftext|> |
<commit_before>/******************************************************************************\
* ___ __ *
* /\_ \ __/\ \ *
* \//\ \ /\_\ \ \____ ___ _____ _____ __ *
* \ \ \ \/\ \ \ '__`\ /'___\/\ '__`\/\ '__`\ /'__`\ *
* \_\ \_\ \ \ \ \L\ \/\ \__/\ \ \L\ \ \ \L\ \/\ \L\.\_ *
* /\____\\ \_\ \_,__/\ \____\\ \ ,__/\ \ ,__/\ \__/.\_\ *
* \/____/ \/_/\/___/ \/____/ \ \ \/ \ \ \/ \/__/\/_/ *
* \ \_\ \ \_\ *
* \/_/ \/_/ *
* *
* Copyright (C) 2011, 2012 *
* Dominik Charousset <dominik.charousset@haw-hamburg.de> *
* *
* This file is part of libcppa. *
* libcppa is free software: you can redistribute it and/or modify it under *
* the terms of the GNU Lesser General Public License as published by the *
* Free Software Foundation, either version 3 of the License *
* or (at your option) any later version. *
* *
* libcppa 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 libcppa. If not, see <http://www.gnu.org/licenses/>. *
\******************************************************************************/
#ifndef OPTION_HPP
#define OPTION_HPP
#include <new>
#include <utility>
#include "cppa/config.hpp"
namespace cppa {
/**
* @brief Represents an optional value of @p T.
*/
template<typename T>
class option
{
public:
/**
* @brief Typdef for @p T.
*/
typedef T value_type;
/**
* @brief Default constructor.
* @post <tt>valid() == false</tt>
*/
option() : m_valid(false) { }
/**
* @brief Creates an @p option from @p value.
* @post <tt>valid() == true</tt>
*/
option(T&& value) : m_valid(false) { cr(std::move(value)); }
/**
* @brief Creates an @p option from @p value.
* @post <tt>valid() == true</tt>
*/
option(T const& value) : m_valid(false) { cr(value); }
option(option const& other) : m_valid(false)
{
if (other.m_valid) cr(other.m_value);
}
option(option&& other) : m_valid(false)
{
if (other.m_valid) cr(std::move(other.m_value));
}
~option() { destroy(); }
option& operator=(option const& other)
{
if (m_valid)
{
if (other.m_valid) m_value = other.m_value;
else destroy();
}
else if (other.m_valid)
{
cr(other.m_value);
}
return *this;
}
option& operator=(option&& other)
{
if (m_valid)
{
if (other.m_valid) m_value = std::move(other.m_value);
else destroy();
}
else if (other.m_valid)
{
cr(std::move(other.m_value));
}
return *this;
}
option& operator=(T const& value)
{
if (m_valid) m_value = value;
else cr(value);
return *this;
}
option& operator=(T& value)
{
if (m_valid) m_value = std::move(value);
else cr(std::move(value));
return *this;
}
/**
* @brief Returns @p true if this @p option has a valid value;
* otherwise @p false.
*/
inline bool valid() const { return m_valid; }
/**
* @copydoc valid()
*/
inline explicit operator bool() const { return m_valid; }
/**
* @brief Returns <tt>!valid()</tt>
*/
inline bool operator!() const { return !m_valid; }
/**
* @brief Returns the value.
*/
inline T& operator*()
{
CPPA_REQUIRE(valid());
return m_value;
}
/**
* @brief Returns the value.
*/
inline T const& operator*() const
{
CPPA_REQUIRE(valid());
return m_value;
}
/**
* @brief Returns the value.
*/
inline T& get()
{
CPPA_REQUIRE(valid());
return m_value;
}
/**
* @brief Returns the value.
*/
inline T const& get() const
{
CPPA_REQUIRE(valid());
return m_value;
}
/**
* @brief Returns the value. The value is set to @p default_value
* if <tt>valid() == false</tt>.
* @post <tt>valid() == true</tt>
*/
inline T& get_or_else(T const& default_value)
{
if (!m_valid) cr(default_value);
return m_value;
}
/**
* @copydoc get_or_else(T const&)
*/
inline T& get_or_else(T&& default_value)
{
if (!m_valid) cr(std::move(default_value));
return m_value;
}
private:
bool m_valid;
union { T m_value; };
void destroy()
{
if (m_valid)
{
m_value.~T();
m_valid = false;
}
}
template<typename V>
void cr(V&& value)
{
CPPA_REQUIRE(!valid());
m_valid = true;
new (&m_value) T (std::forward<V>(value));
}
};
/** @relates option */
template<typename T, typename U>
bool operator==(option<T> const& lhs, option<U> const& rhs)
{
if ((lhs) && (rhs)) return *lhs == *rhs;
return false;
}
/** @relates option */
template<typename T, typename U>
bool operator==(option<T> const& lhs, U const& rhs)
{
if (lhs) return *lhs == rhs;
return false;
}
/** @relates option */
template<typename T, typename U>
bool operator==(T const& lhs, option<U> const& rhs)
{
return rhs == lhs;
}
/** @relates option */
template<typename T, typename U>
bool operator!=(option<T> const& lhs, option<U> const& rhs)
{
return !(lhs == rhs);
}
/** @relates option */
template<typename T, typename U>
bool operator!=(option<T> const& lhs, U const& rhs)
{
return !(lhs == rhs);
}
/** @relates option */
template<typename T, typename U>
bool operator!=(T const& lhs, option<U> const& rhs)
{
return !(lhs == rhs);
}
} // namespace cppa
#endif // OPTION_HPP
<commit_msg>made get_or_else const<commit_after>/******************************************************************************\
* ___ __ *
* /\_ \ __/\ \ *
* \//\ \ /\_\ \ \____ ___ _____ _____ __ *
* \ \ \ \/\ \ \ '__`\ /'___\/\ '__`\/\ '__`\ /'__`\ *
* \_\ \_\ \ \ \ \L\ \/\ \__/\ \ \L\ \ \ \L\ \/\ \L\.\_ *
* /\____\\ \_\ \_,__/\ \____\\ \ ,__/\ \ ,__/\ \__/.\_\ *
* \/____/ \/_/\/___/ \/____/ \ \ \/ \ \ \/ \/__/\/_/ *
* \ \_\ \ \_\ *
* \/_/ \/_/ *
* *
* Copyright (C) 2011, 2012 *
* Dominik Charousset <dominik.charousset@haw-hamburg.de> *
* *
* This file is part of libcppa. *
* libcppa is free software: you can redistribute it and/or modify it under *
* the terms of the GNU Lesser General Public License as published by the *
* Free Software Foundation, either version 3 of the License *
* or (at your option) any later version. *
* *
* libcppa 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 libcppa. If not, see <http://www.gnu.org/licenses/>. *
\******************************************************************************/
#ifndef OPTION_HPP
#define OPTION_HPP
#include <new>
#include <utility>
#include "cppa/config.hpp"
namespace cppa {
/**
* @brief Represents an optional value of @p T.
*/
template<typename T>
class option
{
public:
/**
* @brief Typdef for @p T.
*/
typedef T type;
/**
* @brief Default constructor.
* @post <tt>valid() == false</tt>
*/
option() : m_valid(false) { }
/**
* @brief Creates an @p option from @p value.
* @post <tt>valid() == true</tt>
*/
option(T value) : m_valid(false) { cr(std::move(value)); }
option(option const& other) : m_valid(false)
{
if (other.m_valid) cr(other.m_value);
}
option(option&& other) : m_valid(false)
{
if (other.m_valid) cr(std::move(other.m_value));
}
~option() { destroy(); }
option& operator=(option const& other)
{
if (m_valid)
{
if (other.m_valid) m_value = other.m_value;
else destroy();
}
else if (other.m_valid)
{
cr(other.m_value);
}
return *this;
}
option& operator=(option&& other)
{
if (m_valid)
{
if (other.m_valid) m_value = std::move(other.m_value);
else destroy();
}
else if (other.m_valid)
{
cr(std::move(other.m_value));
}
return *this;
}
option& operator=(T const& value)
{
if (m_valid) m_value = value;
else cr(value);
return *this;
}
option& operator=(T& value)
{
if (m_valid) m_value = std::move(value);
else cr(std::move(value));
return *this;
}
/**
* @brief Returns @p true if this @p option has a valid value;
* otherwise @p false.
*/
inline bool valid() const { return m_valid; }
inline bool empty() const { return !m_valid; }
/**
* @copydoc valid()
*/
inline explicit operator bool() const { return valid(); }
/**
* @brief Returns <tt>!valid()</tt>
*/
inline bool operator!() const { return empty(); }
/**
* @brief Returns the value.
*/
inline T& operator*()
{
CPPA_REQUIRE(valid());
return m_value;
}
/**
* @brief Returns the value.
*/
inline T const& operator*() const
{
CPPA_REQUIRE(valid());
return m_value;
}
/**
* @brief Returns the value.
*/
inline T& get()
{
CPPA_REQUIRE(valid());
return m_value;
}
/**
* @brief Returns the value.
*/
inline T const& get() const
{
CPPA_REQUIRE(valid());
return m_value;
}
/**
* @brief Returns the value. The value is set to @p default_value
* if <tt>valid() == false</tt>.
* @post <tt>valid() == true</tt>
*/
inline const T& get_or_else(const T& default_value) const
{
if (valid()) return get();
return default_value;
}
private:
bool m_valid;
union { T m_value; };
void destroy()
{
if (m_valid)
{
m_value.~T();
m_valid = false;
}
}
template<typename V>
void cr(V&& value)
{
CPPA_REQUIRE(!valid());
m_valid = true;
new (&m_value) T (std::forward<V>(value));
}
};
/** @relates option */
template<typename T, typename U>
bool operator==(option<T> const& lhs, option<U> const& rhs)
{
if ((lhs) && (rhs)) return *lhs == *rhs;
return false;
}
/** @relates option */
template<typename T, typename U>
bool operator==(option<T> const& lhs, U const& rhs)
{
if (lhs) return *lhs == rhs;
return false;
}
/** @relates option */
template<typename T, typename U>
bool operator==(T const& lhs, option<U> const& rhs)
{
return rhs == lhs;
}
/** @relates option */
template<typename T, typename U>
bool operator!=(option<T> const& lhs, option<U> const& rhs)
{
return !(lhs == rhs);
}
/** @relates option */
template<typename T, typename U>
bool operator!=(option<T> const& lhs, U const& rhs)
{
return !(lhs == rhs);
}
/** @relates option */
template<typename T, typename U>
bool operator!=(T const& lhs, option<U> const& rhs)
{
return !(lhs == rhs);
}
} // namespace cppa
#endif // OPTION_HPP
<|endoftext|> |
<commit_before>// This file is part of the dune-gdt project:
// https://github.com/dune-community/dune-gdt
// Copyright 2010-2017 dune-gdt developers and contributors. All rights reserved.
// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
// or GPL-2.0+ (http://opensource.org/licenses/gpl-license)
// with "runtime exception" (http://www.dune-project.org/license.html)
// Authors:
// Felix Schindler (2016 - 2017)
// Rene Milk (2016 - 2017)
// Tobias Leibner (2016)
#ifndef DUNE_GDT_HYPERBOLIC_PROBLEMS_MOMENTMODELS_KINETICTRANSPORTEQUATION_HH
#define DUNE_GDT_HYPERBOLIC_PROBLEMS_MOMENTMODELS_KINETICTRANSPORTEQUATION_HH
#include <dune/xt/functions/affine.hh>
#include <dune/xt/functions/checkerboard.hh>
#include <dune/xt/functions/lambda/global-function.hh>
#include <dune/xt/functions/lambda/global-flux-function.hh>
#include "../kineticequation.hh"
namespace Dune {
namespace GDT {
namespace Hyperbolic {
namespace Problems {
template <class BasisfunctionImp, class GridLayerImp, class U_, size_t quadratureDim = BasisfunctionImp::dimDomain>
class KineticTransportEquation : public KineticEquationImplementation<BasisfunctionImp, GridLayerImp, U_>,
public XT::Common::ParametricInterface
{
typedef KineticTransportEquation ThisType;
typedef KineticEquationImplementation<BasisfunctionImp, GridLayerImp, U_> BaseType;
public:
static const bool linear = true;
using typename BaseType::BasisfunctionType;
using typename BaseType::GridLayerType;
using typename BaseType::DomainFieldType;
using typename BaseType::StateType;
using typename BaseType::RangeFieldType;
using typename BaseType::DomainType;
using typename BaseType::RangeType;
using typename BaseType::MatrixType;
using BaseType::dimDomain;
using BaseType::dimRange;
using typename BaseType::FluxType;
using typename BaseType::RhsType;
using typename BaseType::InitialValueType;
using typename BaseType::BoundaryValueType;
using typename BaseType::ActualFluxType;
using typename BaseType::ActualRhsType;
using typename BaseType::ActualInitialValueType;
using typename BaseType::ActualBoundaryValueType;
using typename BaseType::RhsAffineFunctionType;
typedef Dune::QuadratureRule<DomainFieldType, quadratureDim> QuadratureType;
using BaseType::default_grid_cfg;
using BaseType::default_boundary_cfg;
static QuadratureType default_quadrature(const XT::Common::Configuration& grid_cfg = default_grid_cfg())
{
std::vector<int> num_quad_cells = grid_cfg.get("num_quad_cells", std::vector<int>{2, 2, 2});
int quad_order = grid_cfg.get("quad_order", 20);
// quadrature that consists of a Gauss-Legendre quadrature on each cell of the velocity grid
QuadratureType quadrature;
Dune::FieldVector<double, quadratureDim> lower_left(-1);
Dune::FieldVector<double, quadratureDim> upper_right(1);
std::array<int, quadratureDim> s;
for (size_t ii = 0; ii < quadratureDim; ++ii)
s[ii] = num_quad_cells[ii];
typedef typename Dune::YaspGrid<quadratureDim, Dune::EquidistantOffsetCoordinates<double, quadratureDim>> GridType;
GridType velocity_grid(lower_left, upper_right, s);
const auto velocity_grid_view = velocity_grid.leafGridView();
for (const auto& entity : elements(velocity_grid_view)) {
const auto local_quadrature = Dune::QuadratureRules<DomainFieldType, quadratureDim>::rule(
entity.type(), quad_order, Dune::QuadratureType::GaussLegendre);
for (const auto& quad_point : local_quadrature) {
quadrature.push_back(Dune::QuadraturePoint<DomainFieldType, quadratureDim>(
entity.geometry().global(quad_point.position()),
quad_point.weight() * entity.geometry().integrationElement(quad_point.position())));
}
}
return quadrature;
}
KineticTransportEquation(const BasisfunctionType& basis_functions,
const GridLayerType& grid_layer,
const QuadratureType quadrature = QuadratureType(),
DynamicVector<size_t> num_segments = {1, 1, 1},
const XT::Common::Configuration& grid_cfg = default_grid_cfg(),
const XT::Common::Configuration& boundary_cfg = default_boundary_cfg(),
const RangeFieldType psi_vac = 5e-9,
const XT::Common::ParameterType& parameter_type = XT::Common::ParameterType())
: BaseType(basis_functions, grid_layer)
, num_segments_(num_segments)
, grid_cfg_(grid_cfg)
, boundary_cfg_(boundary_cfg)
, psi_vac_(psi_vac)
, quadrature_(quadrature)
, parameter_type_(parameter_type)
{
num_segments_.resize(dimDomain);
if (quadrature_.empty())
quadrature_ = default_quadrature(grid_cfg);
if (parameter_type_.empty())
parameter_type_ = XT::Common::ParameterType({std::make_pair("sigma_a", get_num_regions(num_segments)),
std::make_pair("sigma_s", get_num_regions(num_segments)),
std::make_pair("Q", get_num_regions(num_segments)),
std::make_pair("CFL", 1),
std::make_pair("t_end", 1)});
}
virtual ~KineticTransportEquation()
{
}
virtual bool is_parametric() const override
{
return true;
}
virtual const XT::Common::ParameterType& parameter_type() const override
{
return parameter_type_;
}
virtual XT::Common::Parameter parameters() const = 0;
using XT::Common::ParametricInterface::parse_parameter;
// flux matrix A = B M^{-1} with B_{ij} = <v h_i h_j>
virtual FluxType* create_flux() const override
{
// calculate B row-wise by solving M^{T} A^T = B^T column-wise
auto A = basis_functions_.mass_matrix_with_v();
auto M_T = basis_functions_.mass_matrix();
transpose_in_place(M_T);
// solve
DynamicVector<RangeFieldType> tmp_row(M_T.N(), 0.);
for (size_t dd = 0; dd < dimDomain; ++dd) {
for (size_t ii = 0; ii < M_T.N(); ++ii) {
M_T.solve(tmp_row, A[dd][ii]);
A[dd][ii] = tmp_row;
}
}
return new ActualFluxType(A, typename ActualFluxType::RangeType(0));
}
// RHS is (sigma_s/vol*G - sigma_t * I)u + Q<b>,
// where sigma_t = sigma_s + sigma_a, G = <b><b>^T M^{-1} = <b>*c^T and
// vol = <1> is the volume of the integration domain.
virtual RhsType* create_rhs() const override
{
const auto param = parse_parameter(parameters());
const size_t num_regions = get_num_regions(num_segments_);
auto sigma_a = param.get("sigma_a");
auto sigma_s = param.get("sigma_s");
auto Q = param.get("Q");
assert(sigma_a.size() == sigma_s.size() && sigma_a.size() == Q.size() && sigma_a.size() == num_regions);
const DomainType lower_left = XT::Common::from_string<DomainType>(grid_cfg_["lower_left"]);
const DomainType upper_right = XT::Common::from_string<DomainType>(grid_cfg_["upper_right"]);
auto sigma_t = sigma_a;
for (size_t ii = 0; ii < num_regions; ++ii)
sigma_t[ii] += sigma_s[ii];
const RangeType basis_integrated = basis_functions_.integrated();
std::cout << "basis_integrated = " << XT::Common::to_string(basis_integrated, 15) << std::endl;
// calculate c = M^{-T} <b>
auto M_T = basis_functions_.mass_matrix();
// calculate c = M^{-T} <b>
transpose_in_place(M_T);
RangeType c(0.);
M_T.solve(c, basis_integrated);
MatrixType I(dimRange, dimRange, 0.);
for (size_t rr = 0; rr < dimRange; ++rr)
I[rr][rr] = 1;
MatrixType G(dimRange, dimRange, 0.);
for (size_t rr = 0; rr < dimRange; ++rr)
for (size_t cc = 0; cc < dimRange; ++cc)
G[rr][cc] = basis_integrated[rr] * c[cc];
const auto vol = unit_ball_volume();
std::vector<RhsAffineFunctionType> affine_functions;
for (size_t ii = 0; ii < num_regions; ++ii) {
MatrixType G_scaled = G;
G_scaled *= sigma_s[ii] / vol;
MatrixType I_scaled = I;
I_scaled *= sigma_t[ii];
MatrixType A = G_scaled;
A -= I_scaled;
RangeType b = basis_integrated;
b *= Q[ii];
affine_functions.emplace_back(A, b, true, "rhs");
} // ii
return new ActualRhsType(lower_left, upper_right, num_segments_, affine_functions);
} // ... create_rhs(...)
// Initial value of the kinetic equation is a constant vacuum concentration psi_vac.
// Thus, the initial value of the n-th moment is basis_integrated * psi_vac.
virtual InitialValueType* create_initial_values() const override
{
const DomainType lower_left = XT::Common::from_string<DomainType>(grid_cfg_["lower_left"]);
const DomainType upper_right = XT::Common::from_string<DomainType>(grid_cfg_["upper_right"]);
RangeType value = basis_functions_.integrated();
value *= psi_vac_;
std::vector<typename ActualInitialValueType::LocalizableFunctionType> initial_vals;
const size_t num_regions = get_num_regions(num_segments_);
for (size_t ii = 0; ii < num_regions; ++ii)
initial_vals.emplace_back([=](const DomainType&, const XT::Common::Parameter&) { return value; }, 0);
return new ActualInitialValueType(lower_left, upper_right, num_segments_, initial_vals, "initial_values");
} // ... create_initial_values()
// Use a constant vacuum concentration basis_integrated * psi_vac as boundary value
virtual BoundaryValueType* create_boundary_values() const override
{
RangeType value = basis_functions_.integrated();
value *= psi_vac_;
return new ActualBoundaryValueType([=](const DomainType&, const XT::Common::Parameter&) { return value; }, 0);
} // ... create_boundary_values()
virtual RangeFieldType CFL() const override
{
return parameters().get("CFL")[0];
}
virtual RangeFieldType t_end() const override
{
return parameters().get("t_end")[0];
}
virtual XT::Common::Configuration grid_config() const override
{
return grid_cfg_;
}
virtual XT::Common::Configuration boundary_config() const override
{
return boundary_cfg_;
}
static std::string static_id()
{
return "kinetictransportequation";
}
virtual const QuadratureType& quadrature() const
{
return quadrature_;
}
protected:
static size_t get_num_regions(const DynamicVector<size_t>& num_segments)
{
return std::accumulate(num_segments.begin(), num_segments.end(), 1, [](auto a, auto b) { return a * b; });
}
static RangeFieldType unit_ball_volume()
{
if (BasisfunctionType::dimDomain == 1)
return 2;
else if (BasisfunctionType::dimDomain == 2)
return 2 * M_PI;
else if (BasisfunctionType::dimDomain == 3)
return 4 * M_PI;
else {
DUNE_THROW(NotImplemented, "");
return 0;
}
}
template <class MatrixType>
void transpose_in_place(MatrixType& M) const
{
for (size_t rr = 0; rr < dimRange; ++rr)
for (size_t cc = 0; cc < rr; ++cc) {
auto tmp_val = M[cc][rr];
M[cc][rr] = M[rr][cc];
M[rr][cc] = tmp_val;
}
}
using BaseType::basis_functions_;
DynamicVector<size_t> num_segments_;
const XT::Common::Configuration grid_cfg_;
const XT::Common::Configuration boundary_cfg_;
const RangeFieldType psi_vac_;
QuadratureType quadrature_;
XT::Common::ParameterType parameter_type_;
}; // class KineticTransportEquation<...>
} // namespace Problems
} // namespace Hyperbolic
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_HYPERBOLIC_PROBLEMS_MOMENTMODELS_KINETICTRANSPORTEQUATION_HH
<commit_msg>[test.hyperbolic...kinetictransportequation] fix parameter_type<commit_after>// This file is part of the dune-gdt project:
// https://github.com/dune-community/dune-gdt
// Copyright 2010-2017 dune-gdt developers and contributors. All rights reserved.
// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
// or GPL-2.0+ (http://opensource.org/licenses/gpl-license)
// with "runtime exception" (http://www.dune-project.org/license.html)
// Authors:
// Felix Schindler (2016 - 2017)
// Rene Milk (2016 - 2017)
// Tobias Leibner (2016)
#ifndef DUNE_GDT_HYPERBOLIC_PROBLEMS_MOMENTMODELS_KINETICTRANSPORTEQUATION_HH
#define DUNE_GDT_HYPERBOLIC_PROBLEMS_MOMENTMODELS_KINETICTRANSPORTEQUATION_HH
#include <dune/xt/functions/affine.hh>
#include <dune/xt/functions/checkerboard.hh>
#include <dune/xt/functions/lambda/global-function.hh>
#include <dune/xt/functions/lambda/global-flux-function.hh>
#include "../kineticequation.hh"
namespace Dune {
namespace GDT {
namespace Hyperbolic {
namespace Problems {
template <class BasisfunctionImp, class GridLayerImp, class U_, size_t quadratureDim = BasisfunctionImp::dimDomain>
class KineticTransportEquation : public KineticEquationImplementation<BasisfunctionImp, GridLayerImp, U_>,
public XT::Common::ParametricInterface
{
typedef KineticTransportEquation ThisType;
typedef KineticEquationImplementation<BasisfunctionImp, GridLayerImp, U_> BaseType;
public:
static const bool linear = true;
using typename BaseType::BasisfunctionType;
using typename BaseType::GridLayerType;
using typename BaseType::DomainFieldType;
using typename BaseType::StateType;
using typename BaseType::RangeFieldType;
using typename BaseType::DomainType;
using typename BaseType::RangeType;
using typename BaseType::MatrixType;
using BaseType::dimDomain;
using BaseType::dimRange;
using typename BaseType::FluxType;
using typename BaseType::RhsType;
using typename BaseType::InitialValueType;
using typename BaseType::BoundaryValueType;
using typename BaseType::ActualFluxType;
using typename BaseType::ActualRhsType;
using typename BaseType::ActualInitialValueType;
using typename BaseType::ActualBoundaryValueType;
using typename BaseType::RhsAffineFunctionType;
typedef Dune::QuadratureRule<DomainFieldType, quadratureDim> QuadratureType;
using BaseType::default_grid_cfg;
using BaseType::default_boundary_cfg;
static QuadratureType default_quadrature(const XT::Common::Configuration& grid_cfg = default_grid_cfg())
{
std::vector<int> num_quad_cells = grid_cfg.get("num_quad_cells", std::vector<int>{2, 2, 2});
int quad_order = grid_cfg.get("quad_order", 20);
// quadrature that consists of a Gauss-Legendre quadrature on each cell of the velocity grid
QuadratureType quadrature;
Dune::FieldVector<double, quadratureDim> lower_left(-1);
Dune::FieldVector<double, quadratureDim> upper_right(1);
std::array<int, quadratureDim> s;
for (size_t ii = 0; ii < quadratureDim; ++ii)
s[ii] = num_quad_cells[ii];
typedef typename Dune::YaspGrid<quadratureDim, Dune::EquidistantOffsetCoordinates<double, quadratureDim>> GridType;
GridType velocity_grid(lower_left, upper_right, s);
const auto velocity_grid_view = velocity_grid.leafGridView();
for (const auto& entity : elements(velocity_grid_view)) {
const auto local_quadrature = Dune::QuadratureRules<DomainFieldType, quadratureDim>::rule(
entity.type(), quad_order, Dune::QuadratureType::GaussLegendre);
for (const auto& quad_point : local_quadrature) {
quadrature.push_back(Dune::QuadraturePoint<DomainFieldType, quadratureDim>(
entity.geometry().global(quad_point.position()),
quad_point.weight() * entity.geometry().integrationElement(quad_point.position())));
}
}
return quadrature;
}
KineticTransportEquation(const BasisfunctionType& basis_functions,
const GridLayerType& grid_layer,
const QuadratureType quadrature = QuadratureType(),
DynamicVector<size_t> num_segments = {1, 1, 1},
const XT::Common::Configuration& grid_cfg = default_grid_cfg(),
const XT::Common::Configuration& boundary_cfg = default_boundary_cfg(),
const RangeFieldType psi_vac = 5e-9,
const XT::Common::ParameterType& parameter_type = XT::Common::ParameterType())
: BaseType(basis_functions, grid_layer)
, num_segments_(num_segments)
, grid_cfg_(grid_cfg)
, boundary_cfg_(boundary_cfg)
, psi_vac_(psi_vac)
, quadrature_(quadrature)
, parameter_type_(parameter_type)
{
num_segments_.resize(dimDomain);
if (quadrature_.empty())
quadrature_ = default_quadrature(grid_cfg);
if (parameter_type_.empty())
parameter_type_ = XT::Common::ParameterType({std::make_pair("sigma_a", get_num_regions(num_segments_)),
std::make_pair("sigma_s", get_num_regions(num_segments_)),
std::make_pair("Q", get_num_regions(num_segments_)),
std::make_pair("CFL", 1),
std::make_pair("t_end", 1)});
}
virtual ~KineticTransportEquation()
{
}
virtual bool is_parametric() const override
{
return true;
}
virtual const XT::Common::ParameterType& parameter_type() const override
{
return parameter_type_;
}
virtual XT::Common::Parameter parameters() const = 0;
using XT::Common::ParametricInterface::parse_parameter;
// flux matrix A = B M^{-1} with B_{ij} = <v h_i h_j>
virtual FluxType* create_flux() const override
{
// calculate B row-wise by solving M^{T} A^T = B^T column-wise
auto A = basis_functions_.mass_matrix_with_v();
auto M_T = basis_functions_.mass_matrix();
transpose_in_place(M_T);
// solve
DynamicVector<RangeFieldType> tmp_row(M_T.N(), 0.);
for (size_t dd = 0; dd < dimDomain; ++dd) {
for (size_t ii = 0; ii < M_T.N(); ++ii) {
M_T.solve(tmp_row, A[dd][ii]);
A[dd][ii] = tmp_row;
}
}
return new ActualFluxType(A, typename ActualFluxType::RangeType(0));
}
// RHS is (sigma_s/vol*G - sigma_t * I)u + Q<b>,
// where sigma_t = sigma_s + sigma_a, G = <b><b>^T M^{-1} = <b>*c^T and
// vol = <1> is the volume of the integration domain.
virtual RhsType* create_rhs() const override
{
const auto param = parse_parameter(parameters());
const size_t num_regions = get_num_regions(num_segments_);
auto sigma_a = param.get("sigma_a");
auto sigma_s = param.get("sigma_s");
auto Q = param.get("Q");
assert(sigma_a.size() == sigma_s.size() && sigma_a.size() == Q.size() && sigma_a.size() == num_regions);
const DomainType lower_left = XT::Common::from_string<DomainType>(grid_cfg_["lower_left"]);
const DomainType upper_right = XT::Common::from_string<DomainType>(grid_cfg_["upper_right"]);
auto sigma_t = sigma_a;
for (size_t ii = 0; ii < num_regions; ++ii)
sigma_t[ii] += sigma_s[ii];
const RangeType basis_integrated = basis_functions_.integrated();
std::cout << "basis_integrated = " << XT::Common::to_string(basis_integrated, 15) << std::endl;
// calculate c = M^{-T} <b>
auto M_T = basis_functions_.mass_matrix();
// calculate c = M^{-T} <b>
transpose_in_place(M_T);
RangeType c(0.);
M_T.solve(c, basis_integrated);
MatrixType I(dimRange, dimRange, 0.);
for (size_t rr = 0; rr < dimRange; ++rr)
I[rr][rr] = 1;
MatrixType G(dimRange, dimRange, 0.);
for (size_t rr = 0; rr < dimRange; ++rr)
for (size_t cc = 0; cc < dimRange; ++cc)
G[rr][cc] = basis_integrated[rr] * c[cc];
const auto vol = unit_ball_volume();
std::vector<RhsAffineFunctionType> affine_functions;
for (size_t ii = 0; ii < num_regions; ++ii) {
MatrixType G_scaled = G;
G_scaled *= sigma_s[ii] / vol;
MatrixType I_scaled = I;
I_scaled *= sigma_t[ii];
MatrixType A = G_scaled;
A -= I_scaled;
RangeType b = basis_integrated;
b *= Q[ii];
affine_functions.emplace_back(A, b, true, "rhs");
} // ii
return new ActualRhsType(lower_left, upper_right, num_segments_, affine_functions);
} // ... create_rhs(...)
// Initial value of the kinetic equation is a constant vacuum concentration psi_vac.
// Thus, the initial value of the n-th moment is basis_integrated * psi_vac.
virtual InitialValueType* create_initial_values() const override
{
const DomainType lower_left = XT::Common::from_string<DomainType>(grid_cfg_["lower_left"]);
const DomainType upper_right = XT::Common::from_string<DomainType>(grid_cfg_["upper_right"]);
RangeType value = basis_functions_.integrated();
value *= psi_vac_;
std::vector<typename ActualInitialValueType::LocalizableFunctionType> initial_vals;
const size_t num_regions = get_num_regions(num_segments_);
for (size_t ii = 0; ii < num_regions; ++ii)
initial_vals.emplace_back([=](const DomainType&, const XT::Common::Parameter&) { return value; }, 0);
return new ActualInitialValueType(lower_left, upper_right, num_segments_, initial_vals, "initial_values");
} // ... create_initial_values()
// Use a constant vacuum concentration basis_integrated * psi_vac as boundary value
virtual BoundaryValueType* create_boundary_values() const override
{
RangeType value = basis_functions_.integrated();
value *= psi_vac_;
return new ActualBoundaryValueType([=](const DomainType&, const XT::Common::Parameter&) { return value; }, 0);
} // ... create_boundary_values()
virtual RangeFieldType CFL() const override
{
return parameters().get("CFL")[0];
}
virtual RangeFieldType t_end() const override
{
return parameters().get("t_end")[0];
}
virtual XT::Common::Configuration grid_config() const override
{
return grid_cfg_;
}
virtual XT::Common::Configuration boundary_config() const override
{
return boundary_cfg_;
}
static std::string static_id()
{
return "kinetictransportequation";
}
virtual const QuadratureType& quadrature() const
{
return quadrature_;
}
protected:
static size_t get_num_regions(const DynamicVector<size_t>& num_segments)
{
return std::accumulate(num_segments.begin(), num_segments.end(), 1, [](auto a, auto b) { return a * b; });
}
static RangeFieldType unit_ball_volume()
{
if (BasisfunctionType::dimDomain == 1)
return 2;
else if (BasisfunctionType::dimDomain == 2)
return 2 * M_PI;
else if (BasisfunctionType::dimDomain == 3)
return 4 * M_PI;
else {
DUNE_THROW(NotImplemented, "");
return 0;
}
}
template <class MatrixType>
void transpose_in_place(MatrixType& M) const
{
for (size_t rr = 0; rr < dimRange; ++rr)
for (size_t cc = 0; cc < rr; ++cc) {
auto tmp_val = M[cc][rr];
M[cc][rr] = M[rr][cc];
M[rr][cc] = tmp_val;
}
}
using BaseType::basis_functions_;
DynamicVector<size_t> num_segments_;
const XT::Common::Configuration grid_cfg_;
const XT::Common::Configuration boundary_cfg_;
const RangeFieldType psi_vac_;
QuadratureType quadrature_;
XT::Common::ParameterType parameter_type_;
}; // class KineticTransportEquation<...>
} // namespace Problems
} // namespace Hyperbolic
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_HYPERBOLIC_PROBLEMS_MOMENTMODELS_KINETICTRANSPORTEQUATION_HH
<|endoftext|> |
<commit_before>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Copyright 2014 Cloudius Systems
*
* Modified by Cloudius Systems
*/
#ifndef CQL3_CFNAME_HH
#define CQL3_CFNAME_HH
#include <experimental/optional>
namespace cql3 {
class cf_name {
private:
std::experimental::optional<sstring> _ks_name;
sstring _cf_name;
public:
void set_keyspace(sstring ks, bool keep_case) {
if (!keep_case) {
std::transform(ks.begin(), ks.end(), ks.begin(), ::tolower);
}
_ks_name = std::experimental::make_optional(ks);
}
void set_column_family(sstring cf, bool keep_case) {
_cf_name = cf;
if (!keep_case) {
std::transform(_cf_name.begin(), _cf_name.end(), _cf_name.begin(), ::tolower);
}
}
bool has_keyspace() const {
return _ks_name ? true : false;
}
sstring get_keyspace() const {
return *_ks_name;
}
sstring get_column_family() const {
return _cf_name;
}
friend std::ostream& operator<<(std::ostream& os, const cf_name& n);
};
std::ostream&
operator<<(std::ostream& os, const cf_name& n) {
if (n.has_keyspace()) {
os << n.get_keyspace() << ".";
}
os << n.get_column_family();
return os;
}
}
#endif
<commit_msg>cql3: Make cf_name operator<< inline to avoid multiple copies<commit_after>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Copyright 2014 Cloudius Systems
*
* Modified by Cloudius Systems
*/
#ifndef CQL3_CFNAME_HH
#define CQL3_CFNAME_HH
#include <experimental/optional>
namespace cql3 {
class cf_name {
private:
std::experimental::optional<sstring> _ks_name;
sstring _cf_name;
public:
void set_keyspace(sstring ks, bool keep_case) {
if (!keep_case) {
std::transform(ks.begin(), ks.end(), ks.begin(), ::tolower);
}
_ks_name = std::experimental::make_optional(ks);
}
void set_column_family(sstring cf, bool keep_case) {
_cf_name = cf;
if (!keep_case) {
std::transform(_cf_name.begin(), _cf_name.end(), _cf_name.begin(), ::tolower);
}
}
bool has_keyspace() const {
return _ks_name ? true : false;
}
sstring get_keyspace() const {
return *_ks_name;
}
sstring get_column_family() const {
return _cf_name;
}
friend std::ostream& operator<<(std::ostream& os, const cf_name& n);
};
inline
std::ostream&
operator<<(std::ostream& os, const cf_name& n) {
if (n.has_keyspace()) {
os << n.get_keyspace() << ".";
}
os << n.get_column_family();
return os;
}
}
#endif
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2008, 2009 Nokia Corporation.
*
* Contact: Marius Vollmer <marius.vollmer@nokia.com>
*
* 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., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include <QtTest/QtTest>
#include <QtCore>
#include "fileutils.h"
#include "infoxmlbackend.h"
class InfoXmlBackendUnitTest : public QObject
{
Q_OBJECT
InfoXmlBackend *backend;
private slots:
void initTestCase();
void listKeys();
void listPlugins();
void listKeysForPlugin();
};
void InfoXmlBackendUnitTest::initTestCase()
{
utilSetEnv("CONTEXT_PROVIDERS", LOCAL_DIR);
utilSetEnv("CONTEXT_CORE_DECLARATIONS", "/dev/null");
backend = new InfoXmlBackend();
}
void InfoXmlBackendUnitTest::listKeys()
{
QStringList keys = backend->listKeys();
QVERIFY(keys.contains("Battery.ChargePercentage"));
QVERIFY(keys.contains("Battery.LowBattery"));
QVERIFY(keys.contains("Key.With.Attribute"));
QVERIFY(keys.contains("Key.With.bool"));
QVERIFY(keys.contains("Key.With.int32"));
QVERIFY(keys.contains("Key.With.string"));
QVERIFY(keys.contains("Key.With.double"));
QVERIFY(keys.contains("Key.With.complex"));
QVERIFY(keys.contains("Battery.Charging"));
QVERIFY(keys.contains("Battery.ChargePercentage"));
}
void InfoXmlBackendUnitTest::listPlugins()
{
QStringList plugins = backend->listPlugins();
QCOMPARE(plugins.count(), 1);
QVERIFY(plugins.contains("contextkit-dbus"));
}
void InfoXmlBackendUnitTest::listKeysForPlugin()
{
QStringList keys = backend->listKeysForPlugin("contextkit-dbus");
QVERIFY(keys.contains("Battery.ChargePercentage"));
QVERIFY(keys.contains("Battery.LowBattery"));
QVERIFY(keys.contains("Key.With.Attribute"));
QVERIFY(keys.contains("Key.With.bool"));
QVERIFY(keys.contains("Key.With.int32"));
QVERIFY(keys.contains("Key.With.string"));
QVERIFY(keys.contains("Key.With.double"));
QVERIFY(keys.contains("Key.With.complex"));
QVERIFY(keys.contains("Battery.Charging"));
QVERIFY(keys.contains("Battery.ChargePercentage"));
}
#include "infoxmlbackendunittest.moc"
QTEST_MAIN(InfoXmlBackendUnitTest);
<commit_msg>typeForKey.<commit_after>/*
* Copyright (C) 2008, 2009 Nokia Corporation.
*
* Contact: Marius Vollmer <marius.vollmer@nokia.com>
*
* 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., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include <QtTest/QtTest>
#include <QtCore>
#include "fileutils.h"
#include "infoxmlbackend.h"
class InfoXmlBackendUnitTest : public QObject
{
Q_OBJECT
InfoXmlBackend *backend;
private slots:
void initTestCase();
void listKeys();
void listPlugins();
void listKeysForPlugin();
void typeForKey();
};
void InfoXmlBackendUnitTest::initTestCase()
{
utilSetEnv("CONTEXT_PROVIDERS", LOCAL_DIR);
utilSetEnv("CONTEXT_CORE_DECLARATIONS", "/dev/null");
backend = new InfoXmlBackend();
}
void InfoXmlBackendUnitTest::listKeys()
{
QStringList keys = backend->listKeys();
QVERIFY(keys.contains("Battery.ChargePercentage"));
QVERIFY(keys.contains("Battery.LowBattery"));
QVERIFY(keys.contains("Key.With.Attribute"));
QVERIFY(keys.contains("Key.With.bool"));
QVERIFY(keys.contains("Key.With.int32"));
QVERIFY(keys.contains("Key.With.string"));
QVERIFY(keys.contains("Key.With.double"));
QVERIFY(keys.contains("Key.With.complex"));
QVERIFY(keys.contains("Battery.Charging"));
QVERIFY(keys.contains("Battery.ChargePercentage"));
}
void InfoXmlBackendUnitTest::listPlugins()
{
QStringList plugins = backend->listPlugins();
QCOMPARE(plugins.count(), 1);
QVERIFY(plugins.contains("contextkit-dbus"));
}
void InfoXmlBackendUnitTest::listKeysForPlugin()
{
QStringList keys = backend->listKeysForPlugin("contextkit-dbus");
QVERIFY(keys.contains("Battery.ChargePercentage"));
QVERIFY(keys.contains("Battery.LowBattery"));
QVERIFY(keys.contains("Key.With.Attribute"));
QVERIFY(keys.contains("Key.With.bool"));
QVERIFY(keys.contains("Key.With.int32"));
QVERIFY(keys.contains("Key.With.string"));
QVERIFY(keys.contains("Key.With.double"));
QVERIFY(keys.contains("Key.With.complex"));
QVERIFY(keys.contains("Battery.Charging"));
}
void InfoXmlBackendUnitTest::typeForKey()
{
QCOMPARE(backend->typeForKey("Battery.ChargePercentage"), QString());
QCOMPARE(backend->typeForKey("Key.With.Attribute"), QString("TRUTH"));
QCOMPARE(backend->typeForKey("Battery.LowBattery"), QString("TRUTH"));
QCOMPARE(backend->typeForKey("Key.With.bool"), QString("TRUTH"));
QCOMPARE(backend->typeForKey("Key.With.int32"), QString("INT"));
QCOMPARE(backend->typeForKey("Key.With.string"), QString("STRING"));
QCOMPARE(backend->typeForKey("Key.With.double"), QString("DOUBLE"));
QCOMPARE(backend->typeForKey("Key.With.complex"), QString());
QCOMPARE(backend->typeForKey("Battery.Charging"), QString("TRUTH"));
}
#include "infoxmlbackendunittest.moc"
QTEST_MAIN(InfoXmlBackendUnitTest);
<|endoftext|> |
<commit_before>/*
* Copyright 2003,2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Log$
* Revision 1.13 2004/09/08 13:56:08 peiyongz
* Apache License Version 2.0
*
* Revision 1.12 2004/01/29 11:46:30 cargilld
* Code cleanup changes to get rid of various compiler diagnostic messages.
*
* Revision 1.11 2003/12/24 17:42:02 knoaman
* Misc. PSVI updates
*
* Revision 1.10 2003/12/19 15:09:47 knoaman
* PSVI: process 'final' information
*
* Revision 1.9 2003/12/15 17:23:48 cargilld
* psvi updates; cleanup revisits and bug fixes
*
* Revision 1.8 2003/11/27 16:42:00 neilg
* fixes for segfaults and infinite loops in schema component model implementation; thanks to David Cargill
*
* Revision 1.7 2003/11/25 18:08:31 knoaman
* Misc. PSVI updates. Thanks to David Cargill.
*
* Revision 1.6 2003/11/21 17:19:30 knoaman
* PSVI update.
*
* Revision 1.5 2003/11/14 22:47:53 neilg
* fix bogus log message from previous commit...
*
* Revision 1.4 2003/11/14 22:33:30 neilg
* Second phase of schema component model implementation.
* Implement XSModel, XSNamespaceItem, and the plumbing necessary
* to connect them to the other components.
* Thanks to David Cargill.
*
* Revision 1.3 2003/11/10 21:56:54 neilg
* make internal code use the new, stateless, method of traversing attribute lists
*
* Revision 1.2 2003/11/06 15:30:04 neilg
* first part of PSVI/schema component model implementation, thanks to David Cargill. This covers setting the PSVIHandler on parser objects, as well as implementing XSNotation, XSSimpleTypeDefinition, XSIDCDefinition, and most of XSWildcard, XSComplexTypeDefinition, XSElementDeclaration, XSAttributeDeclaration and XSAttributeUse.
*
* Revision 1.1 2003/09/16 14:33:36 neilg
* PSVI/schema component model classes, with Makefile/configuration changes necessary to build them
*
*/
#include <xercesc/framework/psvi/XSComplexTypeDefinition.hpp>
#include <xercesc/framework/psvi/XSWildcard.hpp>
#include <xercesc/framework/psvi/XSSimpleTypeDefinition.hpp>
#include <xercesc/framework/psvi/XSAttributeUse.hpp>
#include <xercesc/framework/psvi/XSModel.hpp>
#include <xercesc/framework/psvi/XSAnnotation.hpp>
#include <xercesc/framework/psvi/XSParticle.hpp>
#include <xercesc/validators/schema/ComplexTypeInfo.hpp>
#include <xercesc/validators/schema/SchemaElementDecl.hpp>
#include <xercesc/validators/schema/SchemaAttDefList.hpp>
XERCES_CPP_NAMESPACE_BEGIN
// ---------------------------------------------------------------------------
// XSComplexTypeDefinition: Constructors and Destructor
// ---------------------------------------------------------------------------
XSComplexTypeDefinition::XSComplexTypeDefinition
(
ComplexTypeInfo* const complexTypeInfo
, XSWildcard* const xsWildcard
, XSSimpleTypeDefinition* const xsSimpleType
, XSAttributeUseList* const xsAttList
, XSTypeDefinition* const xsBaseType
, XSParticle* const xsParticle
, XSAnnotation* const headAnnot
, XSModel* const xsModel
, MemoryManager* const manager
)
: XSTypeDefinition(COMPLEX_TYPE, xsBaseType, xsModel, manager)
, fComplexTypeInfo(complexTypeInfo)
, fXSWildcard(xsWildcard)
, fXSAttributeUseList(xsAttList)
, fXSSimpleTypeDefinition(xsSimpleType)
, fXSAnnotationList(0)
, fParticle(xsParticle)
, fProhibitedSubstitution(0)
{
int blockset = fComplexTypeInfo->getBlockSet();
if (blockset)
{
if (blockset & SchemaSymbols::XSD_EXTENSION)
fProhibitedSubstitution |= XSConstants::DERIVATION_EXTENSION;
if (blockset & SchemaSymbols::XSD_RESTRICTION)
fProhibitedSubstitution |= XSConstants::DERIVATION_RESTRICTION;
}
int finalSet = fComplexTypeInfo->getFinalSet();
if (finalSet)
{
if (finalSet & SchemaSymbols::XSD_EXTENSION)
fFinal |= XSConstants::DERIVATION_EXTENSION;
if (finalSet & SchemaSymbols::XSD_RESTRICTION)
fFinal |= XSConstants::DERIVATION_RESTRICTION;
}
if (headAnnot)
{
fXSAnnotationList = new (manager) RefVectorOf<XSAnnotation>(1, false, manager);
XSAnnotation* annot = headAnnot;
do
{
fXSAnnotationList->addElement(annot);
annot = annot->getNext();
} while (annot);
}
}
XSComplexTypeDefinition::~XSComplexTypeDefinition()
{
// don't delete fXSWildcard - deleted by XSModel
// don't delete fXSSimpleTypeDefinition - deleted by XSModel
if (fXSAttributeUseList)
delete fXSAttributeUseList;
if (fXSAnnotationList)
delete fXSAnnotationList;
if (fParticle)
delete fParticle;
}
// ---------------------------------------------------------------------------
// XSComplexTypeDefinition: access methods
// ---------------------------------------------------------------------------
XSConstants::DERIVATION_TYPE XSComplexTypeDefinition::getDerivationMethod() const
{
if(fComplexTypeInfo->getDerivedBy() == SchemaSymbols::XSD_EXTENSION)
return XSConstants::DERIVATION_EXTENSION;
return XSConstants::DERIVATION_RESTRICTION;
}
bool XSComplexTypeDefinition::getAbstract() const
{
return fComplexTypeInfo->getAbstract();
}
XSComplexTypeDefinition::CONTENT_TYPE XSComplexTypeDefinition::getContentType() const
{
switch(fComplexTypeInfo->getContentType()) {
case SchemaElementDecl::Simple:
return CONTENTTYPE_SIMPLE;
case SchemaElementDecl::Empty:
return CONTENTTYPE_EMPTY;
case SchemaElementDecl::Children:
return CONTENTTYPE_ELEMENT;
default:
//case SchemaElementDecl::Mixed_Complex:
//case SchemaElementDecl::Mixed_Simple:
//case SchemaElementDecl::Any:
return CONTENTTYPE_MIXED;
}
}
bool XSComplexTypeDefinition::isProhibitedSubstitution(XSConstants::DERIVATION_TYPE toTest)
{
if (fProhibitedSubstitution & toTest)
return true;
return false;
}
XSAnnotationList *XSComplexTypeDefinition::getAnnotations()
{
return fXSAnnotationList;
}
// ---------------------------------------------------------------------------
// XSComplexTypeDefinition: virtual methods
// ---------------------------------------------------------------------------
const XMLCh *XSComplexTypeDefinition::getName()
{
return fComplexTypeInfo->getTypeLocalName();
}
const XMLCh *XSComplexTypeDefinition::getNamespace()
{
return fComplexTypeInfo->getTypeUri();
}
XSNamespaceItem *XSComplexTypeDefinition::getNamespaceItem()
{
return fXSModel->getNamespaceItem(getNamespace());
}
bool XSComplexTypeDefinition::getAnonymous() const
{
return fComplexTypeInfo->getAnonymous();
}
XSTypeDefinition *XSComplexTypeDefinition::getBaseType()
{
return fBaseType;
}
bool XSComplexTypeDefinition::derivedFromType(const XSTypeDefinition * const ancestorType)
{
if (!ancestorType)
return false;
XSTypeDefinition* type = this;
while (type && (type != ancestorType))
{
type = type->getBaseType();
}
return (type == ancestorType);
}
XERCES_CPP_NAMESPACE_END
<commit_msg>Fix for jira bug 1234. Infinite loop in XSComplexTypeDefinition::derviedFromType.<commit_after>/*
* Copyright 2003,2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Log$
* Revision 1.14 2004/10/15 11:15:44 cargilld
* Fix for jira bug 1234. Infinite loop in XSComplexTypeDefinition::derviedFromType.
*
* Revision 1.13 2004/09/08 13:56:08 peiyongz
* Apache License Version 2.0
*
* Revision 1.12 2004/01/29 11:46:30 cargilld
* Code cleanup changes to get rid of various compiler diagnostic messages.
*
* Revision 1.11 2003/12/24 17:42:02 knoaman
* Misc. PSVI updates
*
* Revision 1.10 2003/12/19 15:09:47 knoaman
* PSVI: process 'final' information
*
* Revision 1.9 2003/12/15 17:23:48 cargilld
* psvi updates; cleanup revisits and bug fixes
*
* Revision 1.8 2003/11/27 16:42:00 neilg
* fixes for segfaults and infinite loops in schema component model implementation; thanks to David Cargill
*
* Revision 1.7 2003/11/25 18:08:31 knoaman
* Misc. PSVI updates. Thanks to David Cargill.
*
* Revision 1.6 2003/11/21 17:19:30 knoaman
* PSVI update.
*
* Revision 1.5 2003/11/14 22:47:53 neilg
* fix bogus log message from previous commit...
*
* Revision 1.4 2003/11/14 22:33:30 neilg
* Second phase of schema component model implementation.
* Implement XSModel, XSNamespaceItem, and the plumbing necessary
* to connect them to the other components.
* Thanks to David Cargill.
*
* Revision 1.3 2003/11/10 21:56:54 neilg
* make internal code use the new, stateless, method of traversing attribute lists
*
* Revision 1.2 2003/11/06 15:30:04 neilg
* first part of PSVI/schema component model implementation, thanks to David Cargill. This covers setting the PSVIHandler on parser objects, as well as implementing XSNotation, XSSimpleTypeDefinition, XSIDCDefinition, and most of XSWildcard, XSComplexTypeDefinition, XSElementDeclaration, XSAttributeDeclaration and XSAttributeUse.
*
* Revision 1.1 2003/09/16 14:33:36 neilg
* PSVI/schema component model classes, with Makefile/configuration changes necessary to build them
*
*/
#include <xercesc/framework/psvi/XSComplexTypeDefinition.hpp>
#include <xercesc/framework/psvi/XSWildcard.hpp>
#include <xercesc/framework/psvi/XSSimpleTypeDefinition.hpp>
#include <xercesc/framework/psvi/XSAttributeUse.hpp>
#include <xercesc/framework/psvi/XSModel.hpp>
#include <xercesc/framework/psvi/XSAnnotation.hpp>
#include <xercesc/framework/psvi/XSParticle.hpp>
#include <xercesc/validators/schema/ComplexTypeInfo.hpp>
#include <xercesc/validators/schema/SchemaElementDecl.hpp>
#include <xercesc/validators/schema/SchemaAttDefList.hpp>
XERCES_CPP_NAMESPACE_BEGIN
// ---------------------------------------------------------------------------
// XSComplexTypeDefinition: Constructors and Destructor
// ---------------------------------------------------------------------------
XSComplexTypeDefinition::XSComplexTypeDefinition
(
ComplexTypeInfo* const complexTypeInfo
, XSWildcard* const xsWildcard
, XSSimpleTypeDefinition* const xsSimpleType
, XSAttributeUseList* const xsAttList
, XSTypeDefinition* const xsBaseType
, XSParticle* const xsParticle
, XSAnnotation* const headAnnot
, XSModel* const xsModel
, MemoryManager* const manager
)
: XSTypeDefinition(COMPLEX_TYPE, xsBaseType, xsModel, manager)
, fComplexTypeInfo(complexTypeInfo)
, fXSWildcard(xsWildcard)
, fXSAttributeUseList(xsAttList)
, fXSSimpleTypeDefinition(xsSimpleType)
, fXSAnnotationList(0)
, fParticle(xsParticle)
, fProhibitedSubstitution(0)
{
int blockset = fComplexTypeInfo->getBlockSet();
if (blockset)
{
if (blockset & SchemaSymbols::XSD_EXTENSION)
fProhibitedSubstitution |= XSConstants::DERIVATION_EXTENSION;
if (blockset & SchemaSymbols::XSD_RESTRICTION)
fProhibitedSubstitution |= XSConstants::DERIVATION_RESTRICTION;
}
int finalSet = fComplexTypeInfo->getFinalSet();
if (finalSet)
{
if (finalSet & SchemaSymbols::XSD_EXTENSION)
fFinal |= XSConstants::DERIVATION_EXTENSION;
if (finalSet & SchemaSymbols::XSD_RESTRICTION)
fFinal |= XSConstants::DERIVATION_RESTRICTION;
}
if (headAnnot)
{
fXSAnnotationList = new (manager) RefVectorOf<XSAnnotation>(1, false, manager);
XSAnnotation* annot = headAnnot;
do
{
fXSAnnotationList->addElement(annot);
annot = annot->getNext();
} while (annot);
}
}
XSComplexTypeDefinition::~XSComplexTypeDefinition()
{
// don't delete fXSWildcard - deleted by XSModel
// don't delete fXSSimpleTypeDefinition - deleted by XSModel
if (fXSAttributeUseList)
delete fXSAttributeUseList;
if (fXSAnnotationList)
delete fXSAnnotationList;
if (fParticle)
delete fParticle;
}
// ---------------------------------------------------------------------------
// XSComplexTypeDefinition: access methods
// ---------------------------------------------------------------------------
XSConstants::DERIVATION_TYPE XSComplexTypeDefinition::getDerivationMethod() const
{
if(fComplexTypeInfo->getDerivedBy() == SchemaSymbols::XSD_EXTENSION)
return XSConstants::DERIVATION_EXTENSION;
return XSConstants::DERIVATION_RESTRICTION;
}
bool XSComplexTypeDefinition::getAbstract() const
{
return fComplexTypeInfo->getAbstract();
}
XSComplexTypeDefinition::CONTENT_TYPE XSComplexTypeDefinition::getContentType() const
{
switch(fComplexTypeInfo->getContentType()) {
case SchemaElementDecl::Simple:
return CONTENTTYPE_SIMPLE;
case SchemaElementDecl::Empty:
return CONTENTTYPE_EMPTY;
case SchemaElementDecl::Children:
return CONTENTTYPE_ELEMENT;
default:
//case SchemaElementDecl::Mixed_Complex:
//case SchemaElementDecl::Mixed_Simple:
//case SchemaElementDecl::Any:
return CONTENTTYPE_MIXED;
}
}
bool XSComplexTypeDefinition::isProhibitedSubstitution(XSConstants::DERIVATION_TYPE toTest)
{
if (fProhibitedSubstitution & toTest)
return true;
return false;
}
XSAnnotationList *XSComplexTypeDefinition::getAnnotations()
{
return fXSAnnotationList;
}
// ---------------------------------------------------------------------------
// XSComplexTypeDefinition: virtual methods
// ---------------------------------------------------------------------------
const XMLCh *XSComplexTypeDefinition::getName()
{
return fComplexTypeInfo->getTypeLocalName();
}
const XMLCh *XSComplexTypeDefinition::getNamespace()
{
return fComplexTypeInfo->getTypeUri();
}
XSNamespaceItem *XSComplexTypeDefinition::getNamespaceItem()
{
return fXSModel->getNamespaceItem(getNamespace());
}
bool XSComplexTypeDefinition::getAnonymous() const
{
return fComplexTypeInfo->getAnonymous();
}
XSTypeDefinition *XSComplexTypeDefinition::getBaseType()
{
return fBaseType;
}
bool XSComplexTypeDefinition::derivedFromType(const XSTypeDefinition * const ancestorType)
{
if (!ancestorType)
return false;
XSTypeDefinition* type = this;
XSTypeDefinition* lastType = 0; // anytype has a basetype of anytype so will have infinite loop...
while (type && (type != ancestorType) && (type != lastType))
{
lastType = type;
type = type->getBaseType();
}
return (type == ancestorType);
}
XERCES_CPP_NAMESPACE_END
<|endoftext|> |
<commit_before>// g++ main.cpp -o main -lzmq ./libcryptopp.a -std=c++11
#include <zmq.hpp>
#include <string>
#include <iostream>
#include <unistd.h>
#include <vector>
#include <sstream>
#include <bitset>
#include "cryptopp/osrng.h"
#include "cryptopp/integer.h"
#include "cryptopp/nbtheory.h"
#include "cryptopp/dh.h"
#include "cryptopp/secblock.h"
#include "cryptopp/rsa.h"
#include "cryptopp/queue.h"
#include "cryptopp/pem.h"
#include "cryptopp/files.h"
// For our JSON support
#include "json.hpp"
using json = nlohmann::json;
using CryptoPP::AutoSeededRandomPool;
using CryptoPP::Integer;
using CryptoPP::ModularExponentiation;
using CryptoPP::DH;
using CryptoPP::SecByteBlock;
using CryptoPP::RSA;
using std::cout;
using std::stringstream;
using std::string;
struct RSAPair
{
string str_prv;
string str_pub;
public:
RSAPair(int key_size)
{
CryptoPP::InvertibleRSAFunction rsa;
AutoSeededRandomPool rnd;
rsa.GenerateRandomWithKeySize(rnd, key_size);
RSA::PrivateKey priv(rsa);
RSA::PublicKey pub(rsa);
CryptoPP::StringSink fs(str_prv);
CryptoPP::PEM_Save(fs, priv);
CryptoPP::StringSink fs2(str_pub);
CryptoPP::PEM_Save(fs2, pub);
// Remove trailing newline character
if (str_pub[str_pub.length() - 1] == '\n') {
str_pub.erase(str_pub.length() - 1);
}
if (str_prv[str_prv.length() - 1] == '\n') {
str_prv.erase(str_prv.length() - 1);
}
}
std::vector<string> encrypt(std::vector<string> msgs)
{
AutoSeededRandomPool rnd;
CryptoPP::InvertibleRSAFunction rsa;
RSA::PrivateKey priv (rsa);
RSA::PublicKey pub(rsa);
CryptoPP::StringSink fs(str_prv);
CryptoPP::PEM_Load(fs, priv);
CryptoPP::StringSink fs2(str_pub);
CryptoPP::PEM_Load(fs2, pub);
CryptoPP::RSAES_OAEP_SHA_Encryptor encryptor(pub);
std::vector<string> cipher_list;
for (int i = 0; i < msgs.size(); i ++) {
string cipher;
CryptoPP::StringSource ss1(msgs[i], true,
new CryptoPP::PK_EncryptorFilter(rnd, encryptor,
new CryptoPP::StringSink(cipher)
)
);
cipher_list.push_back(cipher);
}
return cipher_list;
}
};
// g^{priv} == pub mod G
void create_key_pair(AutoSeededRandomPool &rnd, DH &dh, Integer &priv, Integer &pub)
{
SecByteBlock block_priv(dh.PrivateKeyLength());
SecByteBlock block_pub(dh.PublicKeyLength());
dh.GenerateKeyPair(rnd, block_priv, block_pub);
priv.Decode(block_priv, dh.PrivateKeyLength());
pub.Decode(block_pub, dh.PublicKeyLength());
return;
}
// convert Integer object to string (in hex format!)
string integer_to_string(Integer num)
{
stringstream ss;
ss << std::hex << num;
string s = ss.str();
// std::hex prints the number in HEX but it appends 'h'
// at the end of the string
if (s[s.length() - 1] == 'h')
{
s.erase(s.begin() + s.length() - 1);
}
return s;
}
class DataTxn
{
std::vector<string> str_g_r_i;
std::vector<string> str_r_i;
string str_G;
string str_g;
string str_a;
string str_g_a;
string str_r;
string str_g_r;
string str_secret;
int K;
public:
// Create a data txn with given info.
DataTxn(int bit_size, int K, string hashed_identity)
: K(K)
{
AutoSeededRandomPool rnd;
DH dh;
// Generates safe prime G and its generator g.
// "Safe prime" for DH structure is the prime p that is in form
// 2q + 1 where q is an another prime.
dh.AccessGroupParameters().GenerateRandomWithKeySize(rnd, bit_size);
// Get G and g
const Integer &G = dh.GetGroupParameters().GetModulus();
const Integer &g = dh.GetGroupParameters().GetGenerator();
// Key pairs for DH communication with Request TXN
Integer g_a, a;
create_key_pair(rnd, dh, a, g_a);
// For encrypting secret key
Integer r, g_r;
create_key_pair(rnd, dh, r, g_r);
// Create secret secret = g^r + hashed_identity
Integer secret = g_r + Integer(hashed_identity.c_str());
// Create 'tryouts' for ZKP
for (int i = 0; i < K; i++)
{
Integer zkp_r, zkp_g_r;
create_key_pair(rnd, dh, zkp_r, zkp_g_r);
str_r_i.push_back(integer_to_string(zkp_r));
str_g_r_i.push_back(integer_to_string(zkp_g_r));
}
str_G = integer_to_string(G);
str_g = integer_to_string(g);
str_r = integer_to_string(r);
str_g_r = integer_to_string(g_r);
str_a = integer_to_string(a);
str_g_a = integer_to_string(g_a);
str_secret = integer_to_string(secret);
}
string serialize_data(string token)
{
cout << "Finding RSA pairs ... " << std::endl;
RSAPair pair(2048);
json j = {
{"G", str_G},
{"g", str_g},
{"r", str_r},
{"g_r", str_g_r},
{"a", str_a},
{"g_a", str_g_a},
{"secret", str_secret},
{"g_r_i", str_g_r_i},
{"r_i", str_r_i},
{"pub_key", pair.str_pub},
{"prv_key", pair.str_prv},
{"K", K},
{"token", token}};
cout << j << std::endl;
// Return the serialized JSON object
return j.dump();
}
// If it is supplied with RSA private key,
string serialize_data(string token, string prv_key)
{
}
};
class RequestTxn
{
Integer integer_with_hex(string hex)
{
// Insert '0x' at front
hex.insert(0, "0x");
return Integer(hex.c_str());
}
string str_b;
string str_g_b;
string str_g_g_ab_p_r;
string req_str;
public:
RequestTxn(string data_txn_json_str, string hashed_request_identity)
{
auto data_txn_json = json::parse(data_txn_json_str);
Integer G = integer_with_hex(data_txn_json["txn_payload"]["G"]);
Integer g = integer_with_hex(data_txn_json["txn_payload"]["g"]);
Integer g_a = integer_with_hex(data_txn_json["txn_payload"]["g_a"]);
Integer secret = integer_with_hex(data_txn_json["txn_payload"]["secret"]);
int K = data_txn_json["txn_payload"]["K"];
// Initialize DH structure with G and g of data_txn
DH dh_req;
dh_req.AccessGroupParameters().Initialize(G, g);
// Generate b and g^b for request txn
AutoSeededRandomPool rng;
Integer b, g_b;
create_key_pair(rng, dh_req, b, g_b);
// Calculate the shared secret g^ab
SecByteBlock shared (dh_req.AgreedValueLength());
SecByteBlock sec_b (dh_req.PrivateKeyLength()), sec_g_a(dh_req.PublicKeyLength());
b.Encode(sec_b, dh_req.PrivateKeyLength());
g_a.Encode(sec_g_a, dh_req.PublicKeyLength());
dh_req.Agree(shared, sec_b, sec_g_a);
Integer g_ab;
g_ab.Decode(shared, dh_req.AgreedValueLength());
Integer identity_hash = integer_with_hex(hashed_request_identity);
Integer g_g_ab_p_r = ModularExponentiation(g, g_ab, G) * (secret - identity_hash);
string req_str = "";
for (int i = 0; i < K; i ++) {
Integer req (rng, 1);
if (req == 1) {
req_str.push_back('1');
}
else {
req_str.push_back('0');
}
}
str_b = integer_to_string(b);
str_g_b = integer_to_string(g_b);
str_g_g_ab_p_r = integer_to_string(g_g_ab_p_r);
}
string serialize_data(string token)
{
json j = {
{"g_b", str_g_b},
{"g_g_ab_p_r", str_g_g_ab_p_r},
{"req", req_str},
{"b", str_b},
{"token", token}
};
cout << j << std::endl;
return j.dump();
}
};
class AnswerTxn
{
Integer integer_with_hex(string hex)
{
// Insert '0x' at front
hex.insert(0, "0x");
return Integer(hex.c_str());
}
std::vector<string> response;
public:
AnswerTxn(string data_txn_str, string request_txn_str, string secret) {
auto data_txn_json = json::parse(data_txn_str);
auto request_txn_json = json::parse(request_txn_str);
auto secret_json = json::parse(secret);
Integer a = integer_with_hex(secret_json["a"]);
Integer G = integer_with_hex(data_txn_json["txn_payload"]["G"]);
Integer g = integer_with_hex(data_txn_json["txn_payload"]["g"]);
Integer g_b = integer_with_hex(request_txn_json["txn_payload"]["g_b"]);
Integer g_ab = ModularExponentiation(g_b, a, G);
string request = request_txn_json["txn_payload"]["req"];
std::vector<string> r_i_list = secret_json["r_i"];
Integer r = integer_with_hex(secret_json["r"]);
for (int i = 0; i < request.length(); i ++) {
if (request[i] == '0') {
response.push_back(r_i_list[i]);
}
else if (request[i] == '1') {
Integer r_i_num = integer_with_hex(r_i_list[i]);
Integer resp = r_i_num + r + g_ab;
response.push_back(integer_to_string(resp));
}
}
}
string serialize_data(string token) {
json j = {
{"response", response},
{"token", token}
};
cout << j << std::endl;
return j.dump();
}
};
int main()
{
// Prepare our context and socket
zmq::context_t context(1);
zmq::socket_t socket(context, ZMQ_REP);
socket.bind("tcp://*:5555");
cout << "---------- TXN Calculator is started ---------------" << std::endl;
while (true)
{
zmq::message_t request;
// Wait for next request from client
socket.recv(&request);
std::cout << "Request :: " << (char *)request.data() << std::endl;
auto json_data = json::parse(string((char *)request.data()));
string serial = "";
// Request for generating DATA TXN
if (json_data["type"] == 0) {
// Do some 'work'
DataTxn txn(1024, 10, json_data["identity"]);
cout << "Generating Key pairs..." << std::endl;
serial = txn.serialize_data(json_data["token"]);
}
// Request for generating REQUEST TXN
else if (json_data["type"] == 1) {
RequestTxn txn(json_data["data_txn"], json_data["identity"]);
serial = txn.serialize_data(json_data["token"]);
}
else if (json_data["type"] == 2) {
AnswerTxn txn(json_data["data_txn"], json_data["req_txn"], json_data["secret"]);
serial = txn.serialize_data(json_data["token"]);
}
// Send reply back to client
zmq::message_t reply(serial.length() + 1);
memcpy((void *)reply.data(), serial.c_str(), serial.length() + 1);
socket.send(reply);
cout << "Data is sent!" << std::endl;
}
return 0;
}
<commit_msg>Created a way to user to create an additional data_txn<commit_after>// g++ main.cpp -o main -lzmq ./libcryptopp.a -std=c++11
#include <zmq.hpp>
#include <string>
#include <iostream>
#include <unistd.h>
#include <vector>
#include <sstream>
#include <bitset>
#include "cryptopp/osrng.h"
#include "cryptopp/integer.h"
#include "cryptopp/nbtheory.h"
#include "cryptopp/dh.h"
#include "cryptopp/secblock.h"
#include "cryptopp/rsa.h"
#include "cryptopp/queue.h"
#include "cryptopp/pem.h"
#include "cryptopp/files.h"
// For our JSON support
#include "json.hpp"
using json = nlohmann::json;
using CryptoPP::AutoSeededRandomPool;
using CryptoPP::Integer;
using CryptoPP::ModularExponentiation;
using CryptoPP::DH;
using CryptoPP::SecByteBlock;
using CryptoPP::RSA;
using std::cout;
using std::stringstream;
using std::string;
struct RSAPair
{
string str_prv;
string str_pub;
public:
RSAPair(int key_size)
{
CryptoPP::InvertibleRSAFunction rsa;
AutoSeededRandomPool rnd;
rsa.GenerateRandomWithKeySize(rnd, key_size);
RSA::PrivateKey priv(rsa);
RSA::PublicKey pub(rsa);
CryptoPP::StringSink fs(str_prv);
CryptoPP::PEM_Save(fs, priv);
CryptoPP::StringSink fs2(str_pub);
CryptoPP::PEM_Save(fs2, pub);
// Remove trailing newline character
if (str_pub[str_pub.length() - 1] == '\n') {
str_pub.erase(str_pub.length() - 1);
}
if (str_prv[str_prv.length() - 1] == '\n') {
str_prv.erase(str_prv.length() - 1);
}
}
std::vector<string> encrypt(std::vector<string> msgs)
{
AutoSeededRandomPool rnd;
CryptoPP::InvertibleRSAFunction rsa;
RSA::PrivateKey priv (rsa);
RSA::PublicKey pub(rsa);
CryptoPP::StringSink fs(str_prv);
CryptoPP::PEM_Load(fs, priv);
CryptoPP::StringSink fs2(str_pub);
CryptoPP::PEM_Load(fs2, pub);
CryptoPP::RSAES_OAEP_SHA_Encryptor encryptor(pub);
std::vector<string> cipher_list;
for (int i = 0; i < msgs.size(); i ++) {
string cipher;
CryptoPP::StringSource ss1(msgs[i], true,
new CryptoPP::PK_EncryptorFilter(rnd, encryptor,
new CryptoPP::StringSink(cipher)
)
);
cipher_list.push_back(cipher);
}
return cipher_list;
}
};
// g^{priv} == pub mod G
void create_key_pair(AutoSeededRandomPool &rnd, DH &dh, Integer &priv, Integer &pub)
{
SecByteBlock block_priv(dh.PrivateKeyLength());
SecByteBlock block_pub(dh.PublicKeyLength());
dh.GenerateKeyPair(rnd, block_priv, block_pub);
priv.Decode(block_priv, dh.PrivateKeyLength());
pub.Decode(block_pub, dh.PublicKeyLength());
return;
}
// convert Integer object to string (in hex format!)
string integer_to_string(Integer num)
{
stringstream ss;
ss << std::hex << num;
string s = ss.str();
// std::hex prints the number in HEX but it appends 'h'
// at the end of the string
if (s[s.length() - 1] == 'h')
{
s.erase(s.begin() + s.length() - 1);
}
return s;
}
class DataTxn
{
std::vector<string> str_g_r_i;
std::vector<string> str_r_i;
string str_G;
string str_g;
string str_a;
string str_g_a;
string str_r;
string str_g_r;
string str_secret;
int K;
public:
// Create a data txn with given info.
DataTxn(int bit_size, int K, string hashed_identity)
: K(K)
{
AutoSeededRandomPool rnd;
DH dh;
// Generates safe prime G and its generator g.
// "Safe prime" for DH structure is the prime p that is in form
// 2q + 1 where q is an another prime.
dh.AccessGroupParameters().GenerateRandomWithKeySize(rnd, bit_size);
// Get G and g
const Integer &G = dh.GetGroupParameters().GetModulus();
const Integer &g = dh.GetGroupParameters().GetGenerator();
// Key pairs for DH communication with Request TXN
Integer g_a, a;
create_key_pair(rnd, dh, a, g_a);
// For encrypting secret key
Integer r, g_r;
create_key_pair(rnd, dh, r, g_r);
// Create secret secret = g^r + hashed_identity
Integer secret = g_r + Integer(hashed_identity.c_str());
// Create 'tryouts' for ZKP
for (int i = 0; i < K; i++)
{
Integer zkp_r, zkp_g_r;
create_key_pair(rnd, dh, zkp_r, zkp_g_r);
str_r_i.push_back(integer_to_string(zkp_r));
str_g_r_i.push_back(integer_to_string(zkp_g_r));
}
str_G = integer_to_string(G);
str_g = integer_to_string(g);
str_r = integer_to_string(r);
str_g_r = integer_to_string(g_r);
str_a = integer_to_string(a);
str_g_a = integer_to_string(g_a);
str_secret = integer_to_string(secret);
}
string serialize_data(string token)
{
cout << "Finding RSA pairs ... " << std::endl;
RSAPair pair(2048);
json j = {
{"G", str_G},
{"g", str_g},
{"r", str_r},
{"g_r", str_g_r},
{"a", str_a},
{"g_a", str_g_a},
{"secret", str_secret},
{"g_r_i", str_g_r_i},
{"r_i", str_r_i},
{"pub_key", pair.str_pub},
{"prv_key", pair.str_prv},
{"K", K},
{"token", token}};
cout << j << std::endl;
// Return the serialized JSON object
return j.dump();
}
// If it is supplied with RSA private key,
string serialize_data_without_rsa_key(string token)
{
json j = {
{"G", str_G},
{"g", str_g},
{"r", str_r},
{"g_r", str_g_r},
{"a", str_a},
{"g_a", str_g_a},
{"secret", str_secret},
{"g_r_i", str_g_r_i},
{"r_i", str_r_i},
{"K", K},
{"token", token}};
cout << j << std::endl;
// Return the serialized JSON object
return j.dump();
}
};
class RequestTxn
{
Integer integer_with_hex(string hex)
{
// Insert '0x' at front
hex.insert(0, "0x");
return Integer(hex.c_str());
}
string str_b;
string str_g_b;
string str_g_g_ab_p_r;
string req_str;
public:
RequestTxn(string data_txn_json_str, string hashed_request_identity)
{
auto data_txn_json = json::parse(data_txn_json_str);
Integer G = integer_with_hex(data_txn_json["txn_payload"]["G"]);
Integer g = integer_with_hex(data_txn_json["txn_payload"]["g"]);
Integer g_a = integer_with_hex(data_txn_json["txn_payload"]["g_a"]);
Integer secret = integer_with_hex(data_txn_json["txn_payload"]["secret"]);
int K = data_txn_json["txn_payload"]["K"];
// Initialize DH structure with G and g of data_txn
DH dh_req;
dh_req.AccessGroupParameters().Initialize(G, g);
// Generate b and g^b for request txn
AutoSeededRandomPool rng;
Integer b, g_b;
create_key_pair(rng, dh_req, b, g_b);
// Calculate the shared secret g^ab
SecByteBlock shared (dh_req.AgreedValueLength());
SecByteBlock sec_b (dh_req.PrivateKeyLength()), sec_g_a(dh_req.PublicKeyLength());
b.Encode(sec_b, dh_req.PrivateKeyLength());
g_a.Encode(sec_g_a, dh_req.PublicKeyLength());
dh_req.Agree(shared, sec_b, sec_g_a);
Integer g_ab;
g_ab.Decode(shared, dh_req.AgreedValueLength());
Integer identity_hash = integer_with_hex(hashed_request_identity);
Integer g_g_ab_p_r = ModularExponentiation(g, g_ab, G) * (secret - identity_hash);
string req_str = "";
for (int i = 0; i < K; i ++) {
Integer req (rng, 1);
if (req == 1) {
req_str.push_back('1');
}
else {
req_str.push_back('0');
}
}
str_b = integer_to_string(b);
str_g_b = integer_to_string(g_b);
str_g_g_ab_p_r = integer_to_string(g_g_ab_p_r);
}
string serialize_data(string token)
{
json j = {
{"g_b", str_g_b},
{"g_g_ab_p_r", str_g_g_ab_p_r},
{"req", req_str},
{"b", str_b},
{"token", token}
};
cout << j << std::endl;
return j.dump();
}
};
class AnswerTxn
{
Integer integer_with_hex(string hex)
{
// Insert '0x' at front
hex.insert(0, "0x");
return Integer(hex.c_str());
}
std::vector<string> response;
public:
AnswerTxn(string data_txn_str, string request_txn_str, string secret) {
auto data_txn_json = json::parse(data_txn_str);
auto request_txn_json = json::parse(request_txn_str);
auto secret_json = json::parse(secret);
Integer a = integer_with_hex(secret_json["a"]);
Integer G = integer_with_hex(data_txn_json["txn_payload"]["G"]);
Integer g = integer_with_hex(data_txn_json["txn_payload"]["g"]);
Integer g_b = integer_with_hex(request_txn_json["txn_payload"]["g_b"]);
Integer g_ab = ModularExponentiation(g_b, a, G);
string request = request_txn_json["txn_payload"]["req"];
std::vector<string> r_i_list = secret_json["r_i"];
Integer r = integer_with_hex(secret_json["r"]);
for (int i = 0; i < request.size(); i ++) {
if (request[i] == '0') {
response.push_back(r_i_list[i]);
}
else if (request[i] == '1') {
Integer r_i_num = integer_with_hex(r_i_list[i]);
Integer resp = r_i_num + r + g_ab;
response.push_back(integer_to_string(resp));
}
}
}
string serialize_data(string token) {
json j = {
{"response", response},
{"token", token}
};
cout << j << std::endl;
return j.dump();
}
};
int main()
{
// Prepare our context and socket
zmq::context_t context(1);
zmq::socket_t socket(context, ZMQ_REP);
socket.bind("tcp://*:5555");
cout << "---------- TXN Calculator is started ---------------" << std::endl;
while (true)
{
zmq::message_t request;
// Wait for next request from client
socket.recv(&request);
std::cout << "Request :: " << (char *)request.data() << std::endl;
auto json_data = json::parse(string((char *)request.data()));
string serial = "";
// Request for generating DATA TXN
if (json_data["type"] == 0) {
// Do some 'work'
DataTxn txn(1024, 10, json_data["identity"]);
cout << "Generating Key pairs..." << std::endl;
// If 'with_key' flag is enabled, then you must supply the
// newly generated rsa key.
if (json_data["with_key"] == 1) {
serial = txn.serialize_data(json_data["token"]);
}
else {
serial = txn.serialize_data_without_rsa_key(json_data["token"]);
}
}
// Request for generating REQUEST TXN
else if (json_data["type"] == 1) {
RequestTxn txn(json_data["data_txn"], json_data["identity"]);
serial = txn.serialize_data(json_data["token"]);
}
else if (json_data["type"] == 2) {
AnswerTxn txn(json_data["data_txn"], json_data["req_txn"], json_data["secret"]);
serial = txn.serialize_data(json_data["token"]);
}
// Send reply back to client
zmq::message_t reply(serial.length() + 1);
memcpy((void *)reply.data(), serial.c_str(), serial.length() + 1);
socket.send(reply);
cout << "Data is sent!" << std::endl;
}
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2004, 2005, 2006 Apple Computer, Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 "Widget.h"
#include "IntRect.h"
#include "ScrollView.h"
#include <wtf/Assertions.h>
namespace WebCore {
void Widget::init()
{
m_parent = 0;
m_widget = 0;
m_selfVisible = false;
m_parentVisible = false;
m_containingWindow = 0;
}
void Widget::setParent(ScrollView* view)
{
ASSERT(!view || !m_parent);
if (!view || !view->isVisible())
setParentVisible(false);
m_parent = view;
if (view && view->isVisible())
setParentVisible(true);
}
ScrollView* Widget::root() const
{
const Widget* top = this;
while (top->parent())
top = top->parent();
if (top->isFrameView())
return const_cast<ScrollView*>(static_cast<const ScrollView*>(top));
return 0;
}
#if !PLATFORM(MAC)
IntRect Widget::convertToContainingWindow(const IntRect& rect) const
{
IntRect convertedRect = rect;
convertedRect.setLocation(convertToContainingWindow(convertedRect.location()));
return convertedRect;
}
IntPoint Widget::convertToContainingWindow(const IntPoint& point) const
{
IntPoint windowPoint = point;
for (const ScrollView *parentScrollView = parent(), *childWidget = this;
parentScrollView;
childWidget = parentScrollView, parentScrollView = parentScrollView->parent())
windowPoint = parentScrollView->convertChildToSelf(childWidget, windowPoint);
return windowPoint;
}
IntPoint Widget::convertFromContainingWindow(const IntPoint& point) const
{
IntPoint widgetPoint = point;
for (const ScrollView *parentScrollView = parent(), *childWidget = this;
parentScrollView;
childWidget = parentScrollView, parentScrollView = parentScrollView->parent())
widgetPoint = parentScrollView->convertSelfToChild(childWidget, widgetPoint);
return widgetPoint;
}
void Widget::releasePlatformWidget()
{
}
void Widget::retainPlatformWidget()
{
}
#endif
}
<commit_msg>Fix Qt/Win/Gtk bustage.<commit_after>/*
* Copyright (C) 2004, 2005, 2006 Apple Computer, Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 "Widget.h"
#include "IntRect.h"
#include "ScrollView.h"
#include <wtf/Assertions.h>
namespace WebCore {
void Widget::init()
{
m_parent = 0;
m_widget = 0;
m_selfVisible = false;
m_parentVisible = false;
m_containingWindow = 0;
}
void Widget::setParent(ScrollView* view)
{
ASSERT(!view || !m_parent);
if (!view || !view->isVisible())
setParentVisible(false);
m_parent = view;
if (view && view->isVisible())
setParentVisible(true);
}
ScrollView* Widget::root() const
{
const Widget* top = this;
while (top->parent())
top = top->parent();
if (top->isFrameView())
return const_cast<ScrollView*>(static_cast<const ScrollView*>(top));
return 0;
}
#if !PLATFORM(MAC)
IntRect Widget::convertToContainingWindow(const IntRect& rect) const
{
IntRect convertedRect = rect;
convertedRect.setLocation(convertToContainingWindow(convertedRect.location()));
return convertedRect;
}
IntPoint Widget::convertToContainingWindow(const IntPoint& point) const
{
IntPoint windowPoint = point;
const Widget* childWidget = this;
for (const ScrollView* parentScrollView = parent();
parentScrollView;
childWidget = parentScrollView, parentScrollView = parentScrollView->parent())
windowPoint = parentScrollView->convertChildToSelf(childWidget, windowPoint);
return windowPoint;
}
IntPoint Widget::convertFromContainingWindow(const IntPoint& point) const
{
IntPoint widgetPoint = point;
const Widget* childWidget = this;
for (const ScrollView* parentScrollView = parent();
parentScrollView;
childWidget = parentScrollView, parentScrollView = parentScrollView->parent())
widgetPoint = parentScrollView->convertSelfToChild(childWidget, widgetPoint);
return widgetPoint;
}
void Widget::releasePlatformWidget()
{
}
void Widget::retainPlatformWidget()
{
}
#endif
}
<|endoftext|> |
<commit_before><commit_msg>gfe-relnote: (n/a) Always handle MSG_TOO_BIG when sending buffered packets. Protected by existing --gfe2_reloadable_flag_quic_treat_queued_packets_as_sent.<commit_after><|endoftext|> |
<commit_before>// For conditions of distribution and use, see copyright notice in license.txt
#include "StableHeaders.h"
#include "NotificationWidget.h"
#include "NaaliUI.h"
#include "Framework.h"
#include "Renderer.h"
namespace RexLogic
{
NotificationWidget::NotificationWidget(RexLogicModule *rex_logic, QWidget *parent) :
rex_logic_(rex_logic),
framework_(rex_logic->GetFramework()),
QGraphicsView(parent)
{
scene_ = framework_->Ui()->GraphicsScene();
setScene(scene_);
time_line_ = new QTimeLine(3000, this);
frame_pic_ = new QFrame;
scene_->addWidget(frame_pic_);
frame_pic_->setFixedSize(100, 100);
frame_pic_->hide();
start_ = "QFrame {background-color: transparent;"
"border-image: url(./data/ui/images/notificationwidget/";
end_ = ")}";
}
void NotificationWidget::SetupScene()
{
float width = framework_->GetServiceManager()->GetService<OgreRenderer::Renderer>(Foundation::Service::ST_Renderer).lock()->GetWindowWidth();
float height = framework_->GetServiceManager()->GetService<OgreRenderer::Renderer>(Foundation::Service::ST_Renderer).lock()->GetWindowHeight();
frame_pic_->move(width - frame_pic_->width() - 10, 40);
QString style_sheet_ = start_ + picture_name_ + end_;
frame_pic_->show();
frame_pic_->setStyleSheet(style_sheet_);
frame_pic_->setWindowOpacity(1.0);
time_line_->setFrameRange(0, 100);
connect(time_line_, SIGNAL(frameChanged(int)), this, SLOT(updateStep(int)));
time_line_->start();
}
void NotificationWidget::updateStep(int i)
{
frame_pic_->setWindowOpacity((100-i)/100.0);
}
void NotificationWidget::FocusOnObject()
{
picture_name_ = "camera_focus.png" ;
SetupScene();
}
bool NotificationWidget::HandleInputEvent(event_id_t event_id, IEventData* data)
{
if (event_id == InputEvents::CAMERA_TRIPOD)
{
picture_name_ = "tripod_camera.png" ;
SetupScene();
}
else if (event_id == InputEvents::INPUTSTATE_FREECAMERA)
{
picture_name_ = "free_camera.png" ;
SetupScene();
}
else if (event_id == InputEvents::INPUTSTATE_THIRDPERSON)
{
picture_name_ = "third_person.png";
SetupScene();
}
else if (event_id == InputEvents::INPUTSTATE_FOCUSONOBJECT)
{
picture_name_ = "camera_focus_grey.png";
SetupScene();
}
return false;
}
}
<commit_msg>Fixing casesensitive error - #include NaaliUi.h<commit_after>// For conditions of distribution and use, see copyright notice in license.txt
#include "StableHeaders.h"
#include "NotificationWidget.h"
#include "NaaliUi.h"
#include "Framework.h"
#include "Renderer.h"
namespace RexLogic
{
NotificationWidget::NotificationWidget(RexLogicModule *rex_logic, QWidget *parent) :
rex_logic_(rex_logic),
framework_(rex_logic->GetFramework()),
QGraphicsView(parent)
{
scene_ = framework_->Ui()->GraphicsScene();
setScene(scene_);
time_line_ = new QTimeLine(3000, this);
frame_pic_ = new QFrame;
scene_->addWidget(frame_pic_);
frame_pic_->setFixedSize(100, 100);
frame_pic_->hide();
start_ = "QFrame {background-color: transparent;"
"border-image: url(./data/ui/images/notificationwidget/";
end_ = ")}";
}
void NotificationWidget::SetupScene()
{
float width = framework_->GetServiceManager()->GetService<OgreRenderer::Renderer>(Foundation::Service::ST_Renderer).lock()->GetWindowWidth();
float height = framework_->GetServiceManager()->GetService<OgreRenderer::Renderer>(Foundation::Service::ST_Renderer).lock()->GetWindowHeight();
frame_pic_->move(width - frame_pic_->width() - 10, 40);
QString style_sheet_ = start_ + picture_name_ + end_;
frame_pic_->show();
frame_pic_->setStyleSheet(style_sheet_);
frame_pic_->setWindowOpacity(1.0);
time_line_->setFrameRange(0, 100);
connect(time_line_, SIGNAL(frameChanged(int)), this, SLOT(updateStep(int)));
time_line_->start();
}
void NotificationWidget::updateStep(int i)
{
frame_pic_->setWindowOpacity((100-i)/100.0);
}
void NotificationWidget::FocusOnObject()
{
picture_name_ = "camera_focus.png" ;
SetupScene();
}
bool NotificationWidget::HandleInputEvent(event_id_t event_id, IEventData* data)
{
if (event_id == InputEvents::CAMERA_TRIPOD)
{
picture_name_ = "tripod_camera.png" ;
SetupScene();
}
else if (event_id == InputEvents::INPUTSTATE_FREECAMERA)
{
picture_name_ = "free_camera.png" ;
SetupScene();
}
else if (event_id == InputEvents::INPUTSTATE_THIRDPERSON)
{
picture_name_ = "third_person.png";
SetupScene();
}
else if (event_id == InputEvents::INPUTSTATE_FOCUSONOBJECT)
{
picture_name_ = "camera_focus_grey.png";
SetupScene();
}
return false;
}
}
<|endoftext|> |
<commit_before>#include "pch.h"
#include "AssemblyUILayer.h"
#include "GameManager.h"
#include "StageManager.h"
#include "DataManager.h"
#include "ResourceManager.h"
#include "InputManager.h"
#include "AssemblyLineLayer.h"
#include "EquipmentStatusLayer.h"
#include "AssemblyDisplayLayer.h"
#include "SkillLineLayer.h"
#include "ButtonLayer.h"
#include "IconLayer.h"
AssemblyUILayer::AssemblyUILayer()
{
m_viewChangeRect.setRect(1235 * RESOLUTION, 310 * RESOLUTION, 25 * RESOLUTION, 100 * RESOLUTION);
}
AssemblyUILayer::~AssemblyUILayer()
{
}
bool AssemblyUILayer::init()
{
if (!cocos2d::Layer::init())
{
return false;
}
m_IsStarted = false;
m_AssemblyLineLayer = AssemblyLineLayer::create();
m_StatusLayer = EquipmentStatusLayer::create();
m_DisplayLayer = AssemblyDisplayLayer::create();
m_SkillLineLayer = SkillLineLayer::create();
m_AssemblyBackground = GET_RESOURCE_MANAGER()->createSprite(ST_ASSEMBLY_BACKGROUND);
m_AssemblyFrame = GET_RESOURCE_MANAGER()->createSprite(ST_ASSEMBLY_FRAME);
m_ViewChangeArrow = GET_RESOURCE_MANAGER()->createSprite(ST_ASSEMBLY_ARROW);
m_EquipmentRect.setRect(140 * RESOLUTION, 40 * RESOLUTION, 390 * RESOLUTION, 580 * RESOLUTION);
m_SkillRect.setRect(535 * RESOLUTION, 295 * RESOLUTION, 320 * RESOLUTION, 325 * RESOLUTION);
setUIProperties(m_AssemblyBackground, cocos2d::Point::ZERO, cocos2d::Point::ZERO, RESOLUTION, true, 0);
setUIProperties(m_AssemblyFrame, cocos2d::Point::ZERO, cocos2d::Point::ZERO, RESOLUTION, true, 0);
setUIProperties(m_ViewChangeArrow, cocos2d::Point(0.5, 0.5), cocos2d::Point(1055, 360), 1.0f, true, 1);
m_AssemblyLineLayer->setPosition(cocos2d::Point(0, 0));
m_StatusLayer->setPosition(cocos2d::Point(545, 0));
m_DisplayLayer->setPosition(cocos2d::Point(830, 0));
m_SkillLineLayer->setPosition(cocos2d::Point(1280, 0));
assemblyLayerButtonInit();
m_CurrentAssembly = ASSEMBLY_VIEW;
this->addChild(m_AssemblyBackground);
m_AssemblyBackground->addChild(m_AssemblyLineLayer);
m_AssemblyBackground->addChild(m_SkillLineLayer);
this->addChild(m_AssemblyFrame);
m_AssemblyFrame->addChild(m_DisplayLayer);
m_AssemblyFrame->addChild(m_ViewChangeArrow);
m_AssemblyFrame->addChild(m_StatusLayer);
return true;
}
void AssemblyUILayer::update(float dTime)
{
MouseInfo mouseInput = GET_INPUT_MANAGER()->getMouseInfo();
if (m_CurrentAssembly == ASSEMBLY_VIEW)
{
m_StatusLayer->update(dTime);
m_DisplayLayer->update(dTime);
if (m_EquipmentRect.containsPoint(mouseInput.m_MouseMove))
{
m_AssemblyLineLayer->updateEquipments(dTime);
m_AssemblyLineLayer->containerScroll(mouseInput.m_ScollValue, mouseInput.m_MouseMove);
GET_INPUT_MANAGER()->resetMouseWheel();
if (mouseInput.m_DoubleClick == false && mouseInput.m_MouseState == MS_LEFT_UP)
{
m_AssemblyLineLayer->updateClickItem(mouseInput.m_MouseMove);
m_AssemblyLineLayer->setClickedItem(mouseInput.m_MouseMove);
m_StatusLayer->setCurClickedItem(m_AssemblyLineLayer->getClickedItem());
GET_INPUT_MANAGER()->resetMouseState();
}
if (mouseInput.m_DoubleClick)
{
m_AssemblyLineLayer->updateDoubleClickItem(mouseInput.m_MouseMove);
m_AssemblyLineLayer->setConfirmSet(mouseInput.m_MouseMove);
m_StatusLayer->setConfirmSet(m_AssemblyLineLayer->getConfirmSet());
m_DisplayLayer->setConfirmSet(m_AssemblyLineLayer->getConfirmSet());
m_DisplayLayer->assembleRobot();
m_DisplayLayer->moveScanBar();
GET_INPUT_MANAGER()->resetMouseDoubleClick();
}
}
else
{
m_AssemblyLineLayer->hideLabelLayer();
if (mouseInput.m_ScollValue < 0)
{
viewChange(SKILL_VIEW);
}
else if (mouseInput.m_ScollValue > 0)
{
GET_INPUT_MANAGER()->resetMouseWheel();
}
//meaningless double click error exception
if (mouseInput.m_DoubleClick)
{
GET_INPUT_MANAGER()->resetMouseDoubleClick();
}
}
//view change arrow
if (m_viewChangeRect.containsPoint(mouseInput.m_MouseEnd[LEFT_CLICK_POINT]))
{
viewChange(SKILL_VIEW);
}
}
else if (m_CurrentAssembly == SKILL_VIEW)
{
m_DisplayLayer->update(dTime);
if (m_SkillRect.containsPoint(mouseInput.m_MouseMove))
{
m_SkillLineLayer->updateSkills(dTime);
m_SkillLineLayer->containerScroll(mouseInput.m_ScollValue, mouseInput.m_MouseMove);
GET_INPUT_MANAGER()->resetMouseWheel();
if (mouseInput.m_DoubleClick)
{
m_SkillLineLayer->updateDoubleClickSkill(mouseInput.m_MouseMove);
m_SkillLineLayer->setSkillSet(mouseInput.m_MouseMove);
m_DisplayLayer->moveScanBar();
GET_INPUT_MANAGER()->resetMouseDoubleClick();
}
}
else
{
m_SkillLineLayer->hideLabelLayer();
if (mouseInput.m_ScollValue > 0)
{
viewChange(ASSEMBLY_VIEW);
}
else if (mouseInput.m_ScollValue < 0)
{
GET_INPUT_MANAGER()->resetMouseWheel();
}
//meaningless double click error exception
if (mouseInput.m_DoubleClick)
{
GET_INPUT_MANAGER()->resetMouseDoubleClick();
}
}
//view change arrow
if (m_viewChangeRect.containsPoint(mouseInput.m_MouseEnd[LEFT_CLICK_POINT]))
{
viewChange(ASSEMBLY_VIEW);
}
m_ButtonConfirm->update(dTime);
m_ButtonCancel->update(dTime);
}
}
void AssemblyUILayer::viewChange(AssemblyLayerType moveViewTo)
{
if (m_AssemblyBackground->getNumberOfRunningActions() == 0)
{
cocos2d::ActionInterval* moveAction0;
cocos2d::ActionInterval* moveAction1;
if (moveViewTo == SKILL_VIEW)
{
moveAction0 = cocos2d::MoveTo::create(1.0f, cocos2d::Point(-830 * RESOLUTION, 0));
moveAction1 = cocos2d::MoveTo::create(1.2f, cocos2d::Point(-830 * RESOLUTION, 0));
m_viewChangeRect.setRect(20 * RESOLUTION, 310 * RESOLUTION, 25 * RESOLUTION, 100 * RESOLUTION);
m_ViewChangeArrow->setRotation(180);
m_ButtonConfirm->setButtonRect(cocos2d::Point(-830 * RESOLUTION, 0));
m_ButtonCancel->setButtonRect(cocos2d::Point(-830 * RESOLUTION, 0));
m_AssemblyLineLayer->setVisible(false);
m_StatusLayer->setVisible(false);
m_SkillLineLayer->setVisible(true);
m_EquipmentRect.setRect(0, 0, 0, 0);
m_SkillRect.setRect(535 * RESOLUTION, 295 * RESOLUTION, 320 * RESOLUTION, 325 * RESOLUTION);
m_CurrentAssembly = SKILL_VIEW;
}
else
{
moveAction0 = cocos2d::MoveTo::create(1.0f, cocos2d::Point(0, 0));
moveAction1 = cocos2d::MoveTo::create(1.2f, cocos2d::Point(0, 0));
m_viewChangeRect.setRect(1235 * RESOLUTION, 310 * RESOLUTION, 25 * RESOLUTION, 100 * RESOLUTION);
m_ViewChangeArrow->setRotation(0);
m_ButtonConfirm->setButtonRect(cocos2d::Point(0 * RESOLUTION, 0));
m_ButtonCancel->setButtonRect(cocos2d::Point(0 * RESOLUTION, 0));
m_AssemblyLineLayer->setVisible(true);
m_StatusLayer->setVisible(true);
m_SkillLineLayer->setVisible(false);
m_EquipmentRect.setRect(140 * RESOLUTION, 40 * RESOLUTION, 390 * RESOLUTION, 580 * RESOLUTION);
m_SkillRect.setRect(0, 0, 0, 0);
m_CurrentAssembly = ASSEMBLY_VIEW;
}
cocos2d::Action* action0 = cocos2d::EaseExponentialOut::create(moveAction0);
cocos2d::Action* action1 = cocos2d::EaseExponentialOut::create(moveAction1);
m_AssemblyFrame->runAction(action0);
m_AssemblyBackground->runAction(action1);
}
GET_INPUT_MANAGER()->resetMousePoints();
GET_INPUT_MANAGER()->resetMouseWheel();
}
void AssemblyUILayer::assemblyLayerButtonInit()
{
m_ButtonConfirm = ButtonLayer::create();
m_ButtonCancel = ButtonLayer::create();
m_ButtonConfirm->setButtonProperties(BUTTON_ASSEMBLY_CONFIRM, cocos2d::Point(0 * RESOLUTION, 0), cocos2d::Point(1670, 90), "Confirm", 35);
m_ButtonCancel->setButtonProperties(BUTTON_ASSEMBLY_CONFIRM, cocos2d::Point(0 * RESOLUTION, 0), cocos2d::Point(1900, 90), "Cancel", 35);
m_ButtonConfirm->setButtonFunc(std::bind(&AssemblyUILayer::confirmAssembly, this));
m_ButtonCancel->setButtonFunc(std::bind(&AssemblyUILayer::toTitleScene, this));
m_AssemblyFrame->addChild(m_ButtonConfirm);
m_AssemblyFrame->addChild(m_ButtonCancel);
}
void AssemblyUILayer::moveContainer(bool moveLeft, cocos2d::Node* container, cocos2d::Rect containerRect)
{
if (moveLeft)
{
if (container->getBoundingBox().getMaxX() - 140 > containerRect.getMaxX())
{
container->setPosition(cocos2d::Point(container->getPosition().x - 15, container->getPosition().y));
}
GET_INPUT_MANAGER()->resetMouseWheel();
}
else
{
if (container->getBoundingBox().getMinX() * RESOLUTION < containerRect.getMinX())
{
container->setPosition(cocos2d::Point(container->getPosition().x + 15, container->getPosition().y));
}
GET_INPUT_MANAGER()->resetMouseWheel();
}
}
void AssemblyUILayer::confirmAssembly()
{
if (checkAssemblyComplete(m_AssemblyLineLayer->getConfirmSet()))
{
if (!m_IsStarted)
{
m_IsStarted = true;
GET_DATA_MANAGER()->setEquipmentItem(m_AssemblyLineLayer->getConfirmSet());
GET_DATA_MANAGER()->initWorldData();
GET_INPUT_MANAGER()->resetMouseInfo();
GET_GAME_MANAGER()->changeScene(GET_STAGE_MANAGER()->getGameScene(), GAME_SCENE);
GET_STAGE_MANAGER()->start();
}
}
else
{
//̿ϼ !
}
}
void AssemblyUILayer::toTitleScene()
{
//߿ Լ ٲٱ
exit(0);
}
bool AssemblyUILayer::checkAssemblyComplete(ConfirmSet confirmSet)
{
bool okToStart = false;
if (confirmSet.m_Head == HL_START || confirmSet.m_Engine == EL_START ||
confirmSet.m_Armor == AL_START || confirmSet.m_Melee == ML_START ||
confirmSet.m_Range == RL_START || confirmSet.m_Steam == SCL_START || confirmSet.m_Leg == LL_START)
{
okToStart = false;
}
// if (m_DisplayLayer->getPowerOver())
// {
// okToStart = false;
// }
return okToStart;
}
void AssemblyUILayer::onExit()
{
m_IsStarted = false;
}
<commit_msg>일단 작동되게 만듬<commit_after>#include "pch.h"
#include "AssemblyUILayer.h"
#include "GameManager.h"
#include "StageManager.h"
#include "DataManager.h"
#include "ResourceManager.h"
#include "InputManager.h"
#include "AssemblyLineLayer.h"
#include "EquipmentStatusLayer.h"
#include "AssemblyDisplayLayer.h"
#include "SkillLineLayer.h"
#include "ButtonLayer.h"
#include "IconLayer.h"
AssemblyUILayer::AssemblyUILayer()
{
m_viewChangeRect.setRect(1235 * RESOLUTION, 310 * RESOLUTION, 25 * RESOLUTION, 100 * RESOLUTION);
}
AssemblyUILayer::~AssemblyUILayer()
{
}
bool AssemblyUILayer::init()
{
if (!cocos2d::Layer::init())
{
return false;
}
m_IsStarted = false;
m_AssemblyLineLayer = AssemblyLineLayer::create();
m_StatusLayer = EquipmentStatusLayer::create();
m_DisplayLayer = AssemblyDisplayLayer::create();
m_SkillLineLayer = SkillLineLayer::create();
m_AssemblyBackground = GET_RESOURCE_MANAGER()->createSprite(ST_ASSEMBLY_BACKGROUND);
m_AssemblyFrame = GET_RESOURCE_MANAGER()->createSprite(ST_ASSEMBLY_FRAME);
m_ViewChangeArrow = GET_RESOURCE_MANAGER()->createSprite(ST_ASSEMBLY_ARROW);
m_EquipmentRect.setRect(140 * RESOLUTION, 40 * RESOLUTION, 390 * RESOLUTION, 580 * RESOLUTION);
m_SkillRect.setRect(535 * RESOLUTION, 295 * RESOLUTION, 320 * RESOLUTION, 325 * RESOLUTION);
setUIProperties(m_AssemblyBackground, cocos2d::Point::ZERO, cocos2d::Point::ZERO, RESOLUTION, true, 0);
setUIProperties(m_AssemblyFrame, cocos2d::Point::ZERO, cocos2d::Point::ZERO, RESOLUTION, true, 0);
setUIProperties(m_ViewChangeArrow, cocos2d::Point(0.5, 0.5), cocos2d::Point(1055, 360), 1.0f, true, 1);
m_AssemblyLineLayer->setPosition(cocos2d::Point(0, 0));
m_StatusLayer->setPosition(cocos2d::Point(545, 0));
m_DisplayLayer->setPosition(cocos2d::Point(830, 0));
m_SkillLineLayer->setPosition(cocos2d::Point(1280, 0));
assemblyLayerButtonInit();
m_CurrentAssembly = ASSEMBLY_VIEW;
this->addChild(m_AssemblyBackground);
m_AssemblyBackground->addChild(m_AssemblyLineLayer);
m_AssemblyBackground->addChild(m_SkillLineLayer);
this->addChild(m_AssemblyFrame);
m_AssemblyFrame->addChild(m_DisplayLayer);
m_AssemblyFrame->addChild(m_ViewChangeArrow);
m_AssemblyFrame->addChild(m_StatusLayer);
return true;
}
void AssemblyUILayer::update(float dTime)
{
MouseInfo mouseInput = GET_INPUT_MANAGER()->getMouseInfo();
if (m_CurrentAssembly == ASSEMBLY_VIEW)
{
m_StatusLayer->update(dTime);
m_DisplayLayer->update(dTime);
if (m_EquipmentRect.containsPoint(mouseInput.m_MouseMove))
{
m_AssemblyLineLayer->updateEquipments(dTime);
m_AssemblyLineLayer->containerScroll(mouseInput.m_ScollValue, mouseInput.m_MouseMove);
GET_INPUT_MANAGER()->resetMouseWheel();
if (mouseInput.m_DoubleClick == false && mouseInput.m_MouseState == MS_LEFT_UP)
{
m_AssemblyLineLayer->updateClickItem(mouseInput.m_MouseMove);
m_AssemblyLineLayer->setClickedItem(mouseInput.m_MouseMove);
m_StatusLayer->setCurClickedItem(m_AssemblyLineLayer->getClickedItem());
GET_INPUT_MANAGER()->resetMouseState();
}
if (mouseInput.m_DoubleClick)
{
m_AssemblyLineLayer->updateDoubleClickItem(mouseInput.m_MouseMove);
m_AssemblyLineLayer->setConfirmSet(mouseInput.m_MouseMove);
m_StatusLayer->setConfirmSet(m_AssemblyLineLayer->getConfirmSet());
m_DisplayLayer->setConfirmSet(m_AssemblyLineLayer->getConfirmSet());
m_DisplayLayer->assembleRobot();
m_DisplayLayer->moveScanBar();
GET_INPUT_MANAGER()->resetMouseDoubleClick();
}
}
else
{
m_AssemblyLineLayer->hideLabelLayer();
if (mouseInput.m_ScollValue < 0)
{
viewChange(SKILL_VIEW);
}
else if (mouseInput.m_ScollValue > 0)
{
GET_INPUT_MANAGER()->resetMouseWheel();
}
//meaningless double click error exception
if (mouseInput.m_DoubleClick)
{
GET_INPUT_MANAGER()->resetMouseDoubleClick();
}
}
//view change arrow
if (m_viewChangeRect.containsPoint(mouseInput.m_MouseEnd[LEFT_CLICK_POINT]))
{
viewChange(SKILL_VIEW);
}
}
else if (m_CurrentAssembly == SKILL_VIEW)
{
m_DisplayLayer->update(dTime);
if (m_SkillRect.containsPoint(mouseInput.m_MouseMove))
{
m_SkillLineLayer->updateSkills(dTime);
m_SkillLineLayer->containerScroll(mouseInput.m_ScollValue, mouseInput.m_MouseMove);
GET_INPUT_MANAGER()->resetMouseWheel();
if (mouseInput.m_DoubleClick)
{
m_SkillLineLayer->updateDoubleClickSkill(mouseInput.m_MouseMove);
m_SkillLineLayer->setSkillSet(mouseInput.m_MouseMove);
m_DisplayLayer->moveScanBar();
GET_INPUT_MANAGER()->resetMouseDoubleClick();
}
}
else
{
m_SkillLineLayer->hideLabelLayer();
if (mouseInput.m_ScollValue > 0)
{
viewChange(ASSEMBLY_VIEW);
}
else if (mouseInput.m_ScollValue < 0)
{
GET_INPUT_MANAGER()->resetMouseWheel();
}
//meaningless double click error exception
if (mouseInput.m_DoubleClick)
{
GET_INPUT_MANAGER()->resetMouseDoubleClick();
}
}
//view change arrow
if (m_viewChangeRect.containsPoint(mouseInput.m_MouseEnd[LEFT_CLICK_POINT]))
{
viewChange(ASSEMBLY_VIEW);
}
m_ButtonConfirm->update(dTime);
m_ButtonCancel->update(dTime);
}
}
void AssemblyUILayer::viewChange(AssemblyLayerType moveViewTo)
{
if (m_AssemblyBackground->getNumberOfRunningActions() == 0)
{
cocos2d::ActionInterval* moveAction0;
cocos2d::ActionInterval* moveAction1;
if (moveViewTo == SKILL_VIEW)
{
moveAction0 = cocos2d::MoveTo::create(1.0f, cocos2d::Point(-830 * RESOLUTION, 0));
moveAction1 = cocos2d::MoveTo::create(1.2f, cocos2d::Point(-830 * RESOLUTION, 0));
m_viewChangeRect.setRect(20 * RESOLUTION, 310 * RESOLUTION, 25 * RESOLUTION, 100 * RESOLUTION);
m_ViewChangeArrow->setRotation(180);
m_ButtonConfirm->setButtonRect(cocos2d::Point(-830 * RESOLUTION, 0));
m_ButtonCancel->setButtonRect(cocos2d::Point(-830 * RESOLUTION, 0));
m_AssemblyLineLayer->setVisible(false);
m_StatusLayer->setVisible(false);
m_SkillLineLayer->setVisible(true);
m_EquipmentRect.setRect(0, 0, 0, 0);
m_SkillRect.setRect(535 * RESOLUTION, 295 * RESOLUTION, 320 * RESOLUTION, 325 * RESOLUTION);
m_CurrentAssembly = SKILL_VIEW;
}
else
{
moveAction0 = cocos2d::MoveTo::create(1.0f, cocos2d::Point(0, 0));
moveAction1 = cocos2d::MoveTo::create(1.2f, cocos2d::Point(0, 0));
m_viewChangeRect.setRect(1235 * RESOLUTION, 310 * RESOLUTION, 25 * RESOLUTION, 100 * RESOLUTION);
m_ViewChangeArrow->setRotation(0);
m_ButtonConfirm->setButtonRect(cocos2d::Point(0 * RESOLUTION, 0));
m_ButtonCancel->setButtonRect(cocos2d::Point(0 * RESOLUTION, 0));
m_AssemblyLineLayer->setVisible(true);
m_StatusLayer->setVisible(true);
m_SkillLineLayer->setVisible(false);
m_EquipmentRect.setRect(140 * RESOLUTION, 40 * RESOLUTION, 390 * RESOLUTION, 580 * RESOLUTION);
m_SkillRect.setRect(0, 0, 0, 0);
m_CurrentAssembly = ASSEMBLY_VIEW;
}
cocos2d::Action* action0 = cocos2d::EaseExponentialOut::create(moveAction0);
cocos2d::Action* action1 = cocos2d::EaseExponentialOut::create(moveAction1);
m_AssemblyFrame->runAction(action0);
m_AssemblyBackground->runAction(action1);
}
GET_INPUT_MANAGER()->resetMousePoints();
GET_INPUT_MANAGER()->resetMouseWheel();
}
void AssemblyUILayer::assemblyLayerButtonInit()
{
m_ButtonConfirm = ButtonLayer::create();
m_ButtonCancel = ButtonLayer::create();
m_ButtonConfirm->setButtonProperties(BUTTON_ASSEMBLY_CONFIRM, cocos2d::Point(0 * RESOLUTION, 0), cocos2d::Point(1670, 90), "Confirm", 35);
m_ButtonCancel->setButtonProperties(BUTTON_ASSEMBLY_CONFIRM, cocos2d::Point(0 * RESOLUTION, 0), cocos2d::Point(1900, 90), "Cancel", 35);
m_ButtonConfirm->setButtonFunc(std::bind(&AssemblyUILayer::confirmAssembly, this));
m_ButtonCancel->setButtonFunc(std::bind(&AssemblyUILayer::toTitleScene, this));
m_AssemblyFrame->addChild(m_ButtonConfirm);
m_AssemblyFrame->addChild(m_ButtonCancel);
}
void AssemblyUILayer::moveContainer(bool moveLeft, cocos2d::Node* container, cocos2d::Rect containerRect)
{
if (moveLeft)
{
if (container->getBoundingBox().getMaxX() - 140 > containerRect.getMaxX())
{
container->setPosition(cocos2d::Point(container->getPosition().x - 15, container->getPosition().y));
}
GET_INPUT_MANAGER()->resetMouseWheel();
}
else
{
if (container->getBoundingBox().getMinX() * RESOLUTION < containerRect.getMinX())
{
container->setPosition(cocos2d::Point(container->getPosition().x + 15, container->getPosition().y));
}
GET_INPUT_MANAGER()->resetMouseWheel();
}
}
void AssemblyUILayer::confirmAssembly()
{
if (checkAssemblyComplete(m_AssemblyLineLayer->getConfirmSet()))
{
if (!m_IsStarted)
{
m_IsStarted = true;
GET_DATA_MANAGER()->setEquipmentItem(m_AssemblyLineLayer->getConfirmSet());
GET_DATA_MANAGER()->initWorldData();
GET_INPUT_MANAGER()->resetMouseInfo();
GET_GAME_MANAGER()->changeScene(GET_STAGE_MANAGER()->getGameScene(), GAME_SCENE);
GET_STAGE_MANAGER()->start();
}
}
else
{
//̿ϼ !
}
}
void AssemblyUILayer::toTitleScene()
{
//߿ Լ ٲٱ
exit(0);
}
bool AssemblyUILayer::checkAssemblyComplete(ConfirmSet confirmSet)
{
bool okToStart = false;
if (confirmSet.m_Head == HL_START || confirmSet.m_Engine == EL_START ||
confirmSet.m_Armor == AL_START || confirmSet.m_Melee == ML_START ||
confirmSet.m_Range == RL_START || confirmSet.m_Steam == SCL_START || confirmSet.m_Leg == LL_START)
{
okToStart = false;
}
// if (m_DisplayLayer->getPowerOver())
// {
// okToStart = false;
// }
return true;
}
void AssemblyUILayer::onExit()
{
m_IsStarted = false;
}
<|endoftext|> |
<commit_before>#pragma once
#include <array>
#include <vector>
#include "Runtime/RetroTypes.hpp"
#include <zeus/CColor.hpp>
#include <zeus/CMatrix4f.hpp>
#include <zeus/CVector3f.hpp>
#include <zeus/CVector4f.hpp>
namespace urde {
class CElementGen;
class CParticleGlobals {
CParticleGlobals() = default;
static std::unique_ptr<CParticleGlobals> g_ParticleGlobals;
public:
int m_EmitterTime = 0;
float m_EmitterTimeReal = 0.f;
void SetEmitterTime(int frame) {
m_EmitterTime = frame;
m_EmitterTimeReal = frame;
}
int m_ParticleLifetime = 0;
float m_ParticleLifetimeReal = 0.f;
void SetParticleLifetime(int frame) {
m_ParticleLifetime = frame;
m_ParticleLifetimeReal = frame;
}
int m_ParticleLifetimePercentage = 0;
float m_ParticleLifetimePercentageReal = 0.f;
float m_ParticleLifetimePercentageRemainder = 0.f;
void UpdateParticleLifetimeTweenValues(int frame) {
float lt = m_ParticleLifetime != 0.0f ? m_ParticleLifetime : 1.0f;
m_ParticleLifetimePercentageReal = 100.0f * frame / lt;
m_ParticleLifetimePercentage = int(m_ParticleLifetimePercentageReal);
m_ParticleLifetimePercentageRemainder = m_ParticleLifetimePercentageReal - m_ParticleLifetimePercentage;
m_ParticleLifetimePercentage = zeus::clamp(0, m_ParticleLifetimePercentage, 100);
}
const std::array<float, 8>* m_particleAccessParameters = nullptr;
struct SParticleSystem {
FourCC x0_type;
CElementGen* x4_system;
};
SParticleSystem* m_currentParticleSystem = nullptr;
static CParticleGlobals* instance() {
if (!g_ParticleGlobals)
g_ParticleGlobals.reset(new CParticleGlobals());
return g_ParticleGlobals.get();
}
};
struct SParticleInstanceTex {
zeus::CVector4f pos[4];
zeus::CColor color;
zeus::CVector2f uvs[4];
};
extern std::vector<SParticleInstanceTex> g_instTexData;
struct SParticleInstanceIndTex {
zeus::CVector4f pos[4];
zeus::CColor color;
zeus::CVector4f texrTindUVs[4];
zeus::CVector4f sceneUVs;
};
extern std::vector<SParticleInstanceIndTex> g_instIndTexData;
struct SParticleInstanceNoTex {
zeus::CVector4f pos[4];
zeus::CColor color;
};
extern std::vector<SParticleInstanceNoTex> g_instNoTexData;
struct SParticleUniforms {
zeus::CMatrix4f mvp;
zeus::CColor moduColor;
};
} // namespace urde
<commit_msg>CParticleGlobals: Make use of std::array where applicable<commit_after>#pragma once
#include <array>
#include <vector>
#include "Runtime/RetroTypes.hpp"
#include <zeus/CColor.hpp>
#include <zeus/CMatrix4f.hpp>
#include <zeus/CVector3f.hpp>
#include <zeus/CVector4f.hpp>
namespace urde {
class CElementGen;
class CParticleGlobals {
CParticleGlobals() = default;
static std::unique_ptr<CParticleGlobals> g_ParticleGlobals;
public:
int m_EmitterTime = 0;
float m_EmitterTimeReal = 0.f;
void SetEmitterTime(int frame) {
m_EmitterTime = frame;
m_EmitterTimeReal = frame;
}
int m_ParticleLifetime = 0;
float m_ParticleLifetimeReal = 0.f;
void SetParticleLifetime(int frame) {
m_ParticleLifetime = frame;
m_ParticleLifetimeReal = frame;
}
int m_ParticleLifetimePercentage = 0;
float m_ParticleLifetimePercentageReal = 0.f;
float m_ParticleLifetimePercentageRemainder = 0.f;
void UpdateParticleLifetimeTweenValues(int frame) {
float lt = m_ParticleLifetime != 0.0f ? m_ParticleLifetime : 1.0f;
m_ParticleLifetimePercentageReal = 100.0f * frame / lt;
m_ParticleLifetimePercentage = int(m_ParticleLifetimePercentageReal);
m_ParticleLifetimePercentageRemainder = m_ParticleLifetimePercentageReal - m_ParticleLifetimePercentage;
m_ParticleLifetimePercentage = zeus::clamp(0, m_ParticleLifetimePercentage, 100);
}
const std::array<float, 8>* m_particleAccessParameters = nullptr;
struct SParticleSystem {
FourCC x0_type;
CElementGen* x4_system;
};
SParticleSystem* m_currentParticleSystem = nullptr;
static CParticleGlobals* instance() {
if (!g_ParticleGlobals)
g_ParticleGlobals.reset(new CParticleGlobals());
return g_ParticleGlobals.get();
}
};
struct SParticleInstanceTex {
std::array<zeus::CVector4f, 4> pos;
zeus::CColor color;
std::array<zeus::CVector2f, 4> uvs;
};
extern std::vector<SParticleInstanceTex> g_instTexData;
struct SParticleInstanceIndTex {
std::array<zeus::CVector4f, 4> pos;
zeus::CColor color;
std::array<zeus::CVector4f, 4> texrTindUVs;
zeus::CVector4f sceneUVs;
};
extern std::vector<SParticleInstanceIndTex> g_instIndTexData;
struct SParticleInstanceNoTex {
std::array<zeus::CVector4f, 4> pos;
zeus::CColor color;
};
extern std::vector<SParticleInstanceNoTex> g_instNoTexData;
struct SParticleUniforms {
zeus::CMatrix4f mvp;
zeus::CColor moduColor;
};
} // namespace urde
<|endoftext|> |
<commit_before>#include "UIHandler.h"
UIHandler::UIHandler()
{
}
UIHandler::~UIHandler()
{
}
void UIHandler::Initialize(ID3D11Device* device, ID3D11DeviceContext* deviceContext)
{
this->m_maxUIComponents = 10;
this->m_nrOfUIComponents = 0;
for (int i = 0; i < this->m_maxUIComponents; i++)
{
UIComponent* newUIComp = new UIComponent;
this->m_UIComponents.push_back(newUIComp);
}
this->m_maxTextComponents = 10;
this->m_nrOfTextComponents = 0;
for (int i = 0; i < this->m_maxTextComponents; i++)
{
TextComponent* newTextComp = new TextComponent;
this->m_textComponents.push_back(newTextComp);
}
this->m_spriteBatch = new DirectX::SpriteBatch(deviceContext);
this->m_spriteFont = new DirectX::SpriteFont(device, L"consolas.spritefont");
DirectX::CreateWICTextureFromFile(device, L"cat.png", nullptr, &this->m_texture);
this->m_UIComponents.at(0)->position = DirectX::XMFLOAT2(10.f, 10.f);
this->m_UIComponents.at(0)->layerDepth = 1.f;
this->m_UIComponents.at(0)->active = true;
this->m_nrOfUIComponents++;
this->m_UIComponents.at(1)->position = DirectX::XMFLOAT2(200.f, 100.f);
this->m_UIComponents.at(1)->scale = 0.5f;
this->m_UIComponents.at(1)->rotation = 2.0f;
this->m_UIComponents.at(1)->layerDepth = 0.f;
this->m_UIComponents.at(1)->active = true;
this->m_nrOfUIComponents++;
this->m_textComponents.at(0)->active = true;
this->m_textComponents.at(0)->text = L"Hello";
this->m_textComponents.at(0)->layerDepth = 0.5f;
this->m_nrOfTextComponents++;
this->m_textComponents.at(1)->active = true;
this->m_textComponents.at(1)->text = L"Darkness my old friend";
this->m_textComponents.at(1)->position = DirectX::XMFLOAT2(50.f, 85.f);
this->m_textComponents.at(1)->scale = DirectX::XMFLOAT2(0.5f, 0.5f);
this->m_textComponents.at(1)->layerDepth = 0.5f;
this->m_nrOfTextComponents++;
}
void UIHandler::DrawUI()
{
UIComponent* tempUIComp = nullptr;
TextComponent* tempTextComp = nullptr;
this->m_spriteBatch->Begin(DirectX::SpriteSortMode::SpriteSortMode_BackToFront);
for (int i = 0; i < this->m_nrOfUIComponents; i++)
{
tempUIComp = this->m_UIComponents.at(i);
this->m_spriteBatch->Draw(this->m_texture, tempUIComp->position, nullptr, DirectX::Colors::White, tempUIComp->rotation, DirectX::XMFLOAT2(0.f, 0.f), tempUIComp->scale, DirectX::SpriteEffects::SpriteEffects_None, tempUIComp->layerDepth);
}
for (int i = 0; i < this->m_nrOfTextComponents; i++)
{
tempTextComp = this->m_textComponents.at(i);
this->m_spriteFont->DrawString(this->m_spriteBatch, tempTextComp->text.c_str(), tempTextComp->position, DirectX::Colors::White, tempTextComp->rotation, DirectX::XMFLOAT2(0.f, 0.f), tempTextComp->scale, DirectX::SpriteEffects::SpriteEffects_None, tempTextComp->layerDepth);
}
this->m_spriteBatch->End();
}
void UIHandler::Shutdown()
{
for (int i = 0; i < this->m_maxUIComponents; i++)
{
delete this->m_UIComponents.at(i);
}
for (int i = 0; i < this->m_maxTextComponents; i++)
{
delete this->m_textComponents.at(i);
}
//this->m_spriteBatch.release();
if (this->m_spriteBatch)
{
delete this->m_spriteBatch;
this->m_spriteBatch = nullptr;
}
if (this->m_spriteFont)
{
delete this->m_spriteFont;
this->m_spriteFont = nullptr;
}
if (this->m_texture)
{
this->m_texture->Release();
this->m_texture = nullptr;
}
}
UIComponent* UIHandler::GetNextUIComponent()
{
if (this->m_nrOfUIComponents < this->m_maxUIComponents)
{
return this->m_UIComponents.at(this->m_nrOfUIComponents++);
}
return nullptr;
}
TextComponent* UIHandler::GetNextTextComponent()
{
if (this->m_nrOfTextComponents < this->m_maxTextComponents)
{
return this->m_textComponents.at(this->m_nrOfTextComponents++);
}
return nullptr;
}
void UIHandler::UpdateUIComponentsclicked(DirectX::XMFLOAT2 mousePos)
{
std::vector<UIComponent*>::iterator uiCompIter;
for (uiCompIter = this->m_UIComponents.begin(); uiCompIter != this->m_UIComponents.end(); uiCompIter++)
{
(*uiCompIter)->UpdateClicked(mousePos);
}
}
void UIHandler::UpdateUIComponentsclicked(DirectX::XMFLOAT2 mousePos, DirectX::XMFLOAT2 windowSize)
{
std::vector<UIComponent*>::iterator uiCompIter;
for (uiCompIter = this->m_UIComponents.begin(); uiCompIter != this->m_UIComponents.end(); uiCompIter++)
{
(*uiCompIter)->UpdateClicked(mousePos, windowSize);
}
}
<commit_msg>UPDATE only draw ui and text components if active<commit_after>#include "UIHandler.h"
UIHandler::UIHandler()
{
}
UIHandler::~UIHandler()
{
}
void UIHandler::Initialize(ID3D11Device* device, ID3D11DeviceContext* deviceContext)
{
this->m_maxUIComponents = 10;
this->m_nrOfUIComponents = 0;
for (int i = 0; i < this->m_maxUIComponents; i++)
{
UIComponent* newUIComp = new UIComponent;
this->m_UIComponents.push_back(newUIComp);
}
this->m_maxTextComponents = 10;
this->m_nrOfTextComponents = 0;
for (int i = 0; i < this->m_maxTextComponents; i++)
{
TextComponent* newTextComp = new TextComponent;
this->m_textComponents.push_back(newTextComp);
}
this->m_spriteBatch = new DirectX::SpriteBatch(deviceContext);
this->m_spriteFont = new DirectX::SpriteFont(device, L"consolas.spritefont");
DirectX::CreateWICTextureFromFile(device, L"cat.png", nullptr, &this->m_texture);
this->m_UIComponents.at(0)->position = DirectX::XMFLOAT2(10.f, 10.f);
this->m_UIComponents.at(0)->layerDepth = 1.f;
this->m_UIComponents.at(0)->active = true;
this->m_nrOfUIComponents++;
this->m_UIComponents.at(1)->position = DirectX::XMFLOAT2(200.f, 100.f);
this->m_UIComponents.at(1)->scale = 0.5f;
this->m_UIComponents.at(1)->rotation = 2.0f;
this->m_UIComponents.at(1)->layerDepth = 0.f;
this->m_UIComponents.at(1)->active = true;
this->m_nrOfUIComponents++;
this->m_textComponents.at(0)->active = true;
this->m_textComponents.at(0)->text = L"Hello";
this->m_textComponents.at(0)->layerDepth = 0.5f;
this->m_nrOfTextComponents++;
this->m_textComponents.at(1)->active = true;
this->m_textComponents.at(1)->text = L"Darkness my old friend";
this->m_textComponents.at(1)->position = DirectX::XMFLOAT2(50.f, 85.f);
this->m_textComponents.at(1)->scale = DirectX::XMFLOAT2(0.5f, 0.5f);
this->m_textComponents.at(1)->layerDepth = 0.5f;
this->m_nrOfTextComponents++;
}
void UIHandler::DrawUI()
{
UIComponent* tempUIComp = nullptr;
TextComponent* tempTextComp = nullptr;
this->m_spriteBatch->Begin(DirectX::SpriteSortMode::SpriteSortMode_BackToFront);
for (int i = 0; i < this->m_nrOfUIComponents; i++)
{
tempUIComp = this->m_UIComponents.at(i);
if (tempUIComp->active)
{
this->m_spriteBatch->Draw(this->m_texture, tempUIComp->position, nullptr, DirectX::Colors::White, tempUIComp->rotation, DirectX::XMFLOAT2(0.f, 0.f), tempUIComp->scale, DirectX::SpriteEffects::SpriteEffects_None, tempUIComp->layerDepth);
}
}
for (int i = 0; i < this->m_nrOfTextComponents; i++)
{
tempTextComp = this->m_textComponents.at(i);
if (tempTextComp->active)
{
this->m_spriteFont->DrawString(this->m_spriteBatch, tempTextComp->text.c_str(), tempTextComp->position, DirectX::Colors::White, tempTextComp->rotation, DirectX::XMFLOAT2(0.f, 0.f), tempTextComp->scale, DirectX::SpriteEffects::SpriteEffects_None, tempTextComp->layerDepth);
}
}
this->m_spriteBatch->End();
}
void UIHandler::Shutdown()
{
for (int i = 0; i < this->m_maxUIComponents; i++)
{
delete this->m_UIComponents.at(i);
}
for (int i = 0; i < this->m_maxTextComponents; i++)
{
delete this->m_textComponents.at(i);
}
//this->m_spriteBatch.release();
if (this->m_spriteBatch)
{
delete this->m_spriteBatch;
this->m_spriteBatch = nullptr;
}
if (this->m_spriteFont)
{
delete this->m_spriteFont;
this->m_spriteFont = nullptr;
}
if (this->m_texture)
{
this->m_texture->Release();
this->m_texture = nullptr;
}
}
UIComponent* UIHandler::GetNextUIComponent()
{
if (this->m_nrOfUIComponents < this->m_maxUIComponents)
{
return this->m_UIComponents.at(this->m_nrOfUIComponents++);
}
return nullptr;
}
TextComponent* UIHandler::GetNextTextComponent()
{
if (this->m_nrOfTextComponents < this->m_maxTextComponents)
{
return this->m_textComponents.at(this->m_nrOfTextComponents++);
}
return nullptr;
}
void UIHandler::UpdateUIComponentsclicked(DirectX::XMFLOAT2 mousePos)
{
std::vector<UIComponent*>::iterator uiCompIter;
for (uiCompIter = this->m_UIComponents.begin(); uiCompIter != this->m_UIComponents.end(); uiCompIter++)
{
(*uiCompIter)->UpdateClicked(mousePos);
}
}
void UIHandler::UpdateUIComponentsclicked(DirectX::XMFLOAT2 mousePos, DirectX::XMFLOAT2 windowSize)
{
std::vector<UIComponent*>::iterator uiCompIter;
for (uiCompIter = this->m_UIComponents.begin(); uiCompIter != this->m_UIComponents.end(); uiCompIter++)
{
(*uiCompIter)->UpdateClicked(mousePos, windowSize);
}
}
<|endoftext|> |
<commit_before>#include "Scheduler.h"
//#include "Assert.h"
//TODO: Split to files. One file - one class.
namespace MT
{
static const size_t TASK_BUFFER_CAPACITY = 4096;
ThreadContext::ThreadContext()
: taskScheduler(nullptr)
, hasNewTasksEvent(EventReset::AUTOMATIC, true)
, state(ThreadState::ALIVE)
, descBuffer(TASK_BUFFER_CAPACITY)
{
}
ThreadContext::~ThreadContext()
{
}
FiberContext::FiberContext()
: currentTask(nullptr)
, threadContext(nullptr)
, taskStatus(FiberTaskStatus::UNKNOWN)
, subtaskFibersCount(0)
{
}
void FiberContext::WaitGroupAndYield(TaskGroup::Type group)
{
VERIFY(group != currentGroup, "Can't wait the same group. Deadlock detected!", return);
VERIFY(group < TaskGroup::COUNT, "Invalid group!", return);
ASSERT(threadContext->taskScheduler->IsWorkerThread(), "Can't use WaitGroup outside Task. Use TaskScheduler.WaitGroup() instead.");
ConcurrentQueueLIFO<TaskDesc> & groupQueue = threadContext->taskScheduler->waitTaskQueues[group];
//change status
taskStatus = FiberTaskStatus::AWAITING;
// copy current task to awaiting queue
groupQueue.Push(*currentTask);
//
ASSERT(threadContext->thread.IsCurrentThread(), "Thread context sanity check failed");
//switch to scheduler
Fiber::SwitchTo(fiber, threadContext->schedulerFiber);
}
void FiberContext::RunSubtasksAndYield(TaskGroup::Type taskGroup, fixed_array<TaskBucket>& buckets)
{
ASSERT(threadContext, "Sanity check failed!");
ASSERT(currentTask, "Sanity check failed!");
ASSERT(taskGroup < TaskGroup::COUNT, "Sanity check failed!");
// ATTENTION !
// copy current task description to stack.
// pointer to parentTask alive until all child task finished
TaskDesc parentTask = *currentTask;
ASSERT(threadContext->thread.IsCurrentThread(), "Thread context sanity check failed");
for (size_t bucketIndex = 0; bucketIndex < buckets.size(); ++bucketIndex)
{
TaskBucket& bucket = buckets[bucketIndex];
for (size_t i = 0; i < bucket.count; ++i)
bucket.tasks[i].desc.parentTask = &parentTask;
}
//add subtask to scheduler
threadContext->taskScheduler->RunTasksImpl(taskGroup, buckets, &parentTask);
//
ASSERT(threadContext->thread.IsCurrentThread(), "Thread context sanity check failed");
//switch to scheduler
Fiber::SwitchTo(fiber, threadContext->schedulerFiber);
}
TaskScheduler::GroupStats::GroupStats()
{
inProgressTaskCount.Set(0);
allDoneEvent.Create( EventReset::MANUAL, true );
}
TaskScheduler::TaskScheduler()
: roundRobinThreadIndex(0)
{
//query number of processor
threadsCount = Max(Thread::GetNumberOfHardwareThreads() - 2, 1);
if (threadsCount > MT_MAX_THREAD_COUNT)
{
threadsCount = MT_MAX_THREAD_COUNT;
}
// create fiber pool
for (uint32 i = 0; i < MT_MAX_FIBERS_COUNT; i++)
{
FiberContext& context = fiberContext[i];
context.fiber.Create(MT_FIBER_STACK_SIZE, FiberMain, &context);
availableFibers.Push( &context );
}
// create worker thread pool
for (uint32 i = 0; i < threadsCount; i++)
{
threadContext[i].taskScheduler = this;
threadContext[i].thread.Start( MT_SCHEDULER_STACK_SIZE, ThreadMain, &threadContext[i] );
}
}
TaskScheduler::~TaskScheduler()
{
for (uint32 i = 0; i < threadsCount; i++)
{
threadContext[i].state.Set(ThreadState::EXIT);
threadContext[i].hasNewTasksEvent.Signal();
}
for (uint32 i = 0; i < threadsCount; i++)
{
threadContext[i].thread.Stop();
}
}
FiberContext* TaskScheduler::RequestFiberContext()
{
FiberContext *fiber = nullptr;
if (!availableFibers.TryPop(fiber))
{
ASSERT(false, "Fibers pool is empty");
}
return fiber;
}
void TaskScheduler::ReleaseFiberContext(FiberContext* fiberContext)
{
ASSERT(fiberContext != nullptr, "Can't release nullptr Fiber");
fiberContext->currentGroup = TaskGroup::GROUP_UNDEFINED;
fiberContext->currentTask = nullptr;
availableFibers.Push(fiberContext);
}
void TaskScheduler::RestoreAwaitingTasks(TaskGroup::Type taskGroup)
{
ConcurrentQueueLIFO<TaskDesc> & groupQueue = waitTaskQueues[taskGroup];
//TODO: move awaiting tasks into execution thread queues
}
bool TaskScheduler::ExecuteTask (ThreadContext& context, const TaskDesc & taskDesc)
{
bool canDropExecutionContext = false;
TaskDesc taskInProgress = taskDesc;
for(int iteration = 0;;iteration++)
{
ASSERT(taskInProgress.taskFunc != nullptr, "Invalid task function pointer");
ASSERT(taskInProgress.fiberContext, "Invalid execution context.");
taskInProgress.fiberContext->threadContext = &context;
// update task status
taskInProgress.fiberContext->taskStatus = FiberTaskStatus::RUNNED;
ASSERT(context.thread.IsCurrentThread(), "Thread context sanity check failed");
ASSERT(taskInProgress.fiberContext->threadContext->thread.IsCurrentThread(), "Thread context sanity check failed");
// run current task code
Fiber::SwitchTo(context.schedulerFiber, taskInProgress.fiberContext->fiber);
// if task was done
if (taskInProgress.fiberContext->taskStatus == FiberTaskStatus::FINISHED)
{
TaskGroup::Type taskGroup = taskInProgress.fiberContext->currentGroup;
ASSERT(taskGroup < TaskGroup::COUNT, "Invalid group.");
//update group status
int groupTaskCount = context.taskScheduler->groupStats[taskGroup].inProgressTaskCount.Dec();
ASSERT(groupTaskCount >= 0, "Sanity check failed!");
if (groupTaskCount == 0)
{
//restore awaiting tasks
context.taskScheduler->RestoreAwaitingTasks(taskGroup);
context.taskScheduler->groupStats[taskGroup].allDoneEvent.Signal();
}
groupTaskCount = context.taskScheduler->allGroupStats.inProgressTaskCount.Dec();
ASSERT(groupTaskCount >= 0, "Sanity check failed!");
if (groupTaskCount == 0)
{
//notify all tasks in all group finished
context.taskScheduler->allGroupStats.allDoneEvent.Signal();
}
//raise up releasing task fiber flag
canDropExecutionContext = true;
//
if (iteration > 0)
{
context.taskScheduler->ReleaseTaskDescription(taskInProgress);
}
//
if (taskInProgress.parentTask != nullptr)
{
int subTasksCount = taskInProgress.parentTask->fiberContext->subtaskFibersCount.Dec();
ASSERT(subTasksCount >= 0, "Sanity check failed!");
if (subTasksCount == 0)
{
// this is a last subtask. restore parent task
TaskDesc * parent = taskInProgress.parentTask;
ASSERT(context.thread.IsCurrentThread(), "Thread context sanity check failed");
// WARNING!! Thread context can changed here! Set actual current thread context.
parent->fiberContext->threadContext = &context;
ASSERT(parent->fiberContext->threadContext->thread.IsCurrentThread(), "Thread context sanity check failed");
// copy parent to current task.
// can't just use pointer, because parent pointer is pointer on fiber stack
taskInProgress = *parent;
taskInProgress.fiberContext->currentTask = &taskInProgress;
} else
{
// subtask still not finished
// exiting
break;
}
} else
{
// no parent task
// exiting
break;
}
} else
{
if (taskInProgress.fiberContext->taskStatus == FiberTaskStatus::AWAITING)
{
// current task was yielded, due to awaiting another task group
// exiting
break;
} else
{
// current task was yielded, due to subtask spawn
// exiting
break;
}
}
} // loop
return canDropExecutionContext;
}
void TaskScheduler::FiberMain(void* userData)
{
FiberContext& context = *(FiberContext*)(userData);
for(;;)
{
ASSERT(context.currentTask, "Invalid task in fiber context");
ASSERT(context.currentTask->taskFunc, "Invalid task function");
ASSERT(context.currentGroup < TaskGroup::COUNT, "Invalid task group");
ASSERT(context.threadContext, "Invalid thread context");
ASSERT(context.threadContext->thread.IsCurrentThread(), "Thread context sanity check failed");
context.currentTask->taskFunc( context, context.currentTask->userData );
context.taskStatus = FiberTaskStatus::FINISHED;
Fiber::SwitchTo(context.fiber, context.threadContext->schedulerFiber);
}
}
void TaskScheduler::ThreadMain( void* userData )
{
ThreadContext& context = *(ThreadContext*)(userData);
ASSERT(context.taskScheduler, "Task scheduler must be not null!");
context.schedulerFiber.CreateFromThread(context.thread);
while(context.state.Get() != ThreadState::EXIT)
{
GroupedTask task;
if (context.queue.TryPop(task))
{
//there is a new task
context.taskScheduler->PrepareTaskDescription(task);
ASSERT(task.desc.fiberContext, "Can't get execution context from pool");
ASSERT(task.desc.fiberContext->currentTask->taskFunc, "Sanity check failed");
for(;;)
{
// prevent invalid fiber resume from child tasks, before ExecuteTask is done
task.desc.fiberContext->subtaskFibersCount.Inc();
bool canDropContext = ExecuteTask(context, task.desc);
int subtaskCount = task.desc.fiberContext->subtaskFibersCount.Dec();
ASSERT(subtaskCount >= 0, "Sanity check failed");
bool taskIsFinished = (task.desc.fiberContext->taskStatus == FiberTaskStatus::FINISHED);
bool taskIsAwait = (task.desc.fiberContext->taskStatus == FiberTaskStatus::AWAITING);
if (canDropContext)
{
context.taskScheduler->ReleaseTaskDescription(task.desc);
ASSERT(task.desc.fiberContext == nullptr, "Sanity check failed");
}
// if subtasks still exist, drop current task execution. current task will be resumed when last subtask finished
if (subtaskCount > 0)
{
break;
}
//if task is finished or task is in await state drop execution
if (taskIsFinished || taskIsAwait)
{
break;
}
// no subtasks and status is not finished, this mean all subtasks already finished before parent return from ExecuteTask
// continue task execution
}
if (task.desc.fiberContext)
task.desc.fiberContext->currentTask = nullptr;
}
else
{
//TODO: can try to steal tasks from other threads
context.hasNewTasksEvent.Wait(2000);
}
}
}
void TaskScheduler::RunTasksImpl(TaskGroup::Type taskGroup, fixed_array<TaskBucket>& buckets, TaskDesc * parentTask)
{
ASSERT(taskGroup < TaskGroup::COUNT, "Invalid group.");
size_t count = 0;
for (size_t i = 0; i < buckets.size(); ++i)
count += buckets[i].count;
if (parentTask)
{
parentTask->fiberContext->subtaskFibersCount.Add((uint32)count);
}
for (size_t i = 0; i < buckets.size(); ++i)
{
int bucketIndex = roundRobinThreadIndex.Inc() % threadsCount;
ThreadContext & context = threadContext[bucketIndex];
TaskBucket& bucket = buckets[i];
allGroupStats.allDoneEvent.Reset();
allGroupStats.inProgressTaskCount.Add((uint32)bucket.count);
groupStats[taskGroup].allDoneEvent.Reset();
groupStats[taskGroup].inProgressTaskCount.Add((uint32)bucket.count);
context.queue.PushRange(bucket.tasks, bucket.count);
context.hasNewTasksEvent.Signal();
}
}
bool TaskScheduler::WaitGroup(TaskGroup::Type group, uint32 milliseconds)
{
VERIFY(IsWorkerThread() == false, "Can't use WaitGroup inside Task. Use FiberContext.WaitGroupAndYield() instead.", return false);
return groupStats[group].allDoneEvent.Wait(milliseconds);
}
bool TaskScheduler::WaitAll(uint32 milliseconds)
{
VERIFY(IsWorkerThread() == false, "Can't use WaitAll inside Task.", return false);
return allGroupStats.allDoneEvent.Wait(milliseconds);
}
bool TaskScheduler::IsEmpty()
{
for (uint32 i = 0; i < MT_MAX_THREAD_COUNT; i++)
{
if (!threadContext[i].queue.IsEmpty())
{
return false;
}
}
return true;
}
uint32 TaskScheduler::GetWorkerCount() const
{
return threadsCount;
}
bool TaskScheduler::IsWorkerThread() const
{
for (uint32 i = 0; i < MT_MAX_THREAD_COUNT; i++)
{
if (threadContext[i].thread.IsCurrentThread())
{
return true;
}
}
return false;
}
void TaskScheduler::ReleaseTaskDescription(TaskDesc& description)
{
ReleaseFiberContext(description.fiberContext);
description.fiberContext = nullptr;
}
bool TaskScheduler::PrepareTaskDescription(GroupedTask& task)
{
task.desc.fiberContext = RequestFiberContext();
task.desc.fiberContext->currentTask = &task.desc;
task.desc.fiberContext->currentGroup = task.group;
return task.desc.fiberContext != nullptr;
}
}
<commit_msg>Small improvement in diagnostic<commit_after>#include "Scheduler.h"
//#include "Assert.h"
//TODO: Split to files. One file - one class.
namespace MT
{
static const size_t TASK_BUFFER_CAPACITY = 4096;
ThreadContext::ThreadContext()
: taskScheduler(nullptr)
, hasNewTasksEvent(EventReset::AUTOMATIC, true)
, state(ThreadState::ALIVE)
, descBuffer(TASK_BUFFER_CAPACITY)
{
}
ThreadContext::~ThreadContext()
{
}
FiberContext::FiberContext()
: currentTask(nullptr)
, currentGroup(TaskGroup::GROUP_UNDEFINED)
, threadContext(nullptr)
, taskStatus(FiberTaskStatus::UNKNOWN)
, subtaskFibersCount(0)
{
}
void FiberContext::WaitGroupAndYield(TaskGroup::Type group)
{
VERIFY(group != currentGroup, "Can't wait the same group. Deadlock detected!", return);
VERIFY(group < TaskGroup::COUNT, "Invalid group!", return);
ASSERT(threadContext->taskScheduler->IsWorkerThread(), "Can't use WaitGroup outside Task. Use TaskScheduler.WaitGroup() instead.");
ConcurrentQueueLIFO<TaskDesc> & groupQueue = threadContext->taskScheduler->waitTaskQueues[group];
//change status
taskStatus = FiberTaskStatus::AWAITING;
// copy current task to awaiting queue
groupQueue.Push(*currentTask);
//
ASSERT(threadContext->thread.IsCurrentThread(), "Thread context sanity check failed");
//switch to scheduler
Fiber::SwitchTo(fiber, threadContext->schedulerFiber);
}
void FiberContext::RunSubtasksAndYield(TaskGroup::Type taskGroup, fixed_array<TaskBucket>& buckets)
{
ASSERT(threadContext, "Sanity check failed!");
ASSERT(currentTask, "Sanity check failed!");
ASSERT(taskGroup < TaskGroup::COUNT, "Sanity check failed!");
// ATTENTION !
// copy current task description to stack.
// pointer to parentTask alive until all child task finished
TaskDesc parentTask = *currentTask;
ASSERT(threadContext->thread.IsCurrentThread(), "Thread context sanity check failed");
for (size_t bucketIndex = 0; bucketIndex < buckets.size(); ++bucketIndex)
{
TaskBucket& bucket = buckets[bucketIndex];
for (size_t i = 0; i < bucket.count; ++i)
bucket.tasks[i].desc.parentTask = &parentTask;
}
//add subtask to scheduler
threadContext->taskScheduler->RunTasksImpl(taskGroup, buckets, &parentTask);
//
ASSERT(threadContext->thread.IsCurrentThread(), "Thread context sanity check failed");
//switch to scheduler
Fiber::SwitchTo(fiber, threadContext->schedulerFiber);
}
TaskScheduler::GroupStats::GroupStats()
{
inProgressTaskCount.Set(0);
allDoneEvent.Create( EventReset::MANUAL, true );
}
TaskScheduler::TaskScheduler()
: roundRobinThreadIndex(0)
{
//query number of processor
threadsCount = Max(Thread::GetNumberOfHardwareThreads() - 2, 1);
if (threadsCount > MT_MAX_THREAD_COUNT)
{
threadsCount = MT_MAX_THREAD_COUNT;
}
// create fiber pool
for (uint32 i = 0; i < MT_MAX_FIBERS_COUNT; i++)
{
FiberContext& context = fiberContext[i];
context.fiber.Create(MT_FIBER_STACK_SIZE, FiberMain, &context);
availableFibers.Push( &context );
}
// create worker thread pool
for (uint32 i = 0; i < threadsCount; i++)
{
threadContext[i].taskScheduler = this;
threadContext[i].thread.Start( MT_SCHEDULER_STACK_SIZE, ThreadMain, &threadContext[i] );
}
}
TaskScheduler::~TaskScheduler()
{
for (uint32 i = 0; i < threadsCount; i++)
{
threadContext[i].state.Set(ThreadState::EXIT);
threadContext[i].hasNewTasksEvent.Signal();
}
for (uint32 i = 0; i < threadsCount; i++)
{
threadContext[i].thread.Stop();
}
}
FiberContext* TaskScheduler::RequestFiberContext()
{
FiberContext *fiber = nullptr;
if (!availableFibers.TryPop(fiber))
{
ASSERT(false, "Fibers pool is empty");
}
return fiber;
}
void TaskScheduler::ReleaseFiberContext(FiberContext* fiberContext)
{
ASSERT(fiberContext != nullptr, "Can't release nullptr Fiber");
fiberContext->currentGroup = TaskGroup::GROUP_UNDEFINED;
fiberContext->currentTask = nullptr;
availableFibers.Push(fiberContext);
}
void TaskScheduler::RestoreAwaitingTasks(TaskGroup::Type taskGroup)
{
ConcurrentQueueLIFO<TaskDesc> & groupQueue = waitTaskQueues[taskGroup];
//TODO: move awaiting tasks into execution thread queues
}
bool TaskScheduler::ExecuteTask (ThreadContext& context, const TaskDesc & taskDesc)
{
bool canDropExecutionContext = false;
TaskDesc taskInProgress = taskDesc;
for(int iteration = 0;;iteration++)
{
ASSERT(taskInProgress.taskFunc != nullptr, "Invalid task function pointer");
ASSERT(taskInProgress.fiberContext, "Invalid execution context.");
taskInProgress.fiberContext->threadContext = &context;
// update task status
taskInProgress.fiberContext->taskStatus = FiberTaskStatus::RUNNED;
ASSERT(context.thread.IsCurrentThread(), "Thread context sanity check failed");
ASSERT(taskInProgress.fiberContext->threadContext->thread.IsCurrentThread(), "Thread context sanity check failed");
// run current task code
Fiber::SwitchTo(context.schedulerFiber, taskInProgress.fiberContext->fiber);
// if task was done
if (taskInProgress.fiberContext->taskStatus == FiberTaskStatus::FINISHED)
{
TaskGroup::Type taskGroup = taskInProgress.fiberContext->currentGroup;
ASSERT(taskGroup < TaskGroup::COUNT, "Invalid group.");
//update group status
int groupTaskCount = context.taskScheduler->groupStats[taskGroup].inProgressTaskCount.Dec();
ASSERT(groupTaskCount >= 0, "Sanity check failed!");
if (groupTaskCount == 0)
{
//restore awaiting tasks
context.taskScheduler->RestoreAwaitingTasks(taskGroup);
context.taskScheduler->groupStats[taskGroup].allDoneEvent.Signal();
}
groupTaskCount = context.taskScheduler->allGroupStats.inProgressTaskCount.Dec();
ASSERT(groupTaskCount >= 0, "Sanity check failed!");
if (groupTaskCount == 0)
{
//notify all tasks in all group finished
context.taskScheduler->allGroupStats.allDoneEvent.Signal();
}
//raise up releasing task fiber flag
canDropExecutionContext = true;
//
if (iteration > 0)
{
context.taskScheduler->ReleaseTaskDescription(taskInProgress);
}
//
if (taskInProgress.parentTask != nullptr)
{
int subTasksCount = taskInProgress.parentTask->fiberContext->subtaskFibersCount.Dec();
ASSERT(subTasksCount >= 0, "Sanity check failed!");
if (subTasksCount == 0)
{
// this is a last subtask. restore parent task
TaskDesc * parent = taskInProgress.parentTask;
ASSERT(context.thread.IsCurrentThread(), "Thread context sanity check failed");
// WARNING!! Thread context can changed here! Set actual current thread context.
parent->fiberContext->threadContext = &context;
ASSERT(parent->fiberContext->threadContext->thread.IsCurrentThread(), "Thread context sanity check failed");
// copy parent to current task.
// can't just use pointer, because parent pointer is pointer on fiber stack
taskInProgress = *parent;
taskInProgress.fiberContext->currentTask = &taskInProgress;
} else
{
// subtask still not finished
// exiting
break;
}
} else
{
// no parent task
// exiting
break;
}
}
else if (taskInProgress.fiberContext->taskStatus == FiberTaskStatus::AWAITING)
{
// current task was yielded, due to awaiting another task group
// exiting
break;
}
else if (taskInProgress.fiberContext->taskStatus == FiberTaskStatus::RUNNED)
{
// current task was yielded, due to subtask spawn
// exiting
break;
}
else
{
ASSERT(false, "State is not supperted. Undefined behaviour!")
}
} // loop
return canDropExecutionContext;
}
void TaskScheduler::FiberMain(void* userData)
{
FiberContext& context = *(FiberContext*)(userData);
for(;;)
{
ASSERT(context.currentTask, "Invalid task in fiber context");
ASSERT(context.currentTask->taskFunc, "Invalid task function");
ASSERT(context.currentGroup < TaskGroup::COUNT, "Invalid task group");
ASSERT(context.threadContext, "Invalid thread context");
ASSERT(context.threadContext->thread.IsCurrentThread(), "Thread context sanity check failed");
context.currentTask->taskFunc( context, context.currentTask->userData );
context.taskStatus = FiberTaskStatus::FINISHED;
Fiber::SwitchTo(context.fiber, context.threadContext->schedulerFiber);
}
}
void TaskScheduler::ThreadMain( void* userData )
{
ThreadContext& context = *(ThreadContext*)(userData);
ASSERT(context.taskScheduler, "Task scheduler must be not null!");
context.schedulerFiber.CreateFromThread(context.thread);
while(context.state.Get() != ThreadState::EXIT)
{
GroupedTask task;
if (context.queue.TryPop(task))
{
//there is a new task
context.taskScheduler->PrepareTaskDescription(task);
ASSERT(task.desc.fiberContext, "Can't get execution context from pool");
ASSERT(task.desc.fiberContext->currentTask->taskFunc, "Sanity check failed");
for(;;)
{
// prevent invalid fiber resume from child tasks, before ExecuteTask is done
task.desc.fiberContext->subtaskFibersCount.Inc();
bool canDropContext = ExecuteTask(context, task.desc);
int subtaskCount = task.desc.fiberContext->subtaskFibersCount.Dec();
ASSERT(subtaskCount >= 0, "Sanity check failed");
bool taskIsFinished = (task.desc.fiberContext->taskStatus == FiberTaskStatus::FINISHED);
bool taskIsAwait = (task.desc.fiberContext->taskStatus == FiberTaskStatus::AWAITING);
if (canDropContext)
{
context.taskScheduler->ReleaseTaskDescription(task.desc);
ASSERT(task.desc.fiberContext == nullptr, "Sanity check failed");
}
// if subtasks still exist, drop current task execution. current task will be resumed when last subtask finished
if (subtaskCount > 0)
{
break;
}
//if task is finished or task is in await state drop execution
if (taskIsFinished || taskIsAwait)
{
break;
}
// no subtasks and status is not finished, this mean all subtasks already finished before parent return from ExecuteTask
// continue task execution
}
if (task.desc.fiberContext)
task.desc.fiberContext->currentTask = nullptr;
}
else
{
//TODO: can try to steal tasks from other threads
context.hasNewTasksEvent.Wait(2000);
}
}
}
void TaskScheduler::RunTasksImpl(TaskGroup::Type taskGroup, fixed_array<TaskBucket>& buckets, TaskDesc * parentTask)
{
ASSERT(taskGroup < TaskGroup::COUNT, "Invalid group.");
size_t count = 0;
for (size_t i = 0; i < buckets.size(); ++i)
count += buckets[i].count;
if (parentTask)
{
parentTask->fiberContext->subtaskFibersCount.Add((uint32)count);
}
for (size_t i = 0; i < buckets.size(); ++i)
{
int bucketIndex = roundRobinThreadIndex.Inc() % threadsCount;
ThreadContext & context = threadContext[bucketIndex];
TaskBucket& bucket = buckets[i];
allGroupStats.allDoneEvent.Reset();
allGroupStats.inProgressTaskCount.Add((uint32)bucket.count);
groupStats[taskGroup].allDoneEvent.Reset();
groupStats[taskGroup].inProgressTaskCount.Add((uint32)bucket.count);
context.queue.PushRange(bucket.tasks, bucket.count);
context.hasNewTasksEvent.Signal();
}
}
bool TaskScheduler::WaitGroup(TaskGroup::Type group, uint32 milliseconds)
{
VERIFY(IsWorkerThread() == false, "Can't use WaitGroup inside Task. Use FiberContext.WaitGroupAndYield() instead.", return false);
return groupStats[group].allDoneEvent.Wait(milliseconds);
}
bool TaskScheduler::WaitAll(uint32 milliseconds)
{
VERIFY(IsWorkerThread() == false, "Can't use WaitAll inside Task.", return false);
return allGroupStats.allDoneEvent.Wait(milliseconds);
}
bool TaskScheduler::IsEmpty()
{
for (uint32 i = 0; i < MT_MAX_THREAD_COUNT; i++)
{
if (!threadContext[i].queue.IsEmpty())
{
return false;
}
}
return true;
}
uint32 TaskScheduler::GetWorkerCount() const
{
return threadsCount;
}
bool TaskScheduler::IsWorkerThread() const
{
for (uint32 i = 0; i < MT_MAX_THREAD_COUNT; i++)
{
if (threadContext[i].thread.IsCurrentThread())
{
return true;
}
}
return false;
}
void TaskScheduler::ReleaseTaskDescription(TaskDesc& description)
{
ReleaseFiberContext(description.fiberContext);
description.fiberContext = nullptr;
}
bool TaskScheduler::PrepareTaskDescription(GroupedTask& task)
{
task.desc.fiberContext = RequestFiberContext();
task.desc.fiberContext->currentTask = &task.desc;
task.desc.fiberContext->currentGroup = task.group;
return task.desc.fiberContext != nullptr;
}
}
<|endoftext|> |
<commit_before>#include "cinder/app/AppNative.h"
#include "cinder/gl/gl.h"
using namespace ci;
using namespace ci::app;
using namespace std;
class RetinaSampleApp : public AppNative {
public:
void prepareSettings( Settings *settings ) override;
void setup();
void mouseDrag( MouseEvent event );
void mouseDown( MouseEvent event );
void keyDown( KeyEvent event );
void displayChange();
void draw();
// This will maintain a list of points which we will draw line segments between
list<Vec2f> mPoints;
};
void RetinaSampleApp::prepareSettings( Settings *settings )
{
settings->setWindowSize( 800, 600 );
settings->enableHighDensityDisplay();
console() << "settings->getHighDensityDisplayEnabled()= " << settings->isHighDensityDisplayEnabled() << endl;
}
void RetinaSampleApp::setup()
{
getWindow()->getSignalDisplayChange().connect( std::bind( &RetinaSampleApp::displayChange, this ) );
}
void RetinaSampleApp::mouseDrag( MouseEvent event )
{
console() << event.getPos() << endl;
mPoints.push_back( event.getPos() );
}
void RetinaSampleApp::mouseDown( MouseEvent event )
{
console() << "getWindowContentScale = " << getWindowContentScale() << endl;
console() << event.getPos() << endl;
}
void RetinaSampleApp::keyDown( KeyEvent event )
{
if( event.getChar() == 'f' )
setFullScreen( ! isFullScreen() );
}
void RetinaSampleApp::displayChange()
{
console() << "Window display changed: " << getWindow()->getDisplay()->getBounds() << std::endl;
console() << "ContentScale = " << getWindowContentScale() << endl;
console() << "getWindowCenter() = " << getWindowCenter() << endl;
console() << "getWindow()->toPixels( 1.0f ) = " << toPixels( 1.0f ) << endl;
}
void RetinaSampleApp::draw()
{
// float c = getWindowContentScale();
gl::clear( Color( 0.1f, 0.1f, 0.15f ) );
gl::color( 1.0f, 0.5f, 0.25f );
gl::pushMatrices();
gl::begin( GL_LINE_STRIP );
glLineWidth( getWindow()->toPixels( 1.0f ) );
for( auto pointIter = mPoints.begin(); pointIter != mPoints.end(); ++pointIter ) {
gl::vertex( *pointIter );
}
gl::end();
gl::popMatrices();
gl::pushMatrices();
glColor3f( 1.0f, 0.2f, 0.15f );
gl::translate( getWindowCenter() );
gl::rotate( getElapsedSeconds() * 5 );
gl::drawSolidRect( Rectf( toPixels( Area( -100, -100, 100, 100 ) ) ) );
gl::popMatrices();
}
CINDER_APP_NATIVE( RetinaSampleApp, RendererGl )
<commit_msg>samples/RetinaSample to reflect more common use case<commit_after>#include "cinder/app/AppNative.h"
#include "cinder/gl/gl.h"
using namespace ci;
using namespace ci::app;
using namespace std;
class RetinaSampleApp : public AppNative {
public:
void prepareSettings( Settings *settings ) override;
void setup();
void mouseDrag( MouseEvent event );
void keyDown( KeyEvent event );
void displayChange();
void draw();
// This will maintain a list of points which we will draw line segments between
list<Vec2f> mPoints;
};
void RetinaSampleApp::prepareSettings( Settings *settings )
{
settings->enableHighDensityDisplay();
console() << "settings->getHighDensityDisplayEnabled()= " << settings->isHighDensityDisplayEnabled() << endl;
}
void RetinaSampleApp::setup()
{
getWindow()->getSignalDisplayChange().connect( std::bind( &RetinaSampleApp::displayChange, this ) );
}
void RetinaSampleApp::mouseDrag( MouseEvent event )
{
mPoints.push_back( event.getPos() );
}
void RetinaSampleApp::keyDown( KeyEvent event )
{
if( event.getChar() == 'f' )
setFullScreen( ! isFullScreen() );
}
void RetinaSampleApp::displayChange()
{
console() << "Window display changed: " << getWindow()->getDisplay()->getBounds() << std::endl;
console() << "ContentScale = " << getWindowContentScale() << endl;
console() << "getWindowCenter() = " << getWindowCenter() << endl;
console() << "getWindow()->toPixels( 1.0f ) = " << toPixels( 1.0f ) << endl;
}
void RetinaSampleApp::draw()
{
gl::clear( Color( 0.1f, 0.1f, 0.15f ) );
gl::color( 1.0f, 0.5f, 0.25f );
gl::pushMatrices();
glLineWidth( getWindow()->toPixels( 1.0f ) );
gl::begin( GL_LINE_STRIP );
for( auto pointIter = mPoints.begin(); pointIter != mPoints.end(); ++pointIter ) {
gl::vertex( *pointIter );
}
gl::end();
gl::popMatrices();
gl::pushMatrices();
glColor3f( 1.0f, 0.2f, 0.15f );
gl::translate( getWindowCenter() );
gl::rotate( getElapsedSeconds() * 5 );
gl::drawSolidRect( Rectf( Area( -100, -100, 100, 100 ) ) );
gl::popMatrices();
}
CINDER_APP_NATIVE( RetinaSampleApp, RendererGl )<|endoftext|> |
<commit_before>/*
---------------------------------------------------------------------------------
FIXME: Consider avoiding using STL in this instrumentation. Which
might improve performance
FIXME: Try to avoid current requirement of
-finstrument-functions-exclude-file-list=/usr/
-finstrument-functions-exclude-function-list=static_initialization_and_destruction
---------------------------------------------------------------------------------
*/
#include "libunwind_wtf.h"
#include <algorithm>
#include <queue>
#include <map>
#include <set>
#include <vector>
#include <thread>
#define UNW_LOCAL_ONLY
#include <libunwind.h>
#define WTF_ENABLE 1
#include <wtf/macros.h>
// not needed for profiling to function. Just for main().
#include <chrono>
using namespace std;
namespace
{
using Event = ::wtf::ScopedEventIf<kWtfEnabledForNamespace>;
using Scope = ::wtf::AutoScopeIf<kWtfEnabledForNamespace>;
using EventPtr = shared_ptr<Event>;
using ScopePtr = unique_ptr<Scope>;
inline unordered_map<string, queue<ScopePtr>>& gMap() __attribute__((no_instrument_function));
inline unordered_map<string, queue<ScopePtr>>& gMap()
{
// TODO: measure timings with rwlock and compare
thread_local unordered_map<string, queue<ScopePtr>> tlMap {};
return tlMap;
};
inline map<void*, string>& gFuncNamesMap() __attribute__((no_instrument_function));
inline map<void*, string>& gFuncNamesMap()
{
// TODO: measure timings with rwlock and compare
thread_local map<void*, string> tlFuncNamesMap {};
return tlFuncNamesMap;
};
inline void ensureFunctionName(void* caller) __attribute__((no_instrument_function));
inline void ensureFunctionName(void* caller)
{
if (gFuncNamesMap().find(caller) != gFuncNamesMap().end())
return;
// FIXME: handle errors appropriately
unw_context_t ctx;
unw_cursor_t c;
unw_getcontext(&ctx);
unw_init_local(&c, &ctx);
unw_step(&c);
unw_step(&c);
thread_local char name[200];
unw_word_t offset;
unw_get_proc_name(&c, name, 200, &offset);
gFuncNamesMap()[caller] = name;
}
}
extern "C"
{
void __cyg_profile_func_enter (void *func, void *caller)
{
WTF_AUTO_THREAD_ENABLE();
ensureFunctionName(caller);
::wtf::ScopedEventIf<kWtfEnabledForNamespace> __wtf_scope_event0_35{gFuncNamesMap()[caller].c_str()};
ScopePtr s(new Scope(__wtf_scope_event0_35));
s->Enter();
gMap()[gFuncNamesMap()[caller]].emplace(std::move(s));
}
void __cyg_profile_func_exit (void *func, void *caller)
{
gMap()[gFuncNamesMap()[caller]].pop();
}
} //extern C
void saveProfiling(const char* filename)
{
::wtf::Runtime::GetInstance()->SaveToFile(filename);
}
<commit_msg>Few small changes: removed include, added a fixme<commit_after>/*
---------------------------------------------------------------------------------
FIXME: Consider avoiding using STL in this instrumentation. Which
might improve performance
FIXME: Try to avoid current requirement of
-finstrument-functions-exclude-file-list=/usr/
-finstrument-functions-exclude-function-list=static_initialization_and_destruction
FIXME: symbol visibility
---------------------------------------------------------------------------------
*/
#include "libunwind_wtf.h"
#include <algorithm>
#include <queue>
#include <map>
#include <set>
#include <vector>
#include <thread>
#define UNW_LOCAL_ONLY
#include <libunwind.h>
#define WTF_ENABLE 1
#include <wtf/macros.h>
using namespace std;
namespace
{
using Event = ::wtf::ScopedEventIf<kWtfEnabledForNamespace>;
using Scope = ::wtf::AutoScopeIf<kWtfEnabledForNamespace>;
using EventPtr = shared_ptr<Event>;
using ScopePtr = unique_ptr<Scope>;
inline unordered_map<string, queue<ScopePtr>>& gMap() __attribute__((no_instrument_function));
inline unordered_map<string, queue<ScopePtr>>& gMap()
{
// TODO: measure timings with rwlock and compare
thread_local unordered_map<string, queue<ScopePtr>> tlMap {};
return tlMap;
};
inline map<void*, string>& gFuncNamesMap() __attribute__((no_instrument_function));
inline map<void*, string>& gFuncNamesMap()
{
// TODO: measure timings with rwlock and compare
thread_local map<void*, string> tlFuncNamesMap {};
return tlFuncNamesMap;
};
inline void ensureFunctionName(void* caller) __attribute__((no_instrument_function));
inline void ensureFunctionName(void* caller)
{
if (gFuncNamesMap().find(caller) != gFuncNamesMap().end())
return;
// FIXME: handle errors appropriately
unw_context_t ctx;
unw_cursor_t c;
unw_getcontext(&ctx);
unw_init_local(&c, &ctx);
unw_step(&c);
unw_step(&c);
thread_local char name[200];
unw_word_t offset;
unw_get_proc_name(&c, name, 200, &offset);
gFuncNamesMap()[caller] = name;
}
}
extern "C"
{
void __cyg_profile_func_enter (void *func, void *caller)
{
WTF_AUTO_THREAD_ENABLE();
ensureFunctionName(caller);
::wtf::ScopedEventIf<kWtfEnabledForNamespace> __wtf_scope_event0_35{gFuncNamesMap()[caller].c_str()};
ScopePtr s(new Scope(__wtf_scope_event0_35));
s->Enter();
gMap()[gFuncNamesMap()[caller]].emplace(std::move(s));
}
void __cyg_profile_func_exit (void *func, void *caller)
{
gMap()[gFuncNamesMap()[caller]].pop();
}
} //extern C
void saveProfiling(const char* filename)
{
::wtf::Runtime::GetInstance()->SaveToFile(filename);
}
<|endoftext|> |
<commit_before>//
// Allocate objects smaller than a page.
//
#include "types.h"
#include "mmu.h"
#include "kernel.hh"
#include "spinlock.h"
#include "kalloc.hh"
#include "mtrace.h"
#include "cpu.hh"
// allocate in power-of-two sizes up to 2^KMMAX
// must be < 12
#define KMMAX 11
struct header {
struct header *next;
};
struct freelist {
struct header *buckets[KMMAX+1];
char name[MAXNAME];
struct spinlock lock;
};
struct freelist freelists[NCPU];
void
kminit(void)
{
for (int c = 0; c < NCPU; c++) {
freelists[c].name[0] = (char) c + '0';
safestrcpy(freelists[c].name+1, "freelist", MAXNAME-1);
initlock(&freelists[c].lock, freelists[c].name, LOCKSTAT_KMALLOC);
}
}
// get more space for freelists[c].buckets[b]
void
morecore(int c, int b)
{
char *p = kalloc();
if(p == 0)
return;
int sz = 1 << b;
for(char *q = p;
q + sz + sizeof(struct header) <= p + PGSIZE;
q += sz + sizeof(struct header)){
struct header *h = (struct header *) q;
h->next = freelists[c].buckets[b];
freelists[c].buckets[b] = h;
}
}
void *
kmalloc(u64 nbytes)
{
int nn = 1, b = 0;
void *r = 0;
struct header *h;
int c = mycpu()->id;
while(nn < nbytes && b <= KMMAX){
nn *= 2;
b++;
}
if(nn != (1 << b))
panic("kmalloc oops");
if(b > KMMAX)
panic("kmalloc too big");
acquire(&freelists[c].lock);
if(freelists[c].buckets[b] == 0)
morecore(c, b);
h = freelists[c].buckets[b];
if(h){
freelists[c].buckets[b] = h->next;
r = h + 1;
h->next = (header*) (long) b;
}
release(&freelists[c].lock);
if (r)
mtlabel(mtrace_label_heap, r, nbytes, "kmalloc'ed", sizeof("kmalloc'ed"));
if(r == 0)
cprintf("kmalloc(%d) failed\n", (int) nbytes);
return r;
}
void
kmfree(void *ap)
{
int c = mycpu()->id;
struct header *h;
int b;
acquire(&freelists[c].lock);
h = (struct header *) ((char *)ap - sizeof(struct header));
b = (long) h->next;
if(b < 0 || b > KMMAX)
panic("kmfree bad bucket");
verifyfree((char*) ap, (1<<b) - sizeof(struct header));
if (ALLOC_MEMSET)
memset(ap, 3, (1<<b) - sizeof(struct header));
h->next = freelists[c].buckets[b];
freelists[c].buckets[b] = h;
mtunlabel(mtrace_label_heap, ap);
release(&freelists[c].lock);
}
int
kmalign(void **p, int align, u64 size)
{
void *mem = kmalloc(size + (align-1) + sizeof(void*));
char *amem = ((char*)mem) + sizeof(void*);
amem += align - ((uptr)amem & (align - 1));
((void**)amem)[-1] = mem;
*p = amem;
return 0;
}
void kmalignfree(void *mem)
{
kmfree(((void**)mem)[-1]);
}
<commit_msg>atomic (lockless) kmalloc<commit_after>//
// Allocate objects smaller than a page.
//
#include "types.h"
#include "mmu.h"
#include "kernel.hh"
#include "spinlock.h"
#include "kalloc.hh"
#include "mtrace.h"
#include "cpu.hh"
// allocate in power-of-two sizes up to 2^KMMAX
// must be < 12
#define KMMAX 11
struct header {
struct header *next;
};
struct freelist {
std::atomic<header*> buckets[KMMAX+1];
char name[MAXNAME];
};
struct freelist freelists[NCPU];
void
kminit(void)
{
for (int c = 0; c < NCPU; c++) {
freelists[c].name[0] = (char) c + '0';
safestrcpy(freelists[c].name+1, "freelist", MAXNAME-1);
}
}
// get more space for freelists[c].buckets[b]
int
morecore(int c, int b)
{
char *p = kalloc();
if(p == 0)
return -1;
int sz = 1 << b;
for(char *q = p;
q + sz + sizeof(struct header) <= p + PGSIZE;
q += sz + sizeof(struct header)){
struct header *h = (struct header *) q;
h->next = freelists[c].buckets[b];
freelists[c].buckets[b] = h;
}
return 0;
}
void *
kmalloc(u64 nbytes)
{
int nn = 1, b = 0;
while(nn < nbytes && b <= KMMAX){
nn *= 2;
b++;
}
if(nn != (1 << b))
panic("kmalloc oops");
if(b > KMMAX)
panic("kmalloc too big");
scoped_gc_epoch gc;
struct header *h;
int c = mycpu()->id;
for (;;) {
h = freelists[c].buckets[b];
if (!h) {
if (morecore(c, b) < 0) {
cprintf("kmalloc(%d) failed\n", (int) nbytes);
return 0;
}
} else {
if (cmpxch(&freelists[c].buckets[b], h, h->next))
break;
}
}
void *r = h + 1;
h->next = (header*) (long) b;
mtlabel(mtrace_label_heap, r, nbytes, "kmalloc'ed", sizeof("kmalloc'ed"));
return r;
}
void
kmfree(void *ap)
{
int c = mycpu()->id;
struct header *h;
int b;
h = (struct header *) ((char *)ap - sizeof(struct header));
b = (long) h->next;
if(b < 0 || b > KMMAX)
panic("kmfree bad bucket");
verifyfree((char*) ap, (1<<b) - sizeof(struct header));
if (ALLOC_MEMSET)
memset(ap, 3, (1<<b) - sizeof(struct header));
h->next = freelists[c].buckets[b];
while (!cmpxch_update(&freelists[c].buckets[b], &h->next, h))
; /* spin */
mtunlabel(mtrace_label_heap, ap);
}
int
kmalign(void **p, int align, u64 size)
{
void *mem = kmalloc(size + (align-1) + sizeof(void*));
char *amem = ((char*)mem) + sizeof(void*);
amem += align - ((uptr)amem & (align - 1));
((void**)amem)[-1] = mem;
*p = amem;
return 0;
}
void kmalignfree(void *mem)
{
kmfree(((void**)mem)[-1]);
}
<|endoftext|> |
<commit_before>#include "module_scanningsonar.h"
#include <QtCore>
#include <stdio.h>
#include "scanningsonar_form.h"
#include "sonarreturndata.h"
#include "sonardatasourceserial.h"
#include "sonardatasourcefile.h"
#include "sonardatacsvrecorder.h"
#include "sonardata852recorder.h"
#include <Module_ThrusterControlLoop/module_thrustercontrolloop.h>
#include <Module_Simulation/module_simulation.h>
Module_ScanningSonar::Module_ScanningSonar(QString id, Module_Simulation *sim)
: RobotModule(id)
{
this->sim = sim;
setDefaultValue("serialPort", "COM1");
setDefaultValue("range", 50);
setDefaultValue("gain", 20);
setDefaultValue("trainAngle", 70);
setDefaultValue("sectorWidth", 120);
setDefaultValue("stepSize", 1);
setDefaultValue("pulseLength", 127);
setDefaultValue("dataPoints", 25);
setDefaultValue("switchDelay", 0);
setDefaultValue("frequency", 0);
setDefaultValue("readFromFile", false);
setDefaultValue("recorderFilename", "output.txt");
setDefaultValue("fileReaderDelay", 100);
qRegisterMetaType<SonarReturnData>("SonarReturnData");
recorder = NULL;
source = NULL;
timer.moveToThread(this);
}
Module_ScanningSonar::~Module_ScanningSonar()
{
}
void Module_ScanningSonar::init()
{
connect(&timer,SIGNAL(timeout()), this, SLOT(doNextScan()));
connect(this, SIGNAL(enabled(bool)), this, SLOT(gotEnabledChanged(bool)));
/* connect simulation */
connect(sim,SIGNAL(newSonarData(SonarReturnData)), this, SLOT(refreshSimData(SonarReturnData)));
connect(this,SIGNAL(requestSonarSignal()),sim,SLOT(requestSonarSlot()));
reset();
}
void Module_ScanningSonar::terminate()
{
QTimer::singleShot(0,&timer,SLOT(stop()));
logger->debug("Destroying sonar data source and recorder.");
if (this->source != NULL) {
delete this->source;
source = NULL;
}
if (recorder != NULL) {
recorder->stop();
delete recorder;
recorder = NULL;
}
RobotModule::terminate();
}
void Module_ScanningSonar::refreshSimData(SonarReturnData data)
{
addData("currentHeading",data.getHeadPosition());
addData("range",data.getRange());
emit newSonarData(data);
emit dataChanged(this);
}
bool Module_ScanningSonar::doNextScan()
{
if(sim->isEnabled())
{
emit requestSonarSignal();
return true;
}
else
{
if (!source || !source->isOpen())
return false;
const SonarReturnData d = source->getNextPacket();
if (d.isPacketValid()) {
setHealthToOk();
addData("currentHeading", d.getHeadPosition());
addData("range", d.getRange());
emit newSonarData(d);
emit dataChanged(this);
return true;
} else {
setHealthToSick("Received bullshit. Dropping packet.");
return false;
}
}
}
void Module_ScanningSonar::reset()
{
RobotModule::reset();
logger->debug("Destroying and sonar data source.");
if (this->source != NULL) {
this->source->stop();
delete this->source;
source = NULL;
}
if (recorder != NULL) {
recorder->stop();
delete recorder;
recorder = NULL;
}
if (!isEnabled())
return;
if (getSettingsValue("enableRecording").toBool()) {
if (getSettingsValue("formatCSV").toBool())
recorder = new SonarDataCSVRecorder(*this);
else
recorder = new SonarData852Recorder(*this);
recorder->start();
}
if (sim->isEnabled())
{
// XXX: this is inadequate for small sonar ranges
timer.setInterval(100);
timer.start();
} else {
if (getSettingsValue("readFromFile").toBool())
{
source = new SonarDataSourceFile(*this, getSettingsValue("filename").toString());
if(!source->isOpen())
{
logger->error("source not opened");
source = NULL;
}
}
else {
source = new SonarDataSourceSerial(*this);
}
logger->debug("Restarting reader.");
if(source != NULL)
{
timer.setInterval(0); // timerSlot will block
timer.start();
setHealthToOk();
}
else
{
setHealthToSick("source is null");
}
}
}
QList<RobotModule*> Module_ScanningSonar::getDependencies()
{
QList<RobotModule*> ret;
ret.append(sim);
return ret;
}
QWidget* Module_ScanningSonar::createView(QWidget* parent)
{
return new ScanningSonarForm(this, parent);
}
void Module_ScanningSonar::gotEnabledChanged(bool state)
{
if (!state)
reset();
}
<commit_msg>ScanningSonar: Sleep if sonar is not working<commit_after>#include "module_scanningsonar.h"
#include <QtCore>
#include <stdio.h>
#include "scanningsonar_form.h"
#include "sonarreturndata.h"
#include "sonardatasourceserial.h"
#include "sonardatasourcefile.h"
#include "sonardatacsvrecorder.h"
#include "sonardata852recorder.h"
#include <Module_ThrusterControlLoop/module_thrustercontrolloop.h>
#include <Module_Simulation/module_simulation.h>
Module_ScanningSonar::Module_ScanningSonar(QString id, Module_Simulation *sim)
: RobotModule(id)
{
this->sim = sim;
setDefaultValue("serialPort", "COM1");
setDefaultValue("range", 50);
setDefaultValue("gain", 20);
setDefaultValue("trainAngle", 70);
setDefaultValue("sectorWidth", 120);
setDefaultValue("stepSize", 1);
setDefaultValue("pulseLength", 127);
setDefaultValue("dataPoints", 25);
setDefaultValue("switchDelay", 0);
setDefaultValue("frequency", 0);
setDefaultValue("readFromFile", false);
setDefaultValue("recorderFilename", "output.txt");
setDefaultValue("fileReaderDelay", 100);
qRegisterMetaType<SonarReturnData>("SonarReturnData");
recorder = NULL;
source = NULL;
timer.moveToThread(this);
}
Module_ScanningSonar::~Module_ScanningSonar()
{
}
void Module_ScanningSonar::init()
{
connect(&timer,SIGNAL(timeout()), this, SLOT(doNextScan()));
connect(this, SIGNAL(enabled(bool)), this, SLOT(gotEnabledChanged(bool)));
/* connect simulation */
connect(sim,SIGNAL(newSonarData(SonarReturnData)), this, SLOT(refreshSimData(SonarReturnData)));
connect(this,SIGNAL(requestSonarSignal()),sim,SLOT(requestSonarSlot()));
reset();
}
void Module_ScanningSonar::terminate()
{
QTimer::singleShot(0,&timer,SLOT(stop()));
logger->debug("Destroying sonar data source and recorder.");
if (this->source != NULL) {
delete this->source;
source = NULL;
}
if (recorder != NULL) {
recorder->stop();
delete recorder;
recorder = NULL;
}
RobotModule::terminate();
}
void Module_ScanningSonar::refreshSimData(SonarReturnData data)
{
addData("currentHeading",data.getHeadPosition());
addData("range",data.getRange());
emit newSonarData(data);
emit dataChanged(this);
}
bool Module_ScanningSonar::doNextScan()
{
if(sim->isEnabled())
{
emit requestSonarSignal();
return true;
}
else
{
if (!source || !source->isOpen()) {
msleep(100);
return false;
}
const SonarReturnData d = source->getNextPacket();
if (d.isPacketValid()) {
setHealthToOk();
addData("currentHeading", d.getHeadPosition());
addData("range", d.getRange());
emit newSonarData(d);
emit dataChanged(this);
return true;
} else {
setHealthToSick("Received bullshit. Dropping packet.");
return false;
}
}
}
void Module_ScanningSonar::reset()
{
RobotModule::reset();
logger->debug("Destroying and sonar data source.");
if (this->source != NULL) {
this->source->stop();
delete this->source;
source = NULL;
}
if (recorder != NULL) {
recorder->stop();
delete recorder;
recorder = NULL;
}
if (!isEnabled())
return;
if (getSettingsValue("enableRecording").toBool()) {
if (getSettingsValue("formatCSV").toBool())
recorder = new SonarDataCSVRecorder(*this);
else
recorder = new SonarData852Recorder(*this);
recorder->start();
}
if (sim->isEnabled())
{
// XXX: this is inadequate for small sonar ranges
timer.setInterval(100);
timer.start();
} else {
if (getSettingsValue("readFromFile").toBool())
{
source = new SonarDataSourceFile(*this, getSettingsValue("filename").toString());
if(!source->isOpen())
{
logger->error("source not opened");
source = NULL;
}
}
else {
source = new SonarDataSourceSerial(*this);
}
logger->debug("Restarting reader.");
if(source != NULL)
{
timer.setInterval(0); // timerSlot will block
timer.start();
setHealthToOk();
}
else
{
setHealthToSick("source is null");
}
}
}
QList<RobotModule*> Module_ScanningSonar::getDependencies()
{
QList<RobotModule*> ret;
ret.append(sim);
return ret;
}
QWidget* Module_ScanningSonar::createView(QWidget* parent)
{
return new ScanningSonarForm(this, parent);
}
void Module_ScanningSonar::gotEnabledChanged(bool state)
{
if (!state)
reset();
}
<|endoftext|> |
<commit_before>#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <pcl/io/openni_grabber.h>
#include <pcl/visualization/cloud_viewer.h>
#include <pcl/compression/octree_pointcloud_compression.h>
#include <stdio.h>
#include <sstream>
#include <stdlib.h>
using namespace std;
using namespace pcl;
using namespace pcl::octree;
#ifdef WIN32
# define sleep(x) Sleep((x)*1000)
#endif
class SimpleOpenNIViewer
{
public:
SimpleOpenNIViewer () :
viewer (" Point Cloud Compression Example")
{
}
void
cloud_cb_ (const pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr &cloud)
{
if (!viewer.wasStopped ())
{
// stringstream to store compressed point cloud
std::stringstream compressedData;
// output pointcloud
PointCloud<PointXYZRGB>::Ptr cloudOut (new PointCloud<PointXYZRGB> ());
// compress point cloud
PointCloudEncoder->encodePointCloud (cloud, compressedData);
// decompress point cloud
PointCloudDecoder->decodePointCloud (compressedData, cloudOut);
// show decompressed point cloud
viewer.showCloud (cloudOut);
}
}
void
run ()
{
bool showStatistics = true;
// for a full list of profiles see: /io/include/pcl/compression/compression_profiles.h
compression_Profiles_e compressionProfile = pcl::octree::MED_RES_ONLINE_COMPRESSION_WITH_COLOR;
// instantiate point cloud compression for encoding and decoding
PointCloudEncoder = new PointCloudCompression<PointXYZRGB> (compressionProfile, showStatistics);
PointCloudDecoder = new PointCloudCompression<PointXYZRGB> ();
// create a new grabber for OpenNI devices
pcl::Grabber* interface = new pcl::OpenNIGrabber ();
// make callback function from member function
boost::function<void
(const pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr&)> f = boost::bind (&SimpleOpenNIViewer::cloud_cb_, this, _1);
// connect callback function for desired signal. In this case its a point cloud with color values
boost::signals2::connection c = interface->registerCallback (f);
// start receiving point clouds
interface->start ();
while (!viewer.wasStopped ())
{
sleep (1);
}
interface->stop ();
// delete point cloud compression instances
delete (PointCloudEncoder);
delete (PointCloudDecoder);
}
pcl::visualization::CloudViewer viewer;
PointCloudCompression<PointXYZRGB>* PointCloudEncoder;
PointCloudCompression<PointXYZRGB>* PointCloudDecoder;
};
int
main (int argc, char **argv)
{
SimpleOpenNIViewer v;
v.run ();
return 0;
}
<commit_msg>fxining octree_pointcloud_compression.h include in tutorial<commit_after>#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <pcl/io/openni_grabber.h>
#include <pcl/visualization/cloud_viewer.h>
#include <pcl/io/octree_pointcloud_compression.h>
#include <stdio.h>
#include <sstream>
#include <stdlib.h>
using namespace std;
using namespace pcl;
using namespace pcl::octree;
#ifdef WIN32
# define sleep(x) Sleep((x)*1000)
#endif
class SimpleOpenNIViewer
{
public:
SimpleOpenNIViewer () :
viewer (" Point Cloud Compression Example")
{
}
void
cloud_cb_ (const pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr &cloud)
{
if (!viewer.wasStopped ())
{
// stringstream to store compressed point cloud
std::stringstream compressedData;
// output pointcloud
PointCloud<PointXYZRGB>::Ptr cloudOut (new PointCloud<PointXYZRGB> ());
// compress point cloud
PointCloudEncoder->encodePointCloud (cloud, compressedData);
// decompress point cloud
PointCloudDecoder->decodePointCloud (compressedData, cloudOut);
// show decompressed point cloud
viewer.showCloud (cloudOut);
}
}
void
run ()
{
bool showStatistics = true;
// for a full list of profiles see: /io/include/pcl/compression/compression_profiles.h
compression_Profiles_e compressionProfile = pcl::octree::MED_RES_ONLINE_COMPRESSION_WITH_COLOR;
// instantiate point cloud compression for encoding and decoding
PointCloudEncoder = new PointCloudCompression<PointXYZRGB> (compressionProfile, showStatistics);
PointCloudDecoder = new PointCloudCompression<PointXYZRGB> ();
// create a new grabber for OpenNI devices
pcl::Grabber* interface = new pcl::OpenNIGrabber ();
// make callback function from member function
boost::function<void
(const pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr&)> f = boost::bind (&SimpleOpenNIViewer::cloud_cb_, this, _1);
// connect callback function for desired signal. In this case its a point cloud with color values
boost::signals2::connection c = interface->registerCallback (f);
// start receiving point clouds
interface->start ();
while (!viewer.wasStopped ())
{
sleep (1);
}
interface->stop ();
// delete point cloud compression instances
delete (PointCloudEncoder);
delete (PointCloudDecoder);
}
pcl::visualization::CloudViewer viewer;
PointCloudCompression<PointXYZRGB>* PointCloudEncoder;
PointCloudCompression<PointXYZRGB>* PointCloudDecoder;
};
int
main (int argc, char **argv)
{
SimpleOpenNIViewer v;
v.run ();
return 0;
}
<|endoftext|> |
<commit_before>// Copyright 2015 Patrick Putnam
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef CLOTHO_COLUMN_ALIGNED_FREQUENCY_EVALUATOR_HPP_
#define CLOTHO_COLUMN_ALIGNED_FREQUENCY_EVALUATOR_HPP_
#include "clotho/data_spaces/analysis/allele_frequency/frequency_evaluator_def.hpp"
#include "clotho/data_spaces/association_matrix/column_aligned_association_matrix.hpp"
#include <boost/dynamic_bitset.hpp>
#include "clotho/utility/debruijn_bit_walker.hpp"
namespace clotho {
namespace genetics {
template < class BlockType >
struct frequency_evaluator< association_matrix< BlockType, column_aligned > > {
typedef association_matrix< BlockType, column_aligned > space_type;
typedef typename space_type::block_type block_type;
typedef typename space_type::bit_helper_type bit_helper_type;
typedef typename clotho::utility::debruijn_bit_walker< block_type > bit_walker_type;
typedef size_t * result_type;
void operator()( space_type & ss, boost::dynamic_bitset<> & indices, result_type * res ) {
size_t M = ss.column_count();
size_t N = ss.block_column_count();
size_t buffer[ bit_helper_type::BITS_PER_BLOCK ];
memset( buffer, 0, bit_helper_type::BITS_PER_BLOCK * sizeof( size_t ) );
typedef typename space_type::raw_block_pointer iterator;
size_t i = 0, j = M;
while( j ) {
iterator first = ss.begin_block_row( i );
iterator last = ss.end_block_row( i );
size_t k = 0;
while( first != last ) {
block_type b = *first++;
if( indices.test(k++) ) {
while( b ) {
unsigned int b_idx = bit_walker_type::unset_next_index( b );
buffer[ b_idx ] += 1;
}
}
}
size_t l = (( j < bit_helper_type::BITS_PER_BLOCK) ? j : bit_helper_type::BITS_PER_BLOCK);
memcpy( res + i * bit_helper_type::BITS_PER_BLOCK, buffer, sizeof( size_t ) * l );
memset( buffer, 0, bit_helper_type::BITS_PER_BLOCK * sizeof( size_t ) );
j -= l;
++i;
}
}
};
} // namespace genetics
} // namespace clotho
#endif // CLOTHO_COLUMN_ALIGNED_FREQUENCY_EVALUATOR_HPP_
<commit_msg>Cleaned up compiler warning<commit_after>// Copyright 2015 Patrick Putnam
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef CLOTHO_COLUMN_ALIGNED_FREQUENCY_EVALUATOR_HPP_
#define CLOTHO_COLUMN_ALIGNED_FREQUENCY_EVALUATOR_HPP_
#include "clotho/data_spaces/analysis/allele_frequency/frequency_evaluator_def.hpp"
#include "clotho/data_spaces/association_matrix/column_aligned_association_matrix.hpp"
#include <boost/dynamic_bitset.hpp>
#include "clotho/utility/debruijn_bit_walker.hpp"
namespace clotho {
namespace genetics {
template < class BlockType >
struct frequency_evaluator< association_matrix< BlockType, column_aligned > > {
typedef association_matrix< BlockType, column_aligned > space_type;
typedef typename space_type::block_type block_type;
typedef typename space_type::bit_helper_type bit_helper_type;
typedef typename clotho::utility::debruijn_bit_walker< block_type > bit_walker_type;
typedef size_t * result_type;
void operator()( space_type & ss, boost::dynamic_bitset<> & indices, result_type res ) {
size_t M = ss.column_count();
// size_t N = ss.block_column_count();
size_t buffer[ bit_helper_type::BITS_PER_BLOCK ];
memset( buffer, 0, bit_helper_type::BITS_PER_BLOCK * sizeof( size_t ) );
typedef typename space_type::raw_block_pointer iterator;
size_t i = 0, j = M;
while( j ) {
iterator first = ss.begin_block_row( i );
iterator last = ss.end_block_row( i );
size_t k = 0;
while( first != last ) {
block_type b = *first++;
if( indices.test(k++) ) {
while( b ) {
unsigned int b_idx = bit_walker_type::unset_next_index( b );
buffer[ b_idx ] += 1;
}
}
}
size_t l = (( j < bit_helper_type::BITS_PER_BLOCK) ? j : bit_helper_type::BITS_PER_BLOCK);
memcpy( res + i * bit_helper_type::BITS_PER_BLOCK, buffer, sizeof( size_t ) * l );
memset( buffer, 0, bit_helper_type::BITS_PER_BLOCK * sizeof( size_t ) );
j -= l;
++i;
}
}
};
} // namespace genetics
} // namespace clotho
#endif // CLOTHO_COLUMN_ALIGNED_FREQUENCY_EVALUATOR_HPP_
<|endoftext|> |
<commit_before>#ifndef CPP_REF_HPP
#define CPP_REF_HPP
#include <stdexcept>
#include <utility>
#include <cassert>
struct ref_counted {
virtual ~ref_counted() { }
std::size_t rc = 0;
friend void incref(ref_counted* self) { self->rc++; }
friend void decref(ref_counted* self) { if(--self->rc == 0) delete self; }
};
template<class T> class ref;
class ref_any {
using ptr_type = ref_counted*;
ptr_type ptr;
public:
ref_any() : ptr(nullptr) { }
ref_any(ptr_type ptr) : ptr(ptr) {
if(ptr) incref(ptr);
}
ptr_type get() const { return ptr; }
~ref_any() { if(ptr) decref(ptr); }
ref_any(const ref_any& other) noexcept : ptr(other.ptr) {
if(ptr) incref(ptr);
}
ref_any(ref_any&& other) noexcept : ptr(std::move(other.ptr)) {
other.ptr = nullptr;
}
ref_any& operator=(const ref_any& other) noexcept {
if(this == &other) return *this;
if(ptr) decref(ptr);
ptr = other.ptr;
if(ptr) incref(ptr);
return *this;
}
ref_any& operator=(ref_any&& other) noexcept{
if(this == &other) return *this;
if(ptr) decref(ptr);
ptr = std::move(other.ptr);
other.ptr = nullptr;
return *this;
}
explicit operator bool() const { return ptr; }
bool operator==(const ref_any& other) const { return ptr == other.ptr; }
bool operator!=(const ref_any& other) const { return ptr != other.ptr; }
bool operator<(const ref_any& other) const { return ptr < other.ptr; }
std::size_t rc() const {
if(ptr) return ptr->rc;
throw std::invalid_argument("null pointer");
}
// type recovery
template<class T> ref<T> cast() const;
};
template<class T>
struct control_block : ref_counted, T {
template<class ... Args>
control_block(Args&& ... args) : T(std::forward<Args>(args)...) { }
};
template<class T>
class ref {
ref_any impl;
protected:
ref(control_block<T>* block) : impl(block) { }
friend ref ref_any::cast<T>() const;
public:
template<class ... Args>
static ref make(Args&& ... args) {
return new control_block<T>(std::forward<Args>(args)...);
}
T* get() const {
if(impl) return static_cast< control_block<T>* >(impl.get());
return nullptr;
}
T* operator->() const { return get(); }
T& operator*() const { return *get(); }
ref() = default;
ref(const ref& ) = default;
ref(ref&& ) = default;
ref& operator=(const ref& ) = default;
ref& operator=(ref&& ) = default;
// type erasure
ref_any any() const { return impl; }
explicit operator bool() const { return bool(impl); }
bool operator==(const ref& other) const { return impl == other.impl; }
bool operator!=(const ref& other) const { return impl != other.impl; }
bool operator<(const ref& other) const { return impl < other.impl; }
};
template<class T>
ref<T> ref_any::cast() const {
return static_cast<control_block<T>*>(ptr);
}
template<class T, class ... Args>
static ref<T> make_ref(Args&& ... args) { return ref<T>::make(std::forward<Args>(args)...); }
#endif
<commit_msg>friend class lol<commit_after>#ifndef CPP_REF_HPP
#define CPP_REF_HPP
#include <stdexcept>
#include <utility>
#include <cassert>
struct ref_counted {
virtual ~ref_counted() { }
std::size_t rc = 0;
friend void incref(ref_counted* self) { self->rc++; }
friend void decref(ref_counted* self) { if(--self->rc == 0) delete self; }
};
template<class T> class ref;
class ref_any {
using ptr_type = ref_counted*;
ptr_type ptr;
public:
ref_any() : ptr(nullptr) { }
ref_any(ptr_type ptr) : ptr(ptr) {
if(ptr) incref(ptr);
}
ptr_type get() const { return ptr; }
~ref_any() { if(ptr) decref(ptr); }
ref_any(const ref_any& other) noexcept : ptr(other.ptr) {
if(ptr) incref(ptr);
}
ref_any(ref_any&& other) noexcept : ptr(std::move(other.ptr)) {
other.ptr = nullptr;
}
ref_any& operator=(const ref_any& other) noexcept {
if(this == &other) return *this;
if(ptr) decref(ptr);
ptr = other.ptr;
if(ptr) incref(ptr);
return *this;
}
ref_any& operator=(ref_any&& other) noexcept{
if(this == &other) return *this;
if(ptr) decref(ptr);
ptr = std::move(other.ptr);
other.ptr = nullptr;
return *this;
}
explicit operator bool() const { return ptr; }
bool operator==(const ref_any& other) const { return ptr == other.ptr; }
bool operator!=(const ref_any& other) const { return ptr != other.ptr; }
bool operator<(const ref_any& other) const { return ptr < other.ptr; }
std::size_t rc() const {
if(ptr) return ptr->rc;
throw std::invalid_argument("null pointer");
}
// type recovery
template<class T> ref<T> cast() const;
};
template<class T>
struct control_block : ref_counted, T {
template<class ... Args>
control_block(Args&& ... args) : T(std::forward<Args>(args)...) { }
};
template<class T>
class ref {
ref_any impl;
protected:
ref(control_block<T>* block) : impl(block) { }
friend class ref_any;
public:
template<class ... Args>
static ref make(Args&& ... args) {
return new control_block<T>(std::forward<Args>(args)...);
}
T* get() const {
if(impl) return static_cast< control_block<T>* >(impl.get());
return nullptr;
}
T* operator->() const { return get(); }
T& operator*() const { return *get(); }
ref() = default;
ref(const ref& ) = default;
ref(ref&& ) = default;
ref& operator=(const ref& ) = default;
ref& operator=(ref&& ) = default;
// type erasure
ref_any any() const { return impl; }
explicit operator bool() const { return bool(impl); }
bool operator==(const ref& other) const { return impl == other.impl; }
bool operator!=(const ref& other) const { return impl != other.impl; }
bool operator<(const ref& other) const { return impl < other.impl; }
};
template<class T>
ref<T> ref_any::cast() const {
return static_cast<control_block<T>*>(ptr);
}
template<class T, class ... Args>
static ref<T> make_ref(Args&& ... args) { return ref<T>::make(std::forward<Args>(args)...); }
#endif
<|endoftext|> |
<commit_before>/*************************************************
* SEED Source File *
* (C) 1999-2007 The Botan Project *
*************************************************/
#include <botan/seed.h>
#include <botan/bit_ops.h>
namespace Botan {
/*************************************************
* SEED G Function *
*************************************************/
u32bit SEED::G_FUNC::operator()(u32bit X) const
{
return (S0[get_byte(3, X)] ^ S1[get_byte(2, X)] ^
S2[get_byte(1, X)] ^ S3[get_byte(0, X)]);
}
/*************************************************
* SEED Encryption *
*************************************************/
void SEED::enc(const byte in[], byte out[]) const
{
u32bit B0 = load_be<u32bit>(in, 0);
u32bit B1 = load_be<u32bit>(in, 1);
u32bit B2 = load_be<u32bit>(in, 2);
u32bit B3 = load_be<u32bit>(in, 3);
G_FUNC G;
for(u32bit j = 0; j != 16; j += 2)
{
u32bit T0, T1;
T0 = B2 ^ K[2*j];
T1 = G(T0 ^ B3 ^ K[2*j+1]);
T0 = G(T1 + T0);
T1 = G(T1 + T0);
B1 ^= T1;
B0 ^= T0 + T1;
T0 = B0 ^ K[2*j+2];
T1 = G(T0 ^ B1 ^ K[2*j+3]);
T0 = G(T1 + T0);
T1 = G(T1 + T0);
B3 ^= T1;
B2 ^= T0 + T1;
}
store_be(out, B2, B3, B0, B1);
}
/*************************************************
* SEED Decryption *
*************************************************/
void SEED::dec(const byte in[], byte out[]) const
{
u32bit B0 = load_be<u32bit>(in, 0);
u32bit B1 = load_be<u32bit>(in, 1);
u32bit B2 = load_be<u32bit>(in, 2);
u32bit B3 = load_be<u32bit>(in, 3);
G_FUNC G;
for(u32bit j = 0; j != 16; j += 2)
{
u32bit T0, T1;
T0 = B2 ^ K[30-2*j];
T1 = G(T0 ^ B3 ^ K[31-2*j]);
T0 = G(T1 + T0);
T1 = G(T1 + T0);
B1 ^= T1;
B0 ^= T0 + T1;
T0 = B0 ^ K[28-2*j];
T1 = G(T0 ^ B1 ^ K[29-2*j]);
T0 = G(T1 + T0);
T1 = G(T1 + T0);
B3 ^= T1;
B2 ^= T0 + T1;
}
store_be(out, B2, B3, B0, B1);
}
/*************************************************
* SEED Key Schedule *
*************************************************/
void SEED::key(const byte key[], u32bit)
{
const u32bit RC[16] = {
0x9E3779B9, 0x3C6EF373, 0x78DDE6E6, 0xF1BBCDCC,
0xE3779B99, 0xC6EF3733, 0x8DDE6E67, 0x1BBCDCCF,
0x3779B99E, 0x6EF3733C, 0xDDE6E678, 0xBBCDCCF1,
0x779B99E3, 0xEF3733C6, 0xDE6E678D, 0xBCDCCF1B
};
SecureBuffer<u32bit, 4> WK;
for(u32bit j = 0; j != 4; ++j)
WK[j] = load_be<u32bit>(key, j);
G_FUNC G;
for(u32bit j = 0; j != 16; j += 2)
{
K[2*j ] = G(WK[0] + WK[2] - RC[j]);
K[2*j+1] = G(WK[1] - WK[3] + RC[j]);
byte T = get_byte(3, WK[0]);
WK[0] = (WK[0] >> 8) | (get_byte(3, WK[1]) << 24);
WK[1] = (WK[1] >> 8) | (T << 24);
K[2*j+2] = G(WK[0] + WK[2] - RC[j+1]);
K[2*j+3] = G(WK[1] - WK[3] + RC[j+1]);
T = get_byte(0, WK[3]);
WK[3] = (WK[3] << 8) | get_byte(0, WK[2]);
WK[2] = (WK[2] << 8) | T;
}
}
}
<commit_msg>Fold an XOR operation that was happening during SEED encryption/decryption to occur inside the key schedule instead. This should lead to (slightly) better scheduling in the compiled code by reducing the length of a critical path.<commit_after>/*************************************************
* SEED Source File *
* (C) 1999-2007 The Botan Project *
*************************************************/
#include <botan/seed.h>
#include <botan/bit_ops.h>
namespace Botan {
/*************************************************
* SEED G Function *
*************************************************/
u32bit SEED::G_FUNC::operator()(u32bit X) const
{
return (S0[get_byte(3, X)] ^ S1[get_byte(2, X)] ^
S2[get_byte(1, X)] ^ S3[get_byte(0, X)]);
}
/*************************************************
* SEED Encryption *
*************************************************/
void SEED::enc(const byte in[], byte out[]) const
{
u32bit B0 = load_be<u32bit>(in, 0);
u32bit B1 = load_be<u32bit>(in, 1);
u32bit B2 = load_be<u32bit>(in, 2);
u32bit B3 = load_be<u32bit>(in, 3);
G_FUNC G;
for(u32bit j = 0; j != 16; j += 2)
{
u32bit T0, T1;
T0 = B2 ^ K[2*j];
T1 = G(B2 ^ B3 ^ K[2*j+1]);
T0 = G(T1 + T0);
T1 = G(T1 + T0);
B1 ^= T1;
B0 ^= T0 + T1;
T0 = B0 ^ K[2*j+2];
T1 = G(B0 ^ B1 ^ K[2*j+3]);
T0 = G(T1 + T0);
T1 = G(T1 + T0);
B3 ^= T1;
B2 ^= T0 + T1;
}
store_be(out, B2, B3, B0, B1);
}
/*************************************************
* SEED Decryption *
*************************************************/
void SEED::dec(const byte in[], byte out[]) const
{
u32bit B0 = load_be<u32bit>(in, 0);
u32bit B1 = load_be<u32bit>(in, 1);
u32bit B2 = load_be<u32bit>(in, 2);
u32bit B3 = load_be<u32bit>(in, 3);
G_FUNC G;
for(u32bit j = 0; j != 16; j += 2)
{
u32bit T0, T1;
T0 = B2 ^ K[30-2*j];
T1 = G(B2 ^ B3 ^ K[31-2*j]);
T0 = G(T1 + T0);
T1 = G(T1 + T0);
B1 ^= T1;
B0 ^= T0 + T1;
T0 = B0 ^ K[28-2*j];
T1 = G(B0 ^ B1 ^ K[29-2*j]);
T0 = G(T1 + T0);
T1 = G(T1 + T0);
B3 ^= T1;
B2 ^= T0 + T1;
}
store_be(out, B2, B3, B0, B1);
}
/*************************************************
* SEED Key Schedule *
*************************************************/
void SEED::key(const byte key[], u32bit)
{
const u32bit RC[16] = {
0x9E3779B9, 0x3C6EF373, 0x78DDE6E6, 0xF1BBCDCC,
0xE3779B99, 0xC6EF3733, 0x8DDE6E67, 0x1BBCDCCF,
0x3779B99E, 0x6EF3733C, 0xDDE6E678, 0xBBCDCCF1,
0x779B99E3, 0xEF3733C6, 0xDE6E678D, 0xBCDCCF1B
};
SecureBuffer<u32bit, 4> WK;
for(u32bit j = 0; j != 4; ++j)
WK[j] = load_be<u32bit>(key, j);
G_FUNC G;
for(u32bit j = 0; j != 16; j += 2)
{
K[2*j ] = G(WK[0] + WK[2] - RC[j]);
K[2*j+1] = G(WK[1] - WK[3] + RC[j]) ^ K[2*j];
byte T = get_byte(3, WK[0]);
WK[0] = (WK[0] >> 8) | (get_byte(3, WK[1]) << 24);
WK[1] = (WK[1] >> 8) | (T << 24);
K[2*j+2] = G(WK[0] + WK[2] - RC[j+1]);
K[2*j+3] = G(WK[1] - WK[3] + RC[j+1]) ^ K[2*j+2];
T = get_byte(0, WK[3]);
WK[3] = (WK[3] << 8) | get_byte(0, WK[2]);
WK[2] = (WK[2] << 8) | T;
}
}
}
<|endoftext|> |
<commit_before>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkException.h"
void mitk::Exception::AddRethrowData(const char *file, unsigned int lineNumber, const char *message)
{
mitk::Exception::ReThrowData data = {file, lineNumber, message};
this->m_RethrowData.push_back(data);
}
int mitk::Exception::GetNumberOfRethrows()
{
return (int)m_RethrowData.size();
}
void mitk::Exception::GetRethrowData(int rethrowNumber, std::string &file, int &line, std::string &message)
{
if ((rethrowNumber >= (int)m_RethrowData.size()) || (rethrowNumber<0))
{
file = "";
line = 0;
message = "";
return;
}
file = m_RethrowData.at(rethrowNumber).RethrowClassname;
line = m_RethrowData.at(rethrowNumber).RethrowLine;
message = m_RethrowData.at(rethrowNumber).RethrowMessage;
}
std::ostream& operator<<(std::ostream& os, const mitk::Exception& e)
{
os << e.GetDescription();
return os;
}
<commit_msg>COMP: Fixed namespace of operator<< implementation<commit_after>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkException.h"
void mitk::Exception::AddRethrowData(const char *file, unsigned int lineNumber, const char *message)
{
mitk::Exception::ReThrowData data = {file, lineNumber, message};
this->m_RethrowData.push_back(data);
}
int mitk::Exception::GetNumberOfRethrows()
{
return (int)m_RethrowData.size();
}
void mitk::Exception::GetRethrowData(int rethrowNumber, std::string &file, int &line, std::string &message)
{
if ((rethrowNumber >= (int)m_RethrowData.size()) || (rethrowNumber<0))
{
file = "";
line = 0;
message = "";
return;
}
file = m_RethrowData.at(rethrowNumber).RethrowClassname;
line = m_RethrowData.at(rethrowNumber).RethrowLine;
message = m_RethrowData.at(rethrowNumber).RethrowMessage;
}
std::ostream& mitk::operator<<(std::ostream& os, const mitk::Exception& e)
{
os << e.GetDescription();
return os;
}
<|endoftext|> |
<commit_before>/*
This file is part of Akregator.
Copyright (C) 2008 Frank Osterfeld <osterfeld@kde.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include "createfeedcommand.h"
#include "addfeeddialog.h"
#include "feed.h"
#include "feedpropertiesdialog.h"
#include "folder.h"
#include "subscriptionlistview.h"
#include <KInputDialog>
#include <KLocalizedString>
#include <KUrl>
#include <QPointer>
#include <QTimer>
#include <QClipboard>
#include <cassert>
using namespace Akregator;
class CreateFeedCommand::Private
{
CreateFeedCommand* const q;
public:
explicit Private( CreateFeedCommand* qq );
void doCreate();
QPointer<Folder> m_rootFolder;
QPointer<SubscriptionListView> m_subscriptionListView;
QString m_url;
QPointer<Folder> m_parentFolder;
QPointer<TreeNode> m_after;
bool m_autoexec;
};
CreateFeedCommand::Private::Private( CreateFeedCommand* qq )
: q( qq ),
m_rootFolder( 0 ),
m_subscriptionListView( 0 ),
m_parentFolder( 0 ),
m_after( 0 ),
m_autoexec( false )
{
}
void CreateFeedCommand::Private::doCreate()
{
assert( m_rootFolder );
assert( m_subscriptionListView );
QPointer<AddFeedDialog> afd = new AddFeedDialog( q->parentWidget(), "add_feed" );
QString url = m_url;
if( url.isEmpty() )
{
const QClipboard* const clipboard = QApplication::clipboard();
assert( clipboard );
const QString clipboardText = clipboard->text();
// Check for the hostname, since the isValid method is not strict enough
if( !KUrl( clipboardText ).isEmpty() )
url = clipboardText;
}
afd->setUrl( KUrl::fromPercentEncoding( url.toLatin1() ) );
QPointer<QObject> thisPointer( q );
if ( m_autoexec )
afd->accept();
else
afd->exec();
if ( !thisPointer ) // "this" might have been deleted while exec()!
return;
Feed* const feed = afd->feed();
delete afd;
if ( !feed )
{
q->done();
return;
}
QPointer<FeedPropertiesDialog> dlg = new FeedPropertiesDialog( q->parentWidget(), "edit_feed" );
dlg->setFeed( feed );
dlg->selectFeedName();
if ( !m_autoexec && ( dlg->exec() != QDialog::Accepted || !thisPointer ) )
{
delete feed;
}
else
{
m_parentFolder = m_parentFolder ? m_parentFolder : m_rootFolder;
m_parentFolder->insertChild( feed, m_after );
m_subscriptionListView->ensureNodeVisible( feed );
}
delete dlg;
q->done();
}
CreateFeedCommand::CreateFeedCommand( QObject* parent ) : Command( parent ), d( new Private( this ) )
{
}
CreateFeedCommand::~CreateFeedCommand()
{
delete d;
}
void CreateFeedCommand::setSubscriptionListView( SubscriptionListView* view )
{
d->m_subscriptionListView = view;
}
void CreateFeedCommand::setRootFolder( Folder* rootFolder )
{
d->m_rootFolder = rootFolder;
}
void CreateFeedCommand::setUrl( const QString& url )
{
d->m_url = url;
}
void CreateFeedCommand::setPosition( Folder* parent, TreeNode* after )
{
d->m_parentFolder = parent;
d->m_after = after;
}
void CreateFeedCommand::setAutoExecute( bool autoexec )
{
d->m_autoexec = autoexec;
}
void CreateFeedCommand::doStart()
{
QTimer::singleShot( 0, this, SLOT( doCreate() ) );
}
void CreateFeedCommand::doAbort()
{
}
#include "createfeedcommand.moc"
<commit_msg>actually do what the comment says: check host() for being empty, not the whole URL prevents non-URL clipboard content from being pasted<commit_after>/*
This file is part of Akregator.
Copyright (C) 2008 Frank Osterfeld <osterfeld@kde.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include "createfeedcommand.h"
#include "addfeeddialog.h"
#include "feed.h"
#include "feedpropertiesdialog.h"
#include "folder.h"
#include "subscriptionlistview.h"
#include <KInputDialog>
#include <KLocalizedString>
#include <KUrl>
#include <QPointer>
#include <QTimer>
#include <QClipboard>
#include <cassert>
using namespace Akregator;
class CreateFeedCommand::Private
{
CreateFeedCommand* const q;
public:
explicit Private( CreateFeedCommand* qq );
void doCreate();
QPointer<Folder> m_rootFolder;
QPointer<SubscriptionListView> m_subscriptionListView;
QString m_url;
QPointer<Folder> m_parentFolder;
QPointer<TreeNode> m_after;
bool m_autoexec;
};
CreateFeedCommand::Private::Private( CreateFeedCommand* qq )
: q( qq ),
m_rootFolder( 0 ),
m_subscriptionListView( 0 ),
m_parentFolder( 0 ),
m_after( 0 ),
m_autoexec( false )
{
}
void CreateFeedCommand::Private::doCreate()
{
assert( m_rootFolder );
assert( m_subscriptionListView );
QPointer<AddFeedDialog> afd = new AddFeedDialog( q->parentWidget(), "add_feed" );
QString url = m_url;
if( url.isEmpty() )
{
const QClipboard* const clipboard = QApplication::clipboard();
assert( clipboard );
const QString clipboardText = clipboard->text();
// Check for the hostname, since the isValid method is not strict enough
if( !KUrl( clipboardText ).host().isEmpty() )
url = clipboardText;
}
afd->setUrl( KUrl::fromPercentEncoding( url.toLatin1() ) );
QPointer<QObject> thisPointer( q );
if ( m_autoexec )
afd->accept();
else
afd->exec();
if ( !thisPointer ) // "this" might have been deleted while exec()!
return;
Feed* const feed = afd->feed();
delete afd;
if ( !feed )
{
q->done();
return;
}
QPointer<FeedPropertiesDialog> dlg = new FeedPropertiesDialog( q->parentWidget(), "edit_feed" );
dlg->setFeed( feed );
dlg->selectFeedName();
if ( !m_autoexec && ( dlg->exec() != QDialog::Accepted || !thisPointer ) )
{
delete feed;
}
else
{
m_parentFolder = m_parentFolder ? m_parentFolder : m_rootFolder;
m_parentFolder->insertChild( feed, m_after );
m_subscriptionListView->ensureNodeVisible( feed );
}
delete dlg;
q->done();
}
CreateFeedCommand::CreateFeedCommand( QObject* parent ) : Command( parent ), d( new Private( this ) )
{
}
CreateFeedCommand::~CreateFeedCommand()
{
delete d;
}
void CreateFeedCommand::setSubscriptionListView( SubscriptionListView* view )
{
d->m_subscriptionListView = view;
}
void CreateFeedCommand::setRootFolder( Folder* rootFolder )
{
d->m_rootFolder = rootFolder;
}
void CreateFeedCommand::setUrl( const QString& url )
{
d->m_url = url;
}
void CreateFeedCommand::setPosition( Folder* parent, TreeNode* after )
{
d->m_parentFolder = parent;
d->m_after = after;
}
void CreateFeedCommand::setAutoExecute( bool autoexec )
{
d->m_autoexec = autoexec;
}
void CreateFeedCommand::doStart()
{
QTimer::singleShot( 0, this, SLOT( doCreate() ) );
}
void CreateFeedCommand::doAbort()
{
}
#include "createfeedcommand.moc"
<|endoftext|> |
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved
*/
// TEST Foundation::Containers::DataStructures::DoublyLinkedList
#include "Stroika/Foundation/StroikaPreComp.h"
#include <iostream>
#include <sstream>
#include "Stroika/Foundation/Containers/Private/PatchingDataStructures/DoublyLinkedList.h"
#include "Stroika/Foundation/Debug/Assertions.h"
#include "Stroika/Foundation/Debug/Trace.h"
#include "../TestHarness/SimpleClass.h"
#include "../TestHarness/TestHarness.h"
using namespace Stroika;
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Containers;
using namespace Stroika::Foundation::Containers::DataStructures;
using namespace Stroika::Foundation::Containers::Private::PatchingDataStructures;
using Traversal::kUnknownIteratorOwnerID;
namespace {
static void Test1 ()
{
Private::PatchingDataStructures::DoublyLinkedList<size_t> someLL;
const size_t kBigSize = 1001;
Assert (kBigSize > 100);
VerifyTestResult (someLL.GetLength () == 0);
{
for (size_t i = 1; i <= kBigSize; i++) {
someLL.Prepend (0);
}
}
someLL.RemoveAll ();
{
for (size_t i = 1; i <= kBigSize; i++) {
someLL.Prepend (0);
}
}
{
for (size_t i = 1; i <= kBigSize - 10; i++) {
someLL.RemoveFirst ();
}
}
someLL.RemoveAll (); // someLL.SetLength(kBigSize, 0);
{
for (size_t i = 1; i <= kBigSize; i++) {
someLL.Prepend (0);
}
}
VerifyTestResult (someLL.GetLength () == kBigSize);
someLL.SetAt (55, 55); // someLL [55] = 55;
VerifyTestResult (someLL.GetAt (55) == 55); // VerifyTestResult(someArray [55] == 55);
VerifyTestResult (someLL.GetAt (55) != 56); // VerifyTestResult(someArray [55] != 56);
{
size_t i = 1;
size_t cur;
for (Private::PatchingDataStructures::DoublyLinkedList<size_t>::ForwardIterator it (kUnknownIteratorOwnerID, &someLL); it.More (&cur, true); i++) {
if (i == 100) {
someLL.AddAfter (it, 1);
break;
}
}
} // someLL.InsertAt(1, 100);
VerifyTestResult (someLL.GetLength () == kBigSize + 1);
VerifyTestResult (someLL.GetAt (100) == 1); // VerifyTestResult(someArray [100] == 1);
someLL.SetAt (101, someLL.GetAt (100) + 5);
VerifyTestResult (someLL.GetAt (101) == 6);
someLL.RemoveFirst ();
VerifyTestResult (someLL.GetAt (100) == 6);
}
static void Test2 ()
{
Private::PatchingDataStructures::DoublyLinkedList<SimpleClass> someLL;
const size_t kBigSize = 1000;
VerifyTestResult (someLL.GetLength () == 0);
Assert (kBigSize > 10);
VerifyTestResult (someLL.GetLength () == 0);
{
for (size_t i = 1; i <= kBigSize; i++) {
someLL.Prepend (0);
}
}
someLL.RemoveAll ();
{
for (size_t i = 1; i <= kBigSize; i++) {
someLL.Prepend (0);
}
}
{
for (size_t i = 1; i <= kBigSize - 10; i++) {
someLL.RemoveFirst ();
}
}
someLL.RemoveAll (); // someLL.SetLength(kBigSize, 0);
{
for (size_t i = 1; i <= kBigSize; i++) {
someLL.Prepend (0);
}
}
VerifyTestResult (someLL.GetLength () == kBigSize);
someLL.SetAt (55, 55); // someLL [55] = 55;
VerifyTestResult (someLL.GetAt (55) == 55);
VerifyTestResult (not(someLL.GetAt (55) == 56));
someLL.RemoveAll ();
VerifyTestResult (someLL.GetLength () == 0);
for (size_t i = kBigSize; i >= 1; --i) {
VerifyTestResult (not someLL.Contains (i));
someLL.Prepend (i);
VerifyTestResult (someLL.GetFirst () == i);
VerifyTestResult (someLL.Contains (i));
}
for (size_t i = 1; i <= kBigSize; ++i) {
VerifyTestResult (someLL.GetFirst () == i);
someLL.RemoveFirst ();
VerifyTestResult (not someLL.Contains (i));
}
VerifyTestResult (someLL.GetLength () == 0);
for (size_t i = kBigSize; i >= 1; --i) {
someLL.Prepend (i);
}
for (size_t i = kBigSize; i >= 1; --i) {
//cerr << "i, getat(i-1) = " << i << ", " << someLL.GetAt (i-1).GetValue () << endl;
VerifyTestResult (someLL.GetAt (i - 1) == i);
}
}
}
namespace {
void DoRegressionTests_ ()
{
Test1 ();
Test2 ();
}
}
int main ([[maybe_unused]] int argc, [[maybe_unused]] const char* argv[])
{
Stroika::TestHarness::Setup ();
return Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_);
}
<commit_msg>fixed remiaing refernece to Private::PatchingDataStructures<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved
*/
// TEST Foundation::Containers::DataStructures::DoublyLinkedList
#include "Stroika/Foundation/StroikaPreComp.h"
#include <iostream>
#include <sstream>
#include "Stroika/Foundation/Containers/DataStructures/DoublyLinkedList.h"
#include "Stroika/Foundation/Debug/Assertions.h"
#include "Stroika/Foundation/Debug/Trace.h"
#include "../TestHarness/SimpleClass.h"
#include "../TestHarness/TestHarness.h"
using namespace Stroika;
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Containers;
using namespace Stroika::Foundation::Containers::DataStructures;
using Traversal::kUnknownIteratorOwnerID;
namespace {
static void Test1 ()
{
DataStructures::DoublyLinkedList<size_t> someLL;
const size_t kBigSize = 1001;
Assert (kBigSize > 100);
VerifyTestResult (someLL.GetLength () == 0);
{
for (size_t i = 1; i <= kBigSize; i++) {
someLL.Prepend (0);
}
}
someLL.RemoveAll ();
{
for (size_t i = 1; i <= kBigSize; i++) {
someLL.Prepend (0);
}
}
{
for (size_t i = 1; i <= kBigSize - 10; i++) {
someLL.RemoveFirst ();
}
}
someLL.RemoveAll (); // someLL.SetLength(kBigSize, 0);
{
for (size_t i = 1; i <= kBigSize; i++) {
someLL.Prepend (0);
}
}
VerifyTestResult (someLL.GetLength () == kBigSize);
someLL.SetAt (55, 55); // someLL [55] = 55;
VerifyTestResult (someLL.GetAt (55) == 55); // VerifyTestResult(someArray [55] == 55);
VerifyTestResult (someLL.GetAt (55) != 56); // VerifyTestResult(someArray [55] != 56);
{
size_t i = 1;
size_t cur;
for (DataStructures::DoublyLinkedList<size_t>::ForwardIterator it (&someLL); it.More (&cur, true); i++) {
if (i == 100) {
someLL.AddAfter (it, 1);
break;
}
}
} // someLL.InsertAt(1, 100);
VerifyTestResult (someLL.GetLength () == kBigSize + 1);
VerifyTestResult (someLL.GetAt (100) == 1); // VerifyTestResult(someArray [100] == 1);
someLL.SetAt (101, someLL.GetAt (100) + 5);
VerifyTestResult (someLL.GetAt (101) == 6);
someLL.RemoveFirst ();
VerifyTestResult (someLL.GetAt (100) == 6);
}
static void Test2 ()
{
DataStructures::DoublyLinkedList<SimpleClass> someLL;
const size_t kBigSize = 1000;
VerifyTestResult (someLL.GetLength () == 0);
Assert (kBigSize > 10);
VerifyTestResult (someLL.GetLength () == 0);
{
for (size_t i = 1; i <= kBigSize; i++) {
someLL.Prepend (0);
}
}
someLL.RemoveAll ();
{
for (size_t i = 1; i <= kBigSize; i++) {
someLL.Prepend (0);
}
}
{
for (size_t i = 1; i <= kBigSize - 10; i++) {
someLL.RemoveFirst ();
}
}
someLL.RemoveAll (); // someLL.SetLength(kBigSize, 0);
{
for (size_t i = 1; i <= kBigSize; i++) {
someLL.Prepend (0);
}
}
VerifyTestResult (someLL.GetLength () == kBigSize);
someLL.SetAt (55, 55); // someLL [55] = 55;
VerifyTestResult (someLL.GetAt (55) == 55);
VerifyTestResult (not(someLL.GetAt (55) == 56));
someLL.RemoveAll ();
VerifyTestResult (someLL.GetLength () == 0);
for (size_t i = kBigSize; i >= 1; --i) {
VerifyTestResult (not someLL.Contains (i));
someLL.Prepend (i);
VerifyTestResult (someLL.GetFirst () == i);
VerifyTestResult (someLL.Contains (i));
}
for (size_t i = 1; i <= kBigSize; ++i) {
VerifyTestResult (someLL.GetFirst () == i);
someLL.RemoveFirst ();
VerifyTestResult (not someLL.Contains (i));
}
VerifyTestResult (someLL.GetLength () == 0);
for (size_t i = kBigSize; i >= 1; --i) {
someLL.Prepend (i);
}
for (size_t i = kBigSize; i >= 1; --i) {
//cerr << "i, getat(i-1) = " << i << ", " << someLL.GetAt (i-1).GetValue () << endl;
VerifyTestResult (someLL.GetAt (i - 1) == i);
}
}
}
namespace {
void DoRegressionTests_ ()
{
Test1 ();
Test2 ();
}
}
int main ([[maybe_unused]] int argc, [[maybe_unused]] const char* argv[])
{
Stroika::TestHarness::Setup ();
return Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_);
}
<|endoftext|> |
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2022. All rights reserved
*/
// TEST Foundation::Execution::Other
#include "Stroika/Foundation/StroikaPreComp.h"
#include "Stroika/Foundation/Common/Property.h"
#include "Stroika/Foundation/DataExchange/ObjectVariantMapper.h"
#include "Stroika/Foundation/DataExchange/OptionsFile.h"
#include "Stroika/Foundation/Debug/Assertions.h"
#include "Stroika/Foundation/Debug/Trace.h"
#include "Stroika/Foundation/Execution/CommandLine.h"
#include "Stroika/Foundation/Execution/Finally.h"
#include "Stroika/Foundation/Execution/Function.h"
#include "Stroika/Foundation/Execution/Logger.h"
#include "Stroika/Foundation/Execution/ModuleGetterSetter.h"
#include "Stroika/Foundation/Time/DateTime.h"
#include "Stroika/Foundation/Time/Duration.h"
#include "../TestHarness/SimpleClass.h"
#include "../TestHarness/TestHarness.h"
using namespace Stroika;
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Characters;
using namespace Stroika::Foundation::Containers;
using namespace Stroika::Foundation::Execution;
// must be tested before main, so cannot call directly below
namespace {
int TestAtomicInitializedCoorectly_ ();
static int sIgnoredTestValue_ = TestAtomicInitializedCoorectly_ (); // if using static constructors, this will be called before sAtomicBoolNotInitializedTilAfterStaticInitizers_
atomic<bool> sAtomicBoolNotInitializedTilAfterStaticInitizers_{true}; // for calls before start of or after end of main ()
int TestAtomicInitializedCoorectly_ ()
{
#if qCompilerAndStdLib_atomic_bool_initialize_before_main_Buggy
if (sAtomicBoolNotInitializedTilAfterStaticInitizers_) {
#if qDebug
// bug seems to happen just with DEBUG builds - haven't dug into why
Stroika::TestHarness::WarnTestIssue ("qCompilerAndStdLib_atomic_bool_initialize_before_main_Buggy MAYBE fixed");
#endif
}
#else
VerifyTestResult (sAtomicBoolNotInitializedTilAfterStaticInitizers_);
#endif
return 1;
}
}
namespace {
void Test1_Function_ ()
{
// Make sure Function<> works as well as std::function
{
Function<int (bool)> f = [] ([[maybe_unused]] bool b) -> int { return 3; };
VerifyTestResult (f (true) == 3);
function<int (bool)> ff = f;
VerifyTestResult (ff (true) == 3);
}
// Make sure Function<> serves its one purpose - being comparable
{
Function<int (bool)> f1 = [] ([[maybe_unused]] bool b) -> int { return 3; };
Function<int (bool)> f2 = [] ([[maybe_unused]] bool b) -> int { return 3; };
VerifyTestResult (f1 != f2);
VerifyTestResult (f1 < f2 or f2 < f1);
Function<int (bool)> f3 = f1;
VerifyTestResult (f3 == f1);
VerifyTestResult (f3 != f2);
}
}
}
namespace {
void Test2_CommandLine_ ()
{
{
String cmdLine = L"/bin/sh -c \"a b c\"";
Sequence<String> l = ParseCommandLine (cmdLine);
VerifyTestResult (l.size () == 3);
VerifyTestResult (l[0] == L"/bin/sh");
VerifyTestResult (l[1] == L"-c");
VerifyTestResult (l[2] == L"a b c");
}
{
String cmdLine = L"";
Sequence<String> l = ParseCommandLine (cmdLine);
VerifyTestResult (l.size () == 0);
}
{
String cmdLine = L"/bin/sh -c \'a b c\'";
Sequence<String> l = ParseCommandLine (cmdLine);
VerifyTestResult (l.size () == 3);
VerifyTestResult (l[0] == L"/bin/sh");
VerifyTestResult (l[1] == L"-c");
VerifyTestResult (l[2] == L"a b c");
}
{
String cmdLine = L"/bin/sh\t b c -d";
Sequence<String> l = ParseCommandLine (cmdLine);
VerifyTestResult (l.size () == 4);
VerifyTestResult (l[0] == L"/bin/sh");
VerifyTestResult (l[1] == L"b");
VerifyTestResult (l[2] == L"c");
VerifyTestResult (l[3] == L"-d");
}
}
}
namespace {
namespace Test3_ {
void DoAll ()
{
{
unsigned int cnt = 0;
{
[[maybe_unused]] auto&& c = Finally (
[&cnt] () noexcept {
cnt--;
});
++cnt;
}
VerifyTestResult (cnt == 0);
}
}
}
}
namespace {
namespace Test4_ConstantProperty_ {
namespace Private_ {
namespace T1_ {
static const String x{L"3"};
const Common::ConstantProperty<String> kX = [] () { return x; };
void DoIt ()
{
const String a = kX;
}
}
namespace T2_ {
const Common::ConstantProperty<String> kX = [] () { return L"6"; };
void DoIt ()
{
const String a = kX;
VerifyTestResult (a == L"6"); // Before Stroika 2.1b12 there was a bug that ConstantProperty stored teh constant in a static variable not data member!
}
}
namespace T3_ {
// @todo get constexpr working - see docs for Common::ConstantProperty
//constexpr Common::ConstantProperty<int> kX = [] () { return 3; };
const Common::ConstantProperty<int> kX = [] () { return 3; };
void DoIt ()
{
const int a [[maybe_unused]] = kX;
}
}
namespace T4_ {
const Common::ConstantProperty<int> kX = [] () { return 4; };
void DoIt ()
{
const int a [[maybe_unused]] = kX;
VerifyTestResult (a == 4); // Before Stroika 2.1b12 there was a bug that ConstantProperty stored teh constant in a static variable not data member!
}
}
}
void DoAll ()
{
Private_::T1_::DoIt ();
Private_::T2_::DoIt ();
Private_::T3_::DoIt ();
}
}
}
namespace {
namespace Test5_ModuleGetterSetter_ {
namespace PRIVATE_ {
using namespace DataExchange;
using namespace Execution;
using namespace Time;
static const Duration kMinTime_ = 1s;
struct MyData_ {
bool fEnabled = false;
optional<DateTime> fLastSynchronizedAt;
};
struct ModuleGetterSetter_Implementation_MyData_ {
ModuleGetterSetter_Implementation_MyData_ ()
: fOptionsFile_{
L"MyModule",
[] () -> ObjectVariantMapper {
ObjectVariantMapper mapper;
mapper.AddClass<MyData_> (initializer_list<ObjectVariantMapper::StructFieldInfo>{
{L"Enabled", StructFieldMetaInfo{&MyData_::fEnabled}},
{L"Last-Synchronized-At", StructFieldMetaInfo{&MyData_::fLastSynchronizedAt}},
});
return mapper;
}(),
OptionsFile::kDefaultUpgrader, OptionsFile::mkFilenameMapper (L"Put-Your-App-Name-Here")}
, fActualCurrentConfigData_{fOptionsFile_.Read<MyData_> (MyData_{})}
{
Set (fActualCurrentConfigData_); // assure derived data (and changed fields etc) up to date
}
MyData_ Get () const
{
return fActualCurrentConfigData_;
}
void Set (const MyData_& v)
{
fActualCurrentConfigData_ = v;
fOptionsFile_.Write (v);
}
private:
OptionsFile fOptionsFile_;
MyData_ fActualCurrentConfigData_; // automatically initialized just in time, and externally synchronized
};
using Execution::ModuleGetterSetter;
ModuleGetterSetter<MyData_, ModuleGetterSetter_Implementation_MyData_> sModuleConfiguration_;
void TestUse1_ ()
{
if (sModuleConfiguration_.Get ().fEnabled) {
auto n = sModuleConfiguration_.Get ();
n.fEnabled = false;
sModuleConfiguration_.Set (n);
}
}
void TestUse2_ ()
{
sModuleConfiguration_.Update ([] (MyData_ data) { MyData_ result = data; if (result.fLastSynchronizedAt.has_value () and *result.fLastSynchronizedAt + kMinTime_ > DateTime::Now ()) { result.fLastSynchronizedAt = DateTime::Now (); } return result; });
}
void TestUse3_ ()
{
if (sModuleConfiguration_.Update ([] (const MyData_& data) -> optional<MyData_> { if (data.fLastSynchronizedAt.has_value () and *data.fLastSynchronizedAt + kMinTime_ > DateTime::Now ()) { MyData_ result = data; result.fLastSynchronizedAt = DateTime::Now (); return result; } return {}; })) {
// e.g. trigger someone to wakeup and used changes?
}
}
}
void DoAll ()
{
PRIVATE_::TestUse1_ ();
PRIVATE_::TestUse2_ ();
PRIVATE_::TestUse3_ ();
}
}
}
namespace {
void DoRegressionTests_ ()
{
Execution::Logger::Activator logMgrActivator; // needed for OptionsFile test
Test1_Function_ ();
Test2_CommandLine_ ();
Test3_::DoAll ();
Test4_ConstantProperty_::DoAll ();
Test5_ModuleGetterSetter_::DoAll ();
}
}
int main ([[maybe_unused]] int argc, [[maybe_unused]] const char* argv[])
{
Stroika::TestHarness::Setup ();
return Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_);
}
<commit_msg>cosmetic<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2022. All rights reserved
*/
// TEST Foundation::Execution::Other
#include "Stroika/Foundation/StroikaPreComp.h"
#include "Stroika/Foundation/Common/Property.h"
#include "Stroika/Foundation/DataExchange/ObjectVariantMapper.h"
#include "Stroika/Foundation/DataExchange/OptionsFile.h"
#include "Stroika/Foundation/Debug/Assertions.h"
#include "Stroika/Foundation/Debug/Trace.h"
#include "Stroika/Foundation/Execution/CommandLine.h"
#include "Stroika/Foundation/Execution/Finally.h"
#include "Stroika/Foundation/Execution/Function.h"
#include "Stroika/Foundation/Execution/Logger.h"
#include "Stroika/Foundation/Execution/ModuleGetterSetter.h"
#include "Stroika/Foundation/Time/DateTime.h"
#include "Stroika/Foundation/Time/Duration.h"
#include "../TestHarness/SimpleClass.h"
#include "../TestHarness/TestHarness.h"
using namespace Stroika;
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Characters;
using namespace Stroika::Foundation::Containers;
using namespace Stroika::Foundation::Execution;
// must be tested before main, so cannot call directly below
namespace {
int TestAtomicInitializedCoorectly_ ();
static int sIgnoredTestValue_ = TestAtomicInitializedCoorectly_ (); // if using static constructors, this will be called before sAtomicBoolNotInitializedTilAfterStaticInitizers_
atomic<bool> sAtomicBoolNotInitializedTilAfterStaticInitizers_{true}; // for calls before start of or after end of main ()
int TestAtomicInitializedCoorectly_ ()
{
#if qCompilerAndStdLib_atomic_bool_initialize_before_main_Buggy
if (sAtomicBoolNotInitializedTilAfterStaticInitizers_) {
#if qDebug
// bug seems to happen just with DEBUG builds - haven't dug into why
Stroika::TestHarness::WarnTestIssue ("qCompilerAndStdLib_atomic_bool_initialize_before_main_Buggy MAYBE fixed");
#endif
}
#else
VerifyTestResult (sAtomicBoolNotInitializedTilAfterStaticInitizers_);
#endif
return 1;
}
}
namespace {
void Test1_Function_ ()
{
// Make sure Function<> works as well as std::function
{
Function<int (bool)> f = [] ([[maybe_unused]] bool b) -> int { return 3; };
VerifyTestResult (f (true) == 3);
function<int (bool)> ff = f;
VerifyTestResult (ff (true) == 3);
}
// Make sure Function<> serves its one purpose - being comparable
{
Function<int (bool)> f1 = [] ([[maybe_unused]] bool b) -> int { return 3; };
Function<int (bool)> f2 = [] ([[maybe_unused]] bool b) -> int { return 3; };
VerifyTestResult (f1 != f2);
VerifyTestResult (f1 < f2 or f2 < f1);
Function<int (bool)> f3 = f1;
VerifyTestResult (f3 == f1);
VerifyTestResult (f3 != f2);
}
}
}
namespace {
void Test2_CommandLine_ ()
{
{
String cmdLine = L"/bin/sh -c \"a b c\"";
Sequence<String> l = ParseCommandLine (cmdLine);
VerifyTestResult (l.size () == 3);
VerifyTestResult (l[0] == L"/bin/sh");
VerifyTestResult (l[1] == L"-c");
VerifyTestResult (l[2] == L"a b c");
}
{
String cmdLine = L"";
Sequence<String> l = ParseCommandLine (cmdLine);
VerifyTestResult (l.size () == 0);
}
{
String cmdLine = L"/bin/sh -c \'a b c\'";
Sequence<String> l = ParseCommandLine (cmdLine);
VerifyTestResult (l.size () == 3);
VerifyTestResult (l[0] == L"/bin/sh");
VerifyTestResult (l[1] == L"-c");
VerifyTestResult (l[2] == L"a b c");
}
{
String cmdLine = L"/bin/sh\t b c -d";
Sequence<String> l = ParseCommandLine (cmdLine);
VerifyTestResult (l.size () == 4);
VerifyTestResult (l[0] == L"/bin/sh");
VerifyTestResult (l[1] == L"b");
VerifyTestResult (l[2] == L"c");
VerifyTestResult (l[3] == L"-d");
}
}
}
namespace {
namespace Test3_ {
void DoAll ()
{
{
unsigned int cnt = 0;
{
[[maybe_unused]] auto&& c = Finally (
[&cnt] () noexcept {
cnt--;
});
++cnt;
}
VerifyTestResult (cnt == 0);
}
}
}
}
namespace {
namespace Test4_ConstantProperty_ {
namespace Private_ {
namespace T1_ {
static const String x{L"3"};
const Common::ConstantProperty<String> kX = [] () { return x; };
void DoIt ()
{
const String a = kX;
}
}
namespace T2_ {
const Common::ConstantProperty<String> kX = [] () { return L"6"; };
void DoIt ()
{
const String a = kX;
VerifyTestResult (a == L"6"); // Before Stroika 2.1b12 there was a bug that ConstantProperty stored teh constant in a static variable not data member!
}
}
namespace T3_ {
// @todo get constexpr working - see docs for Common::ConstantProperty
//constexpr Common::ConstantProperty<int> kX = [] () { return 3; };
const Common::ConstantProperty<int> kX = [] () { return 3; };
void DoIt ()
{
const int a [[maybe_unused]] = kX;
}
}
namespace T4_ {
const Common::ConstantProperty<int> kX = [] () { return 4; };
void DoIt ()
{
const int a [[maybe_unused]] = kX;
VerifyTestResult (a == 4); // Before Stroika 2.1b12 there was a bug that ConstantProperty stored teh constant in a static variable not data member!
}
}
}
void DoAll ()
{
Private_::T1_::DoIt ();
Private_::T2_::DoIt ();
Private_::T3_::DoIt ();
}
}
}
namespace {
namespace Test5_ModuleGetterSetter_ {
namespace PRIVATE_ {
using namespace DataExchange;
using namespace Execution;
using namespace Time;
static const Duration kMinTime_ = 1s;
struct MyData_ {
bool fEnabled = false;
optional<DateTime> fLastSynchronizedAt;
};
struct ModuleGetterSetter_Implementation_MyData_ {
ModuleGetterSetter_Implementation_MyData_ ()
: fOptionsFile_{
L"MyModule",
[] () -> ObjectVariantMapper {
ObjectVariantMapper mapper;
mapper.AddClass<MyData_> (initializer_list<ObjectVariantMapper::StructFieldInfo>{
{L"Enabled", StructFieldMetaInfo{&MyData_::fEnabled}},
{L"Last-Synchronized-At", StructFieldMetaInfo{&MyData_::fLastSynchronizedAt}},
});
return mapper;
}(),
OptionsFile::kDefaultUpgrader, OptionsFile::mkFilenameMapper (L"Put-Your-App-Name-Here")}
, fActualCurrentConfigData_{fOptionsFile_.Read<MyData_> (MyData_{})}
{
Set (fActualCurrentConfigData_); // assure derived data (and changed fields etc) up to date
}
MyData_ Get () const
{
return fActualCurrentConfigData_;
}
void Set (const MyData_& v)
{
fActualCurrentConfigData_ = v;
fOptionsFile_.Write (v);
}
private:
OptionsFile fOptionsFile_;
MyData_ fActualCurrentConfigData_; // automatically initialized just in time, and externally synchronized
};
using Execution::ModuleGetterSetter;
ModuleGetterSetter<MyData_, ModuleGetterSetter_Implementation_MyData_> sModuleConfiguration_;
void TestUse1_ ()
{
if (sModuleConfiguration_.Get ().fEnabled) {
auto n = sModuleConfiguration_.Get ();
n.fEnabled = false;
sModuleConfiguration_.Set (n);
}
}
void TestUse2_ ()
{
sModuleConfiguration_.Update ([] (MyData_ data) { MyData_ result = data; if (result.fLastSynchronizedAt.has_value () and *result.fLastSynchronizedAt + kMinTime_ > DateTime::Now ()) { result.fLastSynchronizedAt = DateTime::Now (); } return result; });
}
void TestUse3_ ()
{
if (sModuleConfiguration_.Update ([] (const MyData_& data) -> optional<MyData_> { if (data.fLastSynchronizedAt.has_value () and *data.fLastSynchronizedAt + kMinTime_ > DateTime::Now ()) { MyData_ result = data; result.fLastSynchronizedAt = DateTime::Now (); return result; } return {}; })) {
// e.g. trigger someone to wakeup and used changes?
}
}
}
void DoAll ()
{
PRIVATE_::TestUse1_ ();
PRIVATE_::TestUse2_ ();
PRIVATE_::TestUse3_ ();
}
}
}
namespace {
void DoRegressionTests_ ()
{
Execution::Logger::Activator logMgrActivator; // needed for OptionsFile test
Test1_Function_ ();
Test2_CommandLine_ ();
Test3_::DoAll ();
Test4_ConstantProperty_::DoAll ();
Test5_ModuleGetterSetter_::DoAll ();
}
}
int main ([[maybe_unused]] int argc, [[maybe_unused]] const char* argv[])
{
Stroika::TestHarness::Setup ();
return Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_);
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2008 by Singularity Institute for Artificial Intelligence
* 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 "ForwardChainer.h"
#include "AtomSpaceWrapper.h"
#include "utils/NMPrinter.h"
#include "rules/Rules.h"
#include <opencog/util/Logger.h>
#include <opencog/util/mt19937ar.h>
#include <boost/variant.hpp>
#include <time.h>
using std::vector;
using std::cout;
using std::endl;
namespace opencog {
namespace pln {
ForwardChainer::ForwardChainer()
{
float minConfidence = FWD_CHAIN_MIN_CONFIDENCE;
float probStack = FWD_CHAIN_PROB_STACK;
float probGlobal = FWD_CHAIN_PROB_GLOBAL;
}
ForwardChainer::~ForwardChainer()
{
}
pHandle ForwardChainer::fwdChainToTarget(int& maxRuleApps, meta target)
{
// Should usually only be one (or none).
pHandleSeq results = fwdChain(maxRuleApps, target);
if (results.empty())
return PHANDLE_UNDEFINED;
else
return results[0];
}
// Static/Shared random number generator
RandGen* ForwardChainer::rng = NULL;
RandGen* ForwardChainer::getRNG() {
if (!rng)
rng = new opencog::MT19937RandGen((unsigned long) time(NULL));
return rng;
}
void ForwardChainer::printVertexVectorHandles(std::vector< Vertex > hs)
{
bool firstPrint = true;
cout << "< ";
foreach(Vertex v, hs) {
if (firstPrint) {
firstPrint = false;
} else {
cout << ", ";
}
//cout << boost::get<Handle>(v).value();
cout << v;
}
cout << " >";
}
// Possibly should be elsewhere.
// Finds an input filter that has all the constraints, including between arguments.
// inputFilter doesn't include those constraints.
// Sometimes there is more than one input filter available (e.g. for SimSubstRule)
std::set<std::vector<BBvtree> > getFilters(Rule * r)
{
//meta i2oType(const std::vector<Vertex>& h) const
//! @todo extend this for other rules (probably separately for each one)
// generic target for this rule
// meta generic_target(new vtree(mva((pHandle)ASSOCIATIVE_LINK,
// vtree(CreateVar(GET_ASW)),
// vtree(CreateVar(GET_ASW))
// )));
std::vector<meta> inputFilter(r->getInputFilter());
// convert them to BoundVertex instances.
// This should all probably be refactored.
Btr<std::vector<BBvtree> > filter(new std::vector<BBvtree>);
//std::copy(inputFilter.begin(), inputFilter.end(), filter->begin());
foreach(meta item, inputFilter) {
BBvtree Btr_bound_item(new BoundVTree(*item)); // not bound yet, it just means it can be bound
filter->push_back(Btr_bound_item);
}
//return makeSingletonSet(filter);
Rule::setOfMPs ret;
ret.insert(*filter);
return ret;
meta generic_target(new vtree(mva((pHandle)ASSOCIATIVE_LINK,
mva((pHandle)ATOM),
mva((pHandle)ATOM)
)));
//cout << "getFilters";
rawPrint(generic_target->begin(), 2);
// cout << rawPrint(*generic_target,generic_target->begin(),0);
return r->o2iMeta(generic_target);
}
pHandleSeq ForwardChainer::fwdChain(int maxRuleApps, meta target)
{
pHandleSeq results;
while (maxRuleApps > 0) {
//cout << "steps remaining: " << maxRuleApps << endl;
bool appliedRule = false;
// Get the next Rule (no restrictions)
foreach(Rule *r, rp) { // to avoid needing a nextRule method.
//cout << "Using " << r->getName() << endl;
// Find the possible vector(s) of arguments for it
std::set<std::vector<BBvtree> > filters(r->fullInputFilter());
// For each such vector:
foreach(std::vector<BBvtree> f, filters) {
// find a vector of Atoms that matches it
Btr<vector<BoundVertex> > args;
args = findAllArgs(f);
// check for validity (~redundant)
//cout << "FWDCHAIN arguments ";
//printVertexVectorHandles(args); // takes Vertexes not BoundVertexes
//cout << " are valid? " <<endl;
bool foundArguments = !args->empty();//true;// = r->validate(args);
if (!foundArguments) {
//cout << "FWDCHAIN args not valid" << endl;
} else {
//cout << "FWDCHAIN args valid" << endl;
// do the rule computation etc
Vertex V=((r->compute(*args)).GetValue());
pHandle out=boost::get<pHandle>(V);
const TruthValue& tv=GET_ASW->getTV(out);
//cout<<printTV(out)<<'\n';
if (!tv.isNullTv() && tv.getCount() > minConfidence) {
maxRuleApps--;
appliedRule = true;
if (target) { // Match it against the target
// Adapted from in Rule::validate
typedef weak_atom< meta > vertex_wrapper;
vertex_wrapper mp(target);
if (mp(out)) {
results.push_back(out);
return results;
}
} else
results.push_back(out);
//cout<<"Output\n";
NMPrinter np;
np.print(out);
} else {
// Remove atom if not satisfactory
//GET_ASW->removeAtom(_v2h(V));
}
}
}
}
// If it iterated through all Rules and couldn't find any suitable
// input in the AtomSpace. Exit to prevent an infinite loop!
if (!appliedRule) return results;
}
return results;
}
Btr<std::set<BoundVertex> > ForwardChainer::getMatching(const meta target)
{
// Just look it up via LookupRule
LookupRule lookup(GET_ASW);
Btr<std::set<BoundVertex> > matches;
// std::cout << "getMatching: target: ";
rawPrint(target->begin(), 5);
matches = lookup.attemptDirectProduction(target);
return matches;
}
Btr<vector<BoundVertex> > ForwardChainer::findAllArgs(std::vector<BBvtree> filter)
{
Btr<vector<BoundVertex> > args(new vector<BoundVertex>);
//Btr<bindingsT> bindings(new BindingsT());
Btr<bindingsT> bindings(new std::map<pHandle, pHandle>);
bool match = findAllArgs(filter, args, 0, bindings);
return args;
}
bool ForwardChainer::findAllArgs(std::vector<BBvtree> filter, Btr<std::vector<BoundVertex> > args,
uint current_arg, Btr<bindingsT> bindings)
{
if (current_arg >= filter.size())
return true;
// std::cout << "arg #" << current_arg << std::endl;
BoundVertex bv;
BBvtree f;
f = filter[current_arg];
// TODO also subst in any FWVar bindings so far
//Btr<bindingsT> bindings(NULL); // should be a parameter to this method.
//meta virtualized_target(bindings ? bind_vtree(*f,*bindings) : meta(new vtree(*f)));
//meta virtualized_target(bindings ? bind_vtree(*f,*bindings) : meta(new vtree(*f)));
meta virtualized_target(bind_vtree(*f,*bindings));
//meta virtualized_target(meta(new vtree(*f)));
ForceAllLinksVirtual(virtualized_target);
Btr<std::set<BoundVertex> > choices;
choices = getMatching(virtualized_target); // bad_get during LookupRule... (if you use non-FWVars for that thing)
// pick one of the candidates at random to be the bv
// std::cout << "choices size: " << choices->size() << std::endl;
// random selection
//! @todo sort based on strength and exponential random select
//pHandle randArg;
if (choices->size() == 0) {
// std::cout << "backtracking" << std::endl;
return false;
}
//std::cout << "choices: " << (*choices) << std::endl;
// foreach (BoundVertex tmp, *choices)
// std::cout << tmp.GetValue().which() << std::endl;
// Alternative: is there some OpenCog library function to randomly select an item from a set?
std::vector<BoundVertex> ordered_choices;
// std::copy(choices->begin(), choices->end(), ordered_choices.begin());
foreach (BoundVertex tmp, *choices) {
//std::cout << _v2h(tmp.GetValue()) << std::endl;
ordered_choices.push_back(tmp);
}
while (ordered_choices.size() > 0) {
int index = (int) (getRNG()->randfloat() * ordered_choices.size() );
//randArg = choices[index];
bv = ordered_choices[index];
ordered_choices.erase(ordered_choices.begin() + index);
//choices.erase(choices.begin() + index);
//args[i] = randArg;
//boost::get<pHandle>(args[i]);
// std::cout << "arg #" << current_arg << std::endl;
NMPrinter np;
// std::cout << "Using atom: " << std::endl;
np.print(_v2h(bv.GetValue()));
// Separate bindings before and after applying this, in case backtracking is necessary
Btr<bindingsT> new_bindings(new std::map<pHandle, pHandle>);
// Pass down all the bindings so far, plus any for this slot.
foreach(hpair hp, *bindings)
new_bindings->insert(hp);
foreach(hpair hp, *bv.bindings)
new_bindings->insert(hp);
//(*args)[current_arg] = bv;
args->push_back(bv);
// Whether the rest of the slots are successfully filled, when we use bv for this slot
bool rest_filled = findAllArgs(filter, args, current_arg+1, new_bindings);
if (rest_filled)
return true;
args-> pop_back();
// else // tacky code to prevent more than one try
// break;
}
// std::cout << "backtracking" << std::endl;
return false;
}
}} // namespace opencog::pln
<commit_msg>Remove obsolete comment<commit_after>/*
* Copyright (C) 2008 by Singularity Institute for Artificial Intelligence
* 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 "ForwardChainer.h"
#include "AtomSpaceWrapper.h"
#include "utils/NMPrinter.h"
#include "rules/Rules.h"
#include <opencog/util/Logger.h>
#include <opencog/util/mt19937ar.h>
#include <boost/variant.hpp>
#include <time.h>
using std::vector;
using std::cout;
using std::endl;
namespace opencog {
namespace pln {
ForwardChainer::ForwardChainer()
{
float minConfidence = FWD_CHAIN_MIN_CONFIDENCE;
float probStack = FWD_CHAIN_PROB_STACK;
float probGlobal = FWD_CHAIN_PROB_GLOBAL;
}
ForwardChainer::~ForwardChainer()
{
}
pHandle ForwardChainer::fwdChainToTarget(int& maxRuleApps, meta target)
{
// Should usually only be one (or none).
pHandleSeq results = fwdChain(maxRuleApps, target);
if (results.empty())
return PHANDLE_UNDEFINED;
else
return results[0];
}
// Static/Shared random number generator
RandGen* ForwardChainer::rng = NULL;
RandGen* ForwardChainer::getRNG() {
if (!rng)
rng = new opencog::MT19937RandGen((unsigned long) time(NULL));
return rng;
}
void ForwardChainer::printVertexVectorHandles(std::vector< Vertex > hs)
{
bool firstPrint = true;
cout << "< ";
foreach(Vertex v, hs) {
if (firstPrint) {
firstPrint = false;
} else {
cout << ", ";
}
//cout << boost::get<Handle>(v).value();
cout << v;
}
cout << " >";
}
// Possibly should be elsewhere.
// Finds an input filter that has all the constraints, including between arguments.
// inputFilter doesn't include those constraints.
// Sometimes there is more than one input filter available (e.g. for SimSubstRule)
std::set<std::vector<BBvtree> > getFilters(Rule * r)
{
//meta i2oType(const std::vector<Vertex>& h) const
//! @todo extend this for other rules (probably separately for each one)
// generic target for this rule
// meta generic_target(new vtree(mva((pHandle)ASSOCIATIVE_LINK,
// vtree(CreateVar(GET_ASW)),
// vtree(CreateVar(GET_ASW))
// )));
std::vector<meta> inputFilter(r->getInputFilter());
// convert them to BoundVertex instances.
// This should all probably be refactored.
Btr<std::vector<BBvtree> > filter(new std::vector<BBvtree>);
//std::copy(inputFilter.begin(), inputFilter.end(), filter->begin());
foreach(meta item, inputFilter) {
BBvtree Btr_bound_item(new BoundVTree(*item)); // not bound yet, it just means it can be bound
filter->push_back(Btr_bound_item);
}
//return makeSingletonSet(filter);
Rule::setOfMPs ret;
ret.insert(*filter);
return ret;
meta generic_target(new vtree(mva((pHandle)ASSOCIATIVE_LINK,
mva((pHandle)ATOM),
mva((pHandle)ATOM)
)));
//cout << "getFilters";
rawPrint(generic_target->begin(), 2);
// cout << rawPrint(*generic_target,generic_target->begin(),0);
return r->o2iMeta(generic_target);
}
pHandleSeq ForwardChainer::fwdChain(int maxRuleApps, meta target)
{
pHandleSeq results;
while (maxRuleApps > 0) {
//cout << "steps remaining: " << maxRuleApps << endl;
bool appliedRule = false;
// Get the next Rule (no restrictions)
foreach(Rule *r, rp) { // to avoid needing a nextRule method.
//cout << "Using " << r->getName() << endl;
// Find the possible vector(s) of arguments for it
std::set<std::vector<BBvtree> > filters(r->fullInputFilter());
// For each such vector:
foreach(std::vector<BBvtree> f, filters) {
// find a vector of Atoms that matches it
Btr<vector<BoundVertex> > args;
args = findAllArgs(f);
// check for validity (~redundant)
//cout << "FWDCHAIN arguments ";
//printVertexVectorHandles(args); // takes Vertexes not BoundVertexes
//cout << " are valid? " <<endl;
bool foundArguments = !args->empty();//true;// = r->validate(args);
if (!foundArguments) {
//cout << "FWDCHAIN args not valid" << endl;
} else {
//cout << "FWDCHAIN args valid" << endl;
// do the rule computation etc
Vertex V=((r->compute(*args, PHANDLE_UNDEFINED, false)).GetValue());
pHandle out=boost::get<pHandle>(V);
const TruthValue& tv=GET_ASW->getTV(out);
//cout<<printTV(out)<<'\n';
if (!tv.isNullTv() && tv.getCount() > minConfidence) {
maxRuleApps--;
appliedRule = true;
if (target) { // Match it against the target
// Adapted from in Rule::validate
typedef weak_atom< meta > vertex_wrapper;
vertex_wrapper mp(target);
if (mp(out)) {
results.push_back(out);
return results;
}
} else
results.push_back(out);
//cout<<"Output\n";
NMPrinter np;
np.print(out);
} else {
// Remove atom if not satisfactory
//GET_ASW->removeAtom(_v2h(V));
}
}
}
}
// If it iterated through all Rules and couldn't find any suitable
// input in the AtomSpace. Exit to prevent an infinite loop!
if (!appliedRule) return results;
}
return results;
}
Btr<std::set<BoundVertex> > ForwardChainer::getMatching(const meta target)
{
// Just look it up via LookupRule
LookupRule lookup(GET_ASW);
Btr<std::set<BoundVertex> > matches;
// std::cout << "getMatching: target: ";
rawPrint(target->begin(), 5);
matches = lookup.attemptDirectProduction(target);
return matches;
}
Btr<vector<BoundVertex> > ForwardChainer::findAllArgs(std::vector<BBvtree> filter)
{
Btr<vector<BoundVertex> > args(new vector<BoundVertex>);
//Btr<bindingsT> bindings(new BindingsT());
Btr<bindingsT> bindings(new std::map<pHandle, pHandle>);
bool match = findAllArgs(filter, args, 0, bindings);
return args;
}
bool ForwardChainer::findAllArgs(std::vector<BBvtree> filter, Btr<std::vector<BoundVertex> > args,
uint current_arg, Btr<bindingsT> bindings)
{
if (current_arg >= filter.size())
return true;
// std::cout << "arg #" << current_arg << std::endl;
BoundVertex bv;
BBvtree f;
f = filter[current_arg];
// TODO also subst in any FWVar bindings so far
//Btr<bindingsT> bindings(NULL); // should be a parameter to this method.
//meta virtualized_target(bindings ? bind_vtree(*f,*bindings) : meta(new vtree(*f)));
//meta virtualized_target(bindings ? bind_vtree(*f,*bindings) : meta(new vtree(*f)));
meta virtualized_target(bind_vtree(*f,*bindings));
//meta virtualized_target(meta(new vtree(*f)));
ForceAllLinksVirtual(virtualized_target);
Btr<std::set<BoundVertex> > choices;
choices = getMatching(virtualized_target);
// pick one of the candidates at random to be the bv
// std::cout << "choices size: " << choices->size() << std::endl;
// random selection
//! @todo sort based on strength and exponential random select
//pHandle randArg;
if (choices->size() == 0) {
// std::cout << "backtracking" << std::endl;
return false;
}
//std::cout << "choices: " << (*choices) << std::endl;
// foreach (BoundVertex tmp, *choices)
// std::cout << tmp.GetValue().which() << std::endl;
// Alternative: is there some OpenCog library function to randomly select an item from a set?
std::vector<BoundVertex> ordered_choices;
// std::copy(choices->begin(), choices->end(), ordered_choices.begin());
foreach (BoundVertex tmp, *choices) {
//std::cout << _v2h(tmp.GetValue()) << std::endl;
ordered_choices.push_back(tmp);
}
while (ordered_choices.size() > 0) {
int index = (int) (getRNG()->randfloat() * ordered_choices.size() );
//randArg = choices[index];
bv = ordered_choices[index];
ordered_choices.erase(ordered_choices.begin() + index);
//choices.erase(choices.begin() + index);
//args[i] = randArg;
//boost::get<pHandle>(args[i]);
// std::cout << "arg #" << current_arg << std::endl;
NMPrinter np;
// std::cout << "Using atom: " << std::endl;
np.print(_v2h(bv.GetValue()));
// Separate bindings before and after applying this, in case backtracking is necessary
Btr<bindingsT> new_bindings(new std::map<pHandle, pHandle>);
// Pass down all the bindings so far, plus any for this slot.
foreach(hpair hp, *bindings)
new_bindings->insert(hp);
foreach(hpair hp, *bv.bindings)
new_bindings->insert(hp);
//(*args)[current_arg] = bv;
args->push_back(bv);
// Whether the rest of the slots are successfully filled, when we use bv for this slot
bool rest_filled = findAllArgs(filter, args, current_arg+1, new_bindings);
if (rest_filled)
return true;
args-> pop_back();
// else // tacky code to prevent more than one try
// break;
}
// std::cout << "backtracking" << std::endl;
return false;
}
}} // namespace opencog::pln
<|endoftext|> |
<commit_before>#include <iostream>
#include <stdio.h>
#include <fstream>
#include <vector>
//#include <map>
//#include <set>
#include <unordered_set>
//#include <unordered_map>
#include <cmath>
#include <algorithm>
// #include <gnuplot-iostream.h>
#include <assert.h>
#include <boost/program_options.hpp>
#include <boost/filesystem.hpp>
#include "vector3d.hpp"
#include "swiss_to_lat_lon.hpp"
#include "height_map.hpp"
const int horizon_angles = 360;
const int tile_size = 40;
namespace po = boost::program_options;
struct pos_hoz {
vector3d pos;
vector3d norm;
short elevation_angles[horizon_angles];
pos_hoz() : pos(0,0,0), norm(0,0,0) {
memset(elevation_angles, 0, sizeof(short) * horizon_angles);
}
};
bool EQ_DBL(double a, double b){
return std::abs(a-b)<EPS_DBL;
}
int main(int ac, char** av) {
bool test = false;
//Variables to be assigned by program options
double height_map_resolution;
double north_bound;
double south_bound;
double east_bound;
double west_bound;
std::string input_file;
std::string output_dir;
bool verbose = false;
// Declare the supported options.
po::options_description op_desc("Allowed options");
op_desc.add_options()
("help", "print options table")
("input-file,i", po::value<std::string>(&input_file), "File containing height map data in x<space>y<space>z<newline> swiss coordinates format")
("output-dir,o", po::value<std::string>(&output_dir), "Directory for output files (default data_out_<date_time>)")
("resolution,R", po::value<double>(&height_map_resolution)->default_value(25.0), "resolution of data (default: 25.0)")
("nmax",po::value<double>(&north_bound)->default_value(1e100), "maximum north coordinate to be treated (default 1e100)")
("nmin",po::value<double>(&south_bound)->default_value(-1e100), "minimum north coordinate to be treated (default -1e100)")
("emax",po::value<double>(&east_bound)->default_value(1e100), "maximum east coordinate to be treated (default 1e100)")
("emin",po::value<double>(&west_bound)->default_value(-1e100), "minimum east coordinate to be treated (default -1e100)")
("verbose, v", "Verbose: output lots of text")
;
po::positional_options_description pd;
pd.add("input-file", 1).add("output-file", 1);
po::variables_map vm;
po::store(po::parse_command_line(ac, av, op_desc), vm);
po::notify(vm);
if (vm.count("help")) {
std::cout <<"ComputeHorizons [options] [input file] [output base]"<<std::endl<< op_desc << std::endl;
return 1;
}
if (vm.count("verbose")){
verbose = true;
}
if(!vm.count("input-file")){
std::cout << "Input file must be specified" << std::endl;
exit(255);
}
if(!vm.count("output-dir")){
std::time_t now = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
std::string time_string(30, 0);
std::strftime(&time_string[0], time_string.size(), "%Yx%mx%dT%Hx%Mx%S", std::localtime(&now));
output_dir = std::string("hoz_out_")+time_string;
std::cout << "Output directory will be: "+output_dir << std::endl;
}
//create output directory
boost::filesystem::path dir(output_dir);
if(!boost::filesystem::create_directory(dir)) {
std::cout << "Failed to creat output directory" << "\n";
exit(255);
}
std::ifstream ifs(input_file);
if (!ifs.is_open())
throw std::runtime_error("could not open file : " + std::string(input_file));
height_map grid_points(ifs, south_bound, north_bound, east_bound, west_bound);
//grid_points is a height_map, an unordered_set of all points in bounding box with
//the maximum and minimum x,y,h of all values stored.
std::pair<double,double> NE = swiss_to_lat_lon(grid_points.xmax()+height_map_resolution/2.0, grid_points.ymax()+height_map_resolution/2.0);
std::pair<double,double> SW = swiss_to_lat_lon(grid_points.xmin()-height_map_resolution/2.0, grid_points.ymin()-height_map_resolution/2.0);
std::cout << "NE: " << grid_points.xmax() <<", " << grid_points.ymax() << " SW: "<< grid_points.xmin() << " , " << grid_points.ymin() << std::endl;
std::cout << "NE: " << NE.first <<", " << NE.second << " SW: "<< SW.first << ", " << SW.second << std::endl;
std::cout << "Maximum height: " << grid_points.hmax() << std::endl;
std::cout << "Number of points in dataset: " << grid_points.size() << std::endl;
if(test){
double y_test = height_map_resolution*floor(601430.0/height_map_resolution);
double x_test = height_map_resolution*floor(126243.0/height_map_resolution);
auto it_v = grid_points.find_point(vector3d(x_test,y_test,0)); //get the gridpoint from the set
std::cout << "Test point: " << x_test <<" "<< y_test << std::endl;
std::cout << "Resolution: " << height_map_resolution << ", tile size: "<< tile_size << std::endl;
vector3d v = *it_v;
double elevation_angles[360];
int theta_start = 0;
int theta_end = 360;
// time_t start_time = time(NULL);
clock_t t = clock();
for(int theta = theta_start;theta<theta_end;theta++){
elevation_angles[theta] = grid_points.compute_elevation_angle(v, theta, height_map_resolution, 1.0);
}
double run_time = ((double)(clock()-t))/CLOCKS_PER_SEC;
// double run_time = difftime(time(NULL), start_time);
std::cout << "phi = [";
for(int theta = theta_start;theta<theta_end;theta++){
std::cout << elevation_angles[theta] << ";";
}
std::cout << "];" << std::endl;
std::cout << "runtime test point: " << run_time << std::endl;
std::cout << "estimated runtime all points: " << run_time*grid_points.size() << std::endl;
return 0;
}
std::string file_name;
std::ofstream ofs;
time_t start_time = time(NULL);
int N=0;
int NT=0;
int first_tile_y = (int) (grid_points.ymin()+10.0*height_map_resolution);
int first_tile_x = (int) (grid_points.xmin()+10.0*height_map_resolution);
int N_tiles_x = (int) ceil((grid_points.xmax()-grid_points.xmin()-20.0*height_map_resolution)/tile_size);
int N_tiles_y = (int) ceil((grid_points.ymax()-grid_points.ymin()-20.0*height_map_resolution)/tile_size);
pos_hoz tile_points[tile_size*tile_size];
for(int x_tile = 0;x_tile<N_tiles_x; x_tile++){
for(int y_tile = 0; y_tile<N_tiles_y;y_tile++){
double coord_x = (first_tile_x + height_map_resolution*tile_size*x_tile);
double coord_x_end = coord_x+height_map_resolution*tile_size;
int tile_point = 0;
while(coord_x < coord_x_end){
double coord_y = (first_tile_y + height_map_resolution*tile_size*y_tile);
double coord_y_end = coord_y+height_map_resolution*tile_size;
while(coord_y < coord_y_end){
//get point and points to the north, west, south and east
vector3d v(coord_x, coord_y, 0.0);
vector3d vN(v.x+height_map_resolution,v.y,0);
vector3d vW(v.x,v.y+height_map_resolution,0);
vector3d vS(v.x-height_map_resolution,v.y,0);
vector3d vE(v.x,v.y-height_map_resolution,0);
auto itv=grid_points.find_point(v);
auto itE=grid_points.find_point(vE);
auto itN=grid_points.find_point(vN);
auto itW=grid_points.find_point(vW);
auto itS=grid_points.find_point(vS);
if (grid_points.is_end(itv) ||grid_points.is_end(itE) || grid_points.is_end(itN) || grid_points.is_end(itW) || grid_points.is_end(itS)){
coord_y = coord_y + height_map_resolution;
tile_points[tile_point].pos = vector3d(0,0,0);
tile_point++;
continue;
//if one of the neighboring points are not found we continue with the next point
}
v = *itv;
vE = *itE;
vN = *itN;
vW = *itW;
vS = *itS;
tile_points[tile_point].pos = v;
vector3d Normal = ((((vE-v)^(vN-v))+((vW-v)^(vS-v)))/2).norm(); //normal is the crossproduct of two prependicular differences. Avgd.
tile_points[tile_point].norm = Normal;
for(int theta=0;theta<horizon_angles;theta++){
double phi = grid_points.compute_elevation_angle(v,theta, height_map_resolution, 360.0/horizon_angles);
tile_points[tile_point].elevation_angles[theta] = (short)((phi / M_PI_2) * std::numeric_limits<short>::max());
}
N++;
coord_y = coord_y + height_map_resolution;
tile_point++;
if (N%40==0) {
double run_time = difftime(time(NULL), start_time);
int rdays = (int)floor(run_time/86400.0);
int rhours = (int)floor((run_time-rdays*86400)/3600.0);
int rminutes = (int)floor((run_time-rdays*86400.0-rhours*3600.0)/60.0);
int rseconds = (int)floor(run_time-rdays*86400.0-rhours*3600.0-rminutes*60.0);
double remaining_time = ((grid_points.size() - N)*1.0)*run_time/(N*1.0);
int days = (int)floor(remaining_time/86400.0);
int hours = (int)floor((remaining_time-days*86400)/3600.0);
int minutes = (int)floor((remaining_time-days*86400-hours*3600.0)/60.0);
int seconds = (int)floor(remaining_time-days*86400-hours*3600.0-minutes*60.0);
double progress = round(1000.0*100.0*(N*1.0)/(grid_points.size()*1.0))/1000.0;
if(N > 0){
std::cout <<" Progress: "<< progress <<" % ("<<N<<", "<<NT<<") time: "<<rdays<<"d"<<rhours<<":"<<rminutes<<":"<<rseconds<<" time left: "<<days<<"d"<<hours<<":"<<minutes<<":"<<seconds<<" \r";
std::cout.flush();
}
}
}
coord_x = coord_x + height_map_resolution;
}
std::string tile_name;
int tile_x = (first_tile_x + height_map_resolution*tile_size*x_tile);
int tile_y = (first_tile_y + height_map_resolution*tile_size*y_tile);
tile_name = output_dir + std::string("/tile_") + std::to_string(tile_x) + std::string("_") + std::to_string(tile_y) + std::string(".hoz");
// std::cout << std::endl << "tile_name " << tile_name << std::endl;
ofs.open(tile_name, std::iostream::out | std::iostream::binary);
// std::cout << "first point" << tile_points[0].pos << "norm: " << tile_points[0].norm<< std::endl;
//open output file
if (!ofs.is_open()){
std::cout << "Can't open output file " << tile_name << std::endl;
}
ofs.write((char*)&tile_points[0], sizeof(pos_hoz)*tile_size*tile_size);
ofs.flush();
ofs.close();
NT++;
}
}
return 0;
}
<commit_msg>Don't create empty tiles!<commit_after>#include <iostream>
#include <stdio.h>
#include <fstream>
#include <vector>
//#include <map>
//#include <set>
#include <unordered_set>
//#include <unordered_map>
#include <cmath>
#include <algorithm>
// #include <gnuplot-iostream.h>
#include <assert.h>
#include <boost/program_options.hpp>
#include <boost/filesystem.hpp>
#include "vector3d.hpp"
#include "swiss_to_lat_lon.hpp"
#include "height_map.hpp"
const int horizon_angles = 360;
const int tile_size = 40;
namespace po = boost::program_options;
struct pos_hoz {
vector3d pos;
vector3d norm;
short elevation_angles[horizon_angles];
pos_hoz() : pos(0,0,0), norm(0,0,0) {
memset(elevation_angles, 0, sizeof(short) * horizon_angles);
}
};
bool EQ_DBL(double a, double b){
return std::abs(a-b)<EPS_DBL;
}
int main(int ac, char** av) {
bool test = false;
//Variables to be assigned by program options
double height_map_resolution;
double north_bound;
double south_bound;
double east_bound;
double west_bound;
std::string input_file;
std::string output_dir;
bool verbose = false;
// Declare the supported options.
po::options_description op_desc("Allowed options");
op_desc.add_options()
("help", "print options table")
("input-file,i", po::value<std::string>(&input_file), "File containing height map data in x<space>y<space>z<newline> swiss coordinates format")
("output-dir,o", po::value<std::string>(&output_dir), "Directory for output files (default data_out_<date_time>)")
("resolution,R", po::value<double>(&height_map_resolution)->default_value(25.0), "resolution of data (default: 25.0)")
("nmax",po::value<double>(&north_bound)->default_value(1e100), "maximum north coordinate to be treated (default 1e100)")
("nmin",po::value<double>(&south_bound)->default_value(-1e100), "minimum north coordinate to be treated (default -1e100)")
("emax",po::value<double>(&east_bound)->default_value(1e100), "maximum east coordinate to be treated (default 1e100)")
("emin",po::value<double>(&west_bound)->default_value(-1e100), "minimum east coordinate to be treated (default -1e100)")
("verbose, v", "Verbose: output lots of text")
;
po::positional_options_description pd;
pd.add("input-file", 1).add("output-file", 1);
po::variables_map vm;
po::store(po::parse_command_line(ac, av, op_desc), vm);
po::notify(vm);
if (vm.count("help")) {
std::cout <<"ComputeHorizons [options] [input file] [output base]"<<std::endl<< op_desc << std::endl;
return 1;
}
if (vm.count("verbose")){
verbose = true;
}
if(!vm.count("input-file")){
std::cout << "Input file must be specified" << std::endl;
exit(255);
}
if(!vm.count("output-dir")){
std::time_t now = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
std::string time_string(30, 0);
std::strftime(&time_string[0], time_string.size(), "%Yx%mx%dT%Hx%Mx%S", std::localtime(&now));
output_dir = std::string("hoz_out_")+time_string;
std::cout << "Output directory will be: "+output_dir << std::endl;
}
//create output directory
boost::filesystem::path dir(output_dir);
if(!boost::filesystem::create_directory(dir)) {
std::cout << "Failed to creat output directory" << "\n";
exit(255);
}
std::ifstream ifs(input_file);
if (!ifs.is_open())
throw std::runtime_error("could not open file : " + std::string(input_file));
height_map grid_points(ifs, south_bound, north_bound, east_bound, west_bound);
//grid_points is a height_map, an unordered_set of all points in bounding box with
//the maximum and minimum x,y,h of all values stored.
std::pair<double,double> NE = swiss_to_lat_lon(grid_points.xmax()+height_map_resolution/2.0, grid_points.ymax()+height_map_resolution/2.0);
std::pair<double,double> SW = swiss_to_lat_lon(grid_points.xmin()-height_map_resolution/2.0, grid_points.ymin()-height_map_resolution/2.0);
std::cout << "NE: " << grid_points.xmax() <<", " << grid_points.ymax() << " SW: "<< grid_points.xmin() << " , " << grid_points.ymin() << std::endl;
std::cout << "NE: " << NE.first <<", " << NE.second << " SW: "<< SW.first << ", " << SW.second << std::endl;
std::cout << "Maximum height: " << grid_points.hmax() << std::endl;
std::cout << "Number of points in dataset: " << grid_points.size() << std::endl;
if(test){
double y_test = height_map_resolution*floor(601430.0/height_map_resolution);
double x_test = height_map_resolution*floor(126243.0/height_map_resolution);
auto it_v = grid_points.find_point(vector3d(x_test,y_test,0)); //get the gridpoint from the set
std::cout << "Test point: " << x_test <<" "<< y_test << std::endl;
std::cout << "Resolution: " << height_map_resolution << ", tile size: "<< tile_size << std::endl;
vector3d v = *it_v;
double elevation_angles[360];
int theta_start = 0;
int theta_end = 360;
// time_t start_time = time(NULL);
clock_t t = clock();
for(int theta = theta_start;theta<theta_end;theta++){
elevation_angles[theta] = grid_points.compute_elevation_angle(v, theta, height_map_resolution, 1.0);
}
double run_time = ((double)(clock()-t))/CLOCKS_PER_SEC;
// double run_time = difftime(time(NULL), start_time);
std::cout << "phi = [";
for(int theta = theta_start;theta<theta_end;theta++){
std::cout << elevation_angles[theta] << ";";
}
std::cout << "];" << std::endl;
std::cout << "runtime test point: " << run_time << std::endl;
std::cout << "estimated runtime all points: " << run_time*grid_points.size() << std::endl;
return 0;
}
std::string file_name;
std::ofstream ofs;
time_t start_time = time(NULL);
int N=0;
int NT=0;
int first_tile_y = (int) (grid_points.ymin()+10.0*height_map_resolution);
int first_tile_x = (int) (grid_points.xmin()+10.0*height_map_resolution);
int N_tiles_x = (int) ceil((grid_points.xmax()-grid_points.xmin()-20.0*height_map_resolution)/tile_size);
int N_tiles_y = (int) ceil((grid_points.ymax()-grid_points.ymin()-20.0*height_map_resolution)/tile_size);
pos_hoz tile_points[tile_size*tile_size];
bool tile_empty = true;
for(int x_tile = 0;x_tile<N_tiles_x; x_tile++){
for(int y_tile = 0; y_tile<N_tiles_y;y_tile++){
double coord_x = (first_tile_x + height_map_resolution*tile_size*x_tile);
double coord_x_end = coord_x+height_map_resolution*tile_size;
int tile_point = 0;
tile_empty = true;
while(coord_x < coord_x_end){
double coord_y = (first_tile_y + height_map_resolution*tile_size*y_tile);
double coord_y_end = coord_y+height_map_resolution*tile_size;
while(coord_y < coord_y_end){
//get point and points to the north, west, south and east
vector3d v(coord_x, coord_y, 0.0);
vector3d vN(v.x+height_map_resolution,v.y,0);
vector3d vW(v.x,v.y+height_map_resolution,0);
vector3d vS(v.x-height_map_resolution,v.y,0);
vector3d vE(v.x,v.y-height_map_resolution,0);
auto itv=grid_points.find_point(v);
auto itE=grid_points.find_point(vE);
auto itN=grid_points.find_point(vN);
auto itW=grid_points.find_point(vW);
auto itS=grid_points.find_point(vS);
if (grid_points.is_end(itv) ||grid_points.is_end(itE) || grid_points.is_end(itN) || grid_points.is_end(itW) || grid_points.is_end(itS)){
coord_y = coord_y + height_map_resolution;
tile_points[tile_point].pos = vector3d(0,0,0);
tile_point++;
continue;
//if one of the neighboring points are not found we continue with the next point
}
v = *itv;
vE = *itE;
vN = *itN;
vW = *itW;
vS = *itS;
tile_points[tile_point].pos = v;
vector3d Normal = ((((vE-v)^(vN-v))+((vW-v)^(vS-v)))/2).norm(); //normal is the crossproduct of two prependicular differences. Avgd.
tile_points[tile_point].norm = Normal;
for(int theta=0;theta<horizon_angles;theta++){
double phi = grid_points.compute_elevation_angle(v,theta, height_map_resolution, 360.0/horizon_angles);
tile_points[tile_point].elevation_angles[theta] = (short)((phi / M_PI_2) * std::numeric_limits<short>::max());
}
tile_empty = false;
N++;
coord_y = coord_y + height_map_resolution;
tile_point++;
if (N%40==0) {
double run_time = difftime(time(NULL), start_time);
int rdays = (int)floor(run_time/86400.0);
int rhours = (int)floor((run_time-rdays*86400)/3600.0);
int rminutes = (int)floor((run_time-rdays*86400.0-rhours*3600.0)/60.0);
int rseconds = (int)floor(run_time-rdays*86400.0-rhours*3600.0-rminutes*60.0);
double remaining_time = ((grid_points.size() - N)*1.0)*run_time/(N*1.0);
int days = (int)floor(remaining_time/86400.0);
int hours = (int)floor((remaining_time-days*86400)/3600.0);
int minutes = (int)floor((remaining_time-days*86400-hours*3600.0)/60.0);
int seconds = (int)floor(remaining_time-days*86400-hours*3600.0-minutes*60.0);
double progress = round(1000.0*100.0*(N*1.0)/(grid_points.size()*1.0))/1000.0;
if(N > 0){
std::cout <<" Progress: "<< progress <<" % ("<<N<<", "<<NT<<") time: "<<rdays<<"d"<<rhours<<":"<<rminutes<<":"<<rseconds<<" time left: "<<days<<"d"<<hours<<":"<<minutes<<":"<<seconds<<" \r";
std::cout.flush();
}
}
}
coord_x = coord_x + height_map_resolution;
}
if(!tile_empty){
std::string tile_name;
int tile_x = (first_tile_x + height_map_resolution*tile_size*x_tile);
int tile_y = (first_tile_y + height_map_resolution*tile_size*y_tile);
tile_name = output_dir + std::string("/tile_") + std::to_string(tile_x) + std::string("_") + std::to_string(tile_y) + std::string(".hoz");
// std::cout << std::endl << "tile_name " << tile_name << std::endl;
ofs.open(tile_name, std::iostream::out | std::iostream::binary);
// std::cout << "first point" << tile_points[0].pos << "norm: " << tile_points[0].norm<< std::endl;
//open output file
if (!ofs.is_open()){
std::cout << "Can't open output file " << tile_name << std::endl;
}
ofs.write((char*)&tile_points[0], sizeof(pos_hoz)*tile_size*tile_size);
ofs.flush();
ofs.close();
NT++;
}
}
}
return 0;
}
<|endoftext|> |
<commit_before><commit_msg>Delete mqBI2qNewton.cc<commit_after><|endoftext|> |
<commit_before>/*
* Copyright (C) 2007, 2008, 2009, 2010 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 "core/html/HTMLVideoElement.h"
#include "bindings/core/v8/ExceptionState.h"
#include "core/CSSPropertyNames.h"
#include "core/HTMLNames.h"
#include "core/dom/Attribute.h"
#include "core/dom/Document.h"
#include "core/dom/ExceptionCode.h"
#include "core/dom/shadow/ShadowRoot.h"
#include "core/frame/Settings.h"
#include "core/html/HTMLImageLoader.h"
#include "core/html/canvas/CanvasRenderingContext.h"
#include "core/html/parser/HTMLParserIdioms.h"
#include "core/rendering/RenderImage.h"
#include "core/rendering/RenderVideo.h"
#include "platform/UserGestureIndicator.h"
#include "platform/graphics/GraphicsContext.h"
#include "platform/graphics/ImageBuffer.h"
#include "platform/graphics/gpu/Extensions3DUtil.h"
#include "public/platform/WebCanvas.h"
#include "public/platform/WebGraphicsContext3D.h"
namespace blink {
using namespace HTMLNames;
inline HTMLVideoElement::HTMLVideoElement(Document& document)
: HTMLMediaElement(videoTag, document)
{
if (document.settings())
m_defaultPosterURL = AtomicString(document.settings()->defaultVideoPosterURL());
}
PassRefPtrWillBeRawPtr<HTMLVideoElement> HTMLVideoElement::create(Document& document)
{
RefPtrWillBeRawPtr<HTMLVideoElement> video = adoptRefWillBeNoop(new HTMLVideoElement(document));
video->ensureUserAgentShadowRoot();
video->suspendIfNeeded();
return video.release();
}
void HTMLVideoElement::trace(Visitor* visitor)
{
visitor->trace(m_imageLoader);
HTMLMediaElement::trace(visitor);
}
bool HTMLVideoElement::rendererIsNeeded(const RenderStyle& style)
{
return HTMLElement::rendererIsNeeded(style);
}
LayoutObject* HTMLVideoElement::createRenderer(const RenderStyle&)
{
return new RenderVideo(this);
}
void HTMLVideoElement::attach(const AttachContext& context)
{
HTMLMediaElement::attach(context);
updateDisplayState();
if (shouldDisplayPosterImage()) {
if (!m_imageLoader)
m_imageLoader = HTMLImageLoader::create(this);
m_imageLoader->updateFromElement();
if (renderer())
toRenderImage(renderer())->imageResource()->setImageResource(m_imageLoader->image());
}
}
void HTMLVideoElement::collectStyleForPresentationAttribute(const QualifiedName& name, const AtomicString& value, MutableStylePropertySet* style)
{
if (name == widthAttr)
addHTMLLengthToStyle(style, CSSPropertyWidth, value);
else if (name == heightAttr)
addHTMLLengthToStyle(style, CSSPropertyHeight, value);
else
HTMLMediaElement::collectStyleForPresentationAttribute(name, value, style);
}
bool HTMLVideoElement::isPresentationAttribute(const QualifiedName& name) const
{
if (name == widthAttr || name == heightAttr)
return true;
return HTMLMediaElement::isPresentationAttribute(name);
}
void HTMLVideoElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
{
if (name == posterAttr) {
// Force a poster recalc by setting m_displayMode to Unknown directly before calling updateDisplayState.
HTMLMediaElement::setDisplayMode(Unknown);
updateDisplayState();
if (shouldDisplayPosterImage()) {
if (!m_imageLoader)
m_imageLoader = HTMLImageLoader::create(this);
m_imageLoader->updateFromElement(ImageLoader::UpdateIgnorePreviousError);
} else {
if (renderer())
toRenderImage(renderer())->imageResource()->setImageResource(0);
}
// Notify the player when the poster image URL changes.
if (webMediaPlayer())
webMediaPlayer()->setPoster(posterImageURL());
} else {
HTMLMediaElement::parseAttribute(name, value);
}
}
bool HTMLVideoElement::supportsFullscreen() const
{
if (!document().page())
return false;
if (!webMediaPlayer())
return false;
return true;
}
unsigned HTMLVideoElement::videoWidth() const
{
if (!webMediaPlayer())
return 0;
return webMediaPlayer()->naturalSize().width;
}
unsigned HTMLVideoElement::videoHeight() const
{
if (!webMediaPlayer())
return 0;
return webMediaPlayer()->naturalSize().height;
}
bool HTMLVideoElement::isURLAttribute(const Attribute& attribute) const
{
return attribute.name() == posterAttr || HTMLMediaElement::isURLAttribute(attribute);
}
const AtomicString HTMLVideoElement::imageSourceURL() const
{
const AtomicString& url = getAttribute(posterAttr);
if (!stripLeadingAndTrailingHTMLSpaces(url).isEmpty())
return url;
return m_defaultPosterURL;
}
void HTMLVideoElement::setDisplayMode(DisplayMode mode)
{
DisplayMode oldMode = displayMode();
KURL poster = posterImageURL();
if (!poster.isEmpty()) {
// We have a poster path, but only show it until the user triggers display by playing or seeking and the
// media engine has something to display.
// Don't show the poster if there is a seek operation or
// the video has restarted because of loop attribute
if (mode == Video && oldMode == Poster && !hasAvailableVideoFrame())
return;
}
HTMLMediaElement::setDisplayMode(mode);
if (renderer() && displayMode() != oldMode)
renderer()->updateFromElement();
}
void HTMLVideoElement::updateDisplayState()
{
if (posterImageURL().isEmpty())
setDisplayMode(Video);
else if (displayMode() < Poster)
setDisplayMode(Poster);
}
void HTMLVideoElement::paintCurrentFrameInContext(GraphicsContext* context, const IntRect& destRect) const
{
if (!webMediaPlayer())
return;
WebCanvas* canvas = context->canvas();
SkXfermode::Mode mode = context->compositeOperation();
webMediaPlayer()->paint(canvas, destRect, context->getNormalizedAlpha(), mode);
}
bool HTMLVideoElement::copyVideoTextureToPlatformTexture(WebGraphicsContext3D* context, Platform3DObject texture, GLint level, GLenum internalFormat, GLenum type, bool premultiplyAlpha, bool flipY)
{
if (!webMediaPlayer())
return false;
if (!Extensions3DUtil::canUseCopyTextureCHROMIUM(internalFormat, type, level))
return false;
return webMediaPlayer()->copyVideoTextureToPlatformTexture(context, texture, level, internalFormat, type, premultiplyAlpha, flipY);
}
bool HTMLVideoElement::hasAvailableVideoFrame() const
{
if (!webMediaPlayer())
return false;
return webMediaPlayer()->hasVideo() && webMediaPlayer()->readyState() >= blink::WebMediaPlayer::ReadyStateHaveCurrentData;
}
void HTMLVideoElement::webkitEnterFullscreen(ExceptionState& exceptionState)
{
if (isFullscreen())
return;
if (!supportsFullscreen()) {
exceptionState.throwDOMException(InvalidStateError, "This element does not support fullscreen mode.");
return;
}
enterFullscreen();
}
void HTMLVideoElement::webkitExitFullscreen()
{
if (isFullscreen())
exitFullscreen();
}
bool HTMLVideoElement::webkitSupportsFullscreen()
{
return supportsFullscreen();
}
bool HTMLVideoElement::webkitDisplayingFullscreen()
{
return isFullscreen();
}
void HTMLVideoElement::didMoveToNewDocument(Document& oldDocument)
{
if (m_imageLoader)
m_imageLoader->elementDidMoveToNewDocument();
HTMLMediaElement::didMoveToNewDocument(oldDocument);
}
unsigned HTMLVideoElement::webkitDecodedFrameCount() const
{
if (!webMediaPlayer())
return 0;
return webMediaPlayer()->decodedFrameCount();
}
unsigned HTMLVideoElement::webkitDroppedFrameCount() const
{
if (!webMediaPlayer())
return 0;
return webMediaPlayer()->droppedFrameCount();
}
KURL HTMLVideoElement::posterImageURL() const
{
String url = stripLeadingAndTrailingHTMLSpaces(imageSourceURL());
if (url.isEmpty())
return KURL();
return document().completeURL(url);
}
KURL HTMLVideoElement::mediaPlayerPosterURL()
{
return posterImageURL();
}
PassRefPtr<Image> HTMLVideoElement::getSourceImageForCanvas(SourceImageMode mode, SourceImageStatus* status) const
{
if (!hasAvailableVideoFrame()) {
*status = InvalidSourceImageStatus;
return nullptr;
}
IntSize intrinsicSize(videoWidth(), videoHeight());
OwnPtr<ImageBuffer> imageBuffer = ImageBuffer::create(intrinsicSize);
if (!imageBuffer) {
*status = InvalidSourceImageStatus;
return nullptr;
}
paintCurrentFrameInContext(imageBuffer->context(), IntRect(IntPoint(0, 0), intrinsicSize));
*status = NormalSourceImageStatus;
return imageBuffer->copyImage(mode == CopySourceImageIfVolatile ? CopyBackingStore : DontCopyBackingStore, Unscaled);
}
bool HTMLVideoElement::wouldTaintOrigin(SecurityOrigin* destinationSecurityOrigin) const
{
return !hasSingleSecurityOrigin() || (!(webMediaPlayer() && webMediaPlayer()->didPassCORSAccessCheck()) && destinationSecurityOrigin->taintsCanvas(currentSrc()));
}
FloatSize HTMLVideoElement::sourceSize() const
{
return FloatSize(videoWidth(), videoHeight());
}
}
<commit_msg>Fix flaky timeout of yuv-video-on-accelerated-canvas.html<commit_after>/*
* Copyright (C) 2007, 2008, 2009, 2010 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 "core/html/HTMLVideoElement.h"
#include "bindings/core/v8/ExceptionState.h"
#include "core/CSSPropertyNames.h"
#include "core/HTMLNames.h"
#include "core/dom/Attribute.h"
#include "core/dom/Document.h"
#include "core/dom/ExceptionCode.h"
#include "core/dom/shadow/ShadowRoot.h"
#include "core/frame/Settings.h"
#include "core/html/HTMLImageLoader.h"
#include "core/html/canvas/CanvasRenderingContext.h"
#include "core/html/parser/HTMLParserIdioms.h"
#include "core/rendering/RenderImage.h"
#include "core/rendering/RenderVideo.h"
#include "platform/UserGestureIndicator.h"
#include "platform/graphics/GraphicsContext.h"
#include "platform/graphics/ImageBuffer.h"
#include "platform/graphics/gpu/Extensions3DUtil.h"
#include "public/platform/WebCanvas.h"
#include "public/platform/WebGraphicsContext3D.h"
namespace blink {
using namespace HTMLNames;
inline HTMLVideoElement::HTMLVideoElement(Document& document)
: HTMLMediaElement(videoTag, document)
{
if (document.settings())
m_defaultPosterURL = AtomicString(document.settings()->defaultVideoPosterURL());
}
PassRefPtrWillBeRawPtr<HTMLVideoElement> HTMLVideoElement::create(Document& document)
{
RefPtrWillBeRawPtr<HTMLVideoElement> video = adoptRefWillBeNoop(new HTMLVideoElement(document));
video->ensureUserAgentShadowRoot();
video->suspendIfNeeded();
return video.release();
}
void HTMLVideoElement::trace(Visitor* visitor)
{
visitor->trace(m_imageLoader);
HTMLMediaElement::trace(visitor);
}
bool HTMLVideoElement::rendererIsNeeded(const RenderStyle& style)
{
return HTMLElement::rendererIsNeeded(style);
}
LayoutObject* HTMLVideoElement::createRenderer(const RenderStyle&)
{
return new RenderVideo(this);
}
void HTMLVideoElement::attach(const AttachContext& context)
{
HTMLMediaElement::attach(context);
updateDisplayState();
if (shouldDisplayPosterImage()) {
if (!m_imageLoader)
m_imageLoader = HTMLImageLoader::create(this);
m_imageLoader->updateFromElement();
if (renderer())
toRenderImage(renderer())->imageResource()->setImageResource(m_imageLoader->image());
}
}
void HTMLVideoElement::collectStyleForPresentationAttribute(const QualifiedName& name, const AtomicString& value, MutableStylePropertySet* style)
{
if (name == widthAttr)
addHTMLLengthToStyle(style, CSSPropertyWidth, value);
else if (name == heightAttr)
addHTMLLengthToStyle(style, CSSPropertyHeight, value);
else
HTMLMediaElement::collectStyleForPresentationAttribute(name, value, style);
}
bool HTMLVideoElement::isPresentationAttribute(const QualifiedName& name) const
{
if (name == widthAttr || name == heightAttr)
return true;
return HTMLMediaElement::isPresentationAttribute(name);
}
void HTMLVideoElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
{
if (name == posterAttr) {
// Force a poster recalc by setting m_displayMode to Unknown directly before calling updateDisplayState.
HTMLMediaElement::setDisplayMode(Unknown);
updateDisplayState();
if (shouldDisplayPosterImage()) {
if (!m_imageLoader)
m_imageLoader = HTMLImageLoader::create(this);
m_imageLoader->updateFromElement(ImageLoader::UpdateIgnorePreviousError);
} else {
if (renderer())
toRenderImage(renderer())->imageResource()->setImageResource(0);
}
// Notify the player when the poster image URL changes.
if (webMediaPlayer())
webMediaPlayer()->setPoster(posterImageURL());
} else {
HTMLMediaElement::parseAttribute(name, value);
}
}
bool HTMLVideoElement::supportsFullscreen() const
{
if (!document().page())
return false;
if (!webMediaPlayer())
return false;
return true;
}
unsigned HTMLVideoElement::videoWidth() const
{
if (!webMediaPlayer())
return 0;
return webMediaPlayer()->naturalSize().width;
}
unsigned HTMLVideoElement::videoHeight() const
{
if (!webMediaPlayer())
return 0;
return webMediaPlayer()->naturalSize().height;
}
bool HTMLVideoElement::isURLAttribute(const Attribute& attribute) const
{
return attribute.name() == posterAttr || HTMLMediaElement::isURLAttribute(attribute);
}
const AtomicString HTMLVideoElement::imageSourceURL() const
{
const AtomicString& url = getAttribute(posterAttr);
if (!stripLeadingAndTrailingHTMLSpaces(url).isEmpty())
return url;
return m_defaultPosterURL;
}
void HTMLVideoElement::setDisplayMode(DisplayMode mode)
{
DisplayMode oldMode = displayMode();
KURL poster = posterImageURL();
if (!poster.isEmpty()) {
// We have a poster path, but only show it until the user triggers display by playing or seeking and the
// media engine has something to display.
// Don't show the poster if there is a seek operation or
// the video has restarted because of loop attribute
if (mode == Video && oldMode == Poster && !hasAvailableVideoFrame())
return;
}
HTMLMediaElement::setDisplayMode(mode);
if (renderer() && displayMode() != oldMode)
renderer()->updateFromElement();
}
void HTMLVideoElement::updateDisplayState()
{
if (posterImageURL().isEmpty())
setDisplayMode(Video);
else if (displayMode() < Poster)
setDisplayMode(Poster);
}
void HTMLVideoElement::paintCurrentFrameInContext(GraphicsContext* context, const IntRect& destRect) const
{
if (!webMediaPlayer())
return;
WebCanvas* canvas = context->canvas();
SkXfermode::Mode mode = context->compositeOperation();
webMediaPlayer()->paint(canvas, destRect, context->getNormalizedAlpha(), mode);
}
bool HTMLVideoElement::copyVideoTextureToPlatformTexture(WebGraphicsContext3D* context, Platform3DObject texture, GLint level, GLenum internalFormat, GLenum type, bool premultiplyAlpha, bool flipY)
{
if (!webMediaPlayer())
return false;
if (!Extensions3DUtil::canUseCopyTextureCHROMIUM(internalFormat, type, level))
return false;
return webMediaPlayer()->copyVideoTextureToPlatformTexture(context, texture, level, internalFormat, type, premultiplyAlpha, flipY);
}
bool HTMLVideoElement::hasAvailableVideoFrame() const
{
if (!webMediaPlayer())
return false;
return webMediaPlayer()->hasVideo() && webMediaPlayer()->readyState() >= blink::WebMediaPlayer::ReadyStateHaveCurrentData;
}
void HTMLVideoElement::webkitEnterFullscreen(ExceptionState& exceptionState)
{
if (isFullscreen())
return;
if (!supportsFullscreen()) {
exceptionState.throwDOMException(InvalidStateError, "This element does not support fullscreen mode.");
return;
}
enterFullscreen();
}
void HTMLVideoElement::webkitExitFullscreen()
{
if (isFullscreen())
exitFullscreen();
}
bool HTMLVideoElement::webkitSupportsFullscreen()
{
return supportsFullscreen();
}
bool HTMLVideoElement::webkitDisplayingFullscreen()
{
return isFullscreen();
}
void HTMLVideoElement::didMoveToNewDocument(Document& oldDocument)
{
if (m_imageLoader)
m_imageLoader->elementDidMoveToNewDocument();
HTMLMediaElement::didMoveToNewDocument(oldDocument);
}
unsigned HTMLVideoElement::webkitDecodedFrameCount() const
{
if (!webMediaPlayer())
return 0;
return webMediaPlayer()->decodedFrameCount();
}
unsigned HTMLVideoElement::webkitDroppedFrameCount() const
{
if (!webMediaPlayer())
return 0;
return webMediaPlayer()->droppedFrameCount();
}
KURL HTMLVideoElement::posterImageURL() const
{
String url = stripLeadingAndTrailingHTMLSpaces(imageSourceURL());
if (url.isEmpty())
return KURL();
return document().completeURL(url);
}
KURL HTMLVideoElement::mediaPlayerPosterURL()
{
return posterImageURL();
}
PassRefPtr<Image> HTMLVideoElement::getSourceImageForCanvas(SourceImageMode mode, SourceImageStatus* status) const
{
if (!hasAvailableVideoFrame()) {
*status = InvalidSourceImageStatus;
return nullptr;
}
IntSize intrinsicSize(videoWidth(), videoHeight());
OwnPtr<ImageBuffer> imageBuffer = ImageBuffer::create(intrinsicSize);
if (!imageBuffer) {
*status = InvalidSourceImageStatus;
return nullptr;
}
paintCurrentFrameInContext(imageBuffer->context(), IntRect(IntPoint(0, 0), intrinsicSize));
*status = (mode == CopySourceImageIfVolatile) ? NormalSourceImageStatus : ExternalSourceImageStatus;
return imageBuffer->copyImage(mode == CopySourceImageIfVolatile ? CopyBackingStore : DontCopyBackingStore, Unscaled);
}
bool HTMLVideoElement::wouldTaintOrigin(SecurityOrigin* destinationSecurityOrigin) const
{
return !hasSingleSecurityOrigin() || (!(webMediaPlayer() && webMediaPlayer()->didPassCORSAccessCheck()) && destinationSecurityOrigin->taintsCanvas(currentSrc()));
}
FloatSize HTMLVideoElement::sourceSize() const
{
return FloatSize(videoWidth(), videoHeight());
}
}
<|endoftext|> |
<commit_before>#include "ltl/detail/task_queue_impl.hpp"
#include "ltlcontext/ltlcontext.hpp"
#include "ltl/detail/task_context.hpp"
#include "ltl/detail/current_task_context.hpp"
#include "ltl/detail/log.hpp"
#include <condition_variable>
#include <thread>
#include <mutex>
#include <deque>
#include <vector>
#include "stdio.h"
#include "assert.h"
namespace ltl {
namespace detail {
using namespace std::placeholders;
struct task_queue_impl::impl
{
explicit impl(task_queue_impl* task_queue, char const* name)
: main_context_(create_main_context(), &destroy_main_context)
, name_(name ? name : "unnamed")
, mutex_()
, join_(false)
, cv_()
, queue_()
, thread_([&]() {
auto&& work_to_do = [&](){ return !queue_.empty() || join_; };
while (true)
{
work_item wi;
{
std::unique_lock<std::mutex> lock(mutex_);
if (!work_to_do())
{
LTL_LOG("task_queue_impl waiting... %s\n", name_);
cv_.wait(lock, work_to_do);
LTL_LOG("task_queue_impl wakeup %s\n", name_);
}
if (join_)
break;
wi.swap(queue_.front());
queue_.pop_front();
}
if (wi.first)
{
if (wi.second == Resumable)
{
run_in_new_context(std::move(wi.first));
}
else
{
LTL_LOG("task_queue_impl run first %s\n", name_);
wi.first();
}
}
}
LTL_LOG("task_queue_impl leaving thread loop %s\n", name_);
})
, task_queue_(task_queue)
{
}
void run_in_new_context(std::function<void()>&& func)
{
assert(!current_task_context::get());
std::shared_ptr<task_context> ctx;
if (free_task_contexts_.empty())
{
ctx = task_context::create(main_context_.get(), std::bind(&impl::task_complete, this, _1),
task_queue_);
}
else
{
ctx = free_task_contexts_.back();
free_task_contexts_.pop_back();
}
LTL_LOG("task_queue_impl::run_in_new_context %s %p\n", name_, ctx.get());
ctx->reset(std::move(func));
ctx->resume();
LTL_LOG("task_queue_impl::run_in_new_context complete %s %p\n", name_, ctx.get());
}
~impl()
{
join();
}
void enqueue_resumable(std::function<void()> task)
{
std::lock_guard<std::mutex> lock(mutex_);
queue_.emplace_back(work_item(std::move(task), Resumable));
if (queue_.size() == 1)
cv_.notify_one();
}
void execute_next(std::function<void()> task)
{
std::lock_guard<std::mutex> lock(mutex_);
queue_.emplace_front(work_item(std::move(task), First));
if (queue_.size() == 1)
cv_.notify_one();
}
void join()
{
if (thread_.joinable())
{
{
std::lock_guard<std::mutex> lock(mutex_);
queue_.clear();
join_ = true;
cv_.notify_one();
}
thread_.join();
}
}
void task_complete(std::shared_ptr<task_context> const& ctx)
{
free_task_contexts_.push_back(ctx);
}
enum scheduling_policy { Resumable, First };
typedef std::function<void()> task;
typedef std::pair<task, scheduling_policy> work_item;
std::unique_ptr<context, void(*)(context*)> main_context_;
char const* const name_;
mutable std::mutex mutex_;
bool join_;
std::condition_variable cv_;
std::deque<work_item> queue_;
std::thread thread_;
std::vector<std::shared_ptr<task_context>> free_task_contexts_;
task_queue_impl* const task_queue_;
};
task_queue_impl::task_queue_impl(char const* name)
: impl_(new impl(this, name))
{
}
task_queue_impl::~task_queue_impl()
{
}
void task_queue_impl::enqueue_resumable(std::function<void()> task)
{
impl_->enqueue_resumable(std::move(task));
}
void task_queue_impl::execute_next(std::function<void()> task)
{
impl_->execute_next(std::move(task));
}
void task_queue_impl::join()
{
impl_->join();
}
} // namespace detail
} // namespace ltl
<commit_msg>task_queue now cannot shutdown with yielding tasks<commit_after>#include "ltl/detail/task_queue_impl.hpp"
#include "ltlcontext/ltlcontext.hpp"
#include "ltl/detail/task_context.hpp"
#include "ltl/detail/current_task_context.hpp"
#include "ltl/detail/log.hpp"
#include <condition_variable>
#include <thread>
#include <mutex>
#include <deque>
#include <vector>
#include "stdio.h"
#include "assert.h"
namespace ltl {
namespace detail {
using namespace std::placeholders;
struct task_queue_impl::impl
{
explicit impl(task_queue_impl* task_queue, char const* name)
: main_context_(create_main_context(), &destroy_main_context)
, name_(name ? name : "unnamed")
, mutex_()
, join_(false)
, cv_()
, queue_()
, thread_([&]() {
auto&& work_to_do = [&](){ return !queue_.empty() || join_; };
while (true)
{
work_item wi;
{
std::unique_lock<std::mutex> lock(mutex_);
if (!work_to_do())
{
LTL_LOG("task_queue_impl waiting... %s\n", name_);
cv_.wait(lock, work_to_do);
LTL_LOG("task_queue_impl wakeup %s\n", name_);
}
if (join_ && in_progress_count_ == 0)
break;
if (queue_.empty())
continue;
wi.swap(queue_.front());
queue_.pop_front();
}
if (wi.first)
{
if (wi.second == Resumable)
{
run_in_new_context(std::move(wi.first));
}
else
{
LTL_LOG("task_queue_impl run first %s\n", name_);
wi.first();
}
}
}
LTL_LOG("task_queue_impl leaving thread loop %s\n", name_);
})
, task_queue_(task_queue)
, in_progress_count_(0)
{
}
void run_in_new_context(std::function<void()>&& func)
{
assert(!current_task_context::get());
std::shared_ptr<task_context> ctx;
if (free_task_contexts_.empty())
{
ctx = task_context::create(main_context_.get(), std::bind(&impl::task_complete, this, _1),
task_queue_);
}
else
{
ctx = free_task_contexts_.back();
free_task_contexts_.pop_back();
}
LTL_LOG("task_queue_impl::run_in_new_context %s %p\n", name_, ctx.get());
ctx->reset(std::move(func));
++in_progress_count_;
ctx->resume();
LTL_LOG("task_queue_impl::run_in_new_context complete %s %p\n", name_, ctx.get());
}
~impl()
{
join();
}
void enqueue_resumable(std::function<void()> task)
{
std::lock_guard<std::mutex> lock(mutex_);
queue_.emplace_back(work_item(std::move(task), Resumable));
if (queue_.size() == 1)
cv_.notify_one();
}
void execute_next(std::function<void()> task)
{
std::lock_guard<std::mutex> lock(mutex_);
queue_.emplace_front(work_item(std::move(task), First));
if (queue_.size() == 1)
cv_.notify_one();
}
void join()
{
if (thread_.joinable())
{
{
std::lock_guard<std::mutex> lock(mutex_);
queue_.clear();
join_ = true;
cv_.notify_one();
}
thread_.join();
}
}
void task_complete(std::shared_ptr<task_context> const& ctx)
{
--in_progress_count_;
free_task_contexts_.push_back(ctx);
if (in_progress_count_ == 0)
{
std::lock_guard<std::mutex> lock(mutex_);
if (join_)
cv_.notify_one();
}
}
enum scheduling_policy { Resumable, First };
typedef std::function<void()> task;
typedef std::pair<task, scheduling_policy> work_item;
std::unique_ptr<context, void(*)(context*)> main_context_;
char const* const name_;
mutable std::mutex mutex_;
bool join_;
std::condition_variable cv_;
std::deque<work_item> queue_;
std::thread thread_;
std::vector<std::shared_ptr<task_context>> free_task_contexts_;
task_queue_impl* const task_queue_;
int in_progress_count_;
};
task_queue_impl::task_queue_impl(char const* name)
: impl_(new impl(this, name))
{
}
task_queue_impl::~task_queue_impl()
{
}
void task_queue_impl::enqueue_resumable(std::function<void()> task)
{
impl_->enqueue_resumable(std::move(task));
}
void task_queue_impl::execute_next(std::function<void()> task)
{
impl_->execute_next(std::move(task));
}
void task_queue_impl::join()
{
impl_->join();
}
} // namespace detail
} // namespace ltl
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2007-2009 Digital Bazaar, Inc. All rights reserved.
*/
#include "db/mail/SmtpClient.h"
#include "db/net/InternetAddress.h"
using namespace std;
using namespace db::io;
using namespace db::mail;
using namespace db::net;
using namespace db::rt;
SmtpClient::SmtpClient()
{
mSslContext = NULL;
}
SmtpClient::~SmtpClient()
{
if(mSslContext != NULL)
{
delete mSslContext;
}
}
void SmtpClient::activateSsl(Connection* c)
{
mSslContext = new SslContext(NULL, true);
// switch underlying socket with an SSL socket
Socket* s = new SslSocket(
mSslContext, (TcpSocket*)c->getSocket(), true, c->mustCleanupSocket());
c->setSocket(s, true);
c->setSecure(true);
}
int SmtpClient::getResponseCode(Connection* c)
{
int rval = -1;
// get response line
string line;
if(c->getInputStream()->readCrlf(line))
{
// parse code from line
rval = strtoul(line.c_str(), NULL, 10);
}
return rval;
}
bool SmtpClient::sendCrlf(Connection* c)
{
return c->getOutputStream()->write("\r\n", 2);
}
bool SmtpClient::helo(Connection* c, const char* domain)
{
// send "HELO" verb, space, and domain
return
c->getOutputStream()->write("HELO", 4) &&
c->getOutputStream()->write(" ", 1) &&
c->getOutputStream()->write(domain, strlen(domain)) &&
sendCrlf(c);
}
bool SmtpClient::mailFrom(Connection* c, const char* address)
{
// send "MAIL FROM:" verb and SMTP-encoded address
return
c->getOutputStream()->write("MAIL FROM:", 10) &&
c->getOutputStream()->write(address, strlen(address)) &&
sendCrlf(c);
}
bool SmtpClient::rcptTo(Connection* c, const char* address)
{
// send "RCPT TO:" verb and SMTP-encoded address
return
c->getOutputStream()->write("RCPT TO:", 8) &&
c->getOutputStream()->write(address, strlen(address)) &&
sendCrlf(c);
}
bool SmtpClient::startData(Connection* c)
{
// send "DATA" verb
return
c->getOutputStream()->write("DATA", 4) &&
sendCrlf(c);
}
bool SmtpClient::sendMessage(Connection* c, Mail* mail)
{
bool rval = true;
// send headers
Message msg = mail->getMessage();
DynamicObjectIterator i = msg["headers"].getIterator();
while(rval && i->hasNext())
{
// iterate over each header
DynamicObjectIterator hi = i->next().getIterator();
bool comma = false;
while(rval && hi->hasNext())
{
DynamicObject header = hi->next();
if(rval && !comma)
{
// send header name and colon
rval =
c->getOutputStream()->write(
i->getName(), strlen(i->getName())) &&
c->getOutputStream()->write(": ", 2);
}
if(rval && comma)
{
// send comma
rval = c->getOutputStream()->write(", ", 2);
}
else
{
comma = true;
}
if(rval)
{
// send smtp-encoded header value
string value = header->getString();
Mail::smtpMessageEncode(value);
rval = c->getOutputStream()->write(value.c_str(), value.length());
}
}
// send CRLF
if(rval)
{
rval = sendCrlf(c);
}
}
if(rval)
{
// send encoded body
string body = mail->getTransferEncodedBody();
rval = c->getOutputStream()->write(body.c_str(), body.length());
}
return rval;
}
bool SmtpClient::endData(Connection* c)
{
// end with .CRLF
return c->getOutputStream()->write("\r\n.\r\n", 5);
}
bool SmtpClient::quit(Connection* c)
{
// send "QUIT" verb
return
c->getOutputStream()->write("QUIT", 4) &&
sendCrlf(c);
}
bool SmtpClient::sendMail(Connection* c, Mail* mail)
{
bool rval = true;
// create details object in case of exception
DynamicObject details;
DynamicObject& responseCodes = details["responseCodes"];
responseCodes->setType(Map);
// FIXME: this is the simplest implementation to get this thing to
// send mail to our server, it will have to be filled out later if
// we so desire
// for storing server response codes
int code;
// receive response from server
rval = ((code = getResponseCode(c)) == 220);
responseCodes["connect"] = code;
// say helo from sender's domain
if(rval && (rval = helo(c, mail->getSender()["domain"]->getString())))
{
// receive response
rval = ((code = getResponseCode(c)) == 250);
responseCodes["helo"] = code;
}
// send sender's address
if(rval && (rval = mailFrom(
c, mail->getSender()["smtpEncoding"]->getString())))
{
// receive response
rval = ((code = getResponseCode(c)) == 250);
responseCodes["mailFrom"] = code;
}
// do rcpt to
int index = 0;
AddressIterator i = mail->getRecipients().getIterator();
while(rval && i->hasNext())
{
// send recipient's address
if((rval = rcptTo(c, i->next()["smtpEncoding"]->getString())))
{
// receive response
rval = ((code = getResponseCode(c)) == 250);
responseCodes["rcptTo"][index++] = code;
}
}
// start data
if(rval && (rval = startData(c)))
{
// receive response
rval = ((code = getResponseCode(c)) == 354);
responseCodes["startMessage"] = code;
}
// send data
if(rval && (rval = sendMessage(c, mail)));
// end data
if(rval && (rval = endData(c)))
{
// receive response
rval = ((code = getResponseCode(c)) == 250);
responseCodes["endMessage"] = code;
}
// quit
if(rval && (rval = quit(c)))
{
// receive response
rval = ((code = getResponseCode(c)) == 221);
responseCodes["quit"] = code;
}
if(!rval)
{
if(code != -1)
{
// code was not the expected one
ExceptionRef e = new Exception(
"Unexpected SMTP server response code,",
"db.mail.UnexpectedSmtpCode");
details["code"] = code;
e->getDetails() = details;
Exception::setLast(e, false);
}
}
return rval;
}
bool SmtpClient::sendMail(Url* url, Mail* mail)
{
bool rval = false;
// connect, use 30 second timeouts
TcpSocket s;
s.setReceiveTimeout(30000);
Exception::clearLast();
InternetAddress address(url->getHost().c_str(), url->getPort());
if(Exception::hasLast())
{
ExceptionRef e = new Exception(
"Failed to setup SMTP host address.",
"db.mail.SmtpAddressLookupFailure");
e->getDetails()["host"] = url->getHost().c_str();
e->getDetails()["port"] = url->getPort();
Exception::setLast(e, true);
rval = false;
}
else if(s.connect(&address, 30))
{
// create smtp connection
Connection c(&s, false);
// send mail
rval = sendMail(&c, mail);
// disconnect
c.close();
if(!rval)
{
ExceptionRef e = new Exception(
"Failed to send mail.",
"db.mail.MailSendFailed");
e->getDetails()["host"] = url->getHost().c_str();
e->getDetails()["port"] = url->getPort();
Exception::setLast(e, true);
}
}
else
{
ExceptionRef e = new Exception(
"Failed to connect to SMTP host.",
"db.mail.SmtpConnectionFailure");
e->getDetails()["host"] = url->getHost().c_str();
e->getDetails()["port"] = url->getPort();
Exception::setLast(e, true);
rval = false;
}
return rval;
}
<commit_msg>Changed name in exception.<commit_after>/*
* Copyright (c) 2007-2009 Digital Bazaar, Inc. All rights reserved.
*/
#include "db/mail/SmtpClient.h"
#include "db/net/InternetAddress.h"
using namespace std;
using namespace db::io;
using namespace db::mail;
using namespace db::net;
using namespace db::rt;
SmtpClient::SmtpClient()
{
mSslContext = NULL;
}
SmtpClient::~SmtpClient()
{
if(mSslContext != NULL)
{
delete mSslContext;
}
}
void SmtpClient::activateSsl(Connection* c)
{
mSslContext = new SslContext(NULL, true);
// switch underlying socket with an SSL socket
Socket* s = new SslSocket(
mSslContext, (TcpSocket*)c->getSocket(), true, c->mustCleanupSocket());
c->setSocket(s, true);
c->setSecure(true);
}
int SmtpClient::getResponseCode(Connection* c)
{
int rval = -1;
// get response line
string line;
if(c->getInputStream()->readCrlf(line))
{
// parse code from line
rval = strtoul(line.c_str(), NULL, 10);
}
return rval;
}
bool SmtpClient::sendCrlf(Connection* c)
{
return c->getOutputStream()->write("\r\n", 2);
}
bool SmtpClient::helo(Connection* c, const char* domain)
{
// send "HELO" verb, space, and domain
return
c->getOutputStream()->write("HELO", 4) &&
c->getOutputStream()->write(" ", 1) &&
c->getOutputStream()->write(domain, strlen(domain)) &&
sendCrlf(c);
}
bool SmtpClient::mailFrom(Connection* c, const char* address)
{
// send "MAIL FROM:" verb and SMTP-encoded address
return
c->getOutputStream()->write("MAIL FROM:", 10) &&
c->getOutputStream()->write(address, strlen(address)) &&
sendCrlf(c);
}
bool SmtpClient::rcptTo(Connection* c, const char* address)
{
// send "RCPT TO:" verb and SMTP-encoded address
return
c->getOutputStream()->write("RCPT TO:", 8) &&
c->getOutputStream()->write(address, strlen(address)) &&
sendCrlf(c);
}
bool SmtpClient::startData(Connection* c)
{
// send "DATA" verb
return
c->getOutputStream()->write("DATA", 4) &&
sendCrlf(c);
}
bool SmtpClient::sendMessage(Connection* c, Mail* mail)
{
bool rval = true;
// send headers
Message msg = mail->getMessage();
DynamicObjectIterator i = msg["headers"].getIterator();
while(rval && i->hasNext())
{
// iterate over each header
DynamicObjectIterator hi = i->next().getIterator();
bool comma = false;
while(rval && hi->hasNext())
{
DynamicObject header = hi->next();
if(rval && !comma)
{
// send header name and colon
rval =
c->getOutputStream()->write(
i->getName(), strlen(i->getName())) &&
c->getOutputStream()->write(": ", 2);
}
if(rval && comma)
{
// send comma
rval = c->getOutputStream()->write(", ", 2);
}
else
{
comma = true;
}
if(rval)
{
// send smtp-encoded header value
string value = header->getString();
Mail::smtpMessageEncode(value);
rval = c->getOutputStream()->write(value.c_str(), value.length());
}
}
// send CRLF
if(rval)
{
rval = sendCrlf(c);
}
}
if(rval)
{
// send encoded body
string body = mail->getTransferEncodedBody();
rval = c->getOutputStream()->write(body.c_str(), body.length());
}
return rval;
}
bool SmtpClient::endData(Connection* c)
{
// end with .CRLF
return c->getOutputStream()->write("\r\n.\r\n", 5);
}
bool SmtpClient::quit(Connection* c)
{
// send "QUIT" verb
return
c->getOutputStream()->write("QUIT", 4) &&
sendCrlf(c);
}
bool SmtpClient::sendMail(Connection* c, Mail* mail)
{
bool rval = true;
// create details object in case of exception
DynamicObject details;
DynamicObject& responseCodes = details["responseCodes"];
responseCodes->setType(Map);
// FIXME: this is the simplest implementation to get this thing to
// send mail to our server, it will have to be filled out later if
// we so desire
// for storing server response codes
int code;
// receive response from server
rval = ((code = getResponseCode(c)) == 220);
responseCodes["connect"] = code;
// say helo from sender's domain
if(rval && (rval = helo(c, mail->getSender()["domain"]->getString())))
{
// receive response
rval = ((code = getResponseCode(c)) == 250);
responseCodes["helo"] = code;
}
// send sender's address
if(rval && (rval = mailFrom(
c, mail->getSender()["smtpEncoding"]->getString())))
{
// receive response
rval = ((code = getResponseCode(c)) == 250);
responseCodes["mailFrom"] = code;
}
// do rcpt to
int index = 0;
AddressIterator i = mail->getRecipients().getIterator();
while(rval && i->hasNext())
{
// send recipient's address
if((rval = rcptTo(c, i->next()["smtpEncoding"]->getString())))
{
// receive response
rval = ((code = getResponseCode(c)) == 250);
responseCodes["rcptTo"][index++] = code;
}
}
// start data
if(rval && (rval = startData(c)))
{
// receive response
rval = ((code = getResponseCode(c)) == 354);
responseCodes["startData"] = code;
}
// send data
if(rval && (rval = sendMessage(c, mail)));
// end data
if(rval && (rval = endData(c)))
{
// receive response
rval = ((code = getResponseCode(c)) == 250);
responseCodes["endData"] = code;
}
// quit
if(rval && (rval = quit(c)))
{
// receive response
rval = ((code = getResponseCode(c)) == 221);
responseCodes["quit"] = code;
}
if(!rval)
{
if(code != -1)
{
// code was not the expected one
ExceptionRef e = new Exception(
"Unexpected SMTP server response code,",
"db.mail.UnexpectedSmtpCode");
details["code"] = code;
e->getDetails() = details;
Exception::setLast(e, false);
}
}
return rval;
}
bool SmtpClient::sendMail(Url* url, Mail* mail)
{
bool rval = false;
// connect, use 30 second timeouts
TcpSocket s;
s.setReceiveTimeout(30000);
Exception::clearLast();
InternetAddress address(url->getHost().c_str(), url->getPort());
if(Exception::hasLast())
{
ExceptionRef e = new Exception(
"Failed to setup SMTP host address.",
"db.mail.SmtpAddressLookupFailure");
e->getDetails()["host"] = url->getHost().c_str();
e->getDetails()["port"] = url->getPort();
Exception::setLast(e, true);
rval = false;
}
else if(s.connect(&address, 30))
{
// create smtp connection
Connection c(&s, false);
// send mail
rval = sendMail(&c, mail);
// disconnect
c.close();
if(!rval)
{
ExceptionRef e = new Exception(
"Failed to send mail.",
"db.mail.MailSendFailed");
e->getDetails()["host"] = url->getHost().c_str();
e->getDetails()["port"] = url->getPort();
Exception::setLast(e, true);
}
}
else
{
ExceptionRef e = new Exception(
"Failed to connect to SMTP host.",
"db.mail.SmtpConnectionFailure");
e->getDetails()["host"] = url->getHost().c_str();
e->getDetails()["port"] = url->getPort();
Exception::setLast(e, true);
rval = false;
}
return rval;
}
<|endoftext|> |
<commit_before>//=======================================================================
// Copyright 2014-2015 David Simmons-Duffin.
// Distributed under the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include "../../Dual_Constraint_Group.hxx"
El::Matrix<El::BigFloat>
sample_bilinear_basis(const int maxDegree, const int numSamples,
const std::vector<Polynomial> &bilinearBasis,
const std::vector<El::BigFloat> &samplePoints,
const std::vector<El::BigFloat> &sampleScalings);
// Construct a Dual_Constraint_Group from a Polynomial_Vector_Matrix by
// sampling the matrix at the appropriate number of points, as
// described in SDP.h:
//
// (1,y) . M(x) is positive semidefinite
//
// is equivalent to
//
// Tr(A_p Y) + (B y)_p = c_p
//
// for tuples p = (r,s,k).
//
Dual_Constraint_Group::Dual_Constraint_Group(const Polynomial_Vector_Matrix &m)
{
assert(m.rows == m.cols);
dim = m.rows;
degree = m.degree();
size_t numSamples = degree + 1;
size_t numConstraints = numSamples * dim * (dim + 1) / 2;
size_t vectorDim = m.elt(0, 0).size();
// Form the constraintMatrix B and constraintConstants c from the
// polynomials (1,y) . \vec P^{rs}(x)
// The first element of each vector \vec P^{rs}(x) multiplies the constant 1
constraintConstants.resize(numConstraints);
// The rest multiply decision variables y
constraintMatrix.Resize(numConstraints, vectorDim - 1);
// Populate B and c by sampling the polynomial matrix
int p = 0;
for(size_t c = 0; c < dim; c++)
{
for(size_t r = 0; r <= c; r++)
{
for(size_t k = 0; k < numSamples; k++)
{
El::BigFloat x = m.sample_points[k];
El::BigFloat scale = m.sample_scalings[k];
constraintConstants[p] = scale * m.elt(r, c)[0](x);
for(size_t n = 1; n < vectorDim; ++n)
{
constraintMatrix.Set(p, n - 1, -scale * m.elt(r, c)[n](x));
}
++p;
}
}
}
// The matrix Y has two blocks Y_1, Y_2. The bilinearBases for the
// constraint matrices A_p are given by sampling the following
// vectors for each block:
//
// Y_1: {q_0(x), ..., q_delta1(x)}
// Y_2: {\sqrt(x) q_0(x), ..., \sqrt(x) q_delta2(x)
//
int delta1 = degree / 2;
bilinearBases.push_back(sample_bilinear_basis(
delta1, numSamples, m.bilinear_basis, m.sample_points, m.sample_scalings));
int delta2 = (degree - 1) / 2;
// a degree-0 Polynomial_Vector_Matrix only needs one block
if(delta2 >= 0)
{
// The \sqrt(x) factors can be accounted for by replacing the
// scale factors s_k with x_k s_k.
std::vector<El::BigFloat> scaled_samples;
for(size_t ii = 0; ii < m.sample_points.size(); ++ii)
{
scaled_samples.emplace_back(m.sample_points[ii]
* m.sample_scalings[ii]);
}
bilinearBases.push_back(
sample_bilinear_basis(delta2, numSamples, m.bilinear_basis,
m.sample_points, scaled_samples));
}
}
<commit_msg>Create empty blocks for degree=0 polynomials<commit_after>//=======================================================================
// Copyright 2014-2015 David Simmons-Duffin.
// Distributed under the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include "../../Dual_Constraint_Group.hxx"
El::Matrix<El::BigFloat>
sample_bilinear_basis(const int maxDegree, const int numSamples,
const std::vector<Polynomial> &bilinearBasis,
const std::vector<El::BigFloat> &samplePoints,
const std::vector<El::BigFloat> &sampleScalings);
// Construct a Dual_Constraint_Group from a Polynomial_Vector_Matrix by
// sampling the matrix at the appropriate number of points, as
// described in SDP.h:
//
// (1,y) . M(x) is positive semidefinite
//
// is equivalent to
//
// Tr(A_p Y) + (B y)_p = c_p
//
// for tuples p = (r,s,k).
//
Dual_Constraint_Group::Dual_Constraint_Group(const Polynomial_Vector_Matrix &m)
{
assert(m.rows == m.cols);
dim = m.rows;
degree = m.degree();
size_t numSamples = degree + 1;
size_t numConstraints = numSamples * dim * (dim + 1) / 2;
size_t vectorDim = m.elt(0, 0).size();
// Form the constraintMatrix B and constraintConstants c from the
// polynomials (1,y) . \vec P^{rs}(x)
// The first element of each vector \vec P^{rs}(x) multiplies the constant 1
constraintConstants.resize(numConstraints);
// The rest multiply decision variables y
constraintMatrix.Resize(numConstraints, vectorDim - 1);
// Populate B and c by sampling the polynomial matrix
int p = 0;
for(size_t c = 0; c < dim; c++)
{
for(size_t r = 0; r <= c; r++)
{
for(size_t k = 0; k < numSamples; k++)
{
El::BigFloat x = m.sample_points[k];
El::BigFloat scale = m.sample_scalings[k];
constraintConstants[p] = scale * m.elt(r, c)[0](x);
for(size_t n = 1; n < vectorDim; ++n)
{
constraintMatrix.Set(p, n - 1, -scale * m.elt(r, c)[n](x));
}
++p;
}
}
}
// The matrix Y has two blocks Y_1, Y_2. The bilinearBases for the
// constraint matrices A_p are given by sampling the following
// vectors for each block:
//
// Y_1: {q_0(x), ..., q_delta1(x)}
// Y_2: {\sqrt(x) q_0(x), ..., \sqrt(x) q_delta2(x)
//
int delta1 = degree / 2;
bilinearBases.push_back(sample_bilinear_basis(
delta1, numSamples, m.bilinear_basis, m.sample_points, m.sample_scalings));
int delta2 = (degree - 1) / 2;
// a degree-0 Polynomial_Vector_Matrix only needs one block, so this
// will create an empty block.
// The \sqrt(x) factors can be accounted for by replacing the
// scale factors s_k with x_k s_k.
std::vector<El::BigFloat> scaled_samples;
for(size_t ii = 0; ii < m.sample_points.size(); ++ii)
{
scaled_samples.emplace_back(m.sample_points[ii] * m.sample_scalings[ii]);
}
bilinearBases.push_back(sample_bilinear_basis(
delta2, numSamples, m.bilinear_basis, m.sample_points, scaled_samples));
}
<|endoftext|> |
<commit_before>#include <cassert>
#include <yaml-cpp/yaml.h>
int main()
{
YAML::Node node = YAML::Load("[1, 2, 3]");
assert(node.IsSequence());
std::cout << "Successful execution of application that links against yaml-cpp4rkt!" << std::endl;
return 0;
}
<commit_msg>Add missing #include <iostream><commit_after>#include <cassert>
#include <iostream>
#include <yaml-cpp/yaml.h>
int main()
{
YAML::Node node = YAML::Load("[1, 2, 3]");
assert(node.IsSequence());
std::cout << "Successful execution of application that links against yaml-cpp4rkt!" << std::endl;
return 0;
}
<|endoftext|> |
<commit_before>// Copyright (C) 2017 Elviss Strazdins
// This file is part of the Ouzel engine.
#include <unistd.h>
#include <pwd.h>
#include <sys/stat.h>
#include "FileSystemRasp.hpp"
#include "utils/Log.hpp"
extern std::string DEVELOPER_NAME;
extern std::string APPLICATION_NAME;
static char TEMP_BUFFER[1024];
namespace ouzel
{
FileSystemRasp::FileSystemRasp()
{
if (readlink("/proc/self/exe", TEMP_BUFFER, sizeof(TEMP_BUFFER)) != -1)
{
appPath = getDirectoryPart(TEMP_BUFFER);
}
else
{
Log(Log::Level::ERR) << "Failed to get current directory";
}
}
std::string FileSystemRasp::getStorageDirectory(bool user) const
{
std::string path;
passwd* pw = getpwuid(getuid());
if (!pw)
{
Log(Log::Level::ERR) << "Failed to get home directory";
return "";
}
path = pw->pw_dir;
path += DIRECTORY_SEPARATOR + "." + DEVELOPER_NAME;
if (!directoryExists(path))
{
if (mkdir(path.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) != 0)
{
Log(Log::Level::ERR) << "Failed to create directory " << path;
return "";
}
}
path += DIRECTORY_SEPARATOR + APPLICATION_NAME;
if (!directoryExists(path))
{
if (mkdir(path.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) != 0)
{
Log(Log::Level::ERR) << "Failed to create directory " << path;
return "";
}
}
return path;
}
std::string FileSystemRasp::getTempDirectory() const
{
char const* path = getenv("TMPDIR");
if (path)
{
return path;
}
else
{
return "/tmp";
}
}
}
<commit_msg>Use XDG_DATA_HOME also on Raspbian<commit_after>// Copyright (C) 2017 Elviss Strazdins
// This file is part of the Ouzel engine.
#include <unistd.h>
#include <pwd.h>
#include <sys/stat.h>
#include "FileSystemRasp.hpp"
#include "utils/Log.hpp"
extern std::string DEVELOPER_NAME;
extern std::string APPLICATION_NAME;
static char TEMP_BUFFER[1024];
namespace ouzel
{
FileSystemRasp::FileSystemRasp()
{
if (readlink("/proc/self/exe", TEMP_BUFFER, sizeof(TEMP_BUFFER)) != -1)
{
appPath = getDirectoryPart(TEMP_BUFFER);
}
else
{
Log(Log::Level::ERR) << "Failed to get current directory";
}
}
std::string FileSystemRasp::getStorageDirectory(bool user) const
{
std::string path;
char* homeDirectory = getenv("XDG_DATA_HOME");
if (homeDirectory)
{
path = homeDirectory;
}
else
{
passwd* pw = getpwuid(getuid());
if (!pw)
{
Log(Log::Level::ERR) << "Failed to get home directory";
return "";
}
path = pw->pw_dir;
}
path += DIRECTORY_SEPARATOR + "." + DEVELOPER_NAME;
if (!directoryExists(path))
{
if (mkdir(path.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) != 0)
{
Log(Log::Level::ERR) << "Failed to create directory " << path;
return "";
}
}
path += DIRECTORY_SEPARATOR + APPLICATION_NAME;
if (!directoryExists(path))
{
if (mkdir(path.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) != 0)
{
Log(Log::Level::ERR) << "Failed to create directory " << path;
return "";
}
}
return path;
}
std::string FileSystemRasp::getTempDirectory() const
{
char const* path = getenv("TMPDIR");
if (path)
{
return path;
}
else
{
return "/tmp";
}
}
}
<|endoftext|> |
<commit_before>#include "comm.hpp"
#include <stdint.h>
#include <unistd.h>
#include <errno.h>
#include <algorithm>
#include <assert.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include "log.hpp"
namespace fcwt {
const char* const server_ipv4_addr = "192.168.0.1";
sock::sock(int fd)
: sockfd(fd)
{
}
sock::~sock()
{
if (sockfd > 0)
{
close(sockfd);
}
}
sock::sock(sock&& other)
: sockfd(other.sockfd)
{
other.sockfd = 0;
}
sock& sock::operator=(sock&& other)
{
sock tmp(std::move(other));
swap(tmp);
return *this;
}
void sock::swap(sock& other)
{
int tmp = other.sockfd;
other.sockfd = sockfd;
sockfd = tmp;
}
sock connect_to_camera(int port)
{
const int sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
fatal_error("Failed to create socket\n");
sockaddr_in sa = {};
sa.sin_family = AF_INET;
sa.sin_port = htons(port);
inet_pton(AF_INET, server_ipv4_addr, &sa.sin_addr);
if (connect(sockfd, reinterpret_cast<sockaddr*>(&sa), sizeof(sa)) < 0)
fatal_error("ERROR connecting");
LOG_INFO_FORMAT("Connection esatablished (socket %d)", sockfd);
return sockfd;
}
uint32_t to_fuji_size_prefix(uint32_t sizeBytes) {
// TODO, 0x endianess
return sizeBytes;
}
uint32_t from_fuji_size_prefix(uint32_t sizeBytes) {
// TODO, 0x endianess
return sizeBytes;
}
void send_data(int sockfd, void const* data, size_t sizeBytes) {
bool retry = false;
do {
ssize_t const result = write(sockfd, data, sizeBytes);
if (result < 0) {
if (errno == EINTR)
retry = true;
else
fatal_error("Failed to send data from socket\n");
}
} while (retry);
}
void receive_data(int sockfd, void* data, size_t sizeBytes) {
while (sizeBytes > 0) {
ssize_t const result = read(sockfd, data, sizeBytes);
if (result < 0) {
if (errno != EINTR)
fatal_error("Failed to read data from socket\n");
} else {
sizeBytes -= result;
data = static_cast<char*>(data) + result;
}
}
}
void fuji_send(int sockfd, void const* data, uint32_t sizeBytes)
{
uint32_t const size = to_fuji_size_prefix(sizeBytes + sizeof(uint32_t));
send_data(sockfd, &size, sizeof(uint32_t));
send_data(sockfd, data, sizeBytes);
}
size_t fuji_receive(int sockfd, void* data, uint32_t sizeBytes)
{
uint32_t size = 0;
receive_data(sockfd, &size, sizeof(size));
size = from_fuji_size_prefix(size);
if (size < sizeof(size)) {
LOG_WARN("fuji_receive, 0x invalid message");
return 0;
}
size -= sizeof(size);
receive_data(sockfd, data, std::min(sizeBytes, size));
return size;
}
uint32_t generate_message_id()
{
static std::atomic<uint32_t> id_counter;
return ++id_counter;
}
void* fill_message_id(uint32_t id, void* buffer, size_t size)
{
assert(size >= 8);
memcpy(static_cast<uint8_t*>(buffer) + 4, &id, sizeof(id));
return buffer;
}
} // namespace fcwt
<commit_msg>connect timeout<commit_after>#include "comm.hpp"
#include <stdint.h>
#include <unistd.h>
#include <errno.h>
#include <algorithm>
#include <assert.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/select.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include "log.hpp"
namespace fcwt {
const char* const server_ipv4_addr = "192.168.0.1";
sock::sock(int fd)
: sockfd(fd)
{
}
sock::~sock()
{
if (sockfd > 0)
{
close(sockfd);
}
}
sock::sock(sock&& other)
: sockfd(other.sockfd)
{
other.sockfd = 0;
}
sock& sock::operator=(sock&& other)
{
sock tmp(std::move(other));
swap(tmp);
return *this;
}
void sock::swap(sock& other)
{
int tmp = other.sockfd;
other.sockfd = sockfd;
sockfd = tmp;
}
sock connect_to_camera(int port)
{
// TODO: proper error handling
const int sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
fatal_error("Failed to create socket\n");
fcntl(sockfd, F_SETFL, O_NONBLOCK); // for timeout
sockaddr_in sa = {};
sa.sin_family = AF_INET;
sa.sin_port = htons(port);
inet_pton(AF_INET, server_ipv4_addr, &sa.sin_addr);
connect(sockfd, reinterpret_cast<sockaddr*>(&sa), sizeof(sa));
// timeout handling
fd_set fdset;
FD_ZERO(&fdset);
FD_SET(sockfd, &fdset);
struct timeval tv = {};
tv.tv_sec = 1;
tv.tv_usec = 0;
if (select(sockfd + 1, NULL, &fdset, NULL, &tv) == 1)
{
int so_error = 0;
socklen_t len = sizeof so_error;
getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &so_error, &len);
if (so_error == 0)
{
printf("Connection esatablished %s:%d (%d)\n", server_ipv4_addr, port, sockfd);
fcntl(sockfd, F_SETFL, 0);
return sockfd;
}
}
printf("Failed to connect\n");
close(sockfd);
return 0;
}
uint32_t to_fuji_size_prefix(uint32_t sizeBytes) {
// TODO, 0x endianess
return sizeBytes;
}
uint32_t from_fuji_size_prefix(uint32_t sizeBytes) {
// TODO, 0x endianess
return sizeBytes;
}
void send_data(int sockfd, void const* data, size_t sizeBytes) {
bool retry = false;
do {
ssize_t const result = write(sockfd, data, sizeBytes);
if (result < 0) {
if (errno == EINTR)
retry = true;
else
fatal_error("Failed to send data from socket\n");
}
} while (retry);
}
void receive_data(int sockfd, void* data, size_t sizeBytes) {
while (sizeBytes > 0) {
ssize_t const result = read(sockfd, data, sizeBytes);
if (result < 0) {
if (errno != EINTR)
fatal_error("Failed to read data from socket\n");
} else {
sizeBytes -= result;
data = static_cast<char*>(data) + result;
}
}
}
void fuji_send(int sockfd, void const* data, uint32_t sizeBytes)
{
uint32_t const size = to_fuji_size_prefix(sizeBytes + sizeof(uint32_t));
send_data(sockfd, &size, sizeof(uint32_t));
send_data(sockfd, data, sizeBytes);
}
size_t fuji_receive(int sockfd, void* data, uint32_t sizeBytes)
{
uint32_t size = 0;
receive_data(sockfd, &size, sizeof(size));
size = from_fuji_size_prefix(size);
if (size < sizeof(size)) {
LOG_WARN("fuji_receive, 0x invalid message");
return 0;
}
size -= sizeof(size);
receive_data(sockfd, data, std::min(sizeBytes, size));
return size;
}
uint32_t generate_message_id()
{
static std::atomic<uint32_t> id_counter;
return ++id_counter;
}
void* fill_message_id(uint32_t id, void* buffer, size_t size)
{
assert(size >= 8);
memcpy(static_cast<uint8_t*>(buffer) + 4, &id, sizeof(id));
return buffer;
}
} // namespace fcwt
<|endoftext|> |
<commit_before><commit_msg>[openmp] Workaround bug in old Android pthread_attr_setstacksize<commit_after><|endoftext|> |
<commit_before><commit_msg>INTEGRATION: CWS impressfunctions (1.7.38); FILE MERGED 2005/10/28 10:57:35 cl 1.7.38.1: #125341# reworked FuPoor classes to use refcounting<commit_after><|endoftext|> |
<commit_before>#pragma once
#include <cmath>
#include <iostream>
const uint8_t POSIT_ROUND_DOWN = 0;
const uint8_t POSIT_ROUND_TO_NEAREST = 1;
/*
class posit represents arbitrary configuration posits and their arithmetic
*/
template<size_t nbits> class quire : std::bitset<nbits> {
public:
quire<nbits>() {}
quire<nbits>(const quire& q) {
*this = q;
}
// template parameters need names different from class template parameters (for gcc and clang)
template<size_t nnbits>
friend std::ostream& operator<< (std::ostream& ostr, const quire<nnbits>& p);
template<size_t nnbits>
friend std::istream& operator>> (std::istream& istr, quire<nnbits>& p);
template<size_t nnbits>
friend bool operator==(const quire<nnbits>& lhs, const quire<nnbits>& rhs);
template<size_t nnbits>
friend bool operator!=(const quire<nnbits>& lhs, const quire<nnbits>& rhs);
template<size_t nnbitss>
friend bool operator< (const quire<nnbits>>& lhs, const quire<nnbits>& rhs);
template<size_t nnbits>
friend bool operator> (const quire<nnbits>>& lhs, const quire<nnbits>& rhs);
template<size_t nnbits>
friend bool operator<=(const quire<nnbits>>& lhs, const quire<nnbits>& rhs);
template<size_t nnbits>
friend bool operator>=(const quire<nnbits>& lhs, const quire<nnbits>>& rhs);
};
<commit_msg>edits<commit_after>#pragma once
#include <cmath>
#include <iostream>
const uint8_t POSIT_ROUND_DOWN = 0;
const uint8_t POSIT_ROUND_TO_NEAREST = 1;
/*
class posit represents arbitrary configuration posits and their arithmetic
*/
template<size_t nbits> class quire : std::bitset<nbits> {
public:
quire<nbits>() {}
quire<nbits>(const quire& q) {
*this = q;
}
// template parameters need names different from class template parameters (for gcc and clang)
template<size_t nnbits>
friend std::ostream& operator<< (std::ostream& ostr, const quire<nnbits>& p);
template<size_t nnbits>
friend std::istream& operator>> (std::istream& istr, quire<nnbits>& p);
template<size_t nnbits>
friend bool operator==(const quire<nnbits>& lhs, const quire<nnbits>& rhs);
template<size_t nnbits>
friend bool operator!=(const quire<nnbits>& lhs, const quire<nnbits>& rhs);
template<size_t nnbitss>
friend bool operator< (const quire<nnbits>& lhs, const quire<nnbits>& rhs);
template<size_t nnbits>
friend bool operator> (const quire<nnbits>& lhs, const quire<nnbits>& rhs);
template<size_t nnbits>
friend bool operator<=(const quire<nnbits>& lhs, const quire<nnbits>& rhs);
template<size_t nnbits>
friend bool operator>=(const quire<nnbits>& lhs, const quire<nnbits>& rhs);
};
<|endoftext|> |
<commit_before>#include <iostream>
#include <ctime>
#include "mad.h"
int main(int argc, char** argv) {
using namespace mad;
{
srand(time(NULL));
size_t max = rand() % 20 + 1;
Var x0 = 1, x1 = 2, x2 = 3;
std::vector<Var> x = { x0, x1, x2 };
Var y = 0.0;
for(int i = 0; i < max; i++) {
Var xi = i;
y = y + x0 + log(x2) + x1 + xi;
x.push_back(xi);
}
set_zero_all_adjoints();
y.grad();
std::cerr << "y = " << y.val() << std::endl;
for(int i = 0; i < x.size(); ++i)
std::cerr << "dy/dx_" << i << " = " << x[i].adj() << std::endl;
}
}<commit_msg>in loop<commit_after>#include <iostream>
#include <ctime>
#include "mad.h"
int main(int argc, char** argv) {
using namespace mad;
{
srand(time(NULL));
size_t max = rand() % 20 + 1;
Var x0 = 1, x1 = 2, x2 = 3;
std::vector<Var> x = { x0, x1, x2 };
Var y = 0.0;
for(int i = 0; i < max; i++) {
Var xi = i;
y = y + x0 + log(x2) + x1;
for(int j = 0; j < i; ++i) {
y = y + xi;
x.push_back(xi);
}
}
set_zero_all_adjoints();
y.grad();
std::cerr << "y = " << y.val() << std::endl;
for(int i = 0; i < x.size(); ++i)
std::cerr << "dy/dx_" << i << " = " << x[i].adj() << std::endl;
}
}<|endoftext|> |
<commit_before>/*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>
*
* 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.
*
*/
#undef MUX_UNDEF_SEL_TO_UNDEF_RESULTS
#include "opt_status.h"
#include "kernel/register.h"
#include "kernel/sigtools.h"
#include "kernel/log.h"
#include <stdlib.h>
#include <assert.h>
#include <stdio.h>
#include <set>
bool did_something;
void replace_cell(RTLIL::Module *module, RTLIL::Cell *cell, std::string info, std::string out_port, RTLIL::SigSpec out_val)
{
RTLIL::SigSpec Y = cell->connections[out_port];
log("Replacing %s cell `%s' (%s) in module `%s' with constant driver `%s = %s'.\n",
cell->type.c_str(), cell->name.c_str(), info.c_str(),
module->name.c_str(), log_signal(Y), log_signal(out_val));
OPT_DID_SOMETHING = true;
// ILANG_BACKEND::dump_cell(stderr, "--> ", cell);
module->connections.push_back(RTLIL::SigSig(Y, out_val));
module->cells.erase(cell->name);
delete cell;
did_something = true;
}
void replace_const_cells(RTLIL::Design *design, RTLIL::Module *module)
{
if (!design->selected(module))
return;
SigMap assign_map(module);
std::vector<RTLIL::Cell*> cells;
cells.reserve(module->cells.size());
for (auto &cell_it : module->cells)
if (design->selected(module, cell_it.second))
cells.push_back(cell_it.second);
for (auto cell : cells)
{
#define ACTION_DO(_p_, _s_) do { replace_cell(module, cell, input.as_string(), _p_, _s_); goto next_cell; } while (0)
#define ACTION_DO_Y(_v_) ACTION_DO("\\Y", RTLIL::SigSpec(RTLIL::State::S ## _v_))
if (cell->type == "$_INV_") {
RTLIL::SigSpec input = cell->connections["\\A"];
assign_map.apply(input);
if (input.match("1")) ACTION_DO_Y(0);
if (input.match("0")) ACTION_DO_Y(1);
if (input.match("*")) ACTION_DO_Y(x);
}
if (cell->type == "$_AND_") {
RTLIL::SigSpec input;
input.append(cell->connections["\\B"]);
input.append(cell->connections["\\A"]);
assign_map.apply(input);
if (input.match(" 0")) ACTION_DO_Y(0);
if (input.match("0 ")) ACTION_DO_Y(0);
if (input.match("11")) ACTION_DO_Y(1);
if (input.match(" *")) ACTION_DO_Y(x);
if (input.match("* ")) ACTION_DO_Y(x);
if (input.match(" 1")) ACTION_DO("\\Y", input.extract(1, 1));
if (input.match("1 ")) ACTION_DO("\\Y", input.extract(0, 1));
}
if (cell->type == "$_OR_") {
RTLIL::SigSpec input;
input.append(cell->connections["\\B"]);
input.append(cell->connections["\\A"]);
assign_map.apply(input);
if (input.match(" 1")) ACTION_DO_Y(1);
if (input.match("1 ")) ACTION_DO_Y(1);
if (input.match("00")) ACTION_DO_Y(0);
if (input.match(" *")) ACTION_DO_Y(x);
if (input.match("* ")) ACTION_DO_Y(x);
if (input.match(" 0")) ACTION_DO("\\Y", input.extract(1, 1));
if (input.match("0 ")) ACTION_DO("\\Y", input.extract(0, 1));
}
if (cell->type == "$_XOR_") {
RTLIL::SigSpec input;
input.append(cell->connections["\\B"]);
input.append(cell->connections["\\A"]);
assign_map.apply(input);
if (input.match("00")) ACTION_DO_Y(0);
if (input.match("01")) ACTION_DO_Y(1);
if (input.match("10")) ACTION_DO_Y(1);
if (input.match("11")) ACTION_DO_Y(0);
if (input.match(" *")) ACTION_DO_Y(x);
if (input.match("* ")) ACTION_DO_Y(x);
if (input.match(" 0")) ACTION_DO("\\Y", input.extract(1, 1));
if (input.match("0 ")) ACTION_DO("\\Y", input.extract(0, 1));
}
if (cell->type == "$_MUX_" ||(cell->type == "$mux" && cell->parameters["\\WIDTH"].as_int() == 1)) {
RTLIL::SigSpec input;
input.append(cell->connections["\\S"]);
input.append(cell->connections["\\B"]);
input.append(cell->connections["\\A"]);
assign_map.apply(input);
if (input.extract(2, 1) == input.extract(1, 1))
ACTION_DO("\\Y", input.extract(2, 1));
if (input.match(" 0")) ACTION_DO("\\Y", input.extract(2, 1));
if (input.match(" 1")) ACTION_DO("\\Y", input.extract(1, 1));
#ifdef MUX_UNDEF_SEL_TO_UNDEF_RESULTS
if (input.match("01 ")) ACTION_DO("\\Y", input.extract(0, 1));
// TODO: "10 " -> replace with "!S" gate
// TODO: "0 " -> replace with "B AND S" gate
// TODO: " 1 " -> replace with "A OR S" gate
// TODO: "1 " -> replace with "B OR !S" gate
// TODO: " 0 " -> replace with "A AND !S" gate
if (input.match(" *")) ACTION_DO_Y(x);
#endif
}
if (cell->type == "$eq" || cell->type == "$ne")
{
if (cell->parameters["\\A_WIDTH"].as_int() != cell->parameters["\\B_WIDTH"].as_int()) {
int width = std::max(cell->parameters["\\A_WIDTH"].as_int(), cell->parameters["\\B_WIDTH"].as_int());
cell->connections["\\A"].extend(width, cell->parameters["\\A_SIGNED"].as_bool());
cell->connections["\\B"].extend(width, cell->parameters["\\B_SIGNED"].as_bool());
cell->parameters["\\A_WIDTH"] = width;
cell->parameters["\\B_WIDTH"] = width;
}
RTLIL::SigSpec a = cell->connections["\\A"];
RTLIL::SigSpec b = cell->connections["\\B"];
RTLIL::SigSpec new_a, new_b;
a.expand(), b.expand();
assert(a.chunks.size() == b.chunks.size());
for (size_t i = 0; i < a.chunks.size(); i++) {
if (a.chunks[i].wire == NULL && a.chunks[i].data.bits[0] > RTLIL::State::S1)
continue;
if (b.chunks[i].wire == NULL && b.chunks[i].data.bits[0] > RTLIL::State::S1)
continue;
new_a.append(a.chunks[i]);
new_b.append(b.chunks[i]);
}
if (new_a.width != a.width) {
new_a.optimize();
new_b.optimize();
cell->connections["\\A"] = new_a;
cell->connections["\\B"] = new_b;
cell->parameters["\\A_WIDTH"] = new_a.width;
cell->parameters["\\B_WIDTH"] = new_b.width;
}
if (new_a.width == 0) {
replace_cell(module, cell, "empty", "\\Y", RTLIL::SigSpec(cell->type == "$eq" ? RTLIL::State::S1 : RTLIL::State::S0));
goto next_cell;
}
}
#define FOLD_1ARG_CELL(_t) \
if (cell->type == "$" #_t) { \
RTLIL::SigSpec a = cell->connections["\\A"]; \
assign_map.apply(a); \
if (a.is_fully_const()) { \
a.optimize(); \
RTLIL::Const dummy_arg(RTLIL::State::S0, 1); \
RTLIL::SigSpec y(RTLIL::const_ ## _t(a.chunks[0].data, dummy_arg, \
cell->parameters["\\A_SIGNED"].as_bool(), false, \
cell->parameters["\\Y_WIDTH"].as_int())); \
replace_cell(module, cell, stringf("%s", log_signal(a)), "\\Y", y); \
goto next_cell; \
} \
}
#define FOLD_2ARG_CELL(_t) \
if (cell->type == "$" #_t) { \
RTLIL::SigSpec a = cell->connections["\\A"]; \
RTLIL::SigSpec b = cell->connections["\\B"]; \
assign_map.apply(a), assign_map.apply(b); \
if (a.is_fully_const() && b.is_fully_const()) { \
a.optimize(), b.optimize(); \
RTLIL::SigSpec y(RTLIL::const_ ## _t(a.chunks[0].data, b.chunks[0].data, \
cell->parameters["\\A_SIGNED"].as_bool(), \
cell->parameters["\\B_SIGNED"].as_bool(), \
cell->parameters["\\Y_WIDTH"].as_int())); \
replace_cell(module, cell, stringf("%s, %s", log_signal(a), log_signal(b)), "\\Y", y); \
goto next_cell; \
} \
}
FOLD_1ARG_CELL(not)
FOLD_2ARG_CELL(and)
FOLD_2ARG_CELL(or)
FOLD_2ARG_CELL(xor)
FOLD_2ARG_CELL(xnor)
FOLD_1ARG_CELL(reduce_and)
FOLD_1ARG_CELL(reduce_or)
FOLD_1ARG_CELL(reduce_xor)
FOLD_1ARG_CELL(reduce_xnor)
FOLD_1ARG_CELL(reduce_bool)
FOLD_1ARG_CELL(logic_not)
FOLD_2ARG_CELL(logic_and)
FOLD_2ARG_CELL(logic_or)
FOLD_2ARG_CELL(shl)
FOLD_2ARG_CELL(shr)
FOLD_2ARG_CELL(sshl)
FOLD_2ARG_CELL(sshr)
FOLD_2ARG_CELL(lt)
FOLD_2ARG_CELL(le)
FOLD_2ARG_CELL(eq)
FOLD_2ARG_CELL(ne)
FOLD_2ARG_CELL(gt)
FOLD_2ARG_CELL(ge)
FOLD_2ARG_CELL(add)
FOLD_2ARG_CELL(sub)
FOLD_2ARG_CELL(mul)
FOLD_2ARG_CELL(div)
FOLD_2ARG_CELL(mod)
FOLD_2ARG_CELL(pow)
FOLD_1ARG_CELL(pos)
FOLD_1ARG_CELL(neg)
if (cell->type == "$mux") {
RTLIL::SigSpec input = cell->connections["\\S"];
assign_map.apply(input);
if (input.is_fully_const())
ACTION_DO("\\Y", input.as_bool() ? cell->connections["\\B"] : cell->connections["\\A"]);
}
next_cell:;
#undef ACTION_DO
#undef ACTION_DO_Y
#undef FOLD_1ARG_CELL
#undef FOLD_2ARG_CELL
}
}
struct OptConstPass : public Pass {
OptConstPass() : Pass("opt_const", "perform const folding") { }
virtual void help()
{
// |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
log("\n");
log(" opt_const [selection]\n");
log("\n");
log("This pass performs const folding on internal cell types with constant inputs.\n");
log("\n");
}
virtual void execute(std::vector<std::string> args, RTLIL::Design *design)
{
log_header("Executing OPT_CONST pass (perform const folding).\n");
log_push();
extra_args(args, 1, design);
for (auto &mod_it : design->modules)
do {
did_something = false;
replace_const_cells(design, mod_it.second);
} while (did_something);
log_pop();
}
} OptConstPass;
<commit_msg>keep $mux and $_MUX_ optimizations separate in opt_const<commit_after>/*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>
*
* 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.
*
*/
#undef MUX_UNDEF_SEL_TO_UNDEF_RESULTS
#include "opt_status.h"
#include "kernel/register.h"
#include "kernel/sigtools.h"
#include "kernel/log.h"
#include <stdlib.h>
#include <assert.h>
#include <stdio.h>
#include <set>
bool did_something;
void replace_cell(RTLIL::Module *module, RTLIL::Cell *cell, std::string info, std::string out_port, RTLIL::SigSpec out_val)
{
RTLIL::SigSpec Y = cell->connections[out_port];
log("Replacing %s cell `%s' (%s) in module `%s' with constant driver `%s = %s'.\n",
cell->type.c_str(), cell->name.c_str(), info.c_str(),
module->name.c_str(), log_signal(Y), log_signal(out_val));
OPT_DID_SOMETHING = true;
// ILANG_BACKEND::dump_cell(stderr, "--> ", cell);
module->connections.push_back(RTLIL::SigSig(Y, out_val));
module->cells.erase(cell->name);
delete cell;
did_something = true;
}
void replace_const_cells(RTLIL::Design *design, RTLIL::Module *module)
{
if (!design->selected(module))
return;
SigMap assign_map(module);
std::vector<RTLIL::Cell*> cells;
cells.reserve(module->cells.size());
for (auto &cell_it : module->cells)
if (design->selected(module, cell_it.second))
cells.push_back(cell_it.second);
for (auto cell : cells)
{
#define ACTION_DO(_p_, _s_) do { replace_cell(module, cell, input.as_string(), _p_, _s_); goto next_cell; } while (0)
#define ACTION_DO_Y(_v_) ACTION_DO("\\Y", RTLIL::SigSpec(RTLIL::State::S ## _v_))
if (cell->type == "$_INV_") {
RTLIL::SigSpec input = cell->connections["\\A"];
assign_map.apply(input);
if (input.match("1")) ACTION_DO_Y(0);
if (input.match("0")) ACTION_DO_Y(1);
if (input.match("*")) ACTION_DO_Y(x);
}
if (cell->type == "$_AND_") {
RTLIL::SigSpec input;
input.append(cell->connections["\\B"]);
input.append(cell->connections["\\A"]);
assign_map.apply(input);
if (input.match(" 0")) ACTION_DO_Y(0);
if (input.match("0 ")) ACTION_DO_Y(0);
if (input.match("11")) ACTION_DO_Y(1);
if (input.match(" *")) ACTION_DO_Y(x);
if (input.match("* ")) ACTION_DO_Y(x);
if (input.match(" 1")) ACTION_DO("\\Y", input.extract(1, 1));
if (input.match("1 ")) ACTION_DO("\\Y", input.extract(0, 1));
}
if (cell->type == "$_OR_") {
RTLIL::SigSpec input;
input.append(cell->connections["\\B"]);
input.append(cell->connections["\\A"]);
assign_map.apply(input);
if (input.match(" 1")) ACTION_DO_Y(1);
if (input.match("1 ")) ACTION_DO_Y(1);
if (input.match("00")) ACTION_DO_Y(0);
if (input.match(" *")) ACTION_DO_Y(x);
if (input.match("* ")) ACTION_DO_Y(x);
if (input.match(" 0")) ACTION_DO("\\Y", input.extract(1, 1));
if (input.match("0 ")) ACTION_DO("\\Y", input.extract(0, 1));
}
if (cell->type == "$_XOR_") {
RTLIL::SigSpec input;
input.append(cell->connections["\\B"]);
input.append(cell->connections["\\A"]);
assign_map.apply(input);
if (input.match("00")) ACTION_DO_Y(0);
if (input.match("01")) ACTION_DO_Y(1);
if (input.match("10")) ACTION_DO_Y(1);
if (input.match("11")) ACTION_DO_Y(0);
if (input.match(" *")) ACTION_DO_Y(x);
if (input.match("* ")) ACTION_DO_Y(x);
if (input.match(" 0")) ACTION_DO("\\Y", input.extract(1, 1));
if (input.match("0 ")) ACTION_DO("\\Y", input.extract(0, 1));
}
if (cell->type == "$_MUX_") {
RTLIL::SigSpec input;
input.append(cell->connections["\\S"]);
input.append(cell->connections["\\B"]);
input.append(cell->connections["\\A"]);
assign_map.apply(input);
if (input.extract(2, 1) == input.extract(1, 1))
ACTION_DO("\\Y", input.extract(2, 1));
if (input.match(" 0")) ACTION_DO("\\Y", input.extract(2, 1));
if (input.match(" 1")) ACTION_DO("\\Y", input.extract(1, 1));
#ifdef MUX_UNDEF_SEL_TO_UNDEF_RESULTS
if (input.match("01 ")) ACTION_DO("\\Y", input.extract(0, 1));
// TODO: "10 " -> replace with "!S" gate
// TODO: "0 " -> replace with "B AND S" gate
// TODO: " 1 " -> replace with "A OR S" gate
// TODO: "1 " -> replace with "B OR !S" gate (?)
// TODO: " 0 " -> replace with "A AND !S" gate (?)
if (input.match(" *")) ACTION_DO_Y(x);
#endif
}
if (cell->type == "$eq" || cell->type == "$ne")
{
if (cell->parameters["\\A_WIDTH"].as_int() != cell->parameters["\\B_WIDTH"].as_int()) {
int width = std::max(cell->parameters["\\A_WIDTH"].as_int(), cell->parameters["\\B_WIDTH"].as_int());
cell->connections["\\A"].extend(width, cell->parameters["\\A_SIGNED"].as_bool());
cell->connections["\\B"].extend(width, cell->parameters["\\B_SIGNED"].as_bool());
cell->parameters["\\A_WIDTH"] = width;
cell->parameters["\\B_WIDTH"] = width;
}
RTLIL::SigSpec a = cell->connections["\\A"];
RTLIL::SigSpec b = cell->connections["\\B"];
RTLIL::SigSpec new_a, new_b;
a.expand(), b.expand();
assert(a.chunks.size() == b.chunks.size());
for (size_t i = 0; i < a.chunks.size(); i++) {
if (a.chunks[i].wire == NULL && a.chunks[i].data.bits[0] > RTLIL::State::S1)
continue;
if (b.chunks[i].wire == NULL && b.chunks[i].data.bits[0] > RTLIL::State::S1)
continue;
new_a.append(a.chunks[i]);
new_b.append(b.chunks[i]);
}
if (new_a.width != a.width) {
new_a.optimize();
new_b.optimize();
cell->connections["\\A"] = new_a;
cell->connections["\\B"] = new_b;
cell->parameters["\\A_WIDTH"] = new_a.width;
cell->parameters["\\B_WIDTH"] = new_b.width;
}
if (new_a.width == 0) {
replace_cell(module, cell, "empty", "\\Y", RTLIL::SigSpec(cell->type == "$eq" ? RTLIL::State::S1 : RTLIL::State::S0));
goto next_cell;
}
}
#define FOLD_1ARG_CELL(_t) \
if (cell->type == "$" #_t) { \
RTLIL::SigSpec a = cell->connections["\\A"]; \
assign_map.apply(a); \
if (a.is_fully_const()) { \
a.optimize(); \
RTLIL::Const dummy_arg(RTLIL::State::S0, 1); \
RTLIL::SigSpec y(RTLIL::const_ ## _t(a.chunks[0].data, dummy_arg, \
cell->parameters["\\A_SIGNED"].as_bool(), false, \
cell->parameters["\\Y_WIDTH"].as_int())); \
replace_cell(module, cell, stringf("%s", log_signal(a)), "\\Y", y); \
goto next_cell; \
} \
}
#define FOLD_2ARG_CELL(_t) \
if (cell->type == "$" #_t) { \
RTLIL::SigSpec a = cell->connections["\\A"]; \
RTLIL::SigSpec b = cell->connections["\\B"]; \
assign_map.apply(a), assign_map.apply(b); \
if (a.is_fully_const() && b.is_fully_const()) { \
a.optimize(), b.optimize(); \
RTLIL::SigSpec y(RTLIL::const_ ## _t(a.chunks[0].data, b.chunks[0].data, \
cell->parameters["\\A_SIGNED"].as_bool(), \
cell->parameters["\\B_SIGNED"].as_bool(), \
cell->parameters["\\Y_WIDTH"].as_int())); \
replace_cell(module, cell, stringf("%s, %s", log_signal(a), log_signal(b)), "\\Y", y); \
goto next_cell; \
} \
}
FOLD_1ARG_CELL(not)
FOLD_2ARG_CELL(and)
FOLD_2ARG_CELL(or)
FOLD_2ARG_CELL(xor)
FOLD_2ARG_CELL(xnor)
FOLD_1ARG_CELL(reduce_and)
FOLD_1ARG_CELL(reduce_or)
FOLD_1ARG_CELL(reduce_xor)
FOLD_1ARG_CELL(reduce_xnor)
FOLD_1ARG_CELL(reduce_bool)
FOLD_1ARG_CELL(logic_not)
FOLD_2ARG_CELL(logic_and)
FOLD_2ARG_CELL(logic_or)
FOLD_2ARG_CELL(shl)
FOLD_2ARG_CELL(shr)
FOLD_2ARG_CELL(sshl)
FOLD_2ARG_CELL(sshr)
FOLD_2ARG_CELL(lt)
FOLD_2ARG_CELL(le)
FOLD_2ARG_CELL(eq)
FOLD_2ARG_CELL(ne)
FOLD_2ARG_CELL(gt)
FOLD_2ARG_CELL(ge)
FOLD_2ARG_CELL(add)
FOLD_2ARG_CELL(sub)
FOLD_2ARG_CELL(mul)
FOLD_2ARG_CELL(div)
FOLD_2ARG_CELL(mod)
FOLD_2ARG_CELL(pow)
FOLD_1ARG_CELL(pos)
FOLD_1ARG_CELL(neg)
if (cell->type == "$mux") {
RTLIL::SigSpec input = cell->connections["\\S"];
assign_map.apply(input);
if (input.is_fully_const())
ACTION_DO("\\Y", input.as_bool() ? cell->connections["\\B"] : cell->connections["\\A"]);
}
next_cell:;
#undef ACTION_DO
#undef ACTION_DO_Y
#undef FOLD_1ARG_CELL
#undef FOLD_2ARG_CELL
}
}
struct OptConstPass : public Pass {
OptConstPass() : Pass("opt_const", "perform const folding") { }
virtual void help()
{
// |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
log("\n");
log(" opt_const [selection]\n");
log("\n");
log("This pass performs const folding on internal cell types with constant inputs.\n");
log("\n");
}
virtual void execute(std::vector<std::string> args, RTLIL::Design *design)
{
log_header("Executing OPT_CONST pass (perform const folding).\n");
log_push();
extra_args(args, 1, design);
for (auto &mod_it : design->modules)
do {
did_something = false;
replace_const_cells(design, mod_it.second);
} while (did_something);
log_pop();
}
} OptConstPass;
<|endoftext|> |
<commit_before>#include <opencv2/core.hpp>
#include <opencv2/imgproc.hpp>
#include "opencv2/imgcodecs.hpp"
#include <opencv2/highgui.hpp>
#include <opencv2/ml.hpp>
#include <vector>
#include <string>
#include <iostream>
#include <sstream>
/*****************************************************************************************************************************/
using namespace cv;
using namespace cv::ml;
/*****************************************************************************************************************************/
const std::string IMAGETYPE = ".jpg";
const unsigned int NUMBEROFCLASSES = 3;
const unsigned int NUMBEROFIMAGESPERCLASS = 10;
const unsigned int IMAGERESOLUTION = 250;
/*****************************************************************************************************************************/
Mat resizeImageTo1xN(Mat image);
Mat resizeImage(Mat image);
Mat populateTrainingMat(const unsigned int numberOfImages, const unsigned int numberOfClasses);
Mat populateLabels(const unsigned int numberOfImages, const unsigned int numberOfClasses);
/*****************************************************************************************************************************/
auto main() -> int
{
Mat trainingMatrix = populateTrainingMat(NUMBEROFIMAGESPERCLASS,NUMBEROFCLASSES);
Mat labels=populateLabels(NUMBEROFIMAGESPERCLASS,NUMBEROFCLASSES);
/*
// Data for visual representation
int width = 512, height = 512;
Mat image = Mat::zeros(height, width, CV_8UC3);
// Set up training data
int labels[4] = { 1, -1, -1, -1 };
Mat labelsMat(4, 1, CV_32SC1, labels);
float trainingData[4][2] = { { 501, 10 }, { 255, 10 }, { 501, 255 }, { 10, 501 } };
Mat trainingDataMat(4, 2, CV_32FC1, trainingData);
// Set up SVM's parameters
Ptr<SVM> svm = SVM::create();
svm->setType(SVM::C_SVC);
svm->setKernel(SVM::LINEAR);
svm->setTermCriteria(TermCriteria(TermCriteria::MAX_ITER, 100, 1e-6));
// Train the SVM with given parameters
Ptr<TrainData> td = TrainData::create(trainingDataMat, ROW_SAMPLE, labelsMat);
svm->train(td);
// Or train the SVM with optimal parameters
//svm->trainAuto(td);
Vec3b green(0, 255, 0), blue(255, 0, 0);
// Show the decision regions given by the SVM
for (int i = 0; i < image.rows; ++i)
for (int j = 0; j < image.cols; ++j)
{
Mat sampleMat = (Mat_<float>(1, 2) << j, i);
float response = svm->predict(sampleMat);
if (response == 1)
image.at<Vec3b>(i, j) = green;
else if (response == -1)
image.at<Vec3b>(i, j) = blue;
}
// Show the training data
int thickness = -1;
int lineType = 8;
circle(image, Point(501, 10), 5, Scalar(0, 0, 0), thickness, lineType);
circle(image, Point(255, 10), 5, Scalar(255, 255, 255), thickness, lineType);
circle(image, Point(501, 255), 5, Scalar(255, 255, 255), thickness, lineType);
circle(image, Point(10, 501), 5, Scalar(255, 255, 255), thickness, lineType);
// Show support vectors
thickness = 2;
lineType = 8;
Mat sv = svm->getSupportVectors();
for (int i = 0; i < sv.rows; ++i)
{
const float* v = sv.ptr<float>(i);
circle(image, Point((int)v[0], (int)v[1]), 6, Scalar(128, 128, 128), thickness, lineType);
}
imwrite("result.png", image); // save the image
*/
// show it to the user
//std::cout<<(int)trainingMatrix.at<uchar>(0,trainingMatrix.cols);
waitKey(0);
}
/*****************************************************************************************************************************/
Mat resizeImageTo1xN(Mat image){
Size size(image.cols*image.rows,1);
resize(image,image,size);
return image;
}
/*****************************************************************************************************************************/
Mat resizeImage(Mat image){
Size size(IMAGERESOLUTION,IMAGERESOLUTION);
resize(image,image,size);
return image;
}
/*****************************************************************************************************************************/
Mat populateTrainingMat(const unsigned int numberOfImages, const unsigned int numberOfClasses){
// TO DO
// CORRECT THE IMREAD NAME PARAMETER
//char *sampleImageName = "0"+IMAGETYPE.c_str();
cv::String sampleImageName = "0"+IMAGETYPE;
Mat sampleImage = imread(sampleImageName,IMREAD_GRAYSCALE);
Mat trainingMatrix = Mat::zeros(numberOfClasses*numberOfImages,sampleImage.cols*sampleImage.rows,CV_8UC1);
for (unsigned int i=0; i<numberOfClasses;i++){
for (unsigned int j=0 ; j<numberOfImages;j++){
const unsigned int imageNumber = j+(numberOfImages*i);
std::ostringstream ss;
ss<<imageNumber; // Workaround for std::to_string MinGW bug
cv::String imageName = ss.str() + IMAGETYPE;
Mat input=imread(imageName ,IMREAD_GRAYSCALE);
Mat correctedInput=resizeImage(input);
Mat resizedInput = resizeImageTo1xN(correctedInput);
resizedInput.copyTo(trainingMatrix(Rect(0,j+(numberOfImages*i),resizedInput.cols,resizedInput.rows)));
}
}
return trainingMatrix;
}
/*****************************************************************************************************************************/
Mat populateLabels(const unsigned int numberOfImages, const unsigned int numberOfClasses){
int size = numberOfImages *numberOfClasses;
std::vector<int> labels(size);
for (unsigned int i=0; i<numberOfClasses;i++){
for (unsigned int j=0 ; j<numberOfImages;j++){
labels.at(j+(numberOfImages*i))=i;
}
}
Mat labelsMat(numberOfImages, 1, CV_32SC1, labels.data());
return labelsMat;
}
/*****************************************************************************************************************************/
<commit_msg>SVM is now working<commit_after>#include <opencv2/core.hpp>
#include <opencv2/imgproc.hpp>
#include "opencv2/imgcodecs.hpp"
#include <opencv2/highgui.hpp>
#include <opencv2/ml.hpp>
#include <vector>
#include <string>
#include <iostream>
#include <sstream>
/*****************************************************************************************************************************/
using namespace cv;
using namespace cv::ml;
/*****************************************************************************************************************************/
const std::string IMAGETYPE = ".jpg";
const unsigned int NUMBEROFCLASSES = 1;
const unsigned int NUMBEROFIMAGESPERCLASS =5;
const unsigned int IMAGERESOLUTION = 250;
/*****************************************************************************************************************************/
Mat resizeImageTo1xN(Mat image);
Mat resizeImage(Mat image);
Mat populateTrainingMat(const unsigned int numberOfImages, const unsigned int numberOfClasses);
Mat populateLabels(const unsigned int numberOfImages, const unsigned int numberOfClasses);
/*****************************************************************************************************************************/
auto main() -> int {
Mat testImage = imread("test.jpg",IMREAD_GRAYSCALE);
Mat correctedInput=resizeImage(testImage);
Mat sampleImage = resizeImageTo1xN(correctedInput);
sampleImage.convertTo(sampleImage,CV_32F);
Mat trainingMatrix = populateTrainingMat(NUMBEROFIMAGESPERCLASS,NUMBEROFCLASSES);
Mat labels=populateLabels(NUMBEROFIMAGESPERCLASS,NUMBEROFCLASSES);
//trainingMatrix.reshape(1, trainingMatrix.rows);
// Data for visual representation
int width = 512, height = 512;
Mat image = Mat::zeros(height, width, CV_8UC3);
// Set up SVM's parameters
Ptr<SVM> svm = SVM::create();
svm->setType(SVM::C_SVC);
svm->setKernel(SVM::LINEAR);
svm->setTermCriteria(TermCriteria(TermCriteria::MAX_ITER, 100, 1e-6));
// Train the SVM with given parameters
Ptr<TrainData> td = TrainData::create(trainingMatrix, ROW_SAMPLE, labels);
svm->train(td);
// Or train the SVM with optimal parameters
//svm->trainAuto(td);
Vec3b green(0, 255, 0), blue(255, 0, 0);
// Show the decision regions given by the SVM
for (int i = 0; i < image.rows; ++i)
for (int j = 0; j < image.cols; ++j)
{
float response = svm->predict(sampleImage);
if (response == 1)
image.at<Vec3b>(i, j) = green;
else if (response == -1)
image.at<Vec3b>(i, j) = blue;
}
// Show the training data
int thickness = -1;
int lineType = 8;
circle(image, Point(501, 10), 5, Scalar(0, 0, 0), thickness, lineType);
circle(image, Point(255, 10), 5, Scalar(255, 255, 255), thickness, lineType);
circle(image, Point(501, 255), 5, Scalar(255, 255, 255), thickness, lineType);
circle(image, Point(10, 501), 5, Scalar(255, 255, 255), thickness, lineType);
// Show support vectors
thickness = 2;
lineType = 8;
Mat sv = svm->getSupportVectors();
for (int i = 0; i < sv.rows; ++i)
{
const float* v = sv.ptr<float>(i);
circle(image, Point((int)v[0], (int)v[1]), 6, Scalar(128, 128, 128), thickness, lineType);
}
imwrite("result.png", image); // save the image
// show it to the user
//std::cout<<(int)trainingMatrix.at<uchar>(0,trainingMatrix.cols);
waitKey(0);
}
/*****************************************************************************************************************************/
Mat resizeImageTo1xN(Mat image){
Size size(image.cols*image.rows,1);
resize(image,image,size);
return image;
}
/*****************************************************************************************************************************/
Mat resizeImage(Mat image){
Size size(IMAGERESOLUTION,IMAGERESOLUTION);
resize(image,image,size);
return image;
}
/*****************************************************************************************************************************/
Mat populateTrainingMat(const unsigned int numberOfImages, const unsigned int numberOfClasses){
// TO DO
// CORRECT THE IMREAD NAME PARAMETER
//char *sampleImageName = "0"+IMAGETYPE.c_str();
//cv::String sampleImageName = "0"+IMAGETYPE;
Mat trainingMatrix = Mat::zeros(numberOfClasses*numberOfImages,IMAGERESOLUTION*IMAGERESOLUTION,CV_32F);
for (unsigned int i=0; i<numberOfClasses;i++){
for (unsigned int j=0 ; j<numberOfImages;j++){
const unsigned int imageNumber = j+(numberOfImages*i);
std::ostringstream ss;
ss<<imageNumber; // Workaround for std::to_string MinGW bug
cv::String imageName = ss.str() + IMAGETYPE;
Mat input=imread(imageName ,IMREAD_GRAYSCALE);
Mat correctedInput=resizeImage(input);
Mat resizedInput = resizeImageTo1xN(correctedInput);
resizedInput.copyTo(trainingMatrix(Rect(0,j+(numberOfImages*i),resizedInput.cols,resizedInput.rows)));
}
}
std::cout<<trainingMatrix.rows<<" "<<trainingMatrix.cols<<std::endl;
return trainingMatrix;
}
/*****************************************************************************************************************************/
Mat populateLabels(const unsigned int numberOfImages, const unsigned int numberOfClasses){
std::vector<int> labels;
for (unsigned int i=0; i<numberOfClasses;i++){
for (unsigned int j=0 ; j<numberOfImages;j++){
labels.push_back(i);
//std::cout<<"Label:"<<labels.at(j+(numberOfImages*i));
}
}
Mat labelsMat(numberOfImages, 1, CV_32SC1 , labels.data());
return labelsMat;
}
/*****************************************************************************************************************************/
<|endoftext|> |
<commit_before>///
/// @file test.cpp
///
/// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <primecount.hpp>
#include <primesieve.hpp>
#include <stdint.h>
#include <iostream>
#include <cstdlib>
#include <string>
#include <stdexcept>
#include <sstream>
#include <ctime>
using namespace std;
using primecount::MAX_THREADS;
namespace {
void assert_equal(const string& f1_name, int64_t x, int64_t f1_res, int64_t f2_res)
{
if (f1_res != f2_res)
{
ostringstream oss;
oss << f1_name << "(" << x << ") = " << f1_res
<< " is an error, the correct result is " << f2_res;
throw runtime_error(oss.str());
}
}
/// 0 <= get_rand() < 10^7
int get_rand()
{
return (rand() % 10000) * 1000 + 1;
}
template <typename F>
void check_equal(const string& f1_name, F f1, F f2, int64_t iters)
{
srand(static_cast<unsigned int>(time(0)));
cout << "Testing " << (f1_name + "(x)") << flush;
// test for 1 <= x <= iters
for (int64_t x = 1; x <= iters; x++)
assert_equal(f1_name, x, f1(x, MAX_THREADS), f2(x, MAX_THREADS));
int64_t x = 1;
// test using random increment
for (int64_t i = 1; i <= iters; i++, x += get_rand())
assert_equal(f1_name, x, f1(x, MAX_THREADS), f2(x, MAX_THREADS));
cout << " correct" << endl;
}
int64_t pps_nth_prime(int64_t x, int)
{
int64_t prime = primesieve::parallel_nth_prime(x);
return prime;
}
} // namespace
namespace primecount {
bool test()
{
try
{
check_equal("pi_legendre", pi_legendre, pi_primesieve, 100);
check_equal("pi_meissel", pi_meissel, pi_legendre, 500);
check_equal("pi_lehmer", pi_lehmer, pi_meissel, 500);
check_equal("pi_lmo1", pi_lmo1, pi_lehmer, 500);
check_equal("pi_lmo2", pi_lmo2, pi_lehmer, 500);
check_equal("pi_lmo3", pi_lmo3, pi_lehmer, 500);
check_equal("pi_lmo4", pi_lmo4, pi_lehmer, 500);
check_equal("nth_prime", nth_prime, pps_nth_prime, 100);
}
catch (runtime_error& e)
{
cerr << endl << e.what() << endl;
return false;
}
cout << "All tests passed successfully!" << endl;
return true;
}
} // namespace primecount
<commit_msg>Revert "Avoid nth_prime(0) error"<commit_after>///
/// @file test.cpp
///
/// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <primecount.hpp>
#include <primesieve.hpp>
#include <stdint.h>
#include <iostream>
#include <cstdlib>
#include <string>
#include <stdexcept>
#include <sstream>
#include <ctime>
using namespace std;
using primecount::MAX_THREADS;
namespace {
void assert_equal(const string& f1_name, int64_t x, int64_t f1_res, int64_t f2_res)
{
if (f1_res != f2_res)
{
ostringstream oss;
oss << f1_name << "(" << x << ") = " << f1_res
<< " is an error, the correct result is " << f2_res;
throw runtime_error(oss.str());
}
}
/// 0 <= get_rand() < 10^7
int get_rand()
{
return (rand() % 10000) * 1000 + 1;
}
template <typename F>
void check_equal(const string& f1_name, F f1, F f2, int64_t iters)
{
srand(static_cast<unsigned int>(time(0)));
cout << "Testing " << (f1_name + "(x)") << flush;
// test for 0 <= x < iters
for (int64_t x = 0; x < iters; x++)
assert_equal(f1_name, x, f1(x, MAX_THREADS), f2(x, MAX_THREADS));
int64_t x = 0;
// test using random increment
for (int64_t i = 0; i < iters; i++, x += get_rand())
assert_equal(f1_name, x, f1(x, MAX_THREADS), f2(x, MAX_THREADS));
cout << " correct" << endl;
}
int64_t pps_nth_prime(int64_t x, int)
{
int64_t prime = primesieve::parallel_nth_prime(x);
return prime;
}
} // namespace
namespace primecount {
bool test()
{
try
{
check_equal("pi_legendre", pi_legendre, pi_primesieve, 100);
check_equal("pi_meissel", pi_meissel, pi_legendre, 500);
check_equal("pi_lehmer", pi_lehmer, pi_meissel, 500);
check_equal("pi_lmo1", pi_lmo1, pi_lehmer, 500);
check_equal("pi_lmo2", pi_lmo2, pi_lehmer, 500);
check_equal("pi_lmo3", pi_lmo3, pi_lehmer, 500);
check_equal("pi_lmo4", pi_lmo4, pi_lehmer, 500);
check_equal("nth_prime", nth_prime, pps_nth_prime, 100);
}
catch (runtime_error& e)
{
cerr << endl << e.what() << endl;
return false;
}
cout << "All tests passed successfully!" << endl;
return true;
}
} // namespace primecount
<|endoftext|> |
<commit_before>#include <opencv2/core.hpp>
#include <opencv2/imgproc.hpp>
#include "opencv2/imgcodecs.hpp"
#include <opencv2/highgui.hpp>
#include <opencv2/ml.hpp>
using namespace cv;
using namespace cv::ml;
Mat resizeImageTo1xN(const Mat image){
Size size(image.cols*image.rows,1);
resize(image,image,size);
return image;
}
Mat populateTrainingMatrix(const int numberOfImages){
for (auto i=0 ; i<numberOfImages;i++){
}
}
int main(int, char**)
{
Mat test = imread("C:\\Users\\Casa\\Desktop\\1.jpg",IMREAD_GRAYSCALE);
Size size(test.cols*test.rows,1);
resize(test,test,size);
/*
// Data for visual representation
int width = 512, height = 512;
Mat image = Mat::zeros(height, width, CV_8UC3);
// Set up training data
int labels[4] = { 1, -1, -1, -1 };
Mat labelsMat(4, 1, CV_32SC1, labels);
float trainingData[4][2] = { { 501, 10 }, { 255, 10 }, { 501, 255 }, { 10, 501 } };
Mat trainingDataMat(4, 2, CV_32FC1, trainingData);
// Set up SVM's parameters
Ptr<SVM> svm = SVM::create();
svm->setType(SVM::C_SVC);
svm->setKernel(SVM::LINEAR);
svm->setTermCriteria(TermCriteria(TermCriteria::MAX_ITER, 100, 1e-6));
// Train the SVM with given parameters
Ptr<TrainData> td = TrainData::create(trainingDataMat, ROW_SAMPLE, labelsMat);
svm->train(td);
// Or train the SVM with optimal parameters
//svm->trainAuto(td);
Vec3b green(0, 255, 0), blue(255, 0, 0);
// Show the decision regions given by the SVM
for (int i = 0; i < image.rows; ++i)
for (int j = 0; j < image.cols; ++j)
{
Mat sampleMat = (Mat_<float>(1, 2) << j, i);
float response = svm->predict(sampleMat);
if (response == 1)
image.at<Vec3b>(i, j) = green;
else if (response == -1)
image.at<Vec3b>(i, j) = blue;
}
// Show the training data
int thickness = -1;
int lineType = 8;
circle(image, Point(501, 10), 5, Scalar(0, 0, 0), thickness, lineType);
circle(image, Point(255, 10), 5, Scalar(255, 255, 255), thickness, lineType);
circle(image, Point(501, 255), 5, Scalar(255, 255, 255), thickness, lineType);
circle(image, Point(10, 501), 5, Scalar(255, 255, 255), thickness, lineType);
// Show support vectors
thickness = 2;
lineType = 8;
Mat sv = svm->getSupportVectors();
for (int i = 0; i < sv.rows; ++i)
{
const float* v = sv.ptr<float>(i);
circle(image, Point((int)v[0], (int)v[1]), 6, Scalar(128, 128, 128), thickness, lineType);
}
imwrite("result.png", image); // save the image
*/
imshow("SVM Simple Example", test); // show it to the user
waitKey(0);
}
<commit_msg>Adding functions<commit_after>#include <opencv2/core.hpp>
#include <opencv2/imgproc.hpp>
#include "opencv2/imgcodecs.hpp"
#include <opencv2/highgui.hpp>
#include <opencv2/ml.hpp>
#include <array>
using namespace cv;
using namespace cv::ml;
Mat resizeImageTo1xN(const Mat image){
Size size(image.cols*image.rows,1);
resize(image,image,size);
return image;
}
Mat populateTrainingMat(const unsigned int numberOfImages, const unsigned int numberOfClasses){
Mat input = imread(0+".jpg",IMREAD_GRAYSCALE);
Mat trainingMatrix = Mat::zeros(numberOfClasses*numberOfImages,input.cols+1,CV_8UC3);
for (unsigned int i=0; i<numberOfClasses;i++){
for (unsigned int j=0 ; j<numberOfImages;j++){
input = resizeImageTo1xN(input);
input.copyTo(trainingMatrix(Rect(0,j,input.rows,input.cols)));
}
}
return trainingMatrix;
}
Mat populateLabelsMat(const unsigned int numberOfImages, const unsigned int numberOfClasses){
int size = numberOfImages *numberOfClasses;
int labels[size];
for (unsigned int i=0; i<numberOfClasses;i++){
for (unsigned int j=0 ; j<numberOfImages;j++){
labels[j]=i;
}
}
Mat labelsMat(size, 1, CV_32SC1, labels);
return labelsMat;
}
int main(int, char**)
{
Mat test = imread("C:\\Users\\Casa\\Desktop\\1.jpg",IMREAD_GRAYSCALE);
Size size(test.cols*test.rows,1);
resize(test,test,size);
/*
// Data for visual representation
int width = 512, height = 512;
Mat image = Mat::zeros(height, width, CV_8UC3);
// Set up training data
int labels[4] = { 1, -1, -1, -1 };
Mat labelsMat(4, 1, CV_32SC1, labels);
float trainingData[4][2] = { { 501, 10 }, { 255, 10 }, { 501, 255 }, { 10, 501 } };
Mat trainingDataMat(4, 2, CV_32FC1, trainingData);
// Set up SVM's parameters
Ptr<SVM> svm = SVM::create();
svm->setType(SVM::C_SVC);
svm->setKernel(SVM::LINEAR);
svm->setTermCriteria(TermCriteria(TermCriteria::MAX_ITER, 100, 1e-6));
// Train the SVM with given parameters
Ptr<TrainData> td = TrainData::create(trainingDataMat, ROW_SAMPLE, labelsMat);
svm->train(td);
// Or train the SVM with optimal parameters
//svm->trainAuto(td);
Vec3b green(0, 255, 0), blue(255, 0, 0);
// Show the decision regions given by the SVM
for (int i = 0; i < image.rows; ++i)
for (int j = 0; j < image.cols; ++j)
{
Mat sampleMat = (Mat_<float>(1, 2) << j, i);
float response = svm->predict(sampleMat);
if (response == 1)
image.at<Vec3b>(i, j) = green;
else if (response == -1)
image.at<Vec3b>(i, j) = blue;
}
// Show the training data
int thickness = -1;
int lineType = 8;
circle(image, Point(501, 10), 5, Scalar(0, 0, 0), thickness, lineType);
circle(image, Point(255, 10), 5, Scalar(255, 255, 255), thickness, lineType);
circle(image, Point(501, 255), 5, Scalar(255, 255, 255), thickness, lineType);
circle(image, Point(10, 501), 5, Scalar(255, 255, 255), thickness, lineType);
// Show support vectors
thickness = 2;
lineType = 8;
Mat sv = svm->getSupportVectors();
for (int i = 0; i < sv.rows; ++i)
{
const float* v = sv.ptr<float>(i);
circle(image, Point((int)v[0], (int)v[1]), 6, Scalar(128, 128, 128), thickness, lineType);
}
imwrite("result.png", image); // save the image
*/
imshow("SVM Simple Example", test); // show it to the user
waitKey(0);
}
<|endoftext|> |
<commit_before>
/*
* client.cpp
*
* Handles the client env.
*
* Created by Ryan Faulkner on 2014-06-08
* Copyright (c) 2014. All rights reserved.
*/
#include <iostream>
#include <string>
#include <vector>
#include <regex>
#include <assert.h>
#include "column_types.h"
#include "redis.h"
#include "md5.h"
#include "index.h"
#include "bayes.h"
#include "model.h"
#define REDISHOST "127.0.0.1"
#define REDISPORT 6379
using namespace std;
/** Test to ensure that redis keys are correctly returned */
void testRedisSet() {
RedisHandler r;
r.connect();
r.write("foo", "bar");
}
/** Test to ensure that redis keys are correctly returned */
void testRedisGet() {
RedisHandler r;
r.connect();
cout << endl << "VALUE FOR KEY foo" << endl;
cout << r.read("foo") << endl << endl;
}
/** Test to ensure that redis keys are correctly returned */
void testRedisKeys() {
RedisHandler r;
std::vector<std::string> vec;
r.connect();
vec = r.keys("*");
cout << "KEY LIST FOR *" << endl;
for (std::vector<std::string>::iterator it = vec.begin() ; it != vec.end(); ++it) {
cout << *it << endl;
}
cout << endl;
}
/** Test to ensure that redis keys are correctly returned */
void testRedisIO() {
RedisHandler r;
std::vector<string>* vec;
std::string outTrue, outFalse = "";
r.connect();
r.write("test_key", "test value");
outTrue = r.read("test_key");
assert(std::strcmp(outTrue.c_str(), "test value") == 0);
r.deleteKey("test_key");
assert(!r.exists("test_key"));
}
/** Test to ensure that md5 hashing works */
void testMd5Hashing() {
cout << endl << "md5 of 'mykey': " << md5("mykey") << endl;
}
/** Test to ensure that md5 hashing works */
void testRegexForTypes() {
IntegerColumn ic;
FloatColumn fc;
assert(ic.validate("1981"));
assert(fc.validate("5.2"));
cout << "Passed regex tests." << endl;
}
/** Test to ensure that md5 hashing works */
void testOrderPairAlphaNumeric() {
IndexHandler ih;
assert(std::strcmp(ih.orderPairAlphaNumeric("b", "a").c_str(), "a_b") == 0);
cout << "Passed orderPairAlphaNumeric tests." << endl;
}
/**
* Test to ensure that relation entities are encoded properly
*/
void testJSONEntityEncoding() {
IndexHandler ih;
Json::Value json;
std::vector<std::pair<ColumnBase*, std::string>> fields_ent;
fields_ent.push_back(std::make_pair(getColumnType("integer"), "a")); // Create fields
Entity e("test", fields_ent);
ih.writeEntity(e); // Create the entity
ih.fetchEntity("test", json); // Fetch the entity representation
cout << "TEST ENTITY:" << endl << endl << json.toStyledString() << endl;
// Assert that entity as read matches definition
assert(std::strcmp(json["entity"].asCString(), "test") == 0 &&
std::strcmp(json["fields"]["a"].asCString(), "integer") == 0 &&
json["fields"]["_itemcount"].asInt() == 1
);
ih.removeEntity("test"); // Remove the entity
}
/**
* Test to ensure that relation fields are encoded properly
*/
void testJSONRelationEncoding() {
IndexHandler ih;
std::vector<Json::Value> ret;
std::vector<std::pair<ColumnBase*, std::string>> fields_ent_1;
std::vector<std::pair<ColumnBase*, std::string>> fields_ent_2;
std::vector<std::pair<std::string, std::string>> fields_rel_1;
std::vector<std::pair<std::string, std::string>> fields_rel_2;
// Popualate fields
fields_ent_1.push_back(std::make_pair(getColumnType("integer"), "a"));
fields_ent_2.push_back(std::make_pair(getColumnType("string"), "b"));
fields_rel_1.push_back(std::make_pair("a", "1"));
fields_rel_2.push_back(std::make_pair("b", "hello"));
// Create entities
Entity e1("test_1", fields_ent_1), e2("test_2", fields_ent_2);
ih.writeEntity(e1);
ih.writeEntity(e2);
// Create relation in redis
Relation r("test_1", "test_2", fields_rel_1, fields_rel_2);
ih.writeRelation(r);
// Fetch the entity representation
ret = ih.fetchRelationPrefix("test_1", "test_2");
cout << "TEST RELATION:" << endl << endl << ret[0].toStyledString() << endl;
// Assert that entity as read matches definition
assert(
std::strcmp(ret[0]["entity_left"].asCString(), "test_1") == 0 &&
std::strcmp(ret[0]["entity_right"].asCString(), "test_2") == 0 &&
std::strcmp(ret[0]["fields_left"]["a"].asCString(), "1") == 0 &&
std::strcmp(ret[0]["fields_right"]["b"].asCString(), "hello") == 0 &&
ret[0]["fields_left"]["_itemcount"].asInt() == 1 &&
ret[0]["fields_right"]["_itemcount"].asInt() == 1
);
ih.removeEntity("test_1"); // Remove the entity
ih.removeEntity("test_2"); // Remove the entity
ih.removeRelation(r); // Remove the relation
}
/**
* Tests that parseEntityAssignField correctly flags invalid assignments to integer fields
*/
void testFieldAssignTypeMismatchInteger() {
IndexHandler ih;
Json::Value json;
std::vector<std::pair<ColumnBase*, std::string>> fields_ent;
fields_ent.push_back(std::make_pair(getColumnType("integer"), "a")); // Create fields
Entity e("test", fields_ent);
ih.writeEntity(e); // Create the entity
assert(
ih.validateEntityFieldType("test", "a", "1") &&
ih.validateEntityFieldType("test", "a", "12345") &&
!ih.validateEntityFieldType("test", "a", "1.0") &&
!ih.validateEntityFieldType("test", "a", "string")
);
ih.removeEntity("test");
}
/**
* Tests that parseEntityAssignField correctly flags invalid assignments to float fields
*/
void testFieldAssignTypeMismatchFloat() {
IndexHandler ih;
Json::Value json;
std::vector<std::pair<ColumnBase*, std::string>> fields_ent;
fields_ent.push_back(std::make_pair(getColumnType("float"), "a")); // Create fields
Entity e("test", fields_ent); // Create the entity
ih.writeEntity(e); // Create the entity
assert(
ih.validateEntityFieldType("test", "a", "1.2") &&
ih.validateEntityFieldType("test", "a", "12.5") &&
!ih.validateEntityFieldType("test", "a", "string")
);
ih.removeEntity("test");
}
/**
* Tests that parseEntityAssignField correctly flags invalid assignments to string fields
*/
void testFieldAssignTypeMismatchString() {
IndexHandler ih;
Json::Value json;
std::vector<std::pair<ColumnBase*, std::string>> fields_ent;
fields_ent.push_back(std::make_pair(getColumnType("string"), "a")); // Create fields
Entity e("test", fields_ent);
ih.writeEntity(e); // Create the entity
assert(
ih.validateEntityFieldType("test", "a", "1") &&
ih.validateEntityFieldType("test", "a", "12345") &&
ih.validateEntityFieldType("test", "a", "string")
);
ih.removeEntity("test");
}
/**
* Tests that existsEntityField correctly flags when entity does not contain a field
*/
void testEntityDoesNotContainField() {
// TODO - implement
}
/**
* Tests Bayes::computeMarginal function - ensure the marginal likelihood is correct
*/
void testComputeMarginal() {
Bayes bayes;
IndexHandler ih;
std::vector<Json::Value> ret;
std::vector<std::pair<ColumnBase*, std::string>> fields_ent;
std::vector<std::pair<std::string, std::string>> fields_rel;
long num_relations = ih.getRelationCountTotal();
// declare three entities
Entity e1("_w", fields_ent), e2("_x", fields_ent), e3("_y", fields_ent), e4("_z", fields_ent);
ih.writeEntity(e1);
ih.writeEntity(e2);
ih.writeEntity(e3);
ih.writeEntity(e4);
// construct a number of relations
Relation r1("_x", "_y", fields_rel, fields_rel);
Relation r2("_x", "_y", fields_rel, fields_rel);
Relation r3("_x", "_z", fields_rel, fields_rel);
Relation r4("_x", "_z", fields_rel, fields_rel);
Relation r5("_w", "_y", fields_rel, fields_rel);
ih.writeRelation(r1);
ih.writeRelation(r2);
ih.writeRelation(r3);
ih.writeRelation(r4);
ih.writeRelation(r5);
// Ensure marginal likelihood reflects the number of relations that contain each entity
AttributeBucket attrs;
// TODO - fix computeMarginal seg fault
cout << bayes.computeMarginal(e1.name, attrs) << endl;
assert(bayes.computeMarginal(e1.name, attrs) == 4.0 / 5.0);
assert(bayes.computeMarginal(e2.name, attrs) == 3.0 / 5.0);
assert(bayes.computeMarginal(e3.name, attrs) == 2.0 / 5.0);
assert(bayes.computeMarginal(e4.name, attrs) == 1.0 / 5.0);
ih.removeEntity("_w");
ih.removeEntity("_x");
ih.removeEntity("_y");
ih.removeEntity("_z");
ih.removeRelation(r1);
ih.removeRelation(r2);
ih.removeRelation(r3);
ih.removeRelation(r4);
ih.removeRelation(r5);
// Reset the relations count
ih.setRelationCountTotal(num_relations);
}
/**
* Tests that removal of entities functions properly
*/
void testEntityRemoval() {
// TODO - implement
}
/**
* Tests that removal of relations functions properly
*/
void testRelationRemoval() {
// TODO - implement
}
/**
* Tests that removal of relations cascading on entities functions properly
*/
void testEntityCascadeRemoval() {
// TODO - implement
}
/**
* Tests that the correct relations are filtered from a set
*/
void testRelationFiltering() {
// TODO - implement
}
/**
* Tests that the correct relations are filtered from a set
*/
void testRelation_toJson() {
valpair left, right;
left.push_back(std::make_pair("x", "1"));
right.push_back(std::make_pair("y", "2"));
Relation rel("x", "y", left, right);
Json::Value json = rel.toJson();
cout << json.toStyledString() << endl;
}
int main() {
cout << "-- TESTS BEGIN --" << endl << endl;
// testRedisSet();
// testRedisGet();
// testRedisKeys();
// md5Hashing();
// testRedisIO();
// testRegexForTypes();
// testOrderPairAlphaNumeric();
// testJSONEntityEncoding();
// testJSONRelationEncoding();
// testFieldAssignTypeMismatchInteger();
// testFieldAssignTypeMismatchFloat();
// testFieldAssignTypeMismatchString();
// testComputeMarginal();
testRelation_toJson();
cout << endl << "-- TESTS END --" << endl;
return 0;
}
<commit_msg>add assert for toJson test<commit_after>
/*
* client.cpp
*
* Handles the client env.
*
* Created by Ryan Faulkner on 2014-06-08
* Copyright (c) 2014. All rights reserved.
*/
#include <iostream>
#include <string>
#include <vector>
#include <regex>
#include <assert.h>
#include "column_types.h"
#include "redis.h"
#include "md5.h"
#include "index.h"
#include "bayes.h"
#include "model.h"
#define REDISHOST "127.0.0.1"
#define REDISPORT 6379
using namespace std;
/** Test to ensure that redis keys are correctly returned */
void testRedisSet() {
RedisHandler r;
r.connect();
r.write("foo", "bar");
}
/** Test to ensure that redis keys are correctly returned */
void testRedisGet() {
RedisHandler r;
r.connect();
cout << endl << "VALUE FOR KEY foo" << endl;
cout << r.read("foo") << endl << endl;
}
/** Test to ensure that redis keys are correctly returned */
void testRedisKeys() {
RedisHandler r;
std::vector<std::string> vec;
r.connect();
vec = r.keys("*");
cout << "KEY LIST FOR *" << endl;
for (std::vector<std::string>::iterator it = vec.begin() ; it != vec.end(); ++it) {
cout << *it << endl;
}
cout << endl;
}
/** Test to ensure that redis keys are correctly returned */
void testRedisIO() {
RedisHandler r;
std::vector<string>* vec;
std::string outTrue, outFalse = "";
r.connect();
r.write("test_key", "test value");
outTrue = r.read("test_key");
assert(std::strcmp(outTrue.c_str(), "test value") == 0);
r.deleteKey("test_key");
assert(!r.exists("test_key"));
}
/** Test to ensure that md5 hashing works */
void testMd5Hashing() {
cout << endl << "md5 of 'mykey': " << md5("mykey") << endl;
}
/** Test to ensure that md5 hashing works */
void testRegexForTypes() {
IntegerColumn ic;
FloatColumn fc;
assert(ic.validate("1981"));
assert(fc.validate("5.2"));
cout << "Passed regex tests." << endl;
}
/** Test to ensure that md5 hashing works */
void testOrderPairAlphaNumeric() {
IndexHandler ih;
assert(std::strcmp(ih.orderPairAlphaNumeric("b", "a").c_str(), "a_b") == 0);
cout << "Passed orderPairAlphaNumeric tests." << endl;
}
/**
* Test to ensure that relation entities are encoded properly
*/
void testJSONEntityEncoding() {
IndexHandler ih;
Json::Value json;
std::vector<std::pair<ColumnBase*, std::string>> fields_ent;
fields_ent.push_back(std::make_pair(getColumnType("integer"), "a")); // Create fields
Entity e("test", fields_ent);
ih.writeEntity(e); // Create the entity
ih.fetchEntity("test", json); // Fetch the entity representation
cout << "TEST ENTITY:" << endl << endl << json.toStyledString() << endl;
// Assert that entity as read matches definition
assert(std::strcmp(json["entity"].asCString(), "test") == 0 &&
std::strcmp(json["fields"]["a"].asCString(), "integer") == 0 &&
json["fields"]["_itemcount"].asInt() == 1
);
ih.removeEntity("test"); // Remove the entity
}
/**
* Test to ensure that relation fields are encoded properly
*/
void testJSONRelationEncoding() {
IndexHandler ih;
std::vector<Json::Value> ret;
std::vector<std::pair<ColumnBase*, std::string>> fields_ent_1;
std::vector<std::pair<ColumnBase*, std::string>> fields_ent_2;
std::vector<std::pair<std::string, std::string>> fields_rel_1;
std::vector<std::pair<std::string, std::string>> fields_rel_2;
// Popualate fields
fields_ent_1.push_back(std::make_pair(getColumnType("integer"), "a"));
fields_ent_2.push_back(std::make_pair(getColumnType("string"), "b"));
fields_rel_1.push_back(std::make_pair("a", "1"));
fields_rel_2.push_back(std::make_pair("b", "hello"));
// Create entities
Entity e1("test_1", fields_ent_1), e2("test_2", fields_ent_2);
ih.writeEntity(e1);
ih.writeEntity(e2);
// Create relation in redis
Relation r("test_1", "test_2", fields_rel_1, fields_rel_2);
ih.writeRelation(r);
// Fetch the entity representation
ret = ih.fetchRelationPrefix("test_1", "test_2");
cout << "TEST RELATION:" << endl << endl << ret[0].toStyledString() << endl;
// Assert that entity as read matches definition
assert(
std::strcmp(ret[0]["entity_left"].asCString(), "test_1") == 0 &&
std::strcmp(ret[0]["entity_right"].asCString(), "test_2") == 0 &&
std::strcmp(ret[0]["fields_left"]["a"].asCString(), "1") == 0 &&
std::strcmp(ret[0]["fields_right"]["b"].asCString(), "hello") == 0 &&
ret[0]["fields_left"]["_itemcount"].asInt() == 1 &&
ret[0]["fields_right"]["_itemcount"].asInt() == 1
);
ih.removeEntity("test_1"); // Remove the entity
ih.removeEntity("test_2"); // Remove the entity
ih.removeRelation(r); // Remove the relation
}
/**
* Tests that parseEntityAssignField correctly flags invalid assignments to integer fields
*/
void testFieldAssignTypeMismatchInteger() {
IndexHandler ih;
Json::Value json;
std::vector<std::pair<ColumnBase*, std::string>> fields_ent;
fields_ent.push_back(std::make_pair(getColumnType("integer"), "a")); // Create fields
Entity e("test", fields_ent);
ih.writeEntity(e); // Create the entity
assert(
ih.validateEntityFieldType("test", "a", "1") &&
ih.validateEntityFieldType("test", "a", "12345") &&
!ih.validateEntityFieldType("test", "a", "1.0") &&
!ih.validateEntityFieldType("test", "a", "string")
);
ih.removeEntity("test");
}
/**
* Tests that parseEntityAssignField correctly flags invalid assignments to float fields
*/
void testFieldAssignTypeMismatchFloat() {
IndexHandler ih;
Json::Value json;
std::vector<std::pair<ColumnBase*, std::string>> fields_ent;
fields_ent.push_back(std::make_pair(getColumnType("float"), "a")); // Create fields
Entity e("test", fields_ent); // Create the entity
ih.writeEntity(e); // Create the entity
assert(
ih.validateEntityFieldType("test", "a", "1.2") &&
ih.validateEntityFieldType("test", "a", "12.5") &&
!ih.validateEntityFieldType("test", "a", "string")
);
ih.removeEntity("test");
}
/**
* Tests that parseEntityAssignField correctly flags invalid assignments to string fields
*/
void testFieldAssignTypeMismatchString() {
IndexHandler ih;
Json::Value json;
std::vector<std::pair<ColumnBase*, std::string>> fields_ent;
fields_ent.push_back(std::make_pair(getColumnType("string"), "a")); // Create fields
Entity e("test", fields_ent);
ih.writeEntity(e); // Create the entity
assert(
ih.validateEntityFieldType("test", "a", "1") &&
ih.validateEntityFieldType("test", "a", "12345") &&
ih.validateEntityFieldType("test", "a", "string")
);
ih.removeEntity("test");
}
/**
* Tests that existsEntityField correctly flags when entity does not contain a field
*/
void testEntityDoesNotContainField() {
// TODO - implement
}
/**
* Tests Bayes::computeMarginal function - ensure the marginal likelihood is correct
*/
void testComputeMarginal() {
Bayes bayes;
IndexHandler ih;
std::vector<Json::Value> ret;
std::vector<std::pair<ColumnBase*, std::string>> fields_ent;
std::vector<std::pair<std::string, std::string>> fields_rel;
long num_relations = ih.getRelationCountTotal();
// declare three entities
Entity e1("_w", fields_ent), e2("_x", fields_ent), e3("_y", fields_ent), e4("_z", fields_ent);
ih.writeEntity(e1);
ih.writeEntity(e2);
ih.writeEntity(e3);
ih.writeEntity(e4);
// construct a number of relations
Relation r1("_x", "_y", fields_rel, fields_rel);
Relation r2("_x", "_y", fields_rel, fields_rel);
Relation r3("_x", "_z", fields_rel, fields_rel);
Relation r4("_x", "_z", fields_rel, fields_rel);
Relation r5("_w", "_y", fields_rel, fields_rel);
ih.writeRelation(r1);
ih.writeRelation(r2);
ih.writeRelation(r3);
ih.writeRelation(r4);
ih.writeRelation(r5);
// Ensure marginal likelihood reflects the number of relations that contain each entity
AttributeBucket attrs;
// TODO - fix computeMarginal seg fault
cout << bayes.computeMarginal(e1.name, attrs) << endl;
assert(bayes.computeMarginal(e1.name, attrs) == 4.0 / 5.0);
assert(bayes.computeMarginal(e2.name, attrs) == 3.0 / 5.0);
assert(bayes.computeMarginal(e3.name, attrs) == 2.0 / 5.0);
assert(bayes.computeMarginal(e4.name, attrs) == 1.0 / 5.0);
ih.removeEntity("_w");
ih.removeEntity("_x");
ih.removeEntity("_y");
ih.removeEntity("_z");
ih.removeRelation(r1);
ih.removeRelation(r2);
ih.removeRelation(r3);
ih.removeRelation(r4);
ih.removeRelation(r5);
// Reset the relations count
ih.setRelationCountTotal(num_relations);
}
/**
* Tests that removal of entities functions properly
*/
void testEntityRemoval() {
// TODO - implement
}
/**
* Tests that removal of relations functions properly
*/
void testRelationRemoval() {
// TODO - implement
}
/**
* Tests that removal of relations cascading on entities functions properly
*/
void testEntityCascadeRemoval() {
// TODO - implement
}
/**
* Tests that the correct relations are filtered from a set
*/
void testRelationFiltering() {
// TODO - implement
}
/**
* Tests that the correct relations are filtered from a set
*/
void testRelation_toJson() {
valpair left, right;
left.push_back(std::make_pair("x", "1"));
right.push_back(std::make_pair("y", "2"));
Relation rel("x", "y", left, right);
Json::Value json = rel.toJson();
assert(std::atoi(json[JSON_ATTR_REL_FIELDSL]["x"].asCString()) == 1 && std::atoi(json[JSON_ATTR_REL_FIELDSR]["y"].asCString()) == 2);
}
int main() {
cout << "-- TESTS BEGIN --" << endl << endl;
// testRedisSet();
// testRedisGet();
// testRedisKeys();
// md5Hashing();
// testRedisIO();
// testRegexForTypes();
// testOrderPairAlphaNumeric();
// testJSONEntityEncoding();
// testJSONRelationEncoding();
// testFieldAssignTypeMismatchInteger();
// testFieldAssignTypeMismatchFloat();
// testFieldAssignTypeMismatchString();
// testComputeMarginal();
testRelation_toJson();
cout << endl << "-- TESTS END --" << endl;
return 0;
}
<|endoftext|> |
<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2013-2016.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include <tlib/print.hpp>
const char* source = "Hello world";
int main(){
char buffer[16];
for(int i = 0; i < 10; ++i){
auto c = read_input(buffer, 15);
buffer[c] = '\0';
print(buffer);
}
return 0;
}
<commit_msg>Test more<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2013-2016.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include <tlib/print.hpp>
const char* source = "Hello world";
int main(){
char buffer[16];
printf("Read 1 string (max 15)\n");
auto c = read_input(buffer, 15);
buffer[c] = '\0';
print(buffer);
printf("Read 1 string (max 15) with timeout 5\n");
c = read_input(buffer, 15, 5000);
if(c){
buffer[c] = '\0';
print(buffer);
} else {
printf("Timeout reached\n");
}
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2019 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "test/gtest.h"
#include "test/peer_scenario/peer_scenario.h"
namespace webrtc {
namespace test {
TEST(PeerScenarioQualityTest, PsnrIsCollected) {
VideoQualityAnalyzer analyzer;
{
PeerScenario s(*test_info_);
auto caller = s.CreateClient(PeerScenarioClient::Config());
auto callee = s.CreateClient(PeerScenarioClient::Config());
PeerScenarioClient::VideoSendTrackConfig video_conf;
video_conf.generator.squares_video->framerate = 20;
auto video = caller->CreateVideo("VIDEO", video_conf);
auto link_builder = s.net()->NodeBuilder().delay_ms(100).capacity_kbps(600);
s.AttachVideoQualityAnalyzer(&analyzer, video.track, callee);
s.SimpleConnection(caller, callee, {link_builder.Build().node},
{link_builder.Build().node});
s.ProcessMessages(TimeDelta::Seconds(2));
// Exit scope to ensure that there's no pending tasks reporting to analyzer.
}
// We expect ca 40 frames to be produced, but to avoid flakiness on slow
// machines we only test for 10.
EXPECT_GT(analyzer.stats().render.count, 10);
EXPECT_GT(analyzer.stats().psnr_with_freeze.Mean(), 20);
}
} // namespace test
} // namespace webrtc
<commit_msg>Disable PeerScenarioQualityTest.PsnrIsCollected on windows.<commit_after>/*
* Copyright (c) 2019 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "test/gtest.h"
#include "test/peer_scenario/peer_scenario.h"
namespace webrtc {
namespace test {
#if defined(WEBRTC_WIN)
#define MAYBE_PsnrIsCollected DISABLED_PsnrIsCollected
#else
#define MAYBE_PsnrIsCollected PsnrIsCollected
#endif
TEST(PeerScenarioQualityTest, MAYBE_PsnrIsCollected) {
VideoQualityAnalyzer analyzer;
{
PeerScenario s(*test_info_);
auto caller = s.CreateClient(PeerScenarioClient::Config());
auto callee = s.CreateClient(PeerScenarioClient::Config());
PeerScenarioClient::VideoSendTrackConfig video_conf;
video_conf.generator.squares_video->framerate = 20;
auto video = caller->CreateVideo("VIDEO", video_conf);
auto link_builder = s.net()->NodeBuilder().delay_ms(100).capacity_kbps(600);
s.AttachVideoQualityAnalyzer(&analyzer, video.track, callee);
s.SimpleConnection(caller, callee, {link_builder.Build().node},
{link_builder.Build().node});
s.ProcessMessages(TimeDelta::Seconds(2));
// Exit scope to ensure that there's no pending tasks reporting to analyzer.
}
// We expect ca 40 frames to be produced, but to avoid flakiness on slow
// machines we only test for 10.
EXPECT_GT(analyzer.stats().render.count, 10);
EXPECT_GT(analyzer.stats().psnr_with_freeze.Mean(), 20);
}
} // namespace test
} // namespace webrtc
<|endoftext|> |
<commit_before>#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>
#include <cassert>
#include <cstring>
#include <string>
#include <sstream>
#include "phIO.h"
#include "phComm.h"
#include "phio_base.h"
#include "ph_mpi_help.h"
#ifndef PHASTAIO_TIMERS_ON
#define PHASTAIO_TIMERS_ON 0
#endif
struct phastaio_stats {
double readTime;
double writeTime;
double openTime;
double closeTime;
size_t readBytes;
size_t writeBytes;
};
phastaio_stats phio_global_stats;
namespace {
inline double getTime() {
return MPI_Wtime();
}
inline size_t getSize(const char* t) {
std::string type(t);
if(type == "integer")
return sizeof(int);
else if(type == "double")
return sizeof(double);
else {
assert(0);
exit(EXIT_FAILURE);
}
}
}
#define PHIO_TRACING 0
namespace {
void trace(const char* key, const char* aux="", void* obj=NULL) {
if(PHIO_TRACING)
fprintf(stderr, "PHIO_TRACE entering %s %s %p\n", key, aux, obj);
}
void printMinMaxAvg(const char* key, size_t v) {
int val = static_cast<int>(v);
int min = ph_min_int(val);
int max = ph_max_int(val);
long tot = ph_add_long(static_cast<long>(val));
double avg = tot/static_cast<double>(ph_peers());
if(!ph_self())
fprintf(stderr, "phio_%s min max avg %d %d %f\n",
key, min, max, avg);
}
void printMinMaxAvg(const char* key, double v) {
double min = ph_min_double(v);
double max = ph_max_double(v);
double tot = ph_add_double(v);
double avg = tot/ph_peers();
if(!ph_self())
fprintf(stderr, "phio_%s min max avg %f %f %f\n",
key, min, max, avg);
}
}
#ifdef __cplusplus
extern "C" {
#endif
void phio_printStats() {
printMinMaxAvg("readTime",phio_getReadTime());
printMinMaxAvg("writeTime", phio_getWriteTime());
printMinMaxAvg("openTime", phio_getOpenTime());
printMinMaxAvg("closeTime", phio_getCloseTime());
printMinMaxAvg("readBytes", phio_getReadBytes());
printMinMaxAvg("writeBytes", phio_getWriteBytes());
}
void phio_initStats() {
phio_global_stats.readTime = 0;
phio_global_stats.writeTime = 0;
phio_global_stats.openTime = 0;
phio_global_stats.closeTime = 0;
phio_global_stats.readBytes = 0;
phio_global_stats.writeBytes = 0;
}
double phio_getReadTime() {
return phio_global_stats.readTime;
}
double phio_getWriteTime() {
return phio_global_stats.writeTime;
}
double phio_getOpenTime() {
return phio_global_stats.openTime;
}
double phio_getCloseTime() {
return phio_global_stats.closeTime;
}
size_t phio_getReadBytes() {
return phio_global_stats.readBytes;
}
size_t phio_getWriteBytes() {
return phio_global_stats.writeBytes;
}
void phio_readheader(
phio_fp f,
const char keyphrase[],
void* valueArray,
int* nItems,
const char datatype[],
const char iotype[] ) {
const double t0 = getTime();
f->ops->readheader(f->file, keyphrase, valueArray,
nItems, datatype, iotype);
phio_global_stats.readBytes += (*nItems)*getSize(datatype);
phio_global_stats.readTime += getTime()-t0;
}
void phio_writeheader(
phio_fp f,
const char keyphrase[],
const void* valueArray,
const int* nItems,
const int* ndataItems,
const char datatype[],
const char iotype[] ) {
const double t0 = getTime();
f->ops->writeheader(f->file, keyphrase, valueArray,
nItems, ndataItems, datatype, iotype);
phio_global_stats.writeBytes += (*nItems)*getSize(datatype);
phio_global_stats.writeTime += getTime()-t0;
}
void phio_readdatablock(
phio_fp f,
const char keyphrase[],
void* valueArray,
int* nItems,
const char datatype[],
const char iotype[] ) {
const double t0 = getTime();
f->ops->readdatablock(f->file, keyphrase, valueArray,
nItems, datatype, iotype);
phio_global_stats.readBytes += (*nItems)*getSize(datatype);
phio_global_stats.readTime += getTime()-t0;
}
void phio_writedatablock(
phio_fp f,
const char keyphrase[],
const void* valueArray,
const int* nItems,
const char datatype[],
const char iotype[]) {
const double t0 = getTime();
f->ops->writedatablock(f->file, keyphrase, valueArray,
nItems, datatype, iotype);
phio_global_stats.writeBytes += (*nItems)*getSize(datatype);
phio_global_stats.writeTime += getTime()-t0;
}
void phio_constructName(
phio_fp f,
const char inName[],
char* outName) {
f->ops->constructname(inName, outName);
}
void phio_openfile(
const char filename[],
phio_fp f) {
const double t0 = getTime();
trace("openfile",filename,f);
f->ops->openfile(filename, f);
phio_global_stats.openTime += getTime()-t0;
}
void phio_closefile(phio_fp f) {
const double t0 = getTime();
trace("closefile","unknown",f);
f->ops->closefile(f);
phio_global_stats.closeTime += getTime()-t0;
}
void phio_appendInt(char* dest, int v) {
std::stringstream ss;
ss << dest << v << '.';
std::string s = ss.str();
strcpy(dest, s.c_str());
}
#ifdef __cplusplus
}
#endif
<commit_msg>common: write io stat units and r/w bandwidth<commit_after>#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>
#include <cassert>
#include <cstring>
#include <string>
#include <sstream>
#include "phIO.h"
#include "phComm.h"
#include "phio_base.h"
#include "ph_mpi_help.h"
#ifndef PHASTAIO_TIMERS_ON
#define PHASTAIO_TIMERS_ON 0
#endif
struct phastaio_stats {
double readTime;
double writeTime;
double openTime;
double closeTime;
size_t readBytes;
size_t writeBytes;
};
phastaio_stats phio_global_stats;
namespace {
inline double getTime() {
return MPI_Wtime();
}
inline size_t getSize(const char* t) {
std::string type(t);
if(type == "integer")
return sizeof(int);
else if(type == "double")
return sizeof(double);
else {
assert(0);
exit(EXIT_FAILURE);
}
}
}
#define PHIO_TRACING 0
namespace {
void trace(const char* key, const char* aux="", void* obj=NULL) {
if(PHIO_TRACING)
fprintf(stderr, "PHIO_TRACE entering %s %s %p\n", key, aux, obj);
}
void printMinMaxAvg(const char* key, size_t v) {
int val = static_cast<int>(v);
int min = ph_min_int(val);
int max = ph_max_int(val);
long tot = ph_add_long(static_cast<long>(val));
double avg = tot/static_cast<double>(ph_peers());
if(!ph_self())
fprintf(stderr, "phio_%s min max avg %d %d %f\n",
key, min, max, avg);
}
void printMinMaxAvg(const char* key, double v) {
double min = ph_min_double(v);
double max = ph_max_double(v);
double tot = ph_add_double(v);
double avg = tot/ph_peers();
if(!ph_self())
fprintf(stderr, "phio_%s min max avg %f %f %f\n",
key, min, max, avg);
}
}
#ifdef __cplusplus
extern "C" {
#endif
void phio_printStats() {
const int mebi=1024*1024;
printMinMaxAvg("readTime (s)",phio_getReadTime());
printMinMaxAvg("writeTime (s)", phio_getWriteTime());
printMinMaxAvg("openTime (s)", phio_getOpenTime());
printMinMaxAvg("closeTime (s)", phio_getCloseTime());
printMinMaxAvg("readBytes (B)", phio_getReadBytes());
printMinMaxAvg("writeBytes (B)", phio_getWriteBytes());
printMinMaxAvg("readBandwidth (MiB/s)",
(phio_getReadBytes()/phio_getReadTime())/mebi);
printMinMaxAvg("writeBandwidth (MiB/s)",
(phio_getWriteBytes()/phio_getWriteTime())/mebi);
}
void phio_initStats() {
phio_global_stats.readTime = 0;
phio_global_stats.writeTime = 0;
phio_global_stats.openTime = 0;
phio_global_stats.closeTime = 0;
phio_global_stats.readBytes = 0;
phio_global_stats.writeBytes = 0;
}
double phio_getReadTime() {
return phio_global_stats.readTime;
}
double phio_getWriteTime() {
return phio_global_stats.writeTime;
}
double phio_getOpenTime() {
return phio_global_stats.openTime;
}
double phio_getCloseTime() {
return phio_global_stats.closeTime;
}
size_t phio_getReadBytes() {
return phio_global_stats.readBytes;
}
size_t phio_getWriteBytes() {
return phio_global_stats.writeBytes;
}
void phio_readheader(
phio_fp f,
const char keyphrase[],
void* valueArray,
int* nItems,
const char datatype[],
const char iotype[] ) {
const double t0 = getTime();
f->ops->readheader(f->file, keyphrase, valueArray,
nItems, datatype, iotype);
phio_global_stats.readBytes += (*nItems)*getSize(datatype);
phio_global_stats.readTime += getTime()-t0;
}
void phio_writeheader(
phio_fp f,
const char keyphrase[],
const void* valueArray,
const int* nItems,
const int* ndataItems,
const char datatype[],
const char iotype[] ) {
const double t0 = getTime();
f->ops->writeheader(f->file, keyphrase, valueArray,
nItems, ndataItems, datatype, iotype);
phio_global_stats.writeBytes += (*nItems)*getSize(datatype);
phio_global_stats.writeTime += getTime()-t0;
}
void phio_readdatablock(
phio_fp f,
const char keyphrase[],
void* valueArray,
int* nItems,
const char datatype[],
const char iotype[] ) {
const double t0 = getTime();
f->ops->readdatablock(f->file, keyphrase, valueArray,
nItems, datatype, iotype);
phio_global_stats.readBytes += (*nItems)*getSize(datatype);
phio_global_stats.readTime += getTime()-t0;
}
void phio_writedatablock(
phio_fp f,
const char keyphrase[],
const void* valueArray,
const int* nItems,
const char datatype[],
const char iotype[]) {
const double t0 = getTime();
f->ops->writedatablock(f->file, keyphrase, valueArray,
nItems, datatype, iotype);
phio_global_stats.writeBytes += (*nItems)*getSize(datatype);
phio_global_stats.writeTime += getTime()-t0;
}
void phio_constructName(
phio_fp f,
const char inName[],
char* outName) {
f->ops->constructname(inName, outName);
}
void phio_openfile(
const char filename[],
phio_fp f) {
const double t0 = getTime();
trace("openfile",filename,f);
f->ops->openfile(filename, f);
phio_global_stats.openTime += getTime()-t0;
}
void phio_closefile(phio_fp f) {
const double t0 = getTime();
trace("closefile","unknown",f);
f->ops->closefile(f);
phio_global_stats.closeTime += getTime()-t0;
}
void phio_appendInt(char* dest, int v) {
std::stringstream ss;
ss << dest << v << '.';
std::string s = ss.str();
strcpy(dest, s.c_str());
}
#ifdef __cplusplus
}
#endif
<|endoftext|> |
<commit_before>/*
Copyright (c) 2012, Arvid Norberg
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 author 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 "libtorrent/config.hpp"
#include "libtorrent/utf8.hpp"
#include "libtorrent/ConvertUTF.h"
// on windows we need these functions for
// convert_to_native and convert_from_native
#if TORRENT_USE_WSTRING || defined TORRENT_WINDOWS
namespace libtorrent
{
int utf8_wchar(const std::string &utf8, std::wstring &wide)
{
// allocate space for worst-case
wide.resize(utf8.size());
wchar_t const* dst_start = wide.c_str();
char const* src_start = utf8.c_str();
ConversionResult ret;
if (sizeof(wchar_t) == sizeof(UTF32))
{
ret = ConvertUTF8toUTF32((const UTF8**)&src_start, (const UTF8*)src_start
+ utf8.size(), (UTF32**)&dst_start, (UTF32*)dst_start + wide.size()
, lenientConversion);
wide.resize(dst_start - wide.c_str());
return ret;
}
else if (sizeof(wchar_t) == sizeof(UTF16))
{
ret = ConvertUTF8toUTF16((const UTF8**)&src_start, (const UTF8*)src_start
+ utf8.size(), (UTF16**)&dst_start, (UTF16*)dst_start + wide.size()
, lenientConversion);
wide.resize(dst_start - wide.c_str());
return ret;
}
else
{
return sourceIllegal;
}
}
int wchar_utf8(const std::wstring &wide, std::string &utf8)
{
// allocate space for worst-case
utf8.resize(wide.size() * 6);
if (wide.empty()) return 0;
char* dst_start = &utf8[0];
wchar_t const* src_start = wide.c_str();
ConversionResult ret;
if (sizeof(wchar_t) == sizeof(UTF32))
{
ret = ConvertUTF32toUTF8((const UTF32**)&src_start, (const UTF32*)src_start
+ wide.size(), (UTF8**)&dst_start, (UTF8*)dst_start + utf8.size()
, lenientConversion);
utf8.resize(dst_start - &utf8[0]);
return ret;
}
else if (sizeof(wchar_t) == sizeof(UTF16))
{
ret = ConvertUTF16toUTF8((const UTF16**)&src_start, (const UTF16*)src_start
+ wide.size(), (UTF8**)&dst_start, (UTF8*)dst_start + utf8.size()
, lenientConversion);
utf8.resize(dst_start - &utf8[0]);
return ret;
}
else
{
return sourceIllegal;
}
}
#endif
}
<commit_msg>fixed typo in utf8.cpp<commit_after>/*
Copyright (c) 2012, Arvid Norberg
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 author 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 "libtorrent/config.hpp"
#include "libtorrent/utf8.hpp"
#include "libtorrent/ConvertUTF.h"
// on windows we need these functions for
// convert_to_native and convert_from_native
#if TORRENT_USE_WSTRING || defined TORRENT_WINDOWS
namespace libtorrent
{
int utf8_wchar(const std::string &utf8, std::wstring &wide)
{
// allocate space for worst-case
wide.resize(utf8.size());
wchar_t const* dst_start = wide.c_str();
char const* src_start = utf8.c_str();
ConversionResult ret;
if (sizeof(wchar_t) == sizeof(UTF32))
{
ret = ConvertUTF8toUTF32((const UTF8**)&src_start, (const UTF8*)src_start
+ utf8.size(), (UTF32**)&dst_start, (UTF32*)dst_start + wide.size()
, lenientConversion);
wide.resize(dst_start - wide.c_str());
return ret;
}
else if (sizeof(wchar_t) == sizeof(UTF16))
{
ret = ConvertUTF8toUTF16((const UTF8**)&src_start, (const UTF8*)src_start
+ utf8.size(), (UTF16**)&dst_start, (UTF16*)dst_start + wide.size()
, lenientConversion);
wide.resize(dst_start - wide.c_str());
return ret;
}
else
{
return sourceIllegal;
}
}
int wchar_utf8(const std::wstring &wide, std::string &utf8)
{
// allocate space for worst-case
utf8.resize(wide.size() * 6);
if (wide.empty()) return 0;
char* dst_start = &utf8[0];
wchar_t const* src_start = wide.c_str();
ConversionResult ret;
if (sizeof(wchar_t) == sizeof(UTF32))
{
ret = ConvertUTF32toUTF8((const UTF32**)&src_start, (const UTF32*)src_start
+ wide.size(), (UTF8**)&dst_start, (UTF8*)dst_start + utf8.size()
, lenientConversion);
utf8.resize(dst_start - &utf8[0]);
return ret;
}
else if (sizeof(wchar_t) == sizeof(UTF16))
{
ret = ConvertUTF16toUTF8((const UTF16**)&src_start, (const UTF16*)src_start
+ wide.size(), (UTF8**)&dst_start, (UTF8*)dst_start + utf8.size()
, lenientConversion);
utf8.resize(dst_start - &utf8[0]);
return ret;
}
else
{
return sourceIllegal;
}
}
}
#endif
<|endoftext|> |
<commit_before>#include <vector>
#include <array>
#include <map>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <tuple>
#include <glm/glm.hpp>
#include <SDL.h>
#include "gl_core_3_3.h"
#include "util.h"
std::string util::readFile(const std::string &fName){
std::ifstream file(fName);
if (!file.is_open()){
std::cout << "Failed to open file: " << fName << std::endl;
return "";
}
return std::string((std::istreambuf_iterator<char>(file)),
std::istreambuf_iterator<char>());
}
GLint util::loadShader(GLenum type, const std::string &file){
GLuint shader = glCreateShader(type);
std::string src = readFile(file);
const char *csrc = src.c_str();
glShaderSource(shader, 1, &csrc, 0);
glCompileShader(shader);
GLint status;
glGetShaderiv(shader, GL_COMPILE_STATUS, &status);
if (status == GL_FALSE){
std::cerr << "loadShader: ";
switch (type){
case GL_VERTEX_SHADER:
std::cerr << "Vertex shader: ";
break;
case GL_FRAGMENT_SHADER:
std::cerr << "Fragment shader: ";
break;
case GL_GEOMETRY_SHADER:
std::cerr << "Geometry shader: ";
break;
default:
std::cerr << "Other shader type: ";
}
std::cerr << file << " failed to compile. Compilation log:\n";
GLint len;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &len);
char *log = new char[len];
glGetShaderInfoLog(shader, len, 0, log);
std::cerr << log << "\n";
delete[] log;
glDeleteShader(shader);
return -1;
}
return shader;
}
GLint util::loadProgram(const std::vector<std::tuple<GLenum, std::string>> &shaders){
std::vector<GLuint> glshaders;
for (const std::tuple<GLenum, std::string> &s : shaders){
GLint h = loadShader(std::get<0>(s), std::get<1>(s));
if (h == -1){
std::cerr << "loadProgram: A required shader failed to compile, aborting\n";
for (GLuint g : glshaders){
glDeleteShader(g);
}
return -1;
}
}
GLuint program = glCreateProgram();
for (GLuint s : glshaders){
glAttachShader(program, s);
}
glLinkProgram(program);
GLint status;
glGetProgramiv(program, GL_LINK_STATUS, &status);
if (status == GL_FALSE){
std::cerr << "loadProgram: Program failed to link, log:\n";
GLint len;
glGetProgramiv(program, GL_INFO_LOG_LENGTH, &len);
char *log = new char[len];
glGetProgramInfoLog(program, len, 0, log);
std::cerr << log << "\n";
delete[] log;
}
for (GLuint s : glshaders){
glDetachShader(program, s);
glDeleteShader(s);
}
if (status == GL_FALSE){
glDeleteProgram(program);
return -1;
}
return program;
}
GLuint util::loadTexture(const std::string &file){
SDL_Surface *surf = SDL_LoadBMP(file.c_str());
//TODO: Throw an error?
if (!surf){
std::cout << "Failed to load bmp: " << file
<< " SDL_error: " << SDL_GetError() << "\n";
return 0;
}
//Assume 4 or 3 bytes per pixel
GLenum format, internal;
if (surf->format->BytesPerPixel == 4){
internal = GL_RGBA;
if (surf->format->Rmask == 0x000000ff){
format = GL_RGBA;
}
else {
format = GL_BGRA;
}
}
else {
internal = GL_RGB;
if (surf->format->Rmask == 0x000000ff){
format = GL_RGB;
}
else {
format = GL_BGR;
}
}
GLuint tex;
glGenTextures(1, &tex);
glBindTexture(GL_TEXTURE_2D, tex);
glTexImage2D(GL_TEXTURE_2D, 0, internal, surf->w, surf->h, 0, format,
GL_UNSIGNED_BYTE, surf->pixels);
glGenerateMipmap(GL_TEXTURE_2D);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
SDL_FreeSurface(surf);
return tex;
}
bool util::logGLError(const std::string &msg){
GLenum err = glGetError();
if (err != GL_NO_ERROR){
std::cerr << "OpenGL Error: ";
switch (err){
case GL_INVALID_ENUM:
std::cerr << "Invalid enum";
break;
case GL_INVALID_VALUE:
std::cerr << "Invalid value";
break;
case GL_INVALID_OPERATION:
std::cerr << "Invalid operation";
break;
case GL_OUT_OF_MEMORY:
std::cerr << "Out of memory";
break;
case GL_INVALID_FRAMEBUFFER_OPERATION:
std::cerr << "Invalid FrameBuffer operation";
break;
default:
std::cerr << std::hex << err << std::dec;
}
std::cerr << " - " << msg << "\n";
return true;
}
return false;
}
#if _MSC_VER
void APIENTRY util::glDebugCallback(GLenum src, GLenum type, GLuint id, GLenum severity,
GLsizei len, const GLchar *msg, GLvoid *user)
#else
void util::glDebugCallback(GLenum src, GLenum type, GLuint id, GLenum severity,
GLsizei len, const GLchar *msg, GLvoid *user)
#endif
{
//Print a time stamp for the message
float sec = SDL_GetTicks() / 1000.f;
int min = static_cast<int>(sec / 60.f);
sec -= sec / 60.f;
std::cout << "[" << min << ":"
<< std::setprecision(3) << sec << "] OpenGL Debug -";
switch (severity){
case GL_DEBUG_SEVERITY_HIGH_ARB:
std::cout << " High severity";
break;
case GL_DEBUG_SEVERITY_MEDIUM_ARB:
std::cout << " Medium severity";
break;
case GL_DEBUG_SEVERITY_LOW_ARB:
std::cout << " Low severity";
}
switch (src){
case GL_DEBUG_SOURCE_API_ARB:
std::cout << " API";
break;
case GL_DEBUG_SOURCE_WINDOW_SYSTEM_ARB:
std::cout << " Window system";
break;
case GL_DEBUG_SOURCE_SHADER_COMPILER_ARB:
std::cout << " Shader compiler";
break;
case GL_DEBUG_SOURCE_THIRD_PARTY_ARB:
std::cout << " Third party";
break;
case GL_DEBUG_SOURCE_APPLICATION_ARB:
std::cout << " Application";
break;
default:
std::cout << " Other";
}
switch (type){
case GL_DEBUG_TYPE_ERROR_ARB:
std::cout << " Error";
break;
case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB:
std::cout << " Deprecated behavior";
break;
case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB:
std::cout << " Undefined behavior";
break;
case GL_DEBUG_TYPE_PORTABILITY_ARB:
std::cout << " Portability";
break;
case GL_DEBUG_TYPE_PERFORMANCE_ARB:
std::cout << " Performance";
break;
default:
std::cout << " Other";
}
std::cout << ":\n\t" << msg << "\n";
}
bool util::loadOBJ(const std::string &fName, GLuint &vbo, GLuint &ebo, size_t &nElems){
std::ifstream file(fName);
if (!file.is_open()){
std::cout << "Failed to find obj file: " << fName << std::endl;
return false;
}
//Temporary storage for the data we read in
std::vector<glm::vec3> tmpPos, tmpNorm;
std::vector<glm::vec2> tmpUv;
//A map to associate a unique vertex with its index
std::map<std::string, GLushort> vertexIndices;
//The final ordered packed vertices and indices
std::vector<glm::vec3> vertexData;
std::vector<GLushort> indices;
std::string line;
while (std::getline(file, line)){
if (line.empty()){
continue;
}
//Parse vertex info: positions, uv coords and normals
else if (line.at(0) == 'v'){
//positions
if (line.at(1) == ' '){
tmpPos.push_back(captureVec3(line));
}
else if (line.at(1) == 't'){
tmpUv.push_back(captureVec2(line));
}
else if (line.at(1) == 'n'){
tmpNorm.push_back(captureVec3(line));
}
}
//Parse faces
else if (line.at(0) == 'f'){
std::array<std::string, 3> face = captureFaces(line);
for (std::string &v : face){
auto fnd = vertexIndices.find(v);
//If we find the vertex already in the list re-use the index
//If not we create a new vertex and index
if (fnd != vertexIndices.end()){
indices.push_back(fnd->second);
}
else {
std::array<unsigned int, 3> vertex = captureVertex(v);
//Pack the position, normal and uv into the vertex data, note that obj data is
//1-indexed so we subtract 1
vertexData.push_back(tmpPos[vertex[0] - 1]);
vertexData.push_back(tmpNorm[vertex[2] - 1]);
vertexData.push_back(glm::vec3(tmpUv[vertex[1] - 1], 0));
//Store the new index, also subract 1 b/c size 1 => idx 0
//and divide by 3 b/c there are 3 components per vertex
indices.push_back((vertexData.size() - 1) / 3);
vertexIndices[v] = indices.back();
}
}
}
}
nElems = indices.size();
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, vertexData.size() * sizeof(glm::vec3), &vertexData[0], GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(GLushort), &indices[0], GL_STATIC_DRAW);
return true;
}
glm::vec2 util::captureVec2(const std::string &str){
glm::vec2 vec;
sscanf(str.c_str(), "%*s %f %f", &vec.x, &vec.y);
return vec;
}
glm::vec3 util::captureVec3(const std::string &str){
glm::vec3 vec;
sscanf(str.c_str(), "%*s %f %f %f", &vec.x, &vec.y, &vec.z);
return vec;
}
std::array<std::string, 3> util::captureFaces(const std::string &str){
std::array<std::string, 3> faces;
//There's face information between each space in the string, and 3 faces total
size_t prev = str.find(" ", 0);
size_t next = prev;
for (std::string &face : faces){
next = str.find(" ", prev + 1);
face = str.substr(prev + 1, next - prev - 1);
prev = next;
}
return faces;
}
std::array<unsigned int, 3> util::captureVertex(const std::string &str){
std::array<unsigned int, 3> vertex;
sscanf(str.c_str(), "%u/%u/%u", &vertex[0], &vertex[1], &vertex[2]);
return vertex;
}
<commit_msg>Was forgetting to actually attach the shaders hah<commit_after>#include <vector>
#include <array>
#include <map>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <tuple>
#include <glm/glm.hpp>
#include <SDL.h>
#include "gl_core_3_3.h"
#include "util.h"
std::string util::readFile(const std::string &fName){
std::ifstream file(fName);
if (!file.is_open()){
std::cout << "Failed to open file: " << fName << std::endl;
return "";
}
return std::string((std::istreambuf_iterator<char>(file)),
std::istreambuf_iterator<char>());
}
GLint util::loadShader(GLenum type, const std::string &file){
GLuint shader = glCreateShader(type);
std::string src = readFile(file);
const char *csrc = src.c_str();
glShaderSource(shader, 1, &csrc, 0);
glCompileShader(shader);
GLint status;
glGetShaderiv(shader, GL_COMPILE_STATUS, &status);
if (status == GL_FALSE){
std::cerr << "loadShader: ";
switch (type){
case GL_VERTEX_SHADER:
std::cerr << "Vertex shader: ";
break;
case GL_FRAGMENT_SHADER:
std::cerr << "Fragment shader: ";
break;
case GL_GEOMETRY_SHADER:
std::cerr << "Geometry shader: ";
break;
default:
std::cerr << "Other shader type: ";
}
std::cerr << file << " failed to compile. Compilation log:\n";
GLint len;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &len);
char *log = new char[len];
glGetShaderInfoLog(shader, len, 0, log);
std::cerr << log << "\n";
delete[] log;
glDeleteShader(shader);
return -1;
}
return shader;
}
GLint util::loadProgram(const std::vector<std::tuple<GLenum, std::string>> &shaders){
std::vector<GLuint> glshaders;
for (const std::tuple<GLenum, std::string> &s : shaders){
GLint h = loadShader(std::get<0>(s), std::get<1>(s));
if (h == -1){
std::cerr << "loadProgram: A required shader failed to compile, aborting\n";
for (GLuint g : glshaders){
glDeleteShader(g);
}
return -1;
}
glshaders.push_back(h);
}
GLuint program = glCreateProgram();
for (GLuint s : glshaders){
glAttachShader(program, s);
}
glLinkProgram(program);
GLint status;
glGetProgramiv(program, GL_LINK_STATUS, &status);
if (status == GL_FALSE){
std::cerr << "loadProgram: Program failed to link, log:\n";
GLint len;
glGetProgramiv(program, GL_INFO_LOG_LENGTH, &len);
char *log = new char[len];
glGetProgramInfoLog(program, len, 0, log);
std::cerr << log << "\n";
delete[] log;
}
for (GLuint s : glshaders){
glDetachShader(program, s);
glDeleteShader(s);
}
if (status == GL_FALSE){
glDeleteProgram(program);
return -1;
}
return program;
}
GLuint util::loadTexture(const std::string &file){
SDL_Surface *surf = SDL_LoadBMP(file.c_str());
//TODO: Throw an error?
if (!surf){
std::cout << "Failed to load bmp: " << file
<< " SDL_error: " << SDL_GetError() << "\n";
return 0;
}
//Assume 4 or 3 bytes per pixel
GLenum format, internal;
if (surf->format->BytesPerPixel == 4){
internal = GL_RGBA;
if (surf->format->Rmask == 0x000000ff){
format = GL_RGBA;
}
else {
format = GL_BGRA;
}
}
else {
internal = GL_RGB;
if (surf->format->Rmask == 0x000000ff){
format = GL_RGB;
}
else {
format = GL_BGR;
}
}
GLuint tex;
glGenTextures(1, &tex);
glBindTexture(GL_TEXTURE_2D, tex);
glTexImage2D(GL_TEXTURE_2D, 0, internal, surf->w, surf->h, 0, format,
GL_UNSIGNED_BYTE, surf->pixels);
glGenerateMipmap(GL_TEXTURE_2D);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
SDL_FreeSurface(surf);
return tex;
}
bool util::logGLError(const std::string &msg){
GLenum err = glGetError();
if (err != GL_NO_ERROR){
std::cerr << "OpenGL Error: ";
switch (err){
case GL_INVALID_ENUM:
std::cerr << "Invalid enum";
break;
case GL_INVALID_VALUE:
std::cerr << "Invalid value";
break;
case GL_INVALID_OPERATION:
std::cerr << "Invalid operation";
break;
case GL_OUT_OF_MEMORY:
std::cerr << "Out of memory";
break;
case GL_INVALID_FRAMEBUFFER_OPERATION:
std::cerr << "Invalid FrameBuffer operation";
break;
default:
std::cerr << std::hex << err << std::dec;
}
std::cerr << " - " << msg << "\n";
return true;
}
return false;
}
#if _MSC_VER
void APIENTRY util::glDebugCallback(GLenum src, GLenum type, GLuint id, GLenum severity,
GLsizei len, const GLchar *msg, GLvoid *user)
#else
void util::glDebugCallback(GLenum src, GLenum type, GLuint id, GLenum severity,
GLsizei len, const GLchar *msg, GLvoid *user)
#endif
{
//Print a time stamp for the message
float sec = SDL_GetTicks() / 1000.f;
int min = static_cast<int>(sec / 60.f);
sec -= sec / 60.f;
std::cout << "[" << min << ":"
<< std::setprecision(3) << sec << "] OpenGL Debug -";
switch (severity){
case GL_DEBUG_SEVERITY_HIGH_ARB:
std::cout << " High severity";
break;
case GL_DEBUG_SEVERITY_MEDIUM_ARB:
std::cout << " Medium severity";
break;
case GL_DEBUG_SEVERITY_LOW_ARB:
std::cout << " Low severity";
}
switch (src){
case GL_DEBUG_SOURCE_API_ARB:
std::cout << " API";
break;
case GL_DEBUG_SOURCE_WINDOW_SYSTEM_ARB:
std::cout << " Window system";
break;
case GL_DEBUG_SOURCE_SHADER_COMPILER_ARB:
std::cout << " Shader compiler";
break;
case GL_DEBUG_SOURCE_THIRD_PARTY_ARB:
std::cout << " Third party";
break;
case GL_DEBUG_SOURCE_APPLICATION_ARB:
std::cout << " Application";
break;
default:
std::cout << " Other";
}
switch (type){
case GL_DEBUG_TYPE_ERROR_ARB:
std::cout << " Error";
break;
case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB:
std::cout << " Deprecated behavior";
break;
case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB:
std::cout << " Undefined behavior";
break;
case GL_DEBUG_TYPE_PORTABILITY_ARB:
std::cout << " Portability";
break;
case GL_DEBUG_TYPE_PERFORMANCE_ARB:
std::cout << " Performance";
break;
default:
std::cout << " Other";
}
std::cout << ":\n\t" << msg << "\n";
}
bool util::loadOBJ(const std::string &fName, GLuint &vbo, GLuint &ebo, size_t &nElems){
std::ifstream file(fName);
if (!file.is_open()){
std::cout << "Failed to find obj file: " << fName << std::endl;
return false;
}
//Temporary storage for the data we read in
std::vector<glm::vec3> tmpPos, tmpNorm;
std::vector<glm::vec2> tmpUv;
//A map to associate a unique vertex with its index
std::map<std::string, GLushort> vertexIndices;
//The final ordered packed vertices and indices
std::vector<glm::vec3> vertexData;
std::vector<GLushort> indices;
std::string line;
while (std::getline(file, line)){
if (line.empty()){
continue;
}
//Parse vertex info: positions, uv coords and normals
else if (line.at(0) == 'v'){
//positions
if (line.at(1) == ' '){
tmpPos.push_back(captureVec3(line));
}
else if (line.at(1) == 't'){
tmpUv.push_back(captureVec2(line));
}
else if (line.at(1) == 'n'){
tmpNorm.push_back(captureVec3(line));
}
}
//Parse faces
else if (line.at(0) == 'f'){
std::array<std::string, 3> face = captureFaces(line);
for (std::string &v : face){
auto fnd = vertexIndices.find(v);
//If we find the vertex already in the list re-use the index
//If not we create a new vertex and index
if (fnd != vertexIndices.end()){
indices.push_back(fnd->second);
}
else {
std::array<unsigned int, 3> vertex = captureVertex(v);
//Pack the position, normal and uv into the vertex data, note that obj data is
//1-indexed so we subtract 1
vertexData.push_back(tmpPos[vertex[0] - 1]);
vertexData.push_back(tmpNorm[vertex[2] - 1]);
vertexData.push_back(glm::vec3(tmpUv[vertex[1] - 1], 0));
//Store the new index, also subract 1 b/c size 1 => idx 0
//and divide by 3 b/c there are 3 components per vertex
indices.push_back((vertexData.size() - 1) / 3);
vertexIndices[v] = indices.back();
}
}
}
}
nElems = indices.size();
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, vertexData.size() * sizeof(glm::vec3), &vertexData[0], GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(GLushort), &indices[0], GL_STATIC_DRAW);
return true;
}
glm::vec2 util::captureVec2(const std::string &str){
glm::vec2 vec;
sscanf(str.c_str(), "%*s %f %f", &vec.x, &vec.y);
return vec;
}
glm::vec3 util::captureVec3(const std::string &str){
glm::vec3 vec;
sscanf(str.c_str(), "%*s %f %f %f", &vec.x, &vec.y, &vec.z);
return vec;
}
std::array<std::string, 3> util::captureFaces(const std::string &str){
std::array<std::string, 3> faces;
//There's face information between each space in the string, and 3 faces total
size_t prev = str.find(" ", 0);
size_t next = prev;
for (std::string &face : faces){
next = str.find(" ", prev + 1);
face = str.substr(prev + 1, next - prev - 1);
prev = next;
}
return faces;
}
std::array<unsigned int, 3> util::captureVertex(const std::string &str){
std::array<unsigned int, 3> vertex;
sscanf(str.c_str(), "%u/%u/%u", &vertex[0], &vertex[1], &vertex[2]);
return vertex;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <ctime>
#include <fstream>
#include <Windows.h>
#include "..\include\Game.h"
#include "..\include\Common.h"
#include "..\include\PlayerTypes\PlayerTypes.h"
#include "..\include\EnemyTypes\EnemyTypes.h"
using namespace std;
using namespace Common;
void Game::MainMenu(){
// Main menu. Loops until you start
// a game or quit.
for (int choice=0; choice!=3;){
ClearScreen();
cout << "========== TURN-BASED FIGHTING GAME ==========" << endl << endl
<< "1) Start Game" << endl
<< "2) How to play" << endl
<< "3) Quit" << endl << endl << "> ";
cin >> choice;
switch(choice){
case 1:
StartGame();
break;
case 2:
HowToPlay();
break;
// There's no 'case 3' because it breaks
// the loop already.
}
}
}
string Game::InitializePlayerName() {
ClearScreen();
string name;
cout << "What is your name?"
<< endl << endl
<< "> ";
cin >> name; // Change to full name
return name;
}
int Game::InitializePlayerClass() {
// Initializes the player's class through user choice.
ClearScreen();
int player_class = 0;
cout << endl
<< "Which class do you want to play as?" << endl
<< "1) Warrior (high damage, low healing capabilities)" << endl
<< "2) Rogue (moderate damage, moderate healing capabilities)" << endl
<< "3) Healer (low damage, high healing capabilities)" << endl
<< "4) Debugger (INFINITE DAMAGE!!!!)" << endl
<< "5) Saitama (self-explanatory)" << endl
<< endl << endl
<< "> ";
cin >> player_class;
SetPlayerClass(player_class);
return player_class;
}
void Game::SetPlayerClass(int player_class) {
// Sets the Player class according to player code given.
switch (player_class) {
case 1:
// Player's class is a warrior.
_Player = new Warrior;
break;
case 2:
// Player's class is a rogue.
_Player = new Rogue;
break;
case 3:
// Player's class is a healer.
_Player = new Healer;
break;
case 4:
// Player's class is a debugger.
// Used to easily defeat enemies. Only for development purposes.
_Player = new Debugger;
break;
case 5:
// You are Saitama.
// Do I have to explain??
_Player = new Saitama;
break;
default:
// If input does not equal any of the cases, the default class is a warrior.
_Player = new Warrior;
break;
}
}
void Game::SetPlayerData(){
/* Data initialized in order of:
* class code
* name
* level
* experience
* health
* arrows
* bombs
* potions
* whetstones
* weaponstrength
* coins
*/
ifstream ReadData;
ReadData.open("data.txt");
// Runs if user has never played the game before or data is not found.
if (!ReadData) {
ReadData.close();
ofstream WriteData;
WriteData.open("data.txt");
WriteData << InitializePlayerClass() << endl
<< InitializePlayerName() << endl
<< 1 << endl
<< 0 << endl
<< 100 << endl
<< 10 << endl
<< 1 << endl
<< 1 << endl
<< 1 << endl
<< 100 << endl
<< 0;
WriteData.close();
}
else {
// Initializes player type from class code given in data.txt
int player_class;
ReadData >> player_class;
SetPlayerClass(player_class);
ReadData.close();
}
}
void Game::SetEnemy(){
// Generates a random integer to determine class of the enemy.
// The abstract class Enemy is morphed with one of its child classes.
int selector = rand()%4;
switch(selector){
case 0:
// Enemy is a crab.
_Enemy = new Crab;
break;
case 1:
// Enemy is a giant crab.
_Enemy = new GiantCrab;
break;
case 2:
// Enemy is a squid.
_Enemy = new Squid;
break;
case 3:
// Enemy is a giant squid.
_Enemy = new GiantSquid;
break;
default:
// If the above cases do not match the selector for any reason,
// the enemy defaults on the crab class.
_Enemy = new Crab;
break;
}
// Simply prints that the enemy's class was encountered.
ColourPrint(_Enemy->GetName(), DARK_GREY);
cout << " encountered!" << endl << endl;
Sleep(SLEEP_MS);
}
bool Game::PlayAgain(){
// Returns a bool value to determine if the player wants to play again.
char choice;
cout << "Keep going? (y/n)" << endl << endl;
choice = (char)input();
// Returns true if the player says yes (Y, y, 1).
if (choice == 'y' || choice == 'Y' || choice == '1') return true;
// Returns false otherwise, regardless of choice=='n'.
return false;
}
void Game::Intermission(){
// Saves game in case player unexpectedly quits (uses X instead of
// in-game quit.
_Player->SaveGame();
// Loops until the player starts another battle or they quit (IsPlaying=false).
for (int choice=0; IsPlaying;){
ClearScreen();
cout << "*--------- Intermission ----------* " << endl << endl;
_Player->DisplayInventory();
cout << "1) Start battle" << endl;
cout << "2) Store" << endl;
cout << "3) Gamble" << endl;
cout << "4) Use Item" << endl;
cout << "5) Quit" << endl << endl;
choice = input();
switch(choice){
case 1:
// Returns to StartGame()'s loop, calling Battle().
return;
case 2:
// Goes to the store where the player can buy items.
/// Currently in working progress.
_Store.StoreFront(_Player);
break;
case 3:
// Goes to the gambling arena.
// _Player is passed in to add items won to the player inventory.
_Gambling.Gamble(_Player);
break;
case 4:
_Player->UseItem();
_Player->SaveGame();
break;
case 5:
// Breaks the loop in StartGame(), going back to MainMenu().
IsPlaying=false;
break;
}
}
}
void Game::StartGame(){
// Starts the game by initializing values for a new game.
// Seeds the random number generator for pseudo-random numbers.
srand((unsigned int)time(NULL));
IsPlaying=true;
// SetPlayerData() initializes the variables in this end.
ClearScreen();
SetPlayerData();
// This initializes the variables on the Player end.
ClearScreen();
_Player->SetPlayerData();
// Loops while the game is still playing.
// Alternates between battles and intermission (gambling, store, et)
while(IsPlaying){
Intermission();
if (!IsPlaying)
break;
Battle();
}
// Saves the player's data to an external file before quitting.
_Player->SaveGame();
}
void Game::Battle(){
ClearScreen();
// Uses random integers to determine class of the enemy.
SetEnemy();
// Loops the actual battle while playing.
while(IsPlaying){
ClearScreen();
// Displays the name and health bar of the player and enemy.
// The Enemy* argument is to display the enemy's
// name. Explained more in _Player->DisplayHealthBar().
_Player->DisplayHUD(_Enemy);
_Enemy->DisplayHUD();
// Player's turn to attack Enemy.
_Enemy->TakeDamage(_Player->Attack());
// Pauses console and ignores user input for SLEEP_MS milliseconds.
Sleep(SLEEP_MS);
// Leaves battle if player chooses to.
if (!IsPlaying){
IsPlaying = true;
return;
}
// Executes when the enemy's health is 0 or below.
if (_Enemy->IsDead()){
// Adds points to player's experience.
_Player->AddExperience(_Enemy->ReturnExperience());
// Adds drops to player's inventory from defeated enemy.
_Player->AddToInventory(_Enemy->GetDrops());
// Replenishes player's health for the next round.
_Player->ReplenishHealth();
// If player wants to battle again, it breaks the loop and uses tail recursion to play again.
if (PlayAgain()) break;
// Returns to StartGame()'s loop, and executes Intermission().
return;
}
// Enemy's turn to attack player.
_Player->TakeDamage(_Enemy->Attack());
Sleep(SLEEP_MS);
// Executes when player's health is 0 or below.
if (_Player->IsDead()){
// Player loses the amount of experience points gained when you defeat the enemy.
_Player->LoseExperience(_Enemy->ReturnExperience());
// Replenishes player's health for the next round.
_Player->ReplenishHealth();
if (PlayAgain()) break;
return;
}
}
Battle();
}
void Game::HowToPlay() {
for (int choice = 0; choice != 1;) {
ClearScreen();
cout << "============== HOW TO PLAY ==============" << endl << endl
<< "Turn is a turn-based RPG game." << endl
<< "Create your character and start playing." << endl
<< "For playing you have to choose what to do by typing" << endl
<< "the corresponding number." << endl
<< "You can perform actions and use items." << endl << endl
<< "-- Actions --" << endl
<< "Attack: Regular attack" << endl
<< "Risk Attack: Attack deals more damage, but with a chance of missing" << endl
<< "Heal: Restore an amount of your HP" << endl
<< "Flee: Run away from battle" << endl << endl
<< "-- Items --" << endl
<< "Bombs: Deals 50HP to your opponent with no chance of missing" << endl
<< "Arrows: Deals 10-15HP to your opponent with no chance of missing" << endl
<< "Potion: Replenishes your HP to 100" << endl
<< "Whetstone: Restores your weapon's sharpness." << endl << endl
<< "Good luck and have fun!" << endl << endl
<< "1) Quit" << endl << endl << "> ";
cin >> choice;
switch (choice) {
case 1:
MainMenu();
}
}
}
<commit_msg>Update Game.cpp<commit_after>#include <iostream>
#include <ctime>
#include <fstream>
#include <Windows.h>
#include "..\include\Game.h"
#include "..\include\Common.h"
#include "..\include\PlayerTypes\PlayerTypes.h"
#include "..\include\EnemyTypes\EnemyTypes.h"
using namespace std;
using namespace Common;
void Game::MainMenu(){
// Main menu. Loops until you start
// a game or quit.
for (int choice=0; choice!=3;){
ClearScreen();
cout << "========== TURN-BASED FIGHTING GAME ==========" << endl << endl
<< "1) Start Game" << endl
<< "2) How to play" << endl
<< "3) Quit" << endl << endl << "> ";
cin >> choice;
switch(choice){
case 1:
StartGame();
break;
case 2:
HowToPlay();
break;
// There's no 'case 3' because it breaks
// the loop already.
}
}
}
string Game::InitializePlayerName() {
ClearScreen();
string name;
cout << "What is your name?"
<< endl << endl
<< "> ";
cin >> name; // Change to full name
return name;
}
int Game::InitializePlayerClass() {
// Initializes the player's class through user choice.
ClearScreen();
int player_class = 0;
cout << endl
<< "Which class do you want to play as?" << endl
<< "1) Warrior (high damage, low healing capabilities)" << endl
<< "2) Rogue (moderate damage, moderate healing capabilities)" << endl
<< "3) Healer (low damage, high healing capabilities)" << endl
<< "4) Debugger (INFINITE DAMAGE!!!!)" << endl
<< "5) Saitama (self-explanatory)" << endl
<< endl << endl
<< "> ";
cin >> player_class;
SetPlayerClass(player_class);
return player_class;
}
void Game::SetPlayerClass(int player_class) {
// Sets the Player class according to player code given.
switch (player_class) {
case 1:
// Player's class is a warrior.
_Player = new Warrior;
break;
case 2:
// Player's class is a rogue.
_Player = new Rogue;
break;
case 3:
// Player's class is a healer.
_Player = new Healer;
break;
case 4:
// Player's class is a debugger.
// Used to easily defeat enemies. Only for development purposes.
_Player = new Debugger;
break;
case 5:
// You are Saitama.
// Do I have to explain??
_Player = new Saitama;
break;
default:
// If input does not equal any of the cases, the default class is a warrior.
_Player = new Warrior;
break;
}
}
void Game::SetPlayerData(){
/* Data initialized in order of:
* class code
* name
* level
* experience
* health
* arrows
* bombs
* potions
* whetstones
* weaponstrength
* coins
*/
ifstream ReadData;
ReadData.open("data.txt");
// Runs if user has never played the game before or data is not found.
if (!ReadData) {
ReadData.close();
ofstream WriteData;
WriteData.open("data.txt");
WriteData << InitializePlayerClass() << endl
<< InitializePlayerName() << endl
<< 1 << endl
<< 0 << endl
<< 100 << endl
<< 10 << endl
<< 1 << endl
<< 1 << endl
<< 1 << endl
<< 100 << endl
<< 0;
WriteData.close();
}
else {
// Initializes player type from class code given in data.txt
int player_class;
ReadData >> player_class;
SetPlayerClass(player_class);
ReadData.close();
}
}
void Game::SetEnemy(){
// Generates a random integer to determine class of the enemy.
// The abstract class Enemy is morphed with one of its child classes.
int selector = rand()%4;
switch(selector){
case 0:
// Enemy is a crab.
_Enemy = new Crab;
break;
case 1:
// Enemy is a giant crab.
_Enemy = new GiantCrab;
break;
case 2:
// Enemy is a squid.
_Enemy = new Squid;
break;
case 3:
// Enemy is a giant squid.
_Enemy = new GiantSquid;
break;
default:
// If the above cases do not match the selector for any reason,
// the enemy defaults on the crab class.
_Enemy = new Crab;
break;
}
// Simply prints that the enemy's class was encountered.
ColourPrint(_Enemy->GetName(), DARK_GREY);
cout << " encountered!" << endl << endl;
Sleep(SLEEP_MS);
}
bool Game::PlayAgain(){
// Returns a bool value to determine if the player wants to play again.
char choice;
cout << "Keep going? (y/n)" << endl << endl;
choice = (char)input();
// Returns true if the player says yes (Y, y, 1).
if (choice == 'y' || choice == 'Y' || choice == '1') return true;
// Returns false otherwise, regardless of choice=='n'.
return false;
}
void Game::Intermission(){
// Saves game in case player unexpectedly quits (uses X instead of
// in-game quit.
_Player->SaveGame();
// Loops until the player starts another battle or they quit (IsPlaying=false).
for (int choice=0; IsPlaying;){
ClearScreen();
cout << "*--------- Intermission ----------* " << endl << endl;
_Player->DisplayInventory();
cout << "1) Start battle" << endl;
cout << "2) Store" << endl;
cout << "3) Gamble" << endl;
cout << "4) Use Item" << endl;
cout << "5) Quit" << endl << endl;
choice = input();
switch(choice){
case 1:
// Returns to StartGame()'s loop, calling Battle().
return;
case 2:
// Goes to the store where the player can buy items.
/// Currently in working progress.
_Store.StoreFront(_Player);
break;
case 3:
// Goes to the gambling arena.
// _Player is passed in to add items won to the player inventory.
_Gambling.Gamble(_Player);
break;
case 4:
_Player->UseItem();
_Player->SaveGame();
break;
case 5:
// Breaks the loop in StartGame(), going back to MainMenu().
IsPlaying=false;
break;
}
}
}
void Game::StartGame(){
// Starts the game by initializing values for a new game.
// Seeds the random number generator for pseudo-random numbers.
srand((unsigned int)time(NULL));
IsPlaying=true;
// SetPlayerData() initializes the variables in this end.
ClearScreen();
SetPlayerData();
// This initializes the variables on the Player end.
ClearScreen();
_Player->SetPlayerData();
// Loops while the game is still playing.
// Alternates between battles and intermission (gambling, store, et)
while(IsPlaying){
Intermission();
if (!IsPlaying)
break;
Battle();
}
// Saves the player's data to an external file before quitting.
_Player->SaveGame();
}
void Game::Battle(){
ClearScreen();
// Uses random integers to determine class of the enemy.
SetEnemy();
// Loops the actual battle while playing.
while(IsPlaying){
ClearScreen();
// Displays the name and health bar of the player and enemy.
// The Enemy* argument is to display the enemy's
// name. Explained more in _Player->DisplayHealthBar().
_Player->DisplayHUD(_Enemy);
_Enemy->DisplayHUD();
// Player's turn to attack Enemy.
_Enemy->TakeDamage(_Player->Attack());
// Pauses console and ignores user input for SLEEP_MS milliseconds.
Sleep(SLEEP_MS);
// Leaves battle if player chooses to.
if (!IsPlaying){
IsPlaying = true;
return;
}
// Executes when the enemy's health is 0 or below.
if (_Enemy->IsDead()){
// Adds points to player's experience.
_Player->AddExperience(_Enemy->ReturnExperience());
// Adds drops to player's inventory from defeated enemy.
_Player->AddToInventory(_Enemy->GetDrops());
// Replenishes player's health for the next round.
_Player->ReplenishHealth();
// If player wants to battle again, it breaks the loop and uses tail recursion to play again.
if (PlayAgain()) break;
// Returns to StartGame()'s loop, and executes Intermission().
return;
}
// Enemy's turn to attack player.
_Player->TakeDamage(_Enemy->Attack());
Sleep(SLEEP_MS);
// Executes when player's health is 0 or below.
if (_Player->IsDead()){
// Player loses the amount of experience points gained when you defeat the enemy.
_Player->LoseExperience(_Enemy->ReturnExperience());
// Replenishes player's health for the next round.
_Player->ReplenishHealth();
if (PlayAgain()) break;
return;
}
}
Battle();
}
void Game::HowToPlay() {
for (int choice = 0; choice != 1;) {
ClearScreen();
cout << "============== HOW TO PLAY ==============" << endl << endl
<< "Turn is a turn-based RPG game." << endl
<< "Create your character and start playing." << endl
<< "For playing you have to choose what to do by typing" << endl
<< "the corresponding number." << endl
<< "You can perform actions and use items." << endl << endl
<< "-- Actions --" << endl
<< "Attack: Regular attack" << endl
<< "Risk Attack: Attack deals more damage, but with a chance of missing" << endl
<< "Heal: Restore an amount of your HP" << endl
<< "Flee: Run away from battle" << endl << endl
<< "-- Items --" << endl
<< "Bombs: Deals 50HP to your opponent with no chance of missing" << endl
<< "Arrows: Deals 10-15HP to your opponent with no chance of missing" << endl
<< "Potion: Replenishes your HP to 100" << endl
<< "Whetstone: Restores your weapon's sharpness." << endl << endl
<< "Good luck and have fun!" << endl << endl
<< "1) Quit" << endl << endl << "> ";
cin >> choice;
switch (choice) {
case 1:
MainMenu();
}
}
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <ctime>
#include <fstream>
#include <Windows.h>
#include <string>
#include "..\include\Game.h"
#include "..\include\Common.h"
#include "..\include\PlayerTypes\PlayerTypes.h"
#include "..\include\EnemyTypes\EnemyTypes.h"
using namespace std;
using namespace Common;
// To avoid conflict with numeric_limits<streamsize>::max used in Game::GetChoice()
#ifdef max
#undef max
#endif
void Game::MainMenu(){
// Main menu. Loops until you start
// a game or quit.
for (int choice=0; choice!=3;){
choice = GetChoice(MenuType::eMain);
switch(choice){
case 1:
StartGame();
break;
case 2:
HowToPlay();
break;
case 3:
break;
}
}
}
string Game::InitializePlayerName() {
ClearScreen();
string name;
cout << "What is your name?"
<< endl << endl
<< "> ";
cin.ignore();
getline(cin,name); // Change to full name
return name;
}
int Game::InitializePlayerClass() {
// Initializes the player's class through user choice.
int player_class = 0;
player_class = GetChoice(MenuType::ePlayerClass);
SetPlayerClass(player_class);
return player_class;
}
void Game::SetPlayerClass(int player_class) {
// Sets the Player class according to player code given.
switch (player_class) {
case 1:
// Player's class is a warrior.
_Player = new Warrior;
break;
case 2:
// Player's class is a rogue.
_Player = new Rogue;
break;
case 3:
// Player's class is a healer.
_Player = new Healer;
break;
case 4:
// Player's class is a debugger.
// Used to easily defeat enemies. Only for development purposes.
_Player = new Debugger;
break;
case 5:
// You are Saitama.
// Do I have to explain??
_Player = new Saitama;
break;
default:
// If input does not equal any of the cases, the default class is a warrior.
_Player = new Warrior;
break;
}
}
void Game::SetPlayerData(){
/* Data initialized in order of:
* class code
* name
* level
* experience
* health
* arrows
* bombs
* potions
* whetstones
* weaponstrength
* coins
*/
ifstream ReadData;
ReadData.open("data.txt");
// Runs if user has never played the game before or data is not found.
if (!ReadData) {
ReadData.close();
ofstream WriteData;
WriteData.open("data.txt");
WriteData << InitializePlayerClass() << endl
<< InitializePlayerName() << endl
<< 1 << endl
<< 0 << endl
<< 100 << endl
<< 10 << endl
<< 1 << endl
<< 1 << endl
<< 1 << endl
<< 100 << endl
<< 0;
WriteData.close();
}
else {
// Initializes player type from class code given in data.txt
int player_class;
ReadData >> player_class;
SetPlayerClass(player_class);
ReadData.close();
}
}
void Game::SetEnemy(){
// Generates a random integer to determine class of the enemy.
// The abstract class Enemy is morphed with one of its child classes.
int selector = rand()%5;
switch(selector){
case 0:
// Enemy is a crab.
_Enemy = new Crab;
break;
case 1:
// Enemy is a giant crab.
_Enemy = new GiantCrab;
break;
case 2:
// Enemy is a squid.
_Enemy = new Squid;
break;
case 3:
// Enemy is a giant squid.
_Enemy = new GiantSquid;
break;
case 4:
// Enemy is a Lich
_Enemy = new Lich;
break;
default:
// If the above cases do not match the selector for any reason,
// the enemy defaults on the crab class.
_Enemy = new Crab;
break;
}
// Simply prints that the enemy's class was encountered.
ColourPrint(_Enemy->GetName(), DARK_GREY);
cout << " encountered!" << endl << endl;
Sleep(SLEEP_MS);
}
bool Game::PlayAgain(){
// Returns a bool value to determine if the player wants to play again.
char choice;
cout << "Keep going? (y/n)" << endl << endl;
choice = (char)input();
// Returns true if the player says yes (Y, y, 1).
if (choice == 'y' || choice == 'Y' || choice == '1') return true;
// Returns false otherwise, regardless of choice=='n'.
return false;
}
void Game::Intermission(){
// Saves game in case player unexpectedly quits (uses X instead of
// in-game quit.
_Player->SaveGame();
// Loops until the player starts another battle or they quit (IsPlaying=false).
for (int choice=0; IsPlaying;){
ClearScreen();
cout << "*--------- Intermission ----------* " << endl << endl;
_Player->DisplayInventory();
cout << "1) Start battle" << endl;
cout << "2) Store" << endl;
cout << "3) Gamble" << endl;
cout << "4) Use Item" << endl;
cout << "5) Quit" << endl << endl;
choice = input();
switch(choice){
case 1:
// Returns to StartGame()'s loop, calling Battle().
return;
case 2:
// Goes to the store where the player can buy items.
/// Currently in working progress.
_Store.StoreFront(_Player);
break;
case 3:
// Goes to the gambling arena.
// _Player is passed in to add items won to the player inventory.
_Gambling.Gamble(_Player);
break;
case 4:
_Player->UseItem();
_Player->SaveGame();
break;
case 5:
// Breaks the loop in StartGame(), going back to MainMenu().
IsPlaying=false;
break;
}
}
}
void Game::StartGame(){
// Starts the game by initializing values for a new game.
// Seeds the random number generator for pseudo-random numbers.
srand((unsigned int)time(NULL));
IsPlaying=true;
// SetPlayerData() initializes the variables in this end.
ClearScreen();
SetPlayerData();
// This initializes the variables on the Player end.
ClearScreen();
_Player->SetPlayerData();
// Loops while the game is still playing.
// Alternates between battles and intermission (gambling, store, et)
while(IsPlaying){
Intermission();
if (!IsPlaying)
break;
Battle();
}
// Saves the player's data to an external file before quitting.
_Player->SaveGame();
}
void Game::Battle(){
ClearScreen();
// Uses random integers to determine class of the enemy.
SetEnemy();
// Loops the actual battle while playing.
while(IsPlaying){
ClearScreen();
// Displays the name and health bar of the player and enemy.
// The Enemy* argument is to display the enemy's
// name. Explained more in _Player->DisplayHealthBar().
_Player->DisplayHUD(_Enemy);
_Enemy->DisplayHUD();
// Player's turn to attack Enemy.
_Enemy->TakeDamage(_Player->Attack());
// Pauses console and ignores user input for SLEEP_MS milliseconds.
Sleep(SLEEP_MS);
// Leaves battle if player chooses to.
if (!IsPlaying){
IsPlaying = true;
return;
}
// Executes when the enemy's health is 0 or below.
if (_Enemy->IsDead()){
// Adds drops to player's inventory from defeated enemy.
_Player->AddToInventory(_Enemy->GetDrops());
// Adds points to player's experience.
_Player->AddExperience(_Enemy->ReturnExperience());
// Replenishes player's health for the next round.
_Player->ReplenishHealth();
// If player wants to battle again, it breaks the loop and uses tail recursion to play again.
if (PlayAgain()) break;
// Returns to StartGame()'s loop, and executes Intermission().
return;
}
// Enemy's turn to attack player.
_Player->TakeDamage(_Enemy->Attack());
Sleep(SLEEP_MS);
// Executes when player's health is 0 or below.
if (_Player->IsDead()){
// Player loses the amount of experience points gained when you defeat the enemy.
_Player->LoseExperience(_Enemy->ReturnExperience());
// Replenishes player's health for the next round.
_Player->ReplenishHealth();
if (PlayAgain()) break;
return;
}
}
Battle();
}
void Game::HowToPlay() {
GetChoice(MenuType::eHowToPlay);
}
int Game::GetChoice(MenuType menuType)
{
DisplayMenu(menuType);
int choice = -1;
while (!(cin >> choice)) {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Invalid input. Please try again.";
Sleep(SLEEP_MS);
DisplayMenu(menuType);
}
return choice;
}
void Game::DisplayMenu(MenuType menuType)
{
ClearScreen();
switch (menuType)
{
case Game::eMain:
cout << "========== TURN-BASED FIGHTING GAME ==========" << endl << endl
<< "1) Start Game" << endl
<< "2) How to play" << endl
<< "3) Exit" << endl << endl << "> ";
break;
case Game::ePlayerClass:
cout << endl
<< "Which class do you want to play as?" << endl
<< "1) Warrior (high damage, low healing capabilities)" << endl
<< "2) Rogue (moderate damage, moderate healing capabilities)" << endl
<< "3) Healer (low damage, high healing capabilities)" << endl
<< "4) Debugger (INFINITE DAMAGE!!!!)" << endl
<< "5) Saitama (self-explanatory)" << endl
<< endl << endl
<< "> ";
break;
case Game::eHowToPlay:
cout << "============== HOW TO PLAY ==============" << endl << endl
<< "Turn is a turn-based RPG game." << endl
<< "Create your character and start playing." << endl
<< "For playing you have to choose what to do by typing" << endl
<< "the corresponding number." << endl
<< "You can perform actions and use items." << endl << endl
<< "-- Actions --" << endl
<< "Attack: Regular attack" << endl
<< "Risk Attack: Attack deals more damage, but with a chance of missing" << endl
<< "Heal: Restore an amount of your HP" << endl
<< "Flee: Run away from battle" << endl << endl
<< "-- Items --" << endl
<< "Bombs: Deals 50HP to your opponent with no chance of missing" << endl
<< "Arrows: Deals 10-15HP to your opponent with no chance of missing" << endl
<< "Potion: Replenishes your HP to 100" << endl
<< "Whetstone: Restores your weapon's sharpness." << endl << endl
<< "Good luck and have fun!" << endl << endl
<< "1) Quit" << endl << endl << "> ";
break;
default:
break;
}
}<commit_msg>Update Game.cpp<commit_after>#include <iostream>
#include <ctime>
#include <fstream>
#include <Windows.h>
#include <string>
#include "..\include\Game.h"
#include "..\include\Common.h"
#include "..\include\PlayerTypes\PlayerTypes.h"
#include "..\include\EnemyTypes\EnemyTypes.h"
using namespace std;
using namespace Common;
// To avoid conflict with numeric_limits<streamsize>::max used in Game::GetChoice()
#ifdef max
#undef max
#endif
void Game::MainMenu(){
// Main menu. Loops until you start
// a game or quit.
for (int choice=0; choice!=3;){
choice = GetChoice(MenuType::eMain);
switch(choice){
case 1:
StartGame();
break;
case 2:
HowToPlay();
break;
case 3:
break;
}
}
}
string Game::InitializePlayerName() {
ClearScreen();
string name;
cout << "What is your name?"
<< endl << endl
<< "> ";
cin.ignore();
getline(cin,name); // Change to full name
return name;
}
int Game::InitializePlayerClass() {
// Initializes the player's class through user choice.
int player_class = 0;
player_class = GetChoice(MenuType::ePlayerClass);
SetPlayerClass(player_class);
return player_class;
}
void Game::SetPlayerClass(int player_class) {
// Sets the Player class according to player code given.
switch (player_class) {
case 1:
// Player's class is a warrior.
_Player = new Warrior;
break;
case 2:
// Player's class is a rogue.
_Player = new Rogue;
break;
case 3:
// Player's class is a healer.
_Player = new Healer;
break;
case 4:
// Player's class is a debugger.
// Used to easily defeat enemies. Only for development purposes.
_Player = new Debugger;
break;
case 5:
// You are Saitama.
// Do I have to explain??
_Player = new Saitama;
break;
default:
// If input does not equal any of the cases, the default class is a warrior.
_Player = new Warrior;
break;
}
}
void Game::SetPlayerData(){
/* Data initialized in order of:
* class code
* name
* level
* experience
* health
* arrows
* bombs
* potions
* whetstones
* weaponstrength
* coins
*/
ifstream ReadData;
ReadData.open("data.txt");
// Runs if user has never played the game before or data is not found.
if (!ReadData) {
ReadData.close();
ofstream WriteData;
WriteData.open("data.txt");
WriteData << InitializePlayerClass() << endl
<< InitializePlayerName() << endl
<< 1 << endl
<< 0 << endl
<< 100 << endl
<< 10 << endl
<< 1 << endl
<< 1 << endl
<< 1 << endl
<< 100 << endl
<< 0;
WriteData.close();
}
else {
// Initializes player type from class code given in data.txt
int player_class;
ReadData >> player_class;
SetPlayerClass(player_class);
ReadData.close();
}
}
void Game::SetEnemy(){
// Generates a random integer to determine class of the enemy.
// The abstract class Enemy is morphed with one of its child classes.
int selector = rand()%6;
switch(selector){
case 0:
// Enemy is a crab.
_Enemy = new Crab;
break;
case 1:
// Enemy is a giant crab.
_Enemy = new GiantCrab;
break;
case 2:
// Enemy is a squid.
_Enemy = new Squid;
break;
case 3:
// Enemy is a giant squid.
_Enemy = new GiantSquid;
break;
case 4:
// Enemy is a Lich
_Enemy = new Lich;
break;
case 5:
// Enemy is a Putnafer
_Enemy = new Putnafer;
break;
default:
// If the above cases do not match the selector for any reason,
// the enemy defaults on the crab class.
_Enemy = new Crab;
break;
}
// Simply prints that the enemy's class was encountered.
ColourPrint(_Enemy->GetName(), DARK_GREY);
cout << " encountered!" << endl << endl;
Sleep(SLEEP_MS);
}
bool Game::PlayAgain(){
// Returns a bool value to determine if the player wants to play again.
char choice;
cout << "Keep going? (y/n)" << endl << endl;
choice = (char)input();
// Returns true if the player says yes (Y, y, 1).
if (choice == 'y' || choice == 'Y' || choice == '1') return true;
// Returns false otherwise, regardless of choice=='n'.
return false;
}
void Game::Intermission(){
// Saves game in case player unexpectedly quits (uses X instead of
// in-game quit.
_Player->SaveGame();
// Loops until the player starts another battle or they quit (IsPlaying=false).
for (int choice=0; IsPlaying;){
ClearScreen();
cout << "*--------- Intermission ----------* " << endl << endl;
_Player->DisplayInventory();
cout << "1) Start battle" << endl;
cout << "2) Store" << endl;
cout << "3) Gamble" << endl;
cout << "4) Use Item" << endl;
cout << "5) Quit" << endl << endl;
choice = input();
switch(choice){
case 1:
// Returns to StartGame()'s loop, calling Battle().
return;
case 2:
// Goes to the store where the player can buy items.
/// Currently in working progress.
_Store.StoreFront(_Player);
break;
case 3:
// Goes to the gambling arena.
// _Player is passed in to add items won to the player inventory.
_Gambling.Gamble(_Player);
break;
case 4:
_Player->UseItem();
_Player->SaveGame();
break;
case 5:
// Breaks the loop in StartGame(), going back to MainMenu().
IsPlaying=false;
break;
}
}
}
void Game::StartGame(){
// Starts the game by initializing values for a new game.
// Seeds the random number generator for pseudo-random numbers.
srand((unsigned int)time(NULL));
IsPlaying=true;
// SetPlayerData() initializes the variables in this end.
ClearScreen();
SetPlayerData();
// This initializes the variables on the Player end.
ClearScreen();
_Player->SetPlayerData();
// Loops while the game is still playing.
// Alternates between battles and intermission (gambling, store, et)
while(IsPlaying){
Intermission();
if (!IsPlaying)
break;
Battle();
}
// Saves the player's data to an external file before quitting.
_Player->SaveGame();
}
void Game::Battle(){
ClearScreen();
// Uses random integers to determine class of the enemy.
SetEnemy();
// Loops the actual battle while playing.
while(IsPlaying){
ClearScreen();
// Displays the name and health bar of the player and enemy.
// The Enemy* argument is to display the enemy's
// name. Explained more in _Player->DisplayHealthBar().
_Player->DisplayHUD(_Enemy);
_Enemy->DisplayHUD();
// Player's turn to attack Enemy.
_Enemy->TakeDamage(_Player->Attack());
// Pauses console and ignores user input for SLEEP_MS milliseconds.
Sleep(SLEEP_MS);
// Leaves battle if player chooses to.
if (!IsPlaying){
IsPlaying = true;
return;
}
// Executes when the enemy's health is 0 or below.
if (_Enemy->IsDead()){
// Adds drops to player's inventory from defeated enemy.
_Player->AddToInventory(_Enemy->GetDrops());
// Adds points to player's experience.
_Player->AddExperience(_Enemy->ReturnExperience());
// Replenishes player's health for the next round.
_Player->ReplenishHealth();
// If player wants to battle again, it breaks the loop and uses tail recursion to play again.
if (PlayAgain()) break;
// Returns to StartGame()'s loop, and executes Intermission().
return;
}
// Enemy's turn to attack player.
_Player->TakeDamage(_Enemy->Attack());
Sleep(SLEEP_MS);
// Executes when player's health is 0 or below.
if (_Player->IsDead()){
// Player loses the amount of experience points gained when you defeat the enemy.
_Player->LoseExperience(_Enemy->ReturnExperience());
// Replenishes player's health for the next round.
_Player->ReplenishHealth();
if (PlayAgain()) break;
return;
}
}
Battle();
}
void Game::HowToPlay() {
GetChoice(MenuType::eHowToPlay);
}
int Game::GetChoice(MenuType menuType)
{
DisplayMenu(menuType);
int choice = -1;
while (!(cin >> choice)) {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Invalid input. Please try again.";
Sleep(SLEEP_MS);
DisplayMenu(menuType);
}
return choice;
}
void Game::DisplayMenu(MenuType menuType)
{
ClearScreen();
switch (menuType)
{
case Game::eMain:
cout << "========== TURN-BASED FIGHTING GAME ==========" << endl << endl
<< "1) Start Game" << endl
<< "2) How to play" << endl
<< "3) Exit" << endl << endl << "> ";
break;
case Game::ePlayerClass:
cout << endl
<< "Which class do you want to play as?" << endl
<< "1) Warrior (high damage, low healing capabilities)" << endl
<< "2) Rogue (moderate damage, moderate healing capabilities)" << endl
<< "3) Healer (low damage, high healing capabilities)" << endl
<< "4) Debugger (INFINITE DAMAGE!!!!)" << endl
<< "5) Saitama (self-explanatory)" << endl
<< endl << endl
<< "> ";
break;
case Game::eHowToPlay:
cout << "============== HOW TO PLAY ==============" << endl << endl
<< "Turn is a turn-based RPG game." << endl
<< "Create your character and start playing." << endl
<< "For playing you have to choose what to do by typing" << endl
<< "the corresponding number." << endl
<< "You can perform actions and use items." << endl << endl
<< "-- Actions --" << endl
<< "Attack: Regular attack" << endl
<< "Risk Attack: Attack deals more damage, but with a chance of missing" << endl
<< "Heal: Restore an amount of your HP" << endl
<< "Flee: Run away from battle" << endl << endl
<< "-- Items --" << endl
<< "Bombs: Deals 50HP to your opponent with no chance of missing" << endl
<< "Arrows: Deals 10-15HP to your opponent with no chance of missing" << endl
<< "Potion: Replenishes your HP to 100" << endl
<< "Whetstone: Restores your weapon's sharpness." << endl << endl
<< "Good luck and have fun!" << endl << endl
<< "1) Quit" << endl << endl << "> ";
break;
default:
break;
}
}
<|endoftext|> |
<commit_before>// This file is part of the dune-stuff project:
// https://github.com/wwu-numerik/dune-stuff/
// Copyright holders: Rene Milk, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
//
// Contributors: Tobias Leibner
#ifndef DUNE_STUFF_LA_CONTAINER_CONTAINER_INTERFACE_HH
#define DUNE_STUFF_LA_CONTAINER_CONTAINER_INTERFACE_HH
#include <cmath>
#include <limits>
#include <type_traits>
#include <boost/numeric/conversion/cast.hpp>
#include <dune/stuff/common/crtp.hh>
#include <dune/stuff/common/exceptions.hh>
#include <dune/stuff/common/type_utils.hh>
namespace Dune {
namespace Stuff {
namespace LA {
enum class ChooseBackend {
common_dense
, istl_sparse
, eigen_dense
, eigen_sparse
}; // enum class ChooseBackend
static constexpr ChooseBackend default_backend =
#if HAVE_EIGEN
ChooseBackend::eigen_sparse;
#elif HAVE_DUNE_ISTL
ChooseBackend::istl_sparse;
#else
ChooseBackend::common_dense;
#endif
static constexpr ChooseBackend default_sparse_backend =
#if HAVE_EIGEN
ChooseBackend::eigen_sparse;
#elif HAVE_DUNE_ISTL
ChooseBackend::istl_sparse;
#else
ChooseBackend::common_dense;
# error "There is no sparse LA backend available!"
#endif
static constexpr ChooseBackend default_dense_backend =
#if HAVE_EIGEN
ChooseBackend::eigen_dense;
#else
ChooseBackend::common_dense;
#endif
/**
* \brief Contains tags mostly needed for python bindings.
*/
namespace Tags {
class ContainerInterface {};
class ProvidesDataAccess {};
} // namespace Tags
namespace internal {
/**
* \brief Tries a boost::numeric_cast and throws an Exceptions::wrong_input_given on failure.
*
* This can be used in the ctor initializer list.
*/
template< class Out, class In >
static Out boost_numeric_cast(const In& in)
{
try {
return boost::numeric_cast< Out >(in);
} catch (boost::bad_numeric_cast& ee) {
DUNE_THROW(Exceptions::wrong_input_given,
"There was an error in boost converting '" << in << "' to '"
<< Common::Typename< Out >::value() << "': " << ee.what());
}
} // ... boost_numeric_cast(...)
} // namespace internal
template< class Traits >
class ProvidesBackend
: public CRTPInterface< ProvidesBackend< Traits >, Traits >
{
public:
typedef typename Traits::BackendType BackendType;
inline BackendType& backend()
{
CHECK_CRTP(this->as_imp().backend());
return this->as_imp().backend();
}
inline const BackendType& backend() const
{
CHECK_CRTP(this->as_imp().backend());
return this->as_imp().backend();
}
}; // class ProvidesBackend
/**
* \brief Interface for all containers (vectors and matrices).
*
* \note All derived classes are supposed to implement copy-on-write. This can be achieved by internally holding a
* shared_prt to the appropriate backend and by passing this shared_prt around on copy, move or assingment. Any
* class method that writes to the backend or exposes a reference to the backend is then required to make a deep
* copy of the backend, if it is not the sole owner of this resource. This can for instance be achieved by
* calling a private method:
\code
inline void ensure_uniqueness() const
{
if (!backend_.unique())
backend_ = std::make_shared< BackendType >(*backend_);
}
\endcode
*/
template< class Traits, class ScalarImp = typename Traits::ScalarType >
class ContainerInterface
: public Tags::ContainerInterface
, public CRTPInterface< ContainerInterface< Traits, ScalarImp >, Traits >
{
typedef CRTPInterface< ContainerInterface< Traits, ScalarImp >, Traits > CRTP;
static_assert(std::is_same< ScalarImp, typename Traits::ScalarType >::value, "");
public:
typedef ScalarImp ScalarType;
using typename CRTP::derived_type;
virtual ~ContainerInterface() {}
/// \name Have to be implemented by a derived class!
/// \{
/**
* \brief Creates a (deep) copy of the underlying resource
* \return A new container
*/
inline derived_type copy() const
{
CHECK_CRTP(this->as_imp().copy());
return this->as_imp().copy();
}
/**
* \brief BLAS SCAL operation (in-place sclar multiplication).
* \param alpha The scalar coefficient with which each element of the container is multiplied.
*/
inline void scal(const ScalarType& alpha)
{
CHECK_AND_CALL_CRTP(this->as_imp().scal(alpha));
}
/**
* \brief BLAS AXPY operation.
* \param alpha The scalar coefficient with which each element of the container is multiplied
* \param xx Container that is to be elementwise added.
*/
inline void axpy(const ScalarType& alpha, const derived_type& xx)
{
CHECK_AND_CALL_CRTP(this->as_imp().axpy(alpha, xx));
}
/**
* \brief Test for equal sizes.
* \param other Container the sizes of which this is to be compared to.
*/
inline bool has_equal_shape(const derived_type& other) const
{
CHECK_CRTP(this->as_imp().has_equal_shape(other));
return this->as_imp().has_equal_shape(other);
}
/// \}
/// \name Are provided by the interface for convenience!
/// \note Those marked as virtual may be implemented more efficiently in a derived class!
/// \{
static std::string type_this()
{
return Common::Typename< derived_type >::value();
}
virtual derived_type& operator*=(const ScalarType& alpha)
{
scal(alpha);
return this->as_imp(*this);
}
/// \}
}; // class ContainerInterface
namespace internal {
template< class C >
struct is_container_helper
{
DSC_has_typedef_initialize_once(Traits)
DSC_has_typedef_initialize_once(ScalarType)
static const bool is_candidate = DSC_has_typedef(Traits)< C >::value
&& DSC_has_typedef(ScalarType)< C >::value;
}; // class is_container_helper
} // namespace internal
template< class C, bool candidate = internal::is_container_helper< C >::is_candidate >
struct is_container
: public std::is_base_of< ContainerInterface< typename C::Traits, typename C::ScalarType >, C >
{};
template< class C >
struct is_container< C, false >
: public std::false_type
{};
template< class Traits >
class ProvidesConstContainer
: public CRTPInterface< ProvidesConstContainer< Traits >, Traits >
{
public:
typedef typename Traits::ContainerType ContainerType;
inline std::shared_ptr< const ContainerType > container() const
{
CHECK_CRTP(this->as_imp().container());
return this->as_imp().container();
}
}; // class ProvidesConstContainer
template< class Traits >
class ProvidesContainer
: public ProvidesConstContainer< Traits >
{
typedef ProvidesConstContainer< Traits > BaseType;
public:
typedef typename Traits::ContainerType ContainerType;
using BaseType::container;
inline std::shared_ptr< ContainerType > container()
{
CHECK_CRTP(this->as_imp().container());
return this->as_imp().container();
}
}; // class ProvidesContainer
template< class Traits >
class ProvidesDataAccess
: public CRTPInterface< ProvidesDataAccess< Traits >, Traits >
, public Tags::ProvidesDataAccess
{
public:
typedef typename Traits::ScalarType ScalarType;
inline ScalarType* data()
{
CHECK_CRTP(this->as_imp().data());
return this->as_imp().data();
}
}; // class ProvidesDataAccess
} // namespace LA
} // namespace Stuff
} // namespace Dune
#endif // #ifndef DUNE_STUFF_LA_CONTAINER_CONTAINER_INTERFACE_HH
<commit_msg>[la.container.container-interface] add RealType to Interface<commit_after>// This file is part of the dune-stuff project:
// https://github.com/wwu-numerik/dune-stuff/
// Copyright holders: Rene Milk, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
//
// Contributors: Tobias Leibner
#ifndef DUNE_STUFF_LA_CONTAINER_CONTAINER_INTERFACE_HH
#define DUNE_STUFF_LA_CONTAINER_CONTAINER_INTERFACE_HH
#include <cmath>
#include <limits>
#include <type_traits>
#include <boost/numeric/conversion/cast.hpp>
#include <dune/stuff/common/crtp.hh>
#include <dune/stuff/common/exceptions.hh>
#include <dune/stuff/common/type_utils.hh>
namespace Dune {
namespace Stuff {
namespace LA {
enum class ChooseBackend {
common_dense
, istl_sparse
, eigen_dense
, eigen_sparse
}; // enum class ChooseBackend
static constexpr ChooseBackend default_backend =
#if HAVE_EIGEN
ChooseBackend::eigen_sparse;
#elif HAVE_DUNE_ISTL
ChooseBackend::istl_sparse;
#else
ChooseBackend::common_dense;
#endif
static constexpr ChooseBackend default_sparse_backend =
#if HAVE_EIGEN
ChooseBackend::eigen_sparse;
#elif HAVE_DUNE_ISTL
ChooseBackend::istl_sparse;
#else
ChooseBackend::common_dense;
# error "There is no sparse LA backend available!"
#endif
static constexpr ChooseBackend default_dense_backend =
#if HAVE_EIGEN
ChooseBackend::eigen_dense;
#else
ChooseBackend::common_dense;
#endif
/**
* \brief Contains tags mostly needed for python bindings.
*/
namespace Tags {
class ContainerInterface {};
class ProvidesDataAccess {};
} // namespace Tags
namespace internal {
/**
* \brief Tries a boost::numeric_cast and throws an Exceptions::wrong_input_given on failure.
*
* This can be used in the ctor initializer list.
*/
template< class Out, class In >
static Out boost_numeric_cast(const In& in)
{
try {
return boost::numeric_cast< Out >(in);
} catch (boost::bad_numeric_cast& ee) {
DUNE_THROW(Exceptions::wrong_input_given,
"There was an error in boost converting '" << in << "' to '"
<< Common::Typename< Out >::value() << "': " << ee.what());
}
} // ... boost_numeric_cast(...)
} // namespace internal
template< class Traits >
class ProvidesBackend
: public CRTPInterface< ProvidesBackend< Traits >, Traits >
{
public:
typedef typename Traits::BackendType BackendType;
inline BackendType& backend()
{
CHECK_CRTP(this->as_imp().backend());
return this->as_imp().backend();
}
inline const BackendType& backend() const
{
CHECK_CRTP(this->as_imp().backend());
return this->as_imp().backend();
}
}; // class ProvidesBackend
/**
* \brief Interface for all containers (vectors and matrices).
*
* \note All derived classes are supposed to implement copy-on-write. This can be achieved by internally holding a
* shared_prt to the appropriate backend and by passing this shared_prt around on copy, move or assingment. Any
* class method that writes to the backend or exposes a reference to the backend is then required to make a deep
* copy of the backend, if it is not the sole owner of this resource. This can for instance be achieved by
* calling a private method:
\code
inline void ensure_uniqueness() const
{
if (!backend_.unique())
backend_ = std::make_shared< BackendType >(*backend_);
}
\endcode
*/
template< class Traits, class ScalarImp = typename Traits::ScalarType >
class ContainerInterface
: public Tags::ContainerInterface
, public CRTPInterface< ContainerInterface< Traits, ScalarImp >, Traits >
{
typedef CRTPInterface< ContainerInterface< Traits, ScalarImp >, Traits > CRTP;
static_assert(std::is_same< ScalarImp, typename Traits::ScalarType >::value, "");
public:
typedef ScalarImp ScalarType;
typedef typename Traits::RealType RealType;
using typename CRTP::derived_type;
virtual ~ContainerInterface() {}
/// \name Have to be implemented by a derived class!
/// \{
/**
* \brief Creates a (deep) copy of the underlying resource
* \return A new container
*/
inline derived_type copy() const
{
CHECK_CRTP(this->as_imp().copy());
return this->as_imp().copy();
}
/**
* \brief BLAS SCAL operation (in-place sclar multiplication).
* \param alpha The scalar coefficient with which each element of the container is multiplied.
*/
inline void scal(const ScalarType& alpha)
{
CHECK_AND_CALL_CRTP(this->as_imp().scal(alpha));
}
/**
* \brief BLAS AXPY operation.
* \param alpha The scalar coefficient with which each element of the container is multiplied
* \param xx Container that is to be elementwise added.
*/
inline void axpy(const ScalarType& alpha, const derived_type& xx)
{
CHECK_AND_CALL_CRTP(this->as_imp().axpy(alpha, xx));
}
/**
* \brief Test for equal sizes.
* \param other Container the sizes of which this is to be compared to.
*/
inline bool has_equal_shape(const derived_type& other) const
{
CHECK_CRTP(this->as_imp().has_equal_shape(other));
return this->as_imp().has_equal_shape(other);
}
/// \}
/// \name Are provided by the interface for convenience!
/// \note Those marked as virtual may be implemented more efficiently in a derived class!
/// \{
static std::string type_this()
{
return Common::Typename< derived_type >::value();
}
virtual derived_type& operator*=(const ScalarType& alpha)
{
scal(alpha);
return this->as_imp(*this);
}
/// \}
}; // class ContainerInterface
namespace internal {
template< class C >
struct is_container_helper
{
DSC_has_typedef_initialize_once(Traits)
DSC_has_typedef_initialize_once(ScalarType)
static const bool is_candidate = DSC_has_typedef(Traits)< C >::value
&& DSC_has_typedef(ScalarType)< C >::value;
}; // class is_container_helper
} // namespace internal
template< class C, bool candidate = internal::is_container_helper< C >::is_candidate >
struct is_container
: public std::is_base_of< ContainerInterface< typename C::Traits, typename C::ScalarType >, C >
{};
template< class C >
struct is_container< C, false >
: public std::false_type
{};
template< class Traits >
class ProvidesConstContainer
: public CRTPInterface< ProvidesConstContainer< Traits >, Traits >
{
public:
typedef typename Traits::ContainerType ContainerType;
inline std::shared_ptr< const ContainerType > container() const
{
CHECK_CRTP(this->as_imp().container());
return this->as_imp().container();
}
}; // class ProvidesConstContainer
template< class Traits >
class ProvidesContainer
: public ProvidesConstContainer< Traits >
{
typedef ProvidesConstContainer< Traits > BaseType;
public:
typedef typename Traits::ContainerType ContainerType;
using BaseType::container;
inline std::shared_ptr< ContainerType > container()
{
CHECK_CRTP(this->as_imp().container());
return this->as_imp().container();
}
}; // class ProvidesContainer
template< class Traits >
class ProvidesDataAccess
: public CRTPInterface< ProvidesDataAccess< Traits >, Traits >
, public Tags::ProvidesDataAccess
{
public:
typedef typename Traits::ScalarType ScalarType;
inline ScalarType* data()
{
CHECK_CRTP(this->as_imp().data());
return this->as_imp().data();
}
}; // class ProvidesDataAccess
} // namespace LA
} // namespace Stuff
} // namespace Dune
#endif // #ifndef DUNE_STUFF_LA_CONTAINER_CONTAINER_INTERFACE_HH
<|endoftext|> |
<commit_before>/*
This file is part of libkcal.
Copyright (c) 2001-2003 Cornelius Schumacher <schumacher@kde.org>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
#include <kglobal.h>
#include <klocale.h>
#include <kdebug.h>
#include "todo.h"
using namespace KCal;
Todo::Todo()
{
mHasDueDate = false;
mHasStartDate = false;
mHasCompletedDate = false;
mPercentComplete = 0;
}
Todo::Todo(const Todo &t) : Incidence(t)
{
mDtDue = t.mDtDue;
mHasDueDate = t.mHasDueDate;
mHasStartDate = t.mHasStartDate;
mCompleted = t.mCompleted;
mHasCompletedDate = t.mHasCompletedDate;
mPercentComplete = t.mPercentComplete;
mDtRecurrence = t.mDtRecurrence;
}
Todo::~Todo()
{
}
Todo *Todo::clone()
{
return new Todo( *this );
}
bool Todo::operator==( const Todo& t2 ) const
{
return
static_cast<const Incidence&>(*this) == static_cast<const Incidence&>(t2) &&
dtDue() == t2.dtDue() &&
hasDueDate() == t2.hasDueDate() &&
hasStartDate() == t2.hasStartDate() &&
completed() == t2.completed() &&
hasCompletedDate() == t2.hasCompletedDate() &&
percentComplete() == t2.percentComplete();
}
void Todo::setDtDue(const QDateTime &dtDue, bool first )
{
//int diffsecs = mDtDue.secsTo(dtDue);
/*if (mReadOnly) return;
const Alarm::List& alarms = alarms();
for (Alarm* alarm = alarms.first(); alarm; alarm = alarms.next()) {
if (alarm->enabled()) {
alarm->setTime(alarm->time().addSecs(diffsecs));
}
}*/
if( doesRecur() && !first ) {
mDtRecurrence = dtDue;
} else {
mDtDue = dtDue;
recurrence()->setRecurStart( dtDue );
}
if ( doesRecur() && dtDue < recurrence()->recurStart() )
setDtStart( dtDue );
//kdDebug(5800) << "setDtDue says date is " << mDtDue.toString() << endl;
/*const Alarm::List& alarms = alarms();
for (Alarm* alarm = alarms.first(); alarm; alarm = alarms.next())
alarm->setAlarmStart(mDtDue);*/
updated();
}
QDateTime Todo::dtDue( bool first ) const
{
if ( doesRecur() && !first && mDtRecurrence.isValid() )
return mDtRecurrence;
return mDtDue;
}
QString Todo::dtDueTimeStr() const
{
return KGlobal::locale()->formatTime( dtDue(!doesRecur()).time() );
}
QString Todo::dtDueDateStr(bool shortfmt) const
{
return KGlobal::locale()->formatDate(dtDue( !doesRecur() ).date(),shortfmt);
}
QString Todo::dtDueStr() const
{
return KGlobal::locale()->formatDateTime( dtDue( !doesRecur() ) );
}
bool Todo::hasDueDate() const
{
return mHasDueDate;
}
void Todo::setHasDueDate(bool f)
{
if (mReadOnly) return;
mHasDueDate = f;
updated();
}
bool Todo::hasStartDate() const
{
return mHasStartDate;
}
void Todo::setHasStartDate(bool f) // zie reinholds opmerking
{
if (mReadOnly) return;
if ( doesRecur() && !f ) {
if ( !comments().grep("NoStartDate").count() )
addComment("NoStartDate"); //TODO: --> custom flag?
} else {
QString s("NoStartDate");
removeComment(s);
}
mHasStartDate = f;
updated();
}
QDateTime Todo::dtStart( bool first ) const
{
if ( doesRecur() && !first )
return mDtRecurrence.addDays( dtDue( true ).daysTo( IncidenceBase::dtStart() ) );
else
return IncidenceBase::dtStart();
}
void Todo::setDtStart( const QDateTime &dtStart )
{
if ( doesRecur() )
recurrence()->setRecurStart( mDtDue );
IncidenceBase::setDtStart( dtStart );
}
QString Todo::dtStartTimeStr( bool first ) const
{
return KGlobal::locale()->formatTime(dtStart(first).time());
}
QString Todo::dtStartDateStr(bool shortfmt, bool first) const
{
return KGlobal::locale()->formatDate(dtStart(first).date(),shortfmt);
}
QString Todo::dtStartStr(bool first) const
{
return KGlobal::locale()->formatDateTime(dtStart(first));
}
bool Todo::isCompleted() const
{
if (mPercentComplete == 100) return true;
else return false;
}
void Todo::setCompleted(bool completed)
{
if (completed) mPercentComplete = 100;
else mPercentComplete = 0;
updated();
}
QDateTime Todo::completed() const
{
return mCompleted;
}
QString Todo::completedStr() const
{
return KGlobal::locale()->formatDateTime(mCompleted);
}
void Todo::setCompleted(const QDateTime &completed)
{
if( !recurTodo() ) {
mHasCompletedDate = true;
mPercentComplete = 100;
mCompleted = completed;
}
updated();
}
bool Todo::hasCompletedDate() const
{
return mHasCompletedDate;
}
int Todo::percentComplete() const
{
return mPercentComplete;
}
void Todo::setPercentComplete(int v)
{
mPercentComplete = v;
updated();
}
void Todo::setDtRecurrence( const QDateTime &dt )
{
mDtRecurrence = dt;
}
QDateTime Todo::dtRecurrence() const
{
return mDtRecurrence.isValid() ? mDtRecurrence : mDtDue;
}
bool Todo::recursOn( const QDate &date )
{
QDate today = QDate::currentDate();
return ( Incidence::recursOn(date) &&
!( date < today && mDtRecurrence.date() < today &&
mDtRecurrence > recurrence()->recurStart() ) );
}
bool Todo::recurTodo()
{
if ( doesRecur() ) {
Recurrence *r = recurrence();
QDateTime endDateTime = r->endDateTime();
QDateTime nextDate = r->getNextDateTime( dtDue() );
if ( ( r->duration() == -1 || ( nextDate.isValid() && endDateTime.isValid()
&& nextDate <= endDateTime ) ) ) {
setDtDue( nextDate );
while ( !recursAt( dtDue() ) || dtDue() <= QDateTime::currentDateTime() ) {
setDtDue( r->getNextDateTime( dtDue() ) );
}
setCompleted( false );
setRevision( revision() + 1 );
return true;
}
}
return false;
}
<commit_msg>CVS_SILENT Forgot to remove a Dutch comment.<commit_after>/*
This file is part of libkcal.
Copyright (c) 2001-2003 Cornelius Schumacher <schumacher@kde.org>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
#include <kglobal.h>
#include <klocale.h>
#include <kdebug.h>
#include "todo.h"
using namespace KCal;
Todo::Todo()
{
mHasDueDate = false;
mHasStartDate = false;
mHasCompletedDate = false;
mPercentComplete = 0;
}
Todo::Todo(const Todo &t) : Incidence(t)
{
mDtDue = t.mDtDue;
mHasDueDate = t.mHasDueDate;
mHasStartDate = t.mHasStartDate;
mCompleted = t.mCompleted;
mHasCompletedDate = t.mHasCompletedDate;
mPercentComplete = t.mPercentComplete;
mDtRecurrence = t.mDtRecurrence;
}
Todo::~Todo()
{
}
Todo *Todo::clone()
{
return new Todo( *this );
}
bool Todo::operator==( const Todo& t2 ) const
{
return
static_cast<const Incidence&>(*this) == static_cast<const Incidence&>(t2) &&
dtDue() == t2.dtDue() &&
hasDueDate() == t2.hasDueDate() &&
hasStartDate() == t2.hasStartDate() &&
completed() == t2.completed() &&
hasCompletedDate() == t2.hasCompletedDate() &&
percentComplete() == t2.percentComplete();
}
void Todo::setDtDue(const QDateTime &dtDue, bool first )
{
//int diffsecs = mDtDue.secsTo(dtDue);
/*if (mReadOnly) return;
const Alarm::List& alarms = alarms();
for (Alarm* alarm = alarms.first(); alarm; alarm = alarms.next()) {
if (alarm->enabled()) {
alarm->setTime(alarm->time().addSecs(diffsecs));
}
}*/
if( doesRecur() && !first ) {
mDtRecurrence = dtDue;
} else {
mDtDue = dtDue;
recurrence()->setRecurStart( dtDue );
}
if ( doesRecur() && dtDue < recurrence()->recurStart() )
setDtStart( dtDue );
//kdDebug(5800) << "setDtDue says date is " << mDtDue.toString() << endl;
/*const Alarm::List& alarms = alarms();
for (Alarm* alarm = alarms.first(); alarm; alarm = alarms.next())
alarm->setAlarmStart(mDtDue);*/
updated();
}
QDateTime Todo::dtDue( bool first ) const
{
if ( doesRecur() && !first && mDtRecurrence.isValid() )
return mDtRecurrence;
return mDtDue;
}
QString Todo::dtDueTimeStr() const
{
return KGlobal::locale()->formatTime( dtDue(!doesRecur()).time() );
}
QString Todo::dtDueDateStr(bool shortfmt) const
{
return KGlobal::locale()->formatDate(dtDue( !doesRecur() ).date(),shortfmt);
}
QString Todo::dtDueStr() const
{
return KGlobal::locale()->formatDateTime( dtDue( !doesRecur() ) );
}
bool Todo::hasDueDate() const
{
return mHasDueDate;
}
void Todo::setHasDueDate(bool f)
{
if (mReadOnly) return;
mHasDueDate = f;
updated();
}
bool Todo::hasStartDate() const
{
return mHasStartDate;
}
void Todo::setHasStartDate(bool f)
{
if (mReadOnly) return;
if ( doesRecur() && !f ) {
if ( !comments().grep("NoStartDate").count() )
addComment("NoStartDate"); //TODO: --> custom flag?
} else {
QString s("NoStartDate");
removeComment(s);
}
mHasStartDate = f;
updated();
}
QDateTime Todo::dtStart( bool first ) const
{
if ( doesRecur() && !first )
return mDtRecurrence.addDays( dtDue( true ).daysTo( IncidenceBase::dtStart() ) );
else
return IncidenceBase::dtStart();
}
void Todo::setDtStart( const QDateTime &dtStart )
{
if ( doesRecur() )
recurrence()->setRecurStart( mDtDue );
IncidenceBase::setDtStart( dtStart );
}
QString Todo::dtStartTimeStr( bool first ) const
{
return KGlobal::locale()->formatTime(dtStart(first).time());
}
QString Todo::dtStartDateStr(bool shortfmt, bool first) const
{
return KGlobal::locale()->formatDate(dtStart(first).date(),shortfmt);
}
QString Todo::dtStartStr(bool first) const
{
return KGlobal::locale()->formatDateTime(dtStart(first));
}
bool Todo::isCompleted() const
{
if (mPercentComplete == 100) return true;
else return false;
}
void Todo::setCompleted(bool completed)
{
if (completed) mPercentComplete = 100;
else mPercentComplete = 0;
updated();
}
QDateTime Todo::completed() const
{
return mCompleted;
}
QString Todo::completedStr() const
{
return KGlobal::locale()->formatDateTime(mCompleted);
}
void Todo::setCompleted(const QDateTime &completed)
{
if( !recurTodo() ) {
mHasCompletedDate = true;
mPercentComplete = 100;
mCompleted = completed;
}
updated();
}
bool Todo::hasCompletedDate() const
{
return mHasCompletedDate;
}
int Todo::percentComplete() const
{
return mPercentComplete;
}
void Todo::setPercentComplete(int v)
{
mPercentComplete = v;
updated();
}
void Todo::setDtRecurrence( const QDateTime &dt )
{
mDtRecurrence = dt;
}
QDateTime Todo::dtRecurrence() const
{
return mDtRecurrence.isValid() ? mDtRecurrence : mDtDue;
}
bool Todo::recursOn( const QDate &date )
{
QDate today = QDate::currentDate();
return ( Incidence::recursOn(date) &&
!( date < today && mDtRecurrence.date() < today &&
mDtRecurrence > recurrence()->recurStart() ) );
}
bool Todo::recurTodo()
{
if ( doesRecur() ) {
Recurrence *r = recurrence();
QDateTime endDateTime = r->endDateTime();
QDateTime nextDate = r->getNextDateTime( dtDue() );
if ( ( r->duration() == -1 || ( nextDate.isValid() && endDateTime.isValid()
&& nextDate <= endDateTime ) ) ) {
setDtDue( nextDate );
while ( !recursAt( dtDue() ) || dtDue() <= QDateTime::currentDateTime() ) {
setDtDue( r->getNextDateTime( dtDue() ) );
}
setCompleted( false );
setRevision( revision() + 1 );
return true;
}
}
return false;
}
<|endoftext|> |
<commit_before>#include "riptide_hardware/dvl_processor.h"
int main(int argc, char **argv)
{
ros::init(argc, argv, "dvl_processor");
DVLProcessor dp;
ros::spin();
}
DVLProcessor::DVLProcessor() : nh("dvl_processor")
{
imu_state_sub = nh.subscribe<riptide_msgs::Imu>("/state/imu", 1, &DVLProcessor::ImuCB, this);
dvl_data_sub = nh.subscribe<nortek_dvl::Dvl>("/dvl/dvl", 1, &DVLProcessor::DvlCB, this);
dvl_state_pub = nh.advertise<nortek_dvl::Dvl>("/state/dvl", 1);
// dvl_data_pub = nh.advertise<riptide_msgs::Dvl>("/state/dvl2", 1);
// Load relative positions between DVL and COM from YAML file
DVLProcessor::LoadParam<string>("properties_file", properties_file);
properties = YAML::LoadFile(properties_file);
DVLProcessor::LoadDVLProperties();
}
template <typename T>
void DVLProcessor::LoadParam(string param, T &var)
{
try
{
if (!nh.getParam(param, var))
{
throw 0;
}
}
catch (int e)
{
string ns = nh.getNamespace();
ROS_ERROR("DVL Processor Namespace: %s", ns.c_str());
ROS_ERROR("Critical! Param \"%s/%s\" does not exist or is not accessed correctly. SHutting down.", ns.c_str(), param.c_str());
ros::shutdown();
}
}
void DVLProcessor::LoadDVLProperties()
{
for (int i = 0; i < 3; i++)
dvl_position(i) = properties["properties"]["dvl"][i].as<double>() - properties["properties"]["center_of_mass"][i].as<double>();
psi = properties["properties"]["dvl"][3].as<double>() * PI / 180;
}
void DVLProcessor::ImuCB(const riptide_msgs::Imu::ConstPtr &imu_msg)
{
Vector3d angular_vel;
angular_vel(0) = imu_msg->ang_vel_rad.x;
angular_vel(1) = imu_msg->ang_vel_rad.y;
angular_vel(2) = imu_msg->ang_vel_rad.z;
relative_vel = angular_vel.cross(dvl_position);
ROS_INFO(dvl_position);
}
void DVLProcessor::DvlCB(const nortek_dvl::Dvl::ConstPtr &dvl_msg)
{
nortek_dvl::Dvl dvl_state(*dvl_msg);
dvl_state.velocity.x = cos(psi) * dvl_msg->velocity.x + sin(psi) * dvl_msg->velocity.y - relative_vel(0);
dvl_state.velocity.y = -sin(psi) * dvl_msg->velocity.x + cos(psi) * dvl_msg->velocity.y - relative_vel(1);
dvl_state.velocity.z = dvl_msg->velocity.z - relative_vel(2);
dvl_state_pub.publish(dvl_state);
// riptide_msgs::Dvl dvl_state2(*dvl_state);
// dvl_data_pub.publish(dvl_state2);
}<commit_msg>delete rosinfo<commit_after>#include "riptide_hardware/dvl_processor.h"
int main(int argc, char **argv)
{
ros::init(argc, argv, "dvl_processor");
DVLProcessor dp;
ros::spin();
}
DVLProcessor::DVLProcessor() : nh("dvl_processor")
{
imu_state_sub = nh.subscribe<riptide_msgs::Imu>("/state/imu", 1, &DVLProcessor::ImuCB, this);
dvl_data_sub = nh.subscribe<nortek_dvl::Dvl>("/dvl/dvl", 1, &DVLProcessor::DvlCB, this);
dvl_state_pub = nh.advertise<nortek_dvl::Dvl>("/state/dvl", 1);
// dvl_data_pub = nh.advertise<riptide_msgs::Dvl>("/state/dvl2", 1);
// Load relative positions between DVL and COM from YAML file
DVLProcessor::LoadParam<string>("properties_file", properties_file);
properties = YAML::LoadFile(properties_file);
DVLProcessor::LoadDVLProperties();
}
template <typename T>
void DVLProcessor::LoadParam(string param, T &var)
{
try
{
if (!nh.getParam(param, var))
{
throw 0;
}
}
catch (int e)
{
string ns = nh.getNamespace();
ROS_ERROR("DVL Processor Namespace: %s", ns.c_str());
ROS_ERROR("Critical! Param \"%s/%s\" does not exist or is not accessed correctly. SHutting down.", ns.c_str(), param.c_str());
ros::shutdown();
}
}
void DVLProcessor::LoadDVLProperties()
{
for (int i = 0; i < 3; i++)
dvl_position(i) = properties["properties"]["dvl"][i].as<double>() - properties["properties"]["center_of_mass"][i].as<double>();
psi = properties["properties"]["dvl"][3].as<double>() * PI / 180;
}
void DVLProcessor::ImuCB(const riptide_msgs::Imu::ConstPtr &imu_msg)
{
Vector3d angular_vel;
angular_vel(0) = imu_msg->ang_vel_rad.x;
angular_vel(1) = imu_msg->ang_vel_rad.y;
angular_vel(2) = imu_msg->ang_vel_rad.z;
relative_vel = angular_vel.cross(dvl_position);
}
void DVLProcessor::DvlCB(const nortek_dvl::Dvl::ConstPtr &dvl_msg)
{
nortek_dvl::Dvl dvl_state(*dvl_msg);
dvl_state.velocity.x = cos(psi) * dvl_msg->velocity.x + sin(psi) * dvl_msg->velocity.y - relative_vel(0);
dvl_state.velocity.y = -sin(psi) * dvl_msg->velocity.x + cos(psi) * dvl_msg->velocity.y - relative_vel(1);
dvl_state.velocity.z = dvl_msg->velocity.z - relative_vel(2);
dvl_state_pub.publish(dvl_state);
// riptide_msgs::Dvl dvl_state2(*dvl_state);
// dvl_data_pub.publish(dvl_state2);
}<|endoftext|> |
<commit_before>#include "Threading.hpp"
#include "ThreadData.hpp"
#include "Config.hpp"
#include PLATFORM_PATH(PlatformSpecific_Threading.inl)
<commit_msg>-: Fix for commit 102<commit_after>#include "Threading.hpp"
#include "ThreadData.hpp"
#include <cassert>
#include "Config.hpp"
#include PLATFORM_PATH(PlatformSpecific_Threading.inl)
<|endoftext|> |
<commit_before>/*
* Copyright 2014 Milian Wolff <mail@milianw.de>
*
* This program 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 program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/**
* @file libheaptrack.cpp
*
* @brief Collect raw heaptrack data by overloading heap allocation functions.
*/
#include <cstdio>
#include <stdio_ext.h>
#include <cstdlib>
#include <atomic>
#include <unordered_map>
#include <string>
#include <tuple>
#include <memory>
#include <unordered_set>
#include <boost/algorithm/string/replace.hpp>
#include <dlfcn.h>
#include <link.h>
#include "tracetree.h"
#include "timer.h"
/**
* uncomment this to get extended debug code for known pointers
* there are still some malloc functions I'm missing apparently,
* related to TLS and such I guess
*/
// #define DEBUG_MALLOC_PTRS
using namespace std;
namespace {
using malloc_t = void* (*) (size_t);
using free_t = void (*) (void*);
using realloc_t = void* (*) (void*, size_t);
using calloc_t = void* (*) (size_t, size_t);
using posix_memalign_t = int (*) (void **, size_t, size_t);
using valloc_t = void* (*) (size_t);
using aligned_alloc_t = void* (*) (size_t, size_t);
using dlopen_t = void* (*) (const char*, int);
using dlclose_t = int (*) (void*);
malloc_t real_malloc = nullptr;
free_t real_free = nullptr;
realloc_t real_realloc = nullptr;
calloc_t real_calloc = nullptr;
posix_memalign_t real_posix_memalign = nullptr;
valloc_t real_valloc = nullptr;
aligned_alloc_t real_aligned_alloc = nullptr;
dlopen_t real_dlopen = nullptr;
dlclose_t real_dlclose = nullptr;
// threadsafe stuff
atomic<bool> moduleCacheDirty(true);
struct HandleGuard
{
HandleGuard()
: wasLocked(inHandler)
{
inHandler = true;
}
~HandleGuard()
{
inHandler = wasLocked;
}
const bool wasLocked;
static thread_local bool inHandler;
};
/**
* Similar to std::lock_guard but operates on the internal stream lock of a FILE*.
*/
class LockGuard
{
public:
LockGuard(FILE* file)
: file(file)
{
flockfile(file);
}
~LockGuard()
{
funlockfile(file);
}
private:
FILE* file;
};
thread_local bool HandleGuard::inHandler = false;
string env(const char* variable)
{
const char* value = getenv(variable);
return value ? string(value) : string();
}
void prepare_fork();
void parent_fork();
void child_fork();
struct Data
{
Data()
{
pthread_atfork(&prepare_fork, &parent_fork, &child_fork);
string outputFileName = env("DUMP_HEAPTRACK_OUTPUT");
if (outputFileName.empty()) {
// env var might not be set when linked directly into an executable
outputFileName = "heaptrack.$$";
} else if (outputFileName == "-" || outputFileName == "stdout") {
out = stdout;
} else if (outputFileName == "stderr") {
out = stderr;
}
if (!out) {
boost::replace_all(outputFileName, "$$", to_string(getpid()));
out = fopen(outputFileName.c_str(), "w");
__fsetlocking(out, FSETLOCKING_BYCALLER);
}
if (!out) {
fprintf(stderr, "Failed to open output file: %s\n", outputFileName.c_str());
exit(1);
}
// TODO: remember meta data about host application, such as cmdline, date of run, ...
// cleanup environment to prevent tracing of child apps
unsetenv("DUMP_HEAPTRACK_OUTPUT");
unsetenv("LD_PRELOAD");
timer.setInterval(1, 0);
}
~Data()
{
HandleGuard::inHandler = true;
if (out) {
fclose(out);
}
}
void updateModuleCache()
{
fprintf(out, "m -\n");
foundExe = false;
dl_iterate_phdr(dlopen_notify_callback, this);
moduleCacheDirty = false;
}
/**
* Mostly copied from vogl's src/libbacktrace/btrace.cpp
*/
static int dlopen_notify_callback(struct dl_phdr_info *info, size_t /*size*/, void *_data)
{
auto data = reinterpret_cast<Data*>(_data);
bool isExe = false;
const char *fileName = info->dlpi_name;
const int BUF_SIZE = 1024;
char buf[BUF_SIZE];
// If we don't have a filename and we haven't added our main exe yet, do it now.
if (!fileName || !fileName[0]) {
if (!data->foundExe) {
isExe = true;
data->foundExe = true;
ssize_t ret = readlink("/proc/self/exe", buf, sizeof(buf));
if ((ret > 0) && (ret < (ssize_t)sizeof(buf))) {
buf[ret] = 0;
fileName = buf;
}
}
if (!fileName || !fileName[0]) {
return 0;
}
}
for (int i = 0; i < info->dlpi_phnum; i++) {
if (info->dlpi_phdr[i].p_type == PT_LOAD) {
const uintptr_t addressStart = info->dlpi_addr + info->dlpi_phdr[i].p_vaddr;
const uintptr_t addressEnd = addressStart + info->dlpi_phdr[i].p_memsz;
fprintf(data->out, "m %s %d %lx %lx\n", fileName, isExe, addressStart, addressEnd);
}
}
return 0;
}
void handleMalloc(void* ptr, size_t size)
{
Trace trace;
if (!trace.fill()) {
return;
}
LockGuard lock(out);
if (lastTimerElapsed != timer.timesElapsed()) {
lastTimerElapsed = timer.timesElapsed();
fprintf(out, "c %lx\n", lastTimerElapsed);
}
if (moduleCacheDirty) {
updateModuleCache();
}
const size_t index = traceTree.index(trace, out);
#ifdef DEBUG_MALLOC_PTRS
auto it = known.find(ptr);
assert(it == known.end());
known.insert(ptr);
#endif
fprintf(out, "+ %lx %lx %lx\n", size, index, reinterpret_cast<uintptr_t>(ptr));
}
void handleFree(void* ptr)
{
LockGuard lock(out);
#ifdef DEBUG_MALLOC_PTRS
auto it = known.find(ptr);
assert(it != known.end());
known.erase(it);
#endif
fprintf(out, "- %lx\n", reinterpret_cast<uintptr_t>(ptr));
}
TraceTree traceTree;
/**
* Note: We use the C stdio API here for performance reasons.
* Esp. in multi-threaded environments this is much faster
* to produce non-per-line-interleaved output.
*/
FILE* out = nullptr;
size_t lastTimerElapsed = 0;
Timer timer;
bool foundExe = false;
#ifdef DEBUG_MALLOC_PTRS
unordered_set<void*> known;
#endif
};
unique_ptr<Data> data;
void prepare_fork()
{
// don't do any custom malloc handling while inside fork
HandleGuard::inHandler = true;
}
void parent_fork()
{
// the parent process can now continue its custom malloc tracking
HandleGuard::inHandler = false;
}
void child_fork()
{
// but the forked child process cleans up itself
// this is important to prevent two processes writing to the same file
if (data) {
data->out = nullptr;
data.reset(nullptr);
}
HandleGuard::inHandler = true;
}
template<typename T>
T findReal(const char* name)
{
auto ret = dlsym(RTLD_NEXT, name);
if (!ret) {
fprintf(stderr, "Could not find original function %s\n", name);
abort();
}
return reinterpret_cast<T>(ret);
}
/**
* Dummy implementation, since the call to dlsym from findReal triggers a call to calloc.
*
* This is only called at startup and will eventually be replaced by the "proper" calloc implementation.
*/
void* dummy_calloc(size_t num, size_t size)
{
const size_t MAX_SIZE = 1024;
static char* buf[MAX_SIZE];
static size_t offset = 0;
if (!offset) {
memset(buf, 0, MAX_SIZE);
}
size_t oldOffset = offset;
offset += num * size;
if (offset >= MAX_SIZE) {
fprintf(stderr, "failed to initialize, dummy calloc buf size exhausted: %lu requested, %lu available\n", offset, MAX_SIZE);
abort();
}
return buf + oldOffset;
}
void init()
{
if (data || HandleGuard::inHandler) {
fprintf(stderr, "initialization recursion detected\n");
abort();
}
HandleGuard guard;
real_calloc = &dummy_calloc;
real_calloc = findReal<calloc_t>("calloc");
real_dlopen = findReal<dlopen_t>("dlopen");
real_dlclose = findReal<dlclose_t>("dlclose");
real_malloc = findReal<malloc_t>("malloc");
real_free = findReal<free_t>("free");
real_realloc = findReal<realloc_t>("realloc");
real_posix_memalign = findReal<posix_memalign_t>("posix_memalign");
real_valloc = findReal<valloc_t>("valloc");
real_aligned_alloc = findReal<aligned_alloc_t>("aligned_alloc");
if (unw_set_caching_policy(unw_local_addr_space, UNW_CACHE_PER_THREAD)) {
fprintf(stderr, "Failed to enable per-thread libunwind caching.\n");
}
if (unw_set_cache_log_size(unw_local_addr_space, 10)) {
fprintf(stderr, "Failed to set libunwind cache size.\n");
}
data.reset(new Data);
}
}
extern "C" {
/// TODO: memalign, pvalloc, ...?
void* malloc(size_t size)
{
if (!real_malloc) {
init();
}
void* ret = real_malloc(size);
if (ret && !HandleGuard::inHandler && data) {
HandleGuard guard;
data->handleMalloc(ret, size);
}
return ret;
}
void free(void* ptr)
{
if (!real_free) {
init();
}
// call handler before handing over the real free implementation
// to ensure the ptr is not reused in-between and thus the output
// stays consistent
if (ptr && !HandleGuard::inHandler && data) {
HandleGuard guard;
data->handleFree(ptr);
}
real_free(ptr);
}
void* realloc(void* ptr, size_t size)
{
if (!real_realloc) {
init();
}
void* ret = real_realloc(ptr, size);
if (ret && !HandleGuard::inHandler && data) {
HandleGuard guard;
if (ptr) {
data->handleFree(ptr);
}
data->handleMalloc(ret, size);
}
return ret;
}
void* calloc(size_t num, size_t size)
{
if (!real_calloc) {
init();
}
void* ret = real_calloc(num, size);
if (ret && !HandleGuard::inHandler && data) {
HandleGuard guard;
data->handleMalloc(ret, num*size);
}
return ret;
}
int posix_memalign(void **memptr, size_t alignment, size_t size)
{
if (!real_posix_memalign) {
init();
}
int ret = real_posix_memalign(memptr, alignment, size);
if (ret && !HandleGuard::inHandler && data) {
HandleGuard guard;
data->handleMalloc(*memptr, size);
}
return ret;
}
void* aligned_alloc(size_t alignment, size_t size)
{
if (!real_aligned_alloc) {
init();
}
void* ret = real_aligned_alloc(alignment, size);
if (ret && !HandleGuard::inHandler && data) {
HandleGuard guard;
data->handleMalloc(ret, size);
}
return ret;
}
void* valloc(size_t size)
{
if (!real_valloc) {
init();
}
void* ret = real_valloc(size);
if (ret && !HandleGuard::inHandler && data) {
HandleGuard guard;
data->handleMalloc(ret, size);
}
return ret;
}
void *dlopen(const char *filename, int flag)
{
if (!real_dlopen) {
init();
}
void* ret = real_dlopen(filename, flag);
if (ret) {
moduleCacheDirty = true;
}
return ret;
}
int dlclose(void *handle)
{
if (!real_dlclose) {
init();
}
int ret = real_dlclose(handle);
if (!ret) {
moduleCacheDirty = true;
}
return ret;
}
}
<commit_msg>Ensure we only ever initialize once.<commit_after>/*
* Copyright 2014 Milian Wolff <mail@milianw.de>
*
* This program 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 program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/**
* @file libheaptrack.cpp
*
* @brief Collect raw heaptrack data by overloading heap allocation functions.
*/
#include <cstdio>
#include <stdio_ext.h>
#include <cstdlib>
#include <atomic>
#include <unordered_map>
#include <string>
#include <tuple>
#include <memory>
#include <unordered_set>
#include <mutex>
#include <boost/algorithm/string/replace.hpp>
#include <dlfcn.h>
#include <link.h>
#include "tracetree.h"
#include "timer.h"
/**
* uncomment this to get extended debug code for known pointers
* there are still some malloc functions I'm missing apparently,
* related to TLS and such I guess
*/
// #define DEBUG_MALLOC_PTRS
using namespace std;
namespace {
using malloc_t = void* (*) (size_t);
using free_t = void (*) (void*);
using realloc_t = void* (*) (void*, size_t);
using calloc_t = void* (*) (size_t, size_t);
using posix_memalign_t = int (*) (void **, size_t, size_t);
using valloc_t = void* (*) (size_t);
using aligned_alloc_t = void* (*) (size_t, size_t);
using dlopen_t = void* (*) (const char*, int);
using dlclose_t = int (*) (void*);
malloc_t real_malloc = nullptr;
free_t real_free = nullptr;
realloc_t real_realloc = nullptr;
calloc_t real_calloc = nullptr;
posix_memalign_t real_posix_memalign = nullptr;
valloc_t real_valloc = nullptr;
aligned_alloc_t real_aligned_alloc = nullptr;
dlopen_t real_dlopen = nullptr;
dlclose_t real_dlclose = nullptr;
// threadsafe stuff
atomic<bool> moduleCacheDirty(true);
struct HandleGuard
{
HandleGuard()
: wasLocked(inHandler)
{
inHandler = true;
}
~HandleGuard()
{
inHandler = wasLocked;
}
const bool wasLocked;
static thread_local bool inHandler;
};
/**
* Similar to std::lock_guard but operates on the internal stream lock of a FILE*.
*/
class LockGuard
{
public:
LockGuard(FILE* file)
: file(file)
{
flockfile(file);
}
~LockGuard()
{
funlockfile(file);
}
private:
FILE* file;
};
thread_local bool HandleGuard::inHandler = false;
string env(const char* variable)
{
const char* value = getenv(variable);
return value ? string(value) : string();
}
void prepare_fork();
void parent_fork();
void child_fork();
struct Data
{
Data()
{
pthread_atfork(&prepare_fork, &parent_fork, &child_fork);
string outputFileName = env("DUMP_HEAPTRACK_OUTPUT");
if (outputFileName.empty()) {
// env var might not be set when linked directly into an executable
outputFileName = "heaptrack.$$";
} else if (outputFileName == "-" || outputFileName == "stdout") {
out = stdout;
} else if (outputFileName == "stderr") {
out = stderr;
}
if (!out) {
boost::replace_all(outputFileName, "$$", to_string(getpid()));
out = fopen(outputFileName.c_str(), "w");
__fsetlocking(out, FSETLOCKING_BYCALLER);
}
if (!out) {
fprintf(stderr, "Failed to open output file: %s\n", outputFileName.c_str());
exit(1);
}
// TODO: remember meta data about host application, such as cmdline, date of run, ...
// cleanup environment to prevent tracing of child apps
unsetenv("DUMP_HEAPTRACK_OUTPUT");
unsetenv("LD_PRELOAD");
timer.setInterval(1, 0);
}
~Data()
{
HandleGuard::inHandler = true;
if (out) {
fclose(out);
}
}
void updateModuleCache()
{
fprintf(out, "m -\n");
foundExe = false;
dl_iterate_phdr(dlopen_notify_callback, this);
moduleCacheDirty = false;
}
/**
* Mostly copied from vogl's src/libbacktrace/btrace.cpp
*/
static int dlopen_notify_callback(struct dl_phdr_info *info, size_t /*size*/, void *_data)
{
auto data = reinterpret_cast<Data*>(_data);
bool isExe = false;
const char *fileName = info->dlpi_name;
const int BUF_SIZE = 1024;
char buf[BUF_SIZE];
// If we don't have a filename and we haven't added our main exe yet, do it now.
if (!fileName || !fileName[0]) {
if (!data->foundExe) {
isExe = true;
data->foundExe = true;
ssize_t ret = readlink("/proc/self/exe", buf, sizeof(buf));
if ((ret > 0) && (ret < (ssize_t)sizeof(buf))) {
buf[ret] = 0;
fileName = buf;
}
}
if (!fileName || !fileName[0]) {
return 0;
}
}
for (int i = 0; i < info->dlpi_phnum; i++) {
if (info->dlpi_phdr[i].p_type == PT_LOAD) {
const uintptr_t addressStart = info->dlpi_addr + info->dlpi_phdr[i].p_vaddr;
const uintptr_t addressEnd = addressStart + info->dlpi_phdr[i].p_memsz;
fprintf(data->out, "m %s %d %lx %lx\n", fileName, isExe, addressStart, addressEnd);
}
}
return 0;
}
void handleMalloc(void* ptr, size_t size)
{
Trace trace;
if (!trace.fill()) {
return;
}
LockGuard lock(out);
if (lastTimerElapsed != timer.timesElapsed()) {
lastTimerElapsed = timer.timesElapsed();
fprintf(out, "c %lx\n", lastTimerElapsed);
}
if (moduleCacheDirty) {
updateModuleCache();
}
const size_t index = traceTree.index(trace, out);
#ifdef DEBUG_MALLOC_PTRS
auto it = known.find(ptr);
assert(it == known.end());
known.insert(ptr);
#endif
fprintf(out, "+ %lx %lx %lx\n", size, index, reinterpret_cast<uintptr_t>(ptr));
}
void handleFree(void* ptr)
{
LockGuard lock(out);
#ifdef DEBUG_MALLOC_PTRS
auto it = known.find(ptr);
assert(it != known.end());
known.erase(it);
#endif
fprintf(out, "- %lx\n", reinterpret_cast<uintptr_t>(ptr));
}
TraceTree traceTree;
/**
* Note: We use the C stdio API here for performance reasons.
* Esp. in multi-threaded environments this is much faster
* to produce non-per-line-interleaved output.
*/
FILE* out = nullptr;
size_t lastTimerElapsed = 0;
Timer timer;
bool foundExe = false;
#ifdef DEBUG_MALLOC_PTRS
unordered_set<void*> known;
#endif
};
unique_ptr<Data> data;
void prepare_fork()
{
// don't do any custom malloc handling while inside fork
HandleGuard::inHandler = true;
}
void parent_fork()
{
// the parent process can now continue its custom malloc tracking
HandleGuard::inHandler = false;
}
void child_fork()
{
// but the forked child process cleans up itself
// this is important to prevent two processes writing to the same file
if (data) {
data->out = nullptr;
data.reset(nullptr);
}
HandleGuard::inHandler = true;
}
template<typename T>
T findReal(const char* name)
{
auto ret = dlsym(RTLD_NEXT, name);
if (!ret) {
fprintf(stderr, "Could not find original function %s\n", name);
abort();
}
return reinterpret_cast<T>(ret);
}
/**
* Dummy implementation, since the call to dlsym from findReal triggers a call to calloc.
*
* This is only called at startup and will eventually be replaced by the "proper" calloc implementation.
*/
void* dummy_calloc(size_t num, size_t size)
{
const size_t MAX_SIZE = 1024;
static char* buf[MAX_SIZE];
static size_t offset = 0;
if (!offset) {
memset(buf, 0, MAX_SIZE);
}
size_t oldOffset = offset;
offset += num * size;
if (offset >= MAX_SIZE) {
fprintf(stderr, "failed to initialize, dummy calloc buf size exhausted: %lu requested, %lu available\n", offset, MAX_SIZE);
abort();
}
return buf + oldOffset;
}
void init()
{
static once_flag once;
call_once(once, [] {
if (data || HandleGuard::inHandler) {
fprintf(stderr, "initialization recursion detected\n");
abort();
}
HandleGuard guard;
real_calloc = &dummy_calloc;
real_calloc = findReal<calloc_t>("calloc");
real_dlopen = findReal<dlopen_t>("dlopen");
real_dlclose = findReal<dlclose_t>("dlclose");
real_malloc = findReal<malloc_t>("malloc");
real_free = findReal<free_t>("free");
real_realloc = findReal<realloc_t>("realloc");
real_posix_memalign = findReal<posix_memalign_t>("posix_memalign");
real_valloc = findReal<valloc_t>("valloc");
real_aligned_alloc = findReal<aligned_alloc_t>("aligned_alloc");
if (unw_set_caching_policy(unw_local_addr_space, UNW_CACHE_PER_THREAD)) {
fprintf(stderr, "Failed to enable per-thread libunwind caching.\n");
}
if (unw_set_cache_log_size(unw_local_addr_space, 10)) {
fprintf(stderr, "Failed to set libunwind cache size.\n");
}
data.reset(new Data);
});
}
}
extern "C" {
/// TODO: memalign, pvalloc, ...?
void* malloc(size_t size)
{
if (!real_malloc) {
init();
}
void* ret = real_malloc(size);
if (ret && !HandleGuard::inHandler && data) {
HandleGuard guard;
data->handleMalloc(ret, size);
}
return ret;
}
void free(void* ptr)
{
if (!real_free) {
init();
}
// call handler before handing over the real free implementation
// to ensure the ptr is not reused in-between and thus the output
// stays consistent
if (ptr && !HandleGuard::inHandler && data) {
HandleGuard guard;
data->handleFree(ptr);
}
real_free(ptr);
}
void* realloc(void* ptr, size_t size)
{
if (!real_realloc) {
init();
}
void* ret = real_realloc(ptr, size);
if (ret && !HandleGuard::inHandler && data) {
HandleGuard guard;
if (ptr) {
data->handleFree(ptr);
}
data->handleMalloc(ret, size);
}
return ret;
}
void* calloc(size_t num, size_t size)
{
if (!real_calloc) {
init();
}
void* ret = real_calloc(num, size);
if (ret && !HandleGuard::inHandler && data) {
HandleGuard guard;
data->handleMalloc(ret, num*size);
}
return ret;
}
int posix_memalign(void **memptr, size_t alignment, size_t size)
{
if (!real_posix_memalign) {
init();
}
int ret = real_posix_memalign(memptr, alignment, size);
if (ret && !HandleGuard::inHandler && data) {
HandleGuard guard;
data->handleMalloc(*memptr, size);
}
return ret;
}
void* aligned_alloc(size_t alignment, size_t size)
{
if (!real_aligned_alloc) {
init();
}
void* ret = real_aligned_alloc(alignment, size);
if (ret && !HandleGuard::inHandler && data) {
HandleGuard guard;
data->handleMalloc(ret, size);
}
return ret;
}
void* valloc(size_t size)
{
if (!real_valloc) {
init();
}
void* ret = real_valloc(size);
if (ret && !HandleGuard::inHandler && data) {
HandleGuard guard;
data->handleMalloc(ret, size);
}
return ret;
}
void *dlopen(const char *filename, int flag)
{
if (!real_dlopen) {
init();
}
void* ret = real_dlopen(filename, flag);
if (ret) {
moduleCacheDirty = true;
}
return ret;
}
int dlclose(void *handle)
{
if (!real_dlclose) {
init();
}
int ret = real_dlclose(handle);
if (!ret) {
moduleCacheDirty = true;
}
return ret;
}
}
<|endoftext|> |
<commit_before><commit_msg>ULTRA RAINBOW SUPERSONIC THREEDEE (u aint never seen nuthin like dis<commit_after><|endoftext|> |
<commit_before>#include "VersatileFile.h"
VersatileFile::VersatileFile(const QString& file_name)
: file_name_(file_name)
{
if (!isLocal())
{
socket_ = new QSslSocket();
socket_->setSocketOption(QAbstractSocket::KeepAliveOption, 1);
server_path_ = getServerPath();
host_name_ = getHostName();
server_port_ = getPortNumber();
file_size_ = getFileSize();
}
}
VersatileFile::~VersatileFile()
{
}
bool VersatileFile::open(QIODevice::OpenMode mode)
{
if (isLocal())
{
local_source_ = QSharedPointer<QFile>(new QFile(file_name_));
local_source_.data()->open(mode);
return local_source_.data()->isOpen();
}
cursor_position_ = 0;
remote_source_ = QSharedPointer<QSslSocket>(socket_);
remote_source_.data()->open(mode);
return remote_source_.data()->isOpen();
}
bool VersatileFile::open(FILE* f, QIODevice::OpenMode ioFlags)
{
if (isLocal())
{
local_source_ = QSharedPointer<QFile>(new QFile(file_name_));
local_source_.data()->open(f, ioFlags);
return local_source_.data()->isOpen();
}
return false;
}
QIODevice::OpenMode VersatileFile::openMode() const
{
if (isLocal()) return local_source_.data()->openMode();
return remote_source_.data()->openMode();
}
bool VersatileFile::isOpen() const
{
if (isLocal()) return local_source_.data()->isOpen();
return remote_source_.data()->isOpen();
}
bool VersatileFile::isReadable() const
{
checkIfOpen();
if (isLocal()) return local_source_.data()->isReadable();
return remote_source_.data()->isReadable();
}
QByteArray VersatileFile::readAll()
{
checkIfOpen();
if (isLocal()) return local_source_.data()->readAll();
return readResponseWithoutHeaders();
}
QByteArray VersatileFile::readLine(qint64 maxlen)
{
checkIfOpen();
if (isLocal()) return local_source_.data()->readLine(maxlen);
return readLineWithoutHeaders();
}
bool VersatileFile::atEnd() const
{
checkIfOpen();
if (isLocal()) return local_source_.data()->atEnd();
return (cursor_position_ >= file_size_);
}
bool VersatileFile::exists()
{
if (!local_source_.isNull()) return local_source_.data()->exists();
return (file_size_ > 0);
}
void VersatileFile::close()
{
if (!local_source_.isNull())
{
if (local_source_.data()->isOpen()) local_source_.data()->close();
}
if (!remote_source_.isNull())
{
if (remote_source_.data()->isOpen()) remote_source_.data()->close();
}
}
qint64 VersatileFile::pos() const
{
checkIfOpen();
if (isLocal()) return local_source_.data()->pos();
return cursor_position_;
}
qint64 VersatileFile::size() const
{
checkIfOpen();
if (isLocal()) return local_source_.data()->size();
return file_size_;
}
QString VersatileFile::fileName() const
{
return file_name_;
}
void VersatileFile::checkIfOpen() const
{
if (isLocal())
{
if (local_source_.isNull()) THROW(FileAccessException, "Local file is not set!");
if (!local_source_.data()->isOpen()) THROW(FileAccessException, "Local file is not open!");
}
else
{
if (remote_source_.isNull()) THROW(FileAccessException, "Remote file is not set!");
if (!remote_source_.data()->isOpen()) THROW(FileAccessException, "Remote file is not open!");
}
}
bool VersatileFile::isLocal() const
{
return (!file_name_.startsWith("http", Qt::CaseInsensitive));
}
QString VersatileFile::getServerPath()
{
QString server_path = file_name_;
server_path = server_path.replace("https://", "", Qt::CaseInsensitive);
QList<QString> parts = server_path.split("/");
if (parts.size() < 2) server_path = server_path.replace(parts.takeFirst(), "", Qt::CaseInsensitive);
return server_path;
}
QString VersatileFile::getHostName()
{
QString host_name = file_name_;
host_name = host_name.replace("https://", "", Qt::CaseInsensitive);
QList<QString> url_parts = host_name.split("/");
if (url_parts.size() > 1) host_name = url_parts.takeFirst();
QList<QString> host_name_parts = host_name.split(":");
if (host_name_parts.size()>1) host_name = host_name_parts.takeFirst();
return host_name;
}
quint16 VersatileFile::getPortNumber()
{
qint16 port_number = 443; // default HTTPS port
QString host_name = file_name_;
host_name = host_name.replace("https://", "", Qt::CaseInsensitive);
QList<QString> url_parts = host_name.split("/");
if (url_parts.size() > 1) host_name = url_parts.takeFirst();
QList<QString> host_name_parts = host_name.split(":");
if (host_name_parts.size()>1) port_number = host_name_parts.takeLast().toInt();
return port_number;
}
QByteArray VersatileFile::createHeadRequestText()
{
QByteArray payload;
payload.append("HEAD ");
payload.append(server_path_);
payload.append(" HTTP/1.1\r\n");
payload.append("Host: ");
payload.append(host_name_ + ":");
payload.append(server_port_);
payload.append("\r\n");
payload.append("Connection: keep-alive\r\n");
payload.append("\r\n");
return payload;
}
QByteArray VersatileFile::createGetRequestText()
{
QByteArray payload;
payload.append("GET ");
payload.append(server_path_);
payload.append(" HTTP/1.1\r\n");
payload.append("Host: ");
payload.append(host_name_ + ":");
payload.append(server_port_);
payload.append("\r\n");
payload.append("Connection: keep-alive\r\n");
payload.append("\r\n");
return payload;
}
void VersatileFile::initiateRequest(const QByteArray& http_request)
{
socket_->connectToHostEncrypted(host_name_, server_port_);
socket_->ignoreSslErrors();
socket_->waitForConnected();
socket_->waitForEncrypted();
socket_->open(QIODevice::ReadWrite);
socket_->write(http_request);
socket_->flush();
socket_->waitForBytesWritten();
}
QByteArray VersatileFile::readAllViaSocket(const QByteArray& http_request)
{
if (socket_->state() != QSslSocket::SocketState::ConnectedState)
{
initiateRequest(http_request);
}
QByteArray response;
while(socket_->waitForReadyRead())
{
while(socket_->bytesAvailable())
{
response.append(socket_->readAll());
cursor_position_ = response.length();
}
}
return response;
}
QByteArray VersatileFile::readLineViaSocket(const QByteArray& http_request, qint64 maxlen)
{
if (buffer_.size() > 0)
{
QByteArray result_line = buffer_.first();
buffer_.removeFirst();
cursor_position_ = cursor_position_ + result_line.length();
return result_line;
}
if (socket_->state() != QSslSocket::SocketState::ConnectedState)
{
initiateRequest(http_request);
bool found_headers = false;
while(socket_->waitForReadyRead())
{
while(socket_->bytesAvailable())
{
QString line = socket_->readLine(maxlen);
if (line.trimmed().length() == 0)
{
found_headers = true;
break;
}
}
if (found_headers) break;
}
}
QByteArray result_line;
bool found_line = false;
while((socket_->waitForReadyRead()) || (socket_->bytesAvailable()))
{
if (socket_->canReadLine())
{
found_line = true;
result_line = socket_->readLine(maxlen);
cursor_position_ = cursor_position_ + result_line.length();
}
if(socket_->bytesAvailable())
{
while (socket_->canReadLine())
{
buffer_.append(socket_->readLine(maxlen));
}
}
if (found_line)
{
return result_line;
}
}
return "";
}
qint64 VersatileFile::getFileSize()
{
QByteArray response = readAllViaSocket(createHeadRequestText());
cursor_position_ = 0;
QTextStream stream(response);
while(!stream.atEnd())
{
QString line = stream.readLine();
if (line.startsWith("Content-Length", Qt::CaseInsensitive))
{
QList<QString> parts = line.split(":");
if (parts.size() > 1) return parts.takeLast().trimmed().toLongLong();
}
}
return 0;
}
QByteArray VersatileFile::readResponseWithoutHeaders()
{
QByteArray response = readAllViaSocket(createGetRequestText());
QTextStream stream(response);
qint64 pos = 0;
while(!stream.atEnd())
{
QString line = stream.readLine();
pos = pos + line.length() ; // end of line characters (\r\n) separate headers from the body
if (line.length() == 0)
{
break;
}
}
return response.mid(pos);
}
QByteArray VersatileFile::readLineWithoutHeaders(qint64 maxlen)
{
QByteArray response = readLineViaSocket(createGetRequestText(), maxlen);
return response;
}
<commit_msg>Fixed reading after the end of file issue<commit_after>#include "VersatileFile.h"
VersatileFile::VersatileFile(const QString& file_name)
: file_name_(file_name)
{
if (!isLocal())
{
socket_ = new QSslSocket();
socket_->setSocketOption(QAbstractSocket::KeepAliveOption, 1);
server_path_ = getServerPath();
host_name_ = getHostName();
server_port_ = getPortNumber();
file_size_ = getFileSize();
}
}
VersatileFile::~VersatileFile()
{
}
bool VersatileFile::open(QIODevice::OpenMode mode)
{
if (isLocal())
{
local_source_ = QSharedPointer<QFile>(new QFile(file_name_));
local_source_.data()->open(mode);
return local_source_.data()->isOpen();
}
cursor_position_ = 0;
remote_source_ = QSharedPointer<QSslSocket>(socket_);
remote_source_.data()->open(mode);
return remote_source_.data()->isOpen();
}
bool VersatileFile::open(FILE* f, QIODevice::OpenMode ioFlags)
{
if (isLocal())
{
local_source_ = QSharedPointer<QFile>(new QFile(file_name_));
local_source_.data()->open(f, ioFlags);
return local_source_.data()->isOpen();
}
return false;
}
QIODevice::OpenMode VersatileFile::openMode() const
{
if (isLocal()) return local_source_.data()->openMode();
return remote_source_.data()->openMode();
}
bool VersatileFile::isOpen() const
{
if (isLocal()) return local_source_.data()->isOpen();
return remote_source_.data()->isOpen();
}
bool VersatileFile::isReadable() const
{
checkIfOpen();
if (isLocal()) return local_source_.data()->isReadable();
return remote_source_.data()->isReadable();
}
QByteArray VersatileFile::readAll()
{
checkIfOpen();
if (isLocal()) return local_source_.data()->readAll();
return readResponseWithoutHeaders();
}
QByteArray VersatileFile::readLine(qint64 maxlen)
{
checkIfOpen();
if (isLocal()) return local_source_.data()->readLine(maxlen);
return readLineWithoutHeaders();
}
bool VersatileFile::atEnd() const
{
checkIfOpen();
if (isLocal()) return local_source_.data()->atEnd();
return (cursor_position_ >= file_size_);
}
bool VersatileFile::exists()
{
if (!local_source_.isNull()) return local_source_.data()->exists();
return (file_size_ > 0);
}
void VersatileFile::close()
{
if (!local_source_.isNull())
{
if (local_source_.data()->isOpen()) local_source_.data()->close();
}
if (!remote_source_.isNull())
{
if (remote_source_.data()->isOpen()) remote_source_.data()->close();
}
}
qint64 VersatileFile::pos() const
{
checkIfOpen();
if (isLocal()) return local_source_.data()->pos();
return cursor_position_;
}
qint64 VersatileFile::size() const
{
checkIfOpen();
if (isLocal()) return local_source_.data()->size();
return file_size_;
}
QString VersatileFile::fileName() const
{
return file_name_;
}
void VersatileFile::checkIfOpen() const
{
if (isLocal())
{
if (local_source_.isNull()) THROW(FileAccessException, "Local file is not set!");
if (!local_source_.data()->isOpen()) THROW(FileAccessException, "Local file is not open!");
}
else
{
if (remote_source_.isNull()) THROW(FileAccessException, "Remote file is not set!");
if (!remote_source_.data()->isOpen()) THROW(FileAccessException, "Remote file is not open!");
}
}
bool VersatileFile::isLocal() const
{
return (!file_name_.startsWith("http", Qt::CaseInsensitive));
}
QString VersatileFile::getServerPath()
{
QString server_path = file_name_;
server_path = server_path.replace("https://", "", Qt::CaseInsensitive);
QList<QString> parts = server_path.split("/");
if (parts.size() < 2) server_path = server_path.replace(parts.takeFirst(), "", Qt::CaseInsensitive);
return server_path;
}
QString VersatileFile::getHostName()
{
QString host_name = file_name_;
host_name = host_name.replace("https://", "", Qt::CaseInsensitive);
QList<QString> url_parts = host_name.split("/");
if (url_parts.size() > 1) host_name = url_parts.takeFirst();
QList<QString> host_name_parts = host_name.split(":");
if (host_name_parts.size()>1) host_name = host_name_parts.takeFirst();
return host_name;
}
quint16 VersatileFile::getPortNumber()
{
qint16 port_number = 443; // default HTTPS port
QString host_name = file_name_;
host_name = host_name.replace("https://", "", Qt::CaseInsensitive);
QList<QString> url_parts = host_name.split("/");
if (url_parts.size() > 1) host_name = url_parts.takeFirst();
QList<QString> host_name_parts = host_name.split(":");
if (host_name_parts.size()>1) port_number = host_name_parts.takeLast().toInt();
return port_number;
}
QByteArray VersatileFile::createHeadRequestText()
{
QByteArray payload;
payload.append("HEAD ");
payload.append(server_path_);
payload.append(" HTTP/1.1\r\n");
payload.append("Host: ");
payload.append(host_name_ + ":");
payload.append(server_port_);
payload.append("\r\n");
payload.append("Connection: keep-alive\r\n");
payload.append("\r\n");
return payload;
}
QByteArray VersatileFile::createGetRequestText()
{
QByteArray payload;
payload.append("GET ");
payload.append(server_path_);
payload.append(" HTTP/1.1\r\n");
payload.append("Host: ");
payload.append(host_name_ + ":");
payload.append(server_port_);
payload.append("\r\n");
payload.append("Connection: keep-alive\r\n");
payload.append("\r\n");
return payload;
}
void VersatileFile::initiateRequest(const QByteArray& http_request)
{
socket_->connectToHostEncrypted(host_name_, server_port_);
socket_->ignoreSslErrors();
socket_->waitForConnected();
socket_->waitForEncrypted();
socket_->open(QIODevice::ReadWrite);
socket_->write(http_request);
socket_->flush();
socket_->waitForBytesWritten();
}
QByteArray VersatileFile::readAllViaSocket(const QByteArray& http_request)
{
if (socket_->state() != QSslSocket::SocketState::ConnectedState)
{
initiateRequest(http_request);
}
QByteArray response;
while(socket_->waitForReadyRead())
{
while(socket_->bytesAvailable())
{
response.append(socket_->readAll());
cursor_position_ = response.length();
}
}
return response;
}
QByteArray VersatileFile::readLineViaSocket(const QByteArray& http_request, qint64 maxlen)
{
if (this->atEnd()) return "";
if (buffer_.size() > 0)
{
QByteArray result_line = buffer_.first();
buffer_.removeFirst();
cursor_position_ = cursor_position_ + result_line.length();
return result_line;
}
if (socket_->state() != QSslSocket::SocketState::ConnectedState)
{
initiateRequest(http_request);
bool found_headers = false;
while(socket_->waitForReadyRead())
{
while(socket_->bytesAvailable())
{
QString line = socket_->readLine(maxlen);
if (line.trimmed().length() == 0)
{
found_headers = true;
break;
}
}
if (found_headers) break;
}
}
QByteArray result_line;
bool found_line = false;
while((socket_->waitForReadyRead()) || (socket_->bytesAvailable()))
{
if (socket_->canReadLine())
{
found_line = true;
result_line = socket_->readLine(maxlen);
cursor_position_ = cursor_position_ + result_line.length();
}
if(socket_->bytesAvailable())
{
while (socket_->canReadLine())
{
buffer_.append(socket_->readLine(maxlen));
}
}
if (found_line)
{
return result_line;
}
}
return "";
}
qint64 VersatileFile::getFileSize()
{
QByteArray response = readAllViaSocket(createHeadRequestText());
cursor_position_ = 0;
QTextStream stream(response);
while(!stream.atEnd())
{
QString line = stream.readLine();
if (line.startsWith("Content-Length", Qt::CaseInsensitive))
{
QList<QString> parts = line.split(":");
if (parts.size() > 1) return parts.takeLast().trimmed().toLongLong();
}
}
return 0;
}
QByteArray VersatileFile::readResponseWithoutHeaders()
{
QByteArray response = readAllViaSocket(createGetRequestText());
QTextStream stream(response);
qint64 pos = 0;
while(!stream.atEnd())
{
QString line = stream.readLine();
pos = pos + line.length() ; // end of line characters (\r\n) separate headers from the body
if (line.length() == 0)
{
break;
}
}
return response.mid(pos);
}
QByteArray VersatileFile::readLineWithoutHeaders(qint64 maxlen)
{
QByteArray response = readLineViaSocket(createGetRequestText(), maxlen);
return response;
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2010, Arvid Norberg
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 author 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 "libtorrent/storage.hpp"
#include "libtorrent/file_pool.hpp"
#include <boost/utility.hpp>
#include <stdlib.h>
using namespace libtorrent;
int main(int argc, char* argv[])
{
if (argc != 3 && argc != 2)
{
fprintf(stderr, "Usage: fragmentation_test torrent-file file-storage-path\n"
" fragmentation_test file\n\n");
return 1;
}
if (argc == 2)
{
error_code ec;
file f(argv[1], file::read_only, ec);
if (ec)
{
fprintf(stderr, "Error opening file %s: %s\n", argv[1], ec.message().c_str());
return 1;
}
size_type off = f.phys_offset(0);
printf("physical offset of file %s: %" PRId64 "\n", argv[1], off);
return 0;
}
error_code ec;
boost::intrusive_ptr<torrent_info> ti(new torrent_info(argv[1], ec));
if (ec)
{
fprintf(stderr, "Error while loading torrent file: %s\n", ec.message().c_str());
return 1;
}
file_pool fp;
boost::shared_ptr<storage_interface> st(default_storage_constructor(ti->files(), 0, argv[2], fp, std::vector<boost::uint8_t>()));
// the first field is the piece index, the second
// one is the physical location of the piece on disk
std::vector<std::pair<int, size_type> > pieces;
// make sure all the files are there
std::vector<std::pair<size_type, std::time_t> > files = get_filesizes(ti->files(), argv[2]);
for (int i = 0; i < ti->num_files(); ++i)
{
if (ti->file_at(i).size == files[i].first) continue;
fprintf(stderr, "Files for this torrent are missing or incomplete: %s was %"PRId64" bytes, expected %"PRId64" bytes\n"
, ti->files().file_path(ti->file_at(i)).c_str(), files[i].first, ti->file_at(i).size);
return 1;
}
for (int i = 0; i < ti->num_pieces(); ++i)
{
pieces.push_back(std::make_pair(i, st->physical_offset(i, 0)));
if (pieces.back().second == size_type(i) * ti->piece_length())
{
// this suggests that the OS doesn't support physical offset
// or that the file doesn't exist, or some other file error
fprintf(stderr, "Your operating system or filesystem "
"does not appear to support querying physical disk offset\n");
return 1;
}
}
FILE* f = fopen("fragmentation.log", "w+");
if (f == 0)
{
fprintf(stderr, "error while opening log file: %s\n", strerror(errno));
return 1;
}
for (int i = 0; i < ti->num_pieces(); ++i)
{
fprintf(f, "%d %"PRId64"\n", pieces[i].first, pieces[i].second);
}
fclose(f);
f = fopen("fragmentation.gnuplot", "w+");
if (f == 0)
{
fprintf(stderr, "error while opening gnuplot file: %s\n", strerror(errno));
return 1;
}
fprintf(f,
"set term png size 1200,800\n"
"set output \"fragmentation.png\"\n"
"set xrange [*:*]\n"
"set xlabel \"piece\"\n"
"set ylabel \"drive offset\"\n"
"set key box\n"
"set title \"fragmentation for '%s'\"\n"
"set tics nomirror\n"
"plot \"fragmentation.log\" using 1:2 with dots lt rgb \"#e07070\" notitle axis x1y1, x=0\n"
, ti->name().c_str());
fclose(f);
system("gnuplot fragmentation.gnuplot");
}
<commit_msg>fix gnuplot syntax error in fragmentation test<commit_after>/*
Copyright (c) 2010, Arvid Norberg
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 author 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 "libtorrent/storage.hpp"
#include "libtorrent/file_pool.hpp"
#include <boost/utility.hpp>
#include <stdlib.h>
using namespace libtorrent;
int main(int argc, char* argv[])
{
if (argc != 3 && argc != 2)
{
fprintf(stderr, "Usage: fragmentation_test torrent-file file-storage-path\n"
" fragmentation_test file\n\n");
return 1;
}
if (argc == 2)
{
error_code ec;
file f(argv[1], file::read_only, ec);
if (ec)
{
fprintf(stderr, "Error opening file %s: %s\n", argv[1], ec.message().c_str());
return 1;
}
size_type off = f.phys_offset(0);
printf("physical offset of file %s: %" PRId64 "\n", argv[1], off);
return 0;
}
error_code ec;
boost::intrusive_ptr<torrent_info> ti(new torrent_info(argv[1], ec));
if (ec)
{
fprintf(stderr, "Error while loading torrent file: %s\n", ec.message().c_str());
return 1;
}
file_pool fp;
boost::shared_ptr<storage_interface> st(default_storage_constructor(ti->files(), 0, argv[2], fp, std::vector<boost::uint8_t>()));
// the first field is the piece index, the second
// one is the physical location of the piece on disk
std::vector<std::pair<int, size_type> > pieces;
// make sure all the files are there
std::vector<std::pair<size_type, std::time_t> > files = get_filesizes(ti->files(), argv[2]);
for (int i = 0; i < ti->num_files(); ++i)
{
if (ti->file_at(i).size == files[i].first) continue;
fprintf(stderr, "Files for this torrent are missing or incomplete: %s was %"PRId64" bytes, expected %"PRId64" bytes\n"
, ti->files().file_path(ti->file_at(i)).c_str(), files[i].first, ti->file_at(i).size);
return 1;
}
for (int i = 0; i < ti->num_pieces(); ++i)
{
pieces.push_back(std::make_pair(i, st->physical_offset(i, 0)));
if (pieces.back().second == size_type(i) * ti->piece_length())
{
// this suggests that the OS doesn't support physical offset
// or that the file doesn't exist, or some other file error
fprintf(stderr, "Your operating system or filesystem "
"does not appear to support querying physical disk offset\n");
return 1;
}
}
FILE* f = fopen("fragmentation.log", "w+");
if (f == 0)
{
fprintf(stderr, "error while opening log file: %s\n", strerror(errno));
return 1;
}
for (int i = 0; i < ti->num_pieces(); ++i)
{
fprintf(f, "%d %"PRId64"\n", pieces[i].first, pieces[i].second);
}
fclose(f);
f = fopen("fragmentation.gnuplot", "w+");
if (f == 0)
{
fprintf(stderr, "error while opening gnuplot file: %s\n", strerror(errno));
return 1;
}
fprintf(f,
"set term png size 1200,800\n"
"set output \"fragmentation.png\"\n"
"set xrange [*:*]\n"
"set xlabel \"piece\"\n"
"set ylabel \"drive offset\"\n"
"set key box\n"
"set title \"fragmentation for '%s'\"\n"
"set tics nomirror\n"
"plot \"fragmentation.log\" using 1:2 with dots lt rgb \"#e07070\" notitle axis x1y1\n"
, ti->name().c_str());
fclose(f);
system("gnuplot fragmentation.gnuplot");
}
<|endoftext|> |
<commit_before>/*
Safety Framework for Component-based Robotics
Created on: August 13, 2012
Copyright (C) 2012-2013 Min Yang Jung, Peter Kazanzides
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#include "config.h"
#include "common.h"
#include "json.h"
#include "monitor.h"
#include "cisstMonitor.h"
#include "cisstEventLocation.h"
#include <cisstCommon/cmnGetChar.h>
#include <cisstOSAbstraction/osaSleep.h>
#include <cisstMultiTask/mtsCollectorState.h>
#include <cisstMultiTask/mtsTaskPeriodic.h>
#include <cisstMultiTask/mtsTaskManager.h>
#include <cisstMultiTask/mtsInterfaceProvided.h>
#include <cisstMultiTask/mtsFixedSizeVectorTypes.h>
#if (CISST_OS == CISST_LINUX_XENOMAI)
#include <sys/mman.h>
#endif
using namespace SF;
class PeriodicTask: public mtsTaskPeriodic {
protected:
//double SleepDuration;
//mtsDouble SleepDuration;
//mtsDouble2 SleepDuration;
vctDoubleVec SleepDuration;
mtsDouble d0;
mtsDouble1 d1;
mtsDouble2 d2;
mtsInt i;
mtsInt1 i1;
mtsInt2 i2;
mtsVctDoubleVec vd;
mtsVctIntVec vi;
mtsVct3 v3;
mtsVct3 v5;
public:
PeriodicTask(const std::string & name, double period) :
mtsTaskPeriodic(name, period, false, 5000)
{
//SleepDuration = 10.0;
//SleepDuration(0) = 100.0;
//SleepDuration(1) = 1000.0;
SleepDuration.SetSize(5);
StateTable.AddData(SleepDuration, "SleepDuration");
#if 0
StateTable.AddData(d0, "SleepDuration");
StateTable.AddData(d1, "SleepDuration");
StateTable.AddData(d2, "SleepDuration");
StateTable.AddData(i, "SleepDuration");
StateTable.AddData(i1, "SleepDuration");
StateTable.AddData(i2, "SleepDuration");
StateTable.AddData(vd, "SleepDuration");
StateTable.AddData(vi, "SleepDuration");
StateTable.AddData(v3, "SleepDuration");
StateTable.AddData(v5, "SleepDuration");
#endif
mtsInterfaceProvided * provided = AddInterfaceProvided("CustomInterface");
if (provided) {
provided->AddCommandReadState(StateTable, SleepDuration, "SleepDuration");
}
}
~PeriodicTask() {}
void Configure(const std::string & CMN_UNUSED(filename) = "") {}
void Startup(void) {}
void Run(void) {
ProcessQueuedCommands();
ProcessQueuedEvents();
//std::cout << "." << std::flush;
/*
static int count = 0;
if (count++ % 10 == 0) {
this->GenerateFaultEvent(std::string("MY FAULT EVENT"));
}
*/
static double T = (1.0 / this->Period) * 60.0 * 60.0;
static int i = 0;
//SleepDuration = this->Period * (0.8 * sin(2 * cmnPI * ((double) ++i / T)));
//osaSleep(SleepDuration);
//SleepDuration(0) += 0.1;
//SleepDuration(1) += 0.1;
//SleepDuration += 0.2;
SleepDuration(0) += 0.1;
SleepDuration(1) += 0.2;
SleepDuration(2) += 0.3;
SleepDuration(3) += 0.4;
SleepDuration(4) += 0.5;
}
void Cleanup(void) {}
};
// Create periodic task
bool CreatePeriodicThread(const std::string & componentName, double period);
// to monitor values in real-time
bool InstallMonitor(const std::string & targetComponentName, unsigned int frequency);
// Local component manager
mtsManagerLocal * ComponentManager = 0;
// Test periodic task
PeriodicTask * task = 0;
int main(int argc, char *argv[])
{
#if SF_USE_G2LOG
// Logger setup
g2LogWorker logger(argv[0], "./");
g2::initializeLogging(&logger);
std::cout << "Log file: \"" << logger.logFileName() << "\"\n" << std::endl;
#endif
cmnLogger::SetMask(CMN_LOG_ALLOW_ALL);
cmnLogger::SetMaskFunction(CMN_LOG_ALLOW_ALL);
cmnLogger::SetMaskDefaultLog(CMN_LOG_ALLOW_ALL);
//cmnLogger::AddChannel(std::cout, CMN_LOG_ALLOW_ERRORS_AND_WARNINGS);
cmnLogger::AddChannel(std::cout, CMN_LOG_ALLOW_ALL);
cmnLogger::SetMaskClassMatching("mtsSafetyCoordinator", CMN_LOG_ALLOW_ALL);
cmnLogger::SetMaskClassMatching("mtsMonitorComponent", CMN_LOG_ALLOW_ALL);
// Get instance of the cisst Component Manager
mtsComponentManager::InstallSafetyCoordinator();
try {
ComponentManager = mtsComponentManager::GetInstance();
} catch (...) {
SFLOG_ERROR << "Failed to initialize local component manager" << std::endl;
return 1;
}
// Print information about middleware(s) available
StrVecType info;
GetMiddlewareInfo(info);
std::cout << "Middleware(s) detected: ";
if (info.size() == 0) {
std::cout << "none" << std::endl;
} else {
std::cout << std::endl;
for (size_t i = 0; i < info.size(); ++i) {
std::cout << "[" << (i+1) << "] " << info[i] << std::endl;
}
}
std::cout << std::endl;
// Create five test components with different T
std::vector<unsigned int> f; // Hz
#if 0
f.push_back(1);
f.push_back(2);
f.push_back(5);
f.push_back(10);
f.push_back(20);
f.push_back(50);
f.push_back(100);
f.push_back(200);
f.push_back(500);
#endif
f.push_back(1);
std::string componentName;
std::stringstream ss;
for (size_t i = 0; i < f.size(); ++i) {
ss.str("");
ss << "Component" << f[i];
componentName = ss.str();
// Create periodic task
if (!CreatePeriodicThread(componentName, 1.0 / (double)f[i])) {
SFLOG_ERROR << "Failed to add periodic component \"" << componentName << "\"" << std::endl;
return 1;
}
// Install monitor
if (!InstallMonitor(componentName, f[i])) {
SFLOG_ERROR << "Failed to install monitor for periodic component \"" << componentName << "\"" << std::endl;
return 1;
}
}
if (ComponentManager->GetCoordinator()) {
if (!ComponentManager->GetCoordinator()->DeployMonitorsAndFDDs()) {
SFLOG_ERROR << "Failed to deploy monitors and FDDs" << std::endl;
return 1;
}
} else {
SFLOG_ERROR << "Failed to get coordinator in this process";
return 1;
}
// Create and run all components
ComponentManager->CreateAll();
ComponentManager->WaitForStateAll(mtsComponentState::READY);
ComponentManager->StartAll();
ComponentManager->WaitForStateAll(mtsComponentState::ACTIVE);
std::cout << "Press 'q' to quit or click CLOSE button of the visualizer." << std::endl;
std::cout << "Running periodic tasks ";
// loop until 'q' is pressed
int key = ' ';
while (key != 'q') {
key = cmnGetChar();
osaSleep(100 * cmn_ms);
}
std::cout << std::endl;
// Clean up resources
SFLOG_INFO << "Cleaning up..." << std::endl;
#if (CISST_OS != CISST_LINUX_XENOMAI)
ComponentManager->KillAll();
ComponentManager->WaitForStateAll(mtsComponentState::FINISHED, 2.0 * cmn_s);
#endif
ComponentManager->Cleanup();
return 0;
}
// Create periodic thread
bool CreatePeriodicThread(const std::string & componentName, double period)
{
// Create periodic thread
task = new PeriodicTask(componentName, period);
if (!ComponentManager->AddComponent(task)) {
SFLOG_ERROR << "Failed to add component \"" << componentName << "\"" << std::endl;
return false;
}
return true;
}
bool InstallMonitor(const std::string & targetComponentName, unsigned int frequency)
{
mtsSafetyCoordinator * coordinator = ComponentManager->GetCoordinator();
if (!coordinator) {
SFLOG_ERROR << "Failed to get coordinator in this process";
return false;
}
// Define target
#if 0
cisstEventLocation * locationID = new cisstEventLocation;
locationID->SetProcessName(ComponentManager->GetProcessName());
locationID->SetComponentName(targetComponentName);
cisstMonitor * monitor;
// Install monitor for timing fault - period
monitor = new cisstMonitor(Monitor::TARGET_THREAD_PERIOD,
locationID,
Monitor::STATE_ON,
Monitor::OUTPUT_STREAM,
frequency);
// MJ TODO: Run system for a few minutes, collect experimental data,
// and determine variance of period with upper/lower limits and thresholds.
if (!coordinator->AddMonitorTarget(monitor)) {
SFLOG_ERROR << "Failed to add new monitor target for component \"" << targetComponentName << "\"" << std::endl;
SFLOG_ERROR << "JSON: " << monitor->GetMonitorJSON() << std::endl;
return false;
}
SFLOG_INFO << "Successfully added monitor target: " << *monitor << std::endl;
// Install monitor for execution time (user)
monitor = new cisstMonitor(Monitor::TARGET_THREAD_DUTYCYCLE_USER,
locationID,
Monitor::STATE_ON,
Monitor::OUTPUT_STREAM,
frequency);
if (!coordinator->AddMonitorTarget(monitor)) {
SFLOG_ERROR << "Failed to add new monitor target for component \"" << targetComponentName << "\"" << std::endl;
SFLOG_ERROR << "JSON: " << monitor->GetMonitorJSON() << std::endl;
return false;
}
SFLOG_INFO << "Successfully added monitor target: " << *monitor << std::endl;
// Install monitor for execution time (total)
monitor = new cisstMonitor(Monitor::TARGET_THREAD_DUTYCYCLE_TOTAL,
locationID,
Monitor::STATE_ON,
Monitor::OUTPUT_STREAM,
frequency);
if (!coordinator->AddMonitorTarget(monitor)) {
SFLOG_ERROR << "Failed to add new monitor target for component \"" << targetComponentName << "\"" << std::endl;
SFLOG_ERROR << "JSON: " << monitor->GetMonitorJSON() << std::endl;
return false;
}
SFLOG_INFO << "Successfully added monitor target: " << *monitor << std::endl;
#else
const std::string jsonFileName(SF_SOURCE_ROOT_DIR"/examples/monitor/monitor.json");
if (!coordinator->AddMonitorTargetFromJSONFile(jsonFileName)) {
SFLOG_ERROR << "Failed to load monitoring target file: \"" << jsonFileName << "\"" << std::endl;
return false;
}
#endif
return true;
}
<commit_msg>updated copyright<commit_after>//------------------------------------------------------------------------
//
// CASROS: Component-based Architecture for Safe Robotic Systems
//
// Copyright (C) 2012-2014 Min Yang Jung and Peter Kazanzides
//
//------------------------------------------------------------------------
//
// Created on : Aug 13, 2012
// Last revision: Apr 15, 2014
// Author : Min Yang Jung (myj@jhu.edu)
// Github : https://github.com/minyang/casros
//
#include "config.h"
#include "common.h"
#include "json.h"
#include "monitor.h"
#include "cisstMonitor.h"
#include "cisstEventLocation.h"
#include <cisstCommon/cmnGetChar.h>
#include <cisstOSAbstraction/osaSleep.h>
#include <cisstMultiTask/mtsCollectorState.h>
#include <cisstMultiTask/mtsTaskPeriodic.h>
#include <cisstMultiTask/mtsTaskManager.h>
#include <cisstMultiTask/mtsInterfaceProvided.h>
#include <cisstMultiTask/mtsFixedSizeVectorTypes.h>
#if (CISST_OS == CISST_LINUX_XENOMAI)
#include <sys/mman.h>
#endif
using namespace SF;
class PeriodicTask: public mtsTaskPeriodic {
protected:
//double SleepDuration;
//mtsDouble SleepDuration;
//mtsDouble2 SleepDuration;
vctDoubleVec SleepDuration;
mtsDouble d0;
mtsDouble1 d1;
mtsDouble2 d2;
mtsInt i;
mtsInt1 i1;
mtsInt2 i2;
mtsVctDoubleVec vd;
mtsVctIntVec vi;
mtsVct3 v3;
mtsVct3 v5;
public:
PeriodicTask(const std::string & name, double period) :
mtsTaskPeriodic(name, period, false, 5000)
{
//SleepDuration = 10.0;
//SleepDuration(0) = 100.0;
//SleepDuration(1) = 1000.0;
SleepDuration.SetSize(5);
StateTable.AddData(SleepDuration, "SleepDuration");
#if 0
StateTable.AddData(d0, "SleepDuration");
StateTable.AddData(d1, "SleepDuration");
StateTable.AddData(d2, "SleepDuration");
StateTable.AddData(i, "SleepDuration");
StateTable.AddData(i1, "SleepDuration");
StateTable.AddData(i2, "SleepDuration");
StateTable.AddData(vd, "SleepDuration");
StateTable.AddData(vi, "SleepDuration");
StateTable.AddData(v3, "SleepDuration");
StateTable.AddData(v5, "SleepDuration");
#endif
mtsInterfaceProvided * provided = AddInterfaceProvided("CustomInterface");
if (provided) {
provided->AddCommandReadState(StateTable, SleepDuration, "SleepDuration");
}
}
~PeriodicTask() {}
void Configure(const std::string & CMN_UNUSED(filename) = "") {}
void Startup(void) {}
void Run(void) {
ProcessQueuedCommands();
ProcessQueuedEvents();
//std::cout << "." << std::flush;
/*
static int count = 0;
if (count++ % 10 == 0) {
this->GenerateFaultEvent(std::string("MY FAULT EVENT"));
}
*/
static double T = (1.0 / this->Period) * 60.0 * 60.0;
static int i = 0;
//SleepDuration = this->Period * (0.8 * sin(2 * cmnPI * ((double) ++i / T)));
//osaSleep(SleepDuration);
//SleepDuration(0) += 0.1;
//SleepDuration(1) += 0.1;
//SleepDuration += 0.2;
SleepDuration(0) += 0.1;
SleepDuration(1) += 0.2;
SleepDuration(2) += 0.3;
SleepDuration(3) += 0.4;
SleepDuration(4) += 0.5;
}
void Cleanup(void) {}
};
// Create periodic task
bool CreatePeriodicThread(const std::string & componentName, double period);
// to monitor values in real-time
bool InstallMonitor(const std::string & targetComponentName, unsigned int frequency);
// Local component manager
mtsManagerLocal * ComponentManager = 0;
// Test periodic task
PeriodicTask * task = 0;
int main(int argc, char *argv[])
{
#if SF_USE_G2LOG
// Logger setup
g2LogWorker logger(argv[0], "./");
g2::initializeLogging(&logger);
std::cout << "Log file: \"" << logger.logFileName() << "\"\n" << std::endl;
#endif
cmnLogger::SetMask(CMN_LOG_ALLOW_ALL);
cmnLogger::SetMaskFunction(CMN_LOG_ALLOW_ALL);
cmnLogger::SetMaskDefaultLog(CMN_LOG_ALLOW_ALL);
//cmnLogger::AddChannel(std::cout, CMN_LOG_ALLOW_ERRORS_AND_WARNINGS);
cmnLogger::AddChannel(std::cout, CMN_LOG_ALLOW_ALL);
cmnLogger::SetMaskClassMatching("mtsSafetyCoordinator", CMN_LOG_ALLOW_ALL);
cmnLogger::SetMaskClassMatching("mtsMonitorComponent", CMN_LOG_ALLOW_ALL);
// Get instance of the cisst Component Manager
mtsComponentManager::InstallSafetyCoordinator();
try {
ComponentManager = mtsComponentManager::GetInstance();
} catch (...) {
SFLOG_ERROR << "Failed to initialize local component manager" << std::endl;
return 1;
}
// Print information about middleware(s) available
StrVecType info;
GetMiddlewareInfo(info);
std::cout << "Middleware(s) detected: ";
if (info.size() == 0) {
std::cout << "none" << std::endl;
} else {
std::cout << std::endl;
for (size_t i = 0; i < info.size(); ++i) {
std::cout << "[" << (i+1) << "] " << info[i] << std::endl;
}
}
std::cout << std::endl;
// Create five test components with different T
std::vector<unsigned int> f; // Hz
#if 0
f.push_back(1);
f.push_back(2);
f.push_back(5);
f.push_back(10);
f.push_back(20);
f.push_back(50);
f.push_back(100);
f.push_back(200);
f.push_back(500);
#endif
f.push_back(1);
std::string componentName;
std::stringstream ss;
for (size_t i = 0; i < f.size(); ++i) {
ss.str("");
ss << "Component" << f[i];
componentName = ss.str();
// Create periodic task
if (!CreatePeriodicThread(componentName, 1.0 / (double)f[i])) {
SFLOG_ERROR << "Failed to add periodic component \"" << componentName << "\"" << std::endl;
return 1;
}
// Install monitor
if (!InstallMonitor(componentName, f[i])) {
SFLOG_ERROR << "Failed to install monitor for periodic component \"" << componentName << "\"" << std::endl;
return 1;
}
}
if (ComponentManager->GetCoordinator()) {
if (!ComponentManager->GetCoordinator()->DeployMonitorsAndFDDs()) {
SFLOG_ERROR << "Failed to deploy monitors and FDDs" << std::endl;
return 1;
}
} else {
SFLOG_ERROR << "Failed to get coordinator in this process";
return 1;
}
// Create and run all components
ComponentManager->CreateAll();
ComponentManager->WaitForStateAll(mtsComponentState::READY);
ComponentManager->StartAll();
ComponentManager->WaitForStateAll(mtsComponentState::ACTIVE);
std::cout << "Press 'q' to quit or click CLOSE button of the visualizer." << std::endl;
std::cout << "Running periodic tasks ";
// loop until 'q' is pressed
int key = ' ';
while (key != 'q') {
key = cmnGetChar();
osaSleep(100 * cmn_ms);
}
std::cout << std::endl;
// Clean up resources
SFLOG_INFO << "Cleaning up..." << std::endl;
#if (CISST_OS != CISST_LINUX_XENOMAI)
ComponentManager->KillAll();
ComponentManager->WaitForStateAll(mtsComponentState::FINISHED, 2.0 * cmn_s);
#endif
ComponentManager->Cleanup();
return 0;
}
// Create periodic thread
bool CreatePeriodicThread(const std::string & componentName, double period)
{
// Create periodic thread
task = new PeriodicTask(componentName, period);
if (!ComponentManager->AddComponent(task)) {
SFLOG_ERROR << "Failed to add component \"" << componentName << "\"" << std::endl;
return false;
}
return true;
}
bool InstallMonitor(const std::string & targetComponentName, unsigned int frequency)
{
mtsSafetyCoordinator * coordinator = ComponentManager->GetCoordinator();
if (!coordinator) {
SFLOG_ERROR << "Failed to get coordinator in this process";
return false;
}
// Define target
#if 0
cisstEventLocation * locationID = new cisstEventLocation;
locationID->SetProcessName(ComponentManager->GetProcessName());
locationID->SetComponentName(targetComponentName);
cisstMonitor * monitor;
// Install monitor for timing fault - period
monitor = new cisstMonitor(Monitor::TARGET_THREAD_PERIOD,
locationID,
Monitor::STATE_ON,
Monitor::OUTPUT_STREAM,
frequency);
// MJ TODO: Run system for a few minutes, collect experimental data,
// and determine variance of period with upper/lower limits and thresholds.
if (!coordinator->AddMonitorTarget(monitor)) {
SFLOG_ERROR << "Failed to add new monitor target for component \"" << targetComponentName << "\"" << std::endl;
SFLOG_ERROR << "JSON: " << monitor->GetMonitorJSON() << std::endl;
return false;
}
SFLOG_INFO << "Successfully added monitor target: " << *monitor << std::endl;
// Install monitor for execution time (user)
monitor = new cisstMonitor(Monitor::TARGET_THREAD_DUTYCYCLE_USER,
locationID,
Monitor::STATE_ON,
Monitor::OUTPUT_STREAM,
frequency);
if (!coordinator->AddMonitorTarget(monitor)) {
SFLOG_ERROR << "Failed to add new monitor target for component \"" << targetComponentName << "\"" << std::endl;
SFLOG_ERROR << "JSON: " << monitor->GetMonitorJSON() << std::endl;
return false;
}
SFLOG_INFO << "Successfully added monitor target: " << *monitor << std::endl;
// Install monitor for execution time (total)
monitor = new cisstMonitor(Monitor::TARGET_THREAD_DUTYCYCLE_TOTAL,
locationID,
Monitor::STATE_ON,
Monitor::OUTPUT_STREAM,
frequency);
if (!coordinator->AddMonitorTarget(monitor)) {
SFLOG_ERROR << "Failed to add new monitor target for component \"" << targetComponentName << "\"" << std::endl;
SFLOG_ERROR << "JSON: " << monitor->GetMonitorJSON() << std::endl;
return false;
}
SFLOG_INFO << "Successfully added monitor target: " << *monitor << std::endl;
#else
const std::string jsonFileName(SF_SOURCE_ROOT_DIR"/examples/monitor/monitor.json");
if (!coordinator->AddMonitorTargetFromJSONFile(jsonFileName)) {
SFLOG_ERROR << "Failed to load monitoring target file: \"" << jsonFileName << "\"" << std::endl;
return false;
}
#endif
return true;
}
<|endoftext|> |
<commit_before>//------------------------------------------------------------------------
//
// CASROS: Component-based Architecture for Safe Robotic Systems
//
// Copyright (C) 2012-2014 Min Yang Jung and Peter Kazanzides
//
//------------------------------------------------------------------------
//
// Created on : Apr 22, 2014
// Last revision: Apr 22, 2014
// Author : Min Yang Jung (myj@jhu.edu)
// Github : https://github.com/minyang/casros
//
#include "gcm.h"
#include "config.h"
#include <cisstMultiTask/mtsComponent.h>
#include <cisstMultiTask/mtsManagerLocal.h>
namespace SF {
using namespace SF;
GCM::GCM(void) : ComponentName(NONAME)
{
// Default constructor should not be used
SFASSERT(false);
}
GCM::GCM(const std::string & componentName)
: ComponentName(componentName)
{
States.ComponentFramework = new StateMachine(componentName);
States.ComponentApplication = new StateMachine(componentName);
}
GCM::~GCM(void)
{
if (States.ComponentFramework)
delete States.ComponentFramework;
if (States.ComponentApplication)
delete States.ComponentApplication;
InterfaceStateMachinesType::iterator it;
while (!States.RequiredInterfaces.empty()) {
it = States.RequiredInterfaces.begin();
States.RequiredInterfaces.erase(it);
delete it->second;
}
while (!States.ProvidedInterfaces.empty()) {
it = States.ProvidedInterfaces.begin();
States.ProvidedInterfaces.erase(it);
delete it->second;
}
}
void GCM::ToStream(std::ostream & out) const
{
out << "Owner: " << this->ComponentName
<< std::endl;
}
bool GCM::AddInterface(const std::string & name, const GCM::InterfaceTypes type)
{
if (type == PROVIDED_INTERFACE) {
if (States.ProvidedInterfaces.find(name) != States.ProvidedInterfaces.end())
return false;
States.ProvidedInterfaces.insert(std::make_pair(name, new StateMachine(name)));
} else {
if (States.RequiredInterfaces.find(name) != States.RequiredInterfaces.end())
return false;
States.RequiredInterfaces.insert(std::make_pair(name, new StateMachine(name)));
}
return true;
}
bool GCM::FindInterface(const std::string & name, const GCM::InterfaceTypes type) const
{
if (type == PROVIDED_INTERFACE)
return (States.ProvidedInterfaces.find(name) != States.ProvidedInterfaces.end());
else
return (States.RequiredInterfaces.find(name) != States.RequiredInterfaces.end());
}
bool GCM::RemoveInterface(const std::string & name, const GCM::InterfaceTypes type)
{
InterfaceStateMachinesType::iterator it;
if (type == PROVIDED_INTERFACE) {
it = States.ProvidedInterfaces.find(name);
if (it == States.ProvidedInterfaces.end())
return false;
SFASSERT(it->second);
delete it->second;
States.ProvidedInterfaces.erase(it);
} else {
it = States.RequiredInterfaces.find(name);
if (it == States.RequiredInterfaces.end())
return false;
SFASSERT(it->second);
delete it->second;
States.RequiredInterfaces.erase(it);
}
return true;
}
void GCM::ProcessEvent_ComponentFramework(const SF::State::TransitionType transition)
{
// TODO
}
void GCM::ProcessEvent_ComponentApplication(const SF::State::TransitionType transition)
{
// TODO
}
void GCM::ProcessEvent_Interface(const SF::State::TransitionType transition)
{
// TODO
}
};
<commit_msg>added debug log to GCM<commit_after>//------------------------------------------------------------------------
//
// CASROS: Component-based Architecture for Safe Robotic Systems
//
// Copyright (C) 2012-2014 Min Yang Jung and Peter Kazanzides
//
//------------------------------------------------------------------------
//
// Created on : Apr 22, 2014
// Last revision: Apr 22, 2014
// Author : Min Yang Jung (myj@jhu.edu)
// Github : https://github.com/minyang/casros
//
#include "gcm.h"
#include "config.h"
#include <cisstMultiTask/mtsComponent.h>
#include <cisstMultiTask/mtsManagerLocal.h>
namespace SF {
using namespace SF;
GCM::GCM(void) : ComponentName(NONAME)
{
// Default constructor should not be used
SFASSERT(false);
}
GCM::GCM(const std::string & componentName)
: ComponentName(componentName)
{
States.ComponentFramework = new StateMachine(componentName);
States.ComponentApplication = new StateMachine(componentName);
}
GCM::~GCM(void)
{
if (States.ComponentFramework)
delete States.ComponentFramework;
if (States.ComponentApplication)
delete States.ComponentApplication;
InterfaceStateMachinesType::iterator it;
while (!States.RequiredInterfaces.empty()) {
it = States.RequiredInterfaces.begin();
States.RequiredInterfaces.erase(it);
delete it->second;
}
while (!States.ProvidedInterfaces.empty()) {
it = States.ProvidedInterfaces.begin();
States.ProvidedInterfaces.erase(it);
delete it->second;
}
}
void GCM::ToStream(std::ostream & out) const
{
out << "Owner component: " << this->ComponentName << std::endl;
out << "Required interfaces: ";
InterfaceStateMachinesType::const_iterator it = States.RequiredInterfaces.begin();
for (; it != States.RequiredInterfaces.end(); ++it)
out << "\"" << it->first << "\" ";
out << std::endl;
out << "Provided interfaces: ";
it = States.ProvidedInterfaces.begin();
for (; it != States.ProvidedInterfaces.end(); ++it)
out << "\"" << it->first << "\" ";
out << std::endl;
}
bool GCM::AddInterface(const std::string & name, const GCM::InterfaceTypes type)
{
if (type == PROVIDED_INTERFACE) {
if (States.ProvidedInterfaces.find(name) != States.ProvidedInterfaces.end()) {
#if ENABLE_UNIT_TEST
std::cout << *this << std::endl;
#endif
return false;
}
States.ProvidedInterfaces.insert(std::make_pair(name, new StateMachine(name)));
} else {
if (States.RequiredInterfaces.find(name) != States.RequiredInterfaces.end()) {
#if ENABLE_UNIT_TEST
std::cout << *this << std::endl;
#endif
return false;
}
States.RequiredInterfaces.insert(std::make_pair(name, new StateMachine(name)));
}
return true;
}
bool GCM::FindInterface(const std::string & name, const GCM::InterfaceTypes type) const
{
if (type == PROVIDED_INTERFACE)
return (States.ProvidedInterfaces.find(name) != States.ProvidedInterfaces.end());
else
return (States.RequiredInterfaces.find(name) != States.RequiredInterfaces.end());
}
bool GCM::RemoveInterface(const std::string & name, const GCM::InterfaceTypes type)
{
InterfaceStateMachinesType::iterator it;
if (type == PROVIDED_INTERFACE) {
it = States.ProvidedInterfaces.find(name);
if (it == States.ProvidedInterfaces.end())
return false;
SFASSERT(it->second);
delete it->second;
States.ProvidedInterfaces.erase(it);
} else {
it = States.RequiredInterfaces.find(name);
if (it == States.RequiredInterfaces.end())
return false;
SFASSERT(it->second);
delete it->second;
States.RequiredInterfaces.erase(it);
}
return true;
}
void GCM::ProcessEvent_ComponentFramework(const SF::State::TransitionType transition)
{
// TODO
}
void GCM::ProcessEvent_ComponentApplication(const SF::State::TransitionType transition)
{
// TODO
}
void GCM::ProcessEvent_Interface(const SF::State::TransitionType transition)
{
// TODO
}
};
<|endoftext|> |
<commit_before>#include <cmath>
#include <iostream>
#include <ale_interface.hpp>
#include <glog/logging.h>
#include <gflags/gflags.h>
#include "prettyprint.hpp"
#include "dqn.hpp"
// DQN Parameters
DEFINE_bool(gpu, true, "Use GPU to brew Caffe");
DEFINE_bool(gui, false, "Open a GUI window");
DEFINE_string(rom, "roms/pong.bin", "Atari 2600 ROM to play");
DEFINE_int32(memory, 400000, "Capacity of replay memory");
DEFINE_int32(explore, 1000000, "Number of iterations needed for epsilon to reach given value.");
DEFINE_double(epsilon, 0.05, "Value of epsilon reached after explore iterations.");
DEFINE_double(gamma, 0.99, "Discount factor of future rewards (0,1]");
DEFINE_int32(clone_freq, 10000, "Frequency (steps) of cloning the target network.");
DEFINE_int32(memory_threshold, 100, "Enough amount of transitions to start learning");
DEFINE_int32(skip_frame, 3, "Number of frames skipped");
DEFINE_bool(show_frame, false, "Show the current frame in CUI");
DEFINE_string(save_screen, "", "File prefix in to save frames");
DEFINE_string(save_binary_screen, "", "File prefix in to save binary frames");
DEFINE_string(weights, "", "The pretrained weights load (*.caffemodel).");
DEFINE_string(snapshot, "", "The solver state to load (*.solverstate).");
DEFINE_bool(evaluate, false, "Evaluation mode: only playing a game, no updates");
DEFINE_double(evaluate_with_epsilon, 0.05, "Epsilon value to be used in evaluation mode");
DEFINE_double(repeat_games, 10, "Number of games played in evaluation mode");
// Solver Parameters
DEFINE_string(solver, "", "Solver parameter file (*.prototxt)");
DEFINE_string(solver_type, "ADADELTA", "Type of solver.");
DEFINE_string(model, "dqn.prototxt", "The model definition (*.prototxt).");
DEFINE_double(momentum, 0.95, "Solver momentum");
DEFINE_double(base_lr, 0.1, "Solver base learning rate");
DEFINE_string(lr_policy, "step", "Solver lr policy");
DEFINE_double(solver_gamma, 0.1, "Solver gamma");
DEFINE_int32(stepsize, 10000000, "Solver stepsize");
DEFINE_int32(max_iter, 10000000, "Maximum number of iterations");
DEFINE_int32(snapshot_frequency, 1000000, "Snapshot frequency in iterations");
DEFINE_int32(display, 10000, "Display frequency in iterations");
DEFINE_string(snapshot_prefix, "state/dqn", "Prefix for saving snapshots");
double CalculateEpsilon(const int iter) {
if (iter < FLAGS_explore) {
return 1.0 - (1.0 - FLAGS_epsilon) * (static_cast<double>(iter) / FLAGS_explore);
} else {
return FLAGS_epsilon;
}
}
void SaveScreen(const ALEScreen& screen, const ALEInterface& ale,
const string filename) {
IntMatrix screen_matrix;
for (auto row = 0; row < screen.height(); row++) {
IntVect row_vec;
for (auto col = 0; col < screen.width(); col++) {
int pixel = screen.get(row, col);
row_vec.emplace_back(pixel);
}
screen_matrix.emplace_back(row_vec);
}
ale.theOSystem->p_export_screen->save_png(&screen_matrix, filename);
}
void SaveInputFrames(const dqn::InputFrames& frames, const string filename) {
std::ofstream ofs;
ofs.open(filename, ios::out | ios::binary);
for (int i = 0; i < dqn::kInputFrameCount; ++i) {
const dqn::FrameData& frame = *frames[i];
for (int j = 0; j < dqn::kCroppedFrameDataSize; ++j) {
ofs.write((char*) &frame[j], sizeof(uint8_t));
}
}
ofs.close();
}
/**
* Play one episode and return the total score
*/
double PlayOneEpisode(ALEInterface& ale, dqn::DQN& dqn, const double epsilon,
const bool update) {
CHECK(!ale.game_over());
std::deque<dqn::FrameDataSp> past_frames;
auto total_score = 0.0;
for (auto frame = 0; !ale.game_over(); ++frame) {
const ALEScreen& screen = ale.getScreen();
if (!FLAGS_save_screen.empty()) {
std::stringstream ss;
ss << FLAGS_save_screen << setfill('0') << setw(5) <<
std::to_string(frame) << ".png";
SaveScreen(screen, ale, ss.str());
}
const auto current_frame = dqn::PreprocessScreen(screen);
past_frames.push_back(current_frame);
if (past_frames.size() < dqn::kInputFrameCount) {
// If there are not past frames enough for DQN input, just select NOOP
for (auto i = 0; i < FLAGS_skip_frame + 1 && !ale.game_over(); ++i) {
total_score += ale.act(PLAYER_A_NOOP);
}
} else {
while (past_frames.size() > dqn::kInputFrameCount) {
past_frames.pop_front();
}
dqn::InputFrames input_frames;
std::copy(past_frames.begin(), past_frames.end(), input_frames.begin());
if (!FLAGS_save_binary_screen.empty()) {
static int binary_save_num = 0;
string fname = FLAGS_save_binary_screen +
std::to_string(binary_save_num++) + ".bin";
SaveInputFrames(input_frames, fname);
}
const auto action = dqn.SelectAction(input_frames, epsilon);
auto immediate_score = 0.0;
for (auto i = 0; i < FLAGS_skip_frame + 1 && !ale.game_over(); ++i) {
immediate_score += ale.act(action);
}
total_score += immediate_score;
// Rewards for DQN are normalized as follows:
// 1 for any positive score, -1 for any negative score, otherwise 0
const auto reward = immediate_score == 0 ? 0 : immediate_score /
std::abs(immediate_score);
assert(reward <= 1 && reward >= -1);
if (update) {
// Add the current transition to replay memory
const auto transition = ale.game_over() ?
dqn::Transition(input_frames, action, reward, boost::none) :
dqn::Transition(input_frames, action, reward,
dqn::PreprocessScreen(ale.getScreen()));
dqn.AddTransition(transition);
// If the size of replay memory is large enough, update DQN
if (dqn.memory_size() > FLAGS_memory_threshold) {
dqn.Update();
}
}
}
}
ale.reset_game();
return total_score;
}
/**
* Evaluate the current player
*/
void Evaluate(ALEInterface& ale, dqn::DQN& dqn) {
auto total_score = 0.0;
std::stringstream ss;
for (auto i = 0; i < FLAGS_repeat_games; ++i) {
const auto score =
PlayOneEpisode(ale, dqn, FLAGS_evaluate_with_epsilon, false);
ss << score << " ";
total_score += score;
}
LOG(INFO) << "Evaluation scores: " << ss.str();
LOG(INFO) << "Average score: " <<
total_score / static_cast<double>(FLAGS_repeat_games) << std::endl;
}
int main(int argc, char** argv) {
gflags::ParseCommandLineFlags(&argc, &argv, true);
google::InitGoogleLogging(argv[0]);
google::InstallFailureSignalHandler();
google::LogToStderr();
if (FLAGS_gpu) {
caffe::Caffe::set_mode(caffe::Caffe::GPU);
} else {
caffe::Caffe::set_mode(caffe::Caffe::CPU);
}
ALEInterface ale;
ale.set("display_screen", FLAGS_gui);
ale.set("disable_color_averaging", true);
// Load the ROM file
ale.loadROM(FLAGS_rom);
// Get the vector of legal actions
const auto legal_actions = ale.getMinimalActionSet();
CHECK(FLAGS_snapshot.empty() || FLAGS_weights.empty())
<< "Give a snapshot to resume training or weights to finetune "
"but not both.";
// Construct the solver either from file or params
caffe::SolverParameter solver_param;
if (!FLAGS_solver.empty()) {
LOG(INFO) << "Reading solver prototxt from " << FLAGS_solver;
caffe::ReadProtoFromTextFileOrDie(FLAGS_solver, &solver_param);
} else {
LOG(INFO) << "Creating solver from scratch.";
solver_param.set_net(FLAGS_model);
::caffe::SolverParameter_SolverType solver_type;
CHECK(::caffe::SolverParameter_SolverType_Parse(FLAGS_solver_type, &solver_type))
<< "Invalid Solver Type " << FLAGS_solver_type;
solver_param.set_solver_type(solver_type);
solver_param.set_momentum(FLAGS_momentum);
solver_param.set_base_lr(FLAGS_base_lr);
solver_param.set_lr_policy(FLAGS_lr_policy);
solver_param.set_gamma(FLAGS_solver_gamma);
solver_param.set_stepsize(FLAGS_stepsize);
solver_param.set_max_iter(FLAGS_max_iter);
solver_param.set_display(FLAGS_display);
solver_param.set_snapshot(FLAGS_snapshot_frequency);
solver_param.set_snapshot_prefix(FLAGS_snapshot_prefix);
}
dqn::DQN dqn(legal_actions, solver_param, FLAGS_memory, FLAGS_gamma,
FLAGS_clone_freq);
dqn.Initialize();
if (!FLAGS_save_screen.empty()) {
LOG(INFO) << "Saving screens to: " << FLAGS_save_screen;
}
if (!FLAGS_snapshot.empty()) {
LOG(INFO) << "Resuming from " << FLAGS_snapshot;
dqn.RestoreSolver(FLAGS_snapshot);
} else if (!FLAGS_weights.empty()) {
LOG(INFO) << "Finetuning from " << FLAGS_weights;
dqn.LoadTrainedModel(FLAGS_weights);
}
if (FLAGS_evaluate) {
Evaluate(ale, dqn);
return 0;
}
auto episode = 0;
while (dqn.current_iteration() < solver_param.max_iter()) {
const auto epsilon = CalculateEpsilon(dqn.current_iteration());
const auto score = PlayOneEpisode(ale, dqn, epsilon, true);
LOG(INFO) << "Episode " << episode << ", score = " << score
<< ", epsilon = " << epsilon << ", iter = "
<< dqn.current_iteration();
episode++;
}
Evaluate(ale, dqn);
};
<commit_msg>Updated arguments.<commit_after>#include <cmath>
#include <iostream>
#include <ale_interface.hpp>
#include <glog/logging.h>
#include <gflags/gflags.h>
#include "prettyprint.hpp"
#include "dqn.hpp"
// DQN Parameters
DEFINE_bool(gpu, true, "Use GPU to brew Caffe");
DEFINE_bool(gui, false, "Open a GUI window");
DEFINE_string(rom, "roms/pong.bin", "Atari 2600 ROM to play");
DEFINE_int32(memory, 400000, "Capacity of replay memory");
DEFINE_int32(explore, 1000000, "Iterations for epsilon to reach given value.");
DEFINE_double(epsilon, .05, "Value of epsilon after explore iterations.");
DEFINE_double(gamma, .99, "Discount factor of future rewards (0,1]");
DEFINE_int32(clone_freq, 10000, "Frequency (steps) of cloning the target network.");
DEFINE_int32(memory_threshold, 100, "Number of transitions to start learning");
DEFINE_int32(skip_frame, 3, "Number of frames skipped");
DEFINE_string(save_screen, "", "File prefix in to save frames");
DEFINE_string(save_binary_screen, "", "File prefix in to save binary frames");
DEFINE_string(weights, "", "The pretrained weights load (*.caffemodel).");
DEFINE_string(snapshot, "", "The solver state to load (*.solverstate).");
DEFINE_bool(evaluate, false, "Evaluation mode: only playing a game, no updates");
DEFINE_double(evaluate_with_epsilon, 0.05, "Epsilon value to be used in evaluation mode");
DEFINE_double(repeat_games, 10, "Number of games played in evaluation mode");
// Solver Parameters
DEFINE_string(solver, "", "Solver parameter file (*.prototxt)");
DEFINE_string(solver_type, "ADADELTA", "Type of solver.");
DEFINE_string(model, "dqn.prototxt", "The model definition (*.prototxt).");
DEFINE_double(momentum, 0.95, "Solver momentum");
DEFINE_double(base_lr, 0.1, "Solver base learning rate");
DEFINE_string(lr_policy, "step", "Solver lr policy");
DEFINE_double(solver_gamma, 0.1, "Solver gamma");
DEFINE_int32(stepsize, 10000000, "Solver stepsize");
DEFINE_int32(max_iter, 10000000, "Maximum number of iterations");
DEFINE_int32(snapshot_frequency, 1000000, "Snapshot frequency in iterations");
DEFINE_int32(display, 10000, "Display frequency in iterations");
DEFINE_string(snapshot_prefix, "state/dqn", "Prefix for saving snapshots");
double CalculateEpsilon(const int iter) {
if (iter < FLAGS_explore) {
return 1.0 - (1.0 - FLAGS_epsilon) * (static_cast<double>(iter) / FLAGS_explore);
} else {
return FLAGS_epsilon;
}
}
void SaveScreen(const ALEScreen& screen, const ALEInterface& ale,
const string filename) {
IntMatrix screen_matrix;
for (auto row = 0; row < screen.height(); row++) {
IntVect row_vec;
for (auto col = 0; col < screen.width(); col++) {
int pixel = screen.get(row, col);
row_vec.emplace_back(pixel);
}
screen_matrix.emplace_back(row_vec);
}
ale.theOSystem->p_export_screen->save_png(&screen_matrix, filename);
}
void SaveInputFrames(const dqn::InputFrames& frames, const string filename) {
std::ofstream ofs;
ofs.open(filename, ios::out | ios::binary);
for (int i = 0; i < dqn::kInputFrameCount; ++i) {
const dqn::FrameData& frame = *frames[i];
for (int j = 0; j < dqn::kCroppedFrameDataSize; ++j) {
ofs.write((char*) &frame[j], sizeof(uint8_t));
}
}
ofs.close();
}
/**
* Play one episode and return the total score
*/
double PlayOneEpisode(ALEInterface& ale, dqn::DQN& dqn, const double epsilon,
const bool update) {
CHECK(!ale.game_over());
std::deque<dqn::FrameDataSp> past_frames;
auto total_score = 0.0;
for (auto frame = 0; !ale.game_over(); ++frame) {
const ALEScreen& screen = ale.getScreen();
if (!FLAGS_save_screen.empty()) {
std::stringstream ss;
ss << FLAGS_save_screen << setfill('0') << setw(5) <<
std::to_string(frame) << ".png";
SaveScreen(screen, ale, ss.str());
}
const auto current_frame = dqn::PreprocessScreen(screen);
past_frames.push_back(current_frame);
if (past_frames.size() < dqn::kInputFrameCount) {
// If there are not past frames enough for DQN input, just select NOOP
for (auto i = 0; i < FLAGS_skip_frame + 1 && !ale.game_over(); ++i) {
total_score += ale.act(PLAYER_A_NOOP);
}
} else {
while (past_frames.size() > dqn::kInputFrameCount) {
past_frames.pop_front();
}
dqn::InputFrames input_frames;
std::copy(past_frames.begin(), past_frames.end(), input_frames.begin());
if (!FLAGS_save_binary_screen.empty()) {
static int binary_save_num = 0;
string fname = FLAGS_save_binary_screen +
std::to_string(binary_save_num++) + ".bin";
SaveInputFrames(input_frames, fname);
}
const auto action = dqn.SelectAction(input_frames, epsilon);
auto immediate_score = 0.0;
for (auto i = 0; i < FLAGS_skip_frame + 1 && !ale.game_over(); ++i) {
immediate_score += ale.act(action);
}
total_score += immediate_score;
// Rewards for DQN are normalized as follows:
// 1 for any positive score, -1 for any negative score, otherwise 0
const auto reward = immediate_score == 0 ? 0 : immediate_score /
std::abs(immediate_score);
assert(reward <= 1 && reward >= -1);
if (update) {
// Add the current transition to replay memory
const auto transition = ale.game_over() ?
dqn::Transition(input_frames, action, reward, boost::none) :
dqn::Transition(input_frames, action, reward,
dqn::PreprocessScreen(ale.getScreen()));
dqn.AddTransition(transition);
// If the size of replay memory is large enough, update DQN
if (dqn.memory_size() > FLAGS_memory_threshold) {
dqn.Update();
}
}
}
}
ale.reset_game();
return total_score;
}
/**
* Evaluate the current player
*/
void Evaluate(ALEInterface& ale, dqn::DQN& dqn) {
auto total_score = 0.0;
std::stringstream ss;
for (auto i = 0; i < FLAGS_repeat_games; ++i) {
const auto score =
PlayOneEpisode(ale, dqn, FLAGS_evaluate_with_epsilon, false);
ss << score << " ";
total_score += score;
}
LOG(INFO) << "Evaluation scores: " << ss.str();
LOG(INFO) << "Average score: " <<
total_score / static_cast<double>(FLAGS_repeat_games) << std::endl;
}
int main(int argc, char** argv) {
gflags::ParseCommandLineFlags(&argc, &argv, true);
google::InitGoogleLogging(argv[0]);
google::InstallFailureSignalHandler();
google::LogToStderr();
if (FLAGS_gpu) {
caffe::Caffe::set_mode(caffe::Caffe::GPU);
} else {
caffe::Caffe::set_mode(caffe::Caffe::CPU);
}
ALEInterface ale;
ale.set("display_screen", FLAGS_gui);
ale.set("disable_color_averaging", true);
// Load the ROM file
ale.loadROM(FLAGS_rom);
// Get the vector of legal actions
const auto legal_actions = ale.getMinimalActionSet();
CHECK(FLAGS_snapshot.empty() || FLAGS_weights.empty())
<< "Give a snapshot to resume training or weights to finetune "
"but not both.";
// Construct the solver either from file or params
caffe::SolverParameter solver_param;
if (!FLAGS_solver.empty()) {
LOG(INFO) << "Reading solver prototxt from " << FLAGS_solver;
caffe::ReadProtoFromTextFileOrDie(FLAGS_solver, &solver_param);
} else {
LOG(INFO) << "Creating solver from scratch.";
solver_param.set_net(FLAGS_model);
::caffe::SolverParameter_SolverType solver_type;
CHECK(::caffe::SolverParameter_SolverType_Parse(FLAGS_solver_type, &solver_type))
<< "Invalid Solver Type " << FLAGS_solver_type;
solver_param.set_solver_type(solver_type);
solver_param.set_momentum(FLAGS_momentum);
solver_param.set_base_lr(FLAGS_base_lr);
solver_param.set_lr_policy(FLAGS_lr_policy);
solver_param.set_gamma(FLAGS_solver_gamma);
solver_param.set_stepsize(FLAGS_stepsize);
solver_param.set_max_iter(FLAGS_max_iter);
solver_param.set_display(FLAGS_display);
solver_param.set_snapshot(FLAGS_snapshot_frequency);
solver_param.set_snapshot_prefix(FLAGS_snapshot_prefix);
}
dqn::DQN dqn(legal_actions, solver_param, FLAGS_memory, FLAGS_gamma,
FLAGS_clone_freq);
dqn.Initialize();
if (!FLAGS_save_screen.empty()) {
LOG(INFO) << "Saving screens to: " << FLAGS_save_screen;
}
if (!FLAGS_snapshot.empty()) {
LOG(INFO) << "Resuming from " << FLAGS_snapshot;
dqn.RestoreSolver(FLAGS_snapshot);
} else if (!FLAGS_weights.empty()) {
LOG(INFO) << "Finetuning from " << FLAGS_weights;
dqn.LoadTrainedModel(FLAGS_weights);
}
if (FLAGS_evaluate) {
Evaluate(ale, dqn);
return 0;
}
auto episode = 0;
while (dqn.current_iteration() < solver_param.max_iter()) {
const auto epsilon = CalculateEpsilon(dqn.current_iteration());
const auto score = PlayOneEpisode(ale, dqn, epsilon, true);
LOG(INFO) << "Episode " << episode << ", score = " << score
<< ", epsilon = " << epsilon << ", iter = "
<< dqn.current_iteration();
episode++;
}
Evaluate(ale, dqn);
};
<|endoftext|> |
<commit_before>//
//
// Copyright (C) 2004 SIPfoundry Inc.
// Licensed by SIPfoundry under the LGPL license.
//
// Copyright (C) 2004 Pingtel Corp.
// Licensed to SIPfoundry under a Contributor Agreement.
//
// $$
//////////////////////////////////////////////////////////////////////////////
// SYSTEM INCLUDES
//#include <...>
// APPLICATION INCLUDES
#include "net/Url.h"
#include "mailboxmgr/VXMLDefs.h"
#include "mailboxmgr/MailboxManager.h"
#include "mailboxmgr/TransferToExtnCGI.h"
#include "mailboxmgr/ValidateMailboxCGIHelper.h"
// DEFINES
// MACROS
// EXTERNAL FUNCTIONS
// EXTERNAL VARIABLES
// CONSTANTS
// STRUCTS
// TYPEDEFS
// FORWARD DECLARATIONS
/* ============================ CREATORS ================================== */
TransferToExtnCGI::TransferToExtnCGI( const UtlString& extension ) :
m_extension ( extension )
{}
TransferToExtnCGI::~TransferToExtnCGI()
{}
OsStatus
TransferToExtnCGI::execute(UtlString* out)
{
OsStatus result = OS_SUCCESS;
// Get fully qualified SIP URL for the extension
Url extensionUrl;
MailboxManager* pMailboxManager = MailboxManager::getInstance();
pMailboxManager->getWellFormedURL( m_extension, extensionUrl );
// Validate the mailbox id and extension.
// If valid, lazy create the physical folders for the mailbox if necessary.
UtlBoolean checkPermissions = FALSE ;
ValidateMailboxCGIHelper validateMailboxHelper ( extensionUrl.toString() );
result = validateMailboxHelper.validate( checkPermissions );
UtlString dynamicVxml;
if ( result == OS_SUCCESS )
{
/*
UtlString transferUrlString;
validateMailboxHelper.getMailboxIdentity( transferUrlString );
if (transferUrlString.index("sip:") == UTL_NOT_FOUND)
{
transferUrlString = "sip:" + transferUrlString;
}
*/
UtlString ivrPromptUrl;
MailboxManager::getInstance()->getIvrPromptURL( ivrPromptUrl );
// Contains the dynamically generated VXML script.
dynamicVxml = VXML_BODY_BEGIN \
"<form> \n" \
"<block> \n" \
"<prompt bargein=\"false\"> \n" \
"<audio src=\"" + ivrPromptUrl + "/" + UtlString (PROMPT_ALIAS) + "/please_hold.wav\" /> \n" \
"</prompt>\n" \
"</block> \n" \
"<transfer dest=\"" + extensionUrl.toString() /* transferUrlString */ + "\" /> \n" \
"</form> \n" \
VXML_END;
// Write out the dynamic VXML script to be processed by OpenVXI
} else
{
dynamicVxml = VXML_BODY_BEGIN \
VXML_INVALID_EXTN_SNIPPET\
VXML_END;
}
if (out)
{
out->remove(0);
UtlString responseHeaders;
MailboxManager::getResponseHeaders(dynamicVxml.length(), responseHeaders);
out->append(responseHeaders.data());
out->append(dynamicVxml.data());
}
return OS_SUCCESS;
}
<commit_msg>Removed playing "please hold" message so to prevent the message being played twice.<commit_after>//
//
// Copyright (C) 2004 SIPfoundry Inc.
// Licensed by SIPfoundry under the LGPL license.
//
// Copyright (C) 2004 Pingtel Corp.
// Licensed to SIPfoundry under a Contributor Agreement.
//
// $$
//////////////////////////////////////////////////////////////////////////////
// SYSTEM INCLUDES
//#include <...>
// APPLICATION INCLUDES
#include "net/Url.h"
#include "mailboxmgr/VXMLDefs.h"
#include "mailboxmgr/MailboxManager.h"
#include "mailboxmgr/TransferToExtnCGI.h"
#include "mailboxmgr/ValidateMailboxCGIHelper.h"
// DEFINES
// MACROS
// EXTERNAL FUNCTIONS
// EXTERNAL VARIABLES
// CONSTANTS
// STRUCTS
// TYPEDEFS
// FORWARD DECLARATIONS
/* ============================ CREATORS ================================== */
TransferToExtnCGI::TransferToExtnCGI( const UtlString& extension ) :
m_extension ( extension )
{}
TransferToExtnCGI::~TransferToExtnCGI()
{}
OsStatus
TransferToExtnCGI::execute(UtlString* out)
{
OsStatus result = OS_SUCCESS;
// Get fully qualified SIP URL for the extension
Url extensionUrl;
MailboxManager* pMailboxManager = MailboxManager::getInstance();
pMailboxManager->getWellFormedURL( m_extension, extensionUrl );
// Validate the mailbox id and extension.
// If valid, lazy create the physical folders for the mailbox if necessary.
UtlBoolean checkPermissions = FALSE ;
ValidateMailboxCGIHelper validateMailboxHelper ( extensionUrl.toString() );
result = validateMailboxHelper.validate( checkPermissions );
UtlString dynamicVxml;
if ( result == OS_SUCCESS )
{
/*
UtlString transferUrlString;
validateMailboxHelper.getMailboxIdentity( transferUrlString );
if (transferUrlString.index("sip:") == UTL_NOT_FOUND)
{
transferUrlString = "sip:" + transferUrlString;
}
*/
UtlString ivrPromptUrl;
MailboxManager::getInstance()->getIvrPromptURL( ivrPromptUrl );
// Contains the dynamically generated VXML script.
dynamicVxml = VXML_BODY_BEGIN \
"<form> \n" \
"<transfer dest=\"" + extensionUrl.toString() /* transferUrlString */ + "\" /> \n" \
"</form> \n" \
VXML_END;
// Write out the dynamic VXML script to be processed by OpenVXI
} else
{
dynamicVxml = VXML_BODY_BEGIN \
VXML_INVALID_EXTN_SNIPPET\
VXML_END;
}
if (out)
{
out->remove(0);
UtlString responseHeaders;
MailboxManager::getResponseHeaders(dynamicVxml.length(), responseHeaders);
out->append(responseHeaders.data());
out->append(dynamicVxml.data());
}
return OS_SUCCESS;
}
<|endoftext|> |
<commit_before>#pragma once
#include <glm/vec3.hpp>
#include <memory>
#include "../linking.hpp"
class btCollisionShape;
class PhysicsManager;
namespace Physics {
class Trigger;
/// Represents a shape for physics objects and facilitates creation of
/// underlying types.
class Shape {
friend class ::PhysicsManager;
friend class Trigger;
public:
/// Parameters used to create a sphere shape.
struct Sphere {
explicit Sphere(float radius) : radius(radius) {}
float radius;
};
/// Parameters used to create a plane shape.
struct Plane {
Plane(const glm::vec3& normal, float planeCoeff)
: normal(normal), planeCoeff(planeCoeff) {}
glm::vec3 normal;
float planeCoeff;
};
/// Parameters used to create a box shape.
struct Box {
Box(float width, float height, float depth)
: width(width), height(height), depth(depth) {}
float width;
float height;
float depth;
};
/// Parameters used to create a cylinder shape.
struct Cylinder {
Cylinder(float radius, float length)
: radius(radius), length(length) {}
float radius;
float length;
};
/// Parameters used to create a cone shape.
struct Cone {
Cone(float radius, float height)
: radius(radius), height(height) {}
float radius;
float height;
};
/// Parameters used to create a capsule shape.
struct Capsule {
Capsule(float radius, float height)
: radius(radius), height(height) {}
float radius;
float height;
};
/// The various kinds of shapes that are wrapped by %Shape.
enum class Kind {
Sphere,
Plane,
Box,
Cylinder,
Cone,
Capsule,
};
/// Construct a sphere shape.
/**
* @param params Sphere specific parameters.
*/
ENGINE_API explicit Shape(const Sphere& params);
/// Construct a plane shape.
/**
* @param params Plane specific parameters.
*/
ENGINE_API explicit Shape(const Plane& params);
/// Construct a box shape.
/**
* @param params Box specific parameters.
*/
ENGINE_API explicit Shape(const Box& params);
/// Construct a cylinder shape.
/**
* @param params Cylinder specific parameters.
*/
ENGINE_API explicit Shape(const Cylinder& params);
/// Construct a cone shape.
/**
* @param params Cone specific parameters.
*/
ENGINE_API explicit Shape(const Cone& params);
/// Construct a capsule shape.
/**
* @param params Capsule specific parameters.
*/
ENGINE_API explicit Shape(const Capsule& params);
/// Destructor
ENGINE_API ~Shape();
/// Get the type of wrapped shape.
/**
* @return The type of shape.
*/
ENGINE_API Kind GetKind() const;
/// Get sphere data of the shape.
/**
* @return Sphere data, or nullptr if the shape is not a sphere.
*/
ENGINE_API const Sphere* GetSphereData() const;
/// Get plane data of the shape.
/**
* @return Plane data, or nullptr if the shape is not a plane.
*/
ENGINE_API const Plane* GetPlaneData() const;
/// Get box data of the shape.
/**
* @return Box data, or nullptr if the shape is not a box.
*/
ENGINE_API const Box* GetBoxData() const;
/// Get cylinder data of the shape.
/**
* @return Cylinder data, or nullptr if the shape is not a cylinder.
*/
ENGINE_API const Cylinder* GetCylinderData() const;
/// Get cone data of the shape.
/**
* @return Cone data, or nullptr if the shape is not a cone.
*/
ENGINE_API const Cone* GetConeData() const;
/// Get capsule data of the shape.
/**
* @return Capsule data, or nullptr if the shape is not a capsule.
*/
ENGINE_API const Capsule* GetCapsuleData() const;
private:
/// Get the wrapped Bullet shape.
/**
* @return The Bullet shape.
*/
btCollisionShape* GetShape() const;
Shape(const Shape& other) = delete;
std::unique_ptr<btCollisionShape> shape;
Kind kind;
union {
Sphere sphere;
Plane plane;
Box box;
Cylinder cylinder;
Cone cone;
Capsule capsule;
};
};
}
<commit_msg>Allow the rigid body component access to private members of the shape helper class.<commit_after>#pragma once
#include <glm/vec3.hpp>
#include <memory>
#include "../linking.hpp"
class btCollisionShape;
class PhysicsManager;
namespace Component {
class RigidBody;
}
namespace Physics {
class Trigger;
/// Represents a shape for physics objects and facilitates creation of
/// underlying types.
class Shape {
friend class ::PhysicsManager;
friend class ::Component::RigidBody;
friend class Trigger;
public:
/// Parameters used to create a sphere shape.
struct Sphere {
explicit Sphere(float radius) : radius(radius) {}
float radius;
};
/// Parameters used to create a plane shape.
struct Plane {
Plane(const glm::vec3& normal, float planeCoeff)
: normal(normal), planeCoeff(planeCoeff) {}
glm::vec3 normal;
float planeCoeff;
};
/// Parameters used to create a box shape.
struct Box {
Box(float width, float height, float depth)
: width(width), height(height), depth(depth) {}
float width;
float height;
float depth;
};
/// Parameters used to create a cylinder shape.
struct Cylinder {
Cylinder(float radius, float length)
: radius(radius), length(length) {}
float radius;
float length;
};
/// Parameters used to create a cone shape.
struct Cone {
Cone(float radius, float height)
: radius(radius), height(height) {}
float radius;
float height;
};
/// Parameters used to create a capsule shape.
struct Capsule {
Capsule(float radius, float height)
: radius(radius), height(height) {}
float radius;
float height;
};
/// The various kinds of shapes that are wrapped by %Shape.
enum class Kind {
Sphere,
Plane,
Box,
Cylinder,
Cone,
Capsule,
};
/// Construct a sphere shape.
/**
* @param params Sphere specific parameters.
*/
ENGINE_API explicit Shape(const Sphere& params);
/// Construct a plane shape.
/**
* @param params Plane specific parameters.
*/
ENGINE_API explicit Shape(const Plane& params);
/// Construct a box shape.
/**
* @param params Box specific parameters.
*/
ENGINE_API explicit Shape(const Box& params);
/// Construct a cylinder shape.
/**
* @param params Cylinder specific parameters.
*/
ENGINE_API explicit Shape(const Cylinder& params);
/// Construct a cone shape.
/**
* @param params Cone specific parameters.
*/
ENGINE_API explicit Shape(const Cone& params);
/// Construct a capsule shape.
/**
* @param params Capsule specific parameters.
*/
ENGINE_API explicit Shape(const Capsule& params);
/// Destructor
ENGINE_API ~Shape();
/// Get the type of wrapped shape.
/**
* @return The type of shape.
*/
ENGINE_API Kind GetKind() const;
/// Get sphere data of the shape.
/**
* @return Sphere data, or nullptr if the shape is not a sphere.
*/
ENGINE_API const Sphere* GetSphereData() const;
/// Get plane data of the shape.
/**
* @return Plane data, or nullptr if the shape is not a plane.
*/
ENGINE_API const Plane* GetPlaneData() const;
/// Get box data of the shape.
/**
* @return Box data, or nullptr if the shape is not a box.
*/
ENGINE_API const Box* GetBoxData() const;
/// Get cylinder data of the shape.
/**
* @return Cylinder data, or nullptr if the shape is not a cylinder.
*/
ENGINE_API const Cylinder* GetCylinderData() const;
/// Get cone data of the shape.
/**
* @return Cone data, or nullptr if the shape is not a cone.
*/
ENGINE_API const Cone* GetConeData() const;
/// Get capsule data of the shape.
/**
* @return Capsule data, or nullptr if the shape is not a capsule.
*/
ENGINE_API const Capsule* GetCapsuleData() const;
private:
/// Get the wrapped Bullet shape.
/**
* @return The Bullet shape.
*/
btCollisionShape* GetShape() const;
Shape(const Shape& other) = delete;
std::unique_ptr<btCollisionShape> shape;
Kind kind;
union {
Sphere sphere;
Plane plane;
Box box;
Cylinder cylinder;
Cone cone;
Capsule capsule;
};
};
}
<|endoftext|> |
<commit_before>/**
@file ConnectionSTREAMImages.cpp
@author Lime Microsystems
@brief Image updating and version checking
*/
#include "ConnectionSTREAM.h"
#include "ErrorReporting.h"
#include "SystemResources.h"
#include "LMS64CProtocol.h"
#include "LMSBoards.h"
#include <iostream>
#include <fstream>
#include <ciso646>
using namespace lime;
/*!
* The entry structure that describes a board revision and its fw/gw images
*/
struct ConnectionSTREAMImageEntry
{
eLMS_DEV dev;
int hw_rev;
int fw_ver;
const char *fw_img;
int gw_ver;
int gw_rev;
const char *gw_rbf;
};
/*!
* Lookup the board information given hardware type and revision.
* Edit each entry for supported hardware and image updates.
*/
static const ConnectionSTREAMImageEntry &lookupImageEntry(const LMS64CProtocol::LMSinfo &info)
{
static const std::vector<ConnectionSTREAMImageEntry> imageEntries = {
ConnectionSTREAMImageEntry({LMS_DEV_UNKNOWN, -1, -1, "Unknown-USB.img", -1, -1, "Unknown-USB.rbf"}),
ConnectionSTREAMImageEntry({LMS_DEV_LIMESDR, 4, 3, "LimeSDR-USB_HW_1.3_r3.0.img", 2, 2, "LimeSDR-USB_HW_1.4_r2.2.rbf"}),
ConnectionSTREAMImageEntry({LMS_DEV_LIMESDR, 3, 3, "LimeSDR-USB_HW_1.3_r3.0.img", 1, 20, "LimeSDR-USB_HW_1.1_r1.20.rbf"}),
ConnectionSTREAMImageEntry({LMS_DEV_LIMESDR, 2, 3, "LimeSDR-USB_HW_1.2_r3.0.img", 1, 20, "LimeSDR-USB_HW_1.1_r1.20.rbf"}),
ConnectionSTREAMImageEntry({LMS_DEV_LIMESDR, 1, 7, "LimeSDR-USB_HW_1.1_r7.0.img", 1, 20, "LimeSDR-USB_HW_1.1_r1.20.rbf"}),
ConnectionSTREAMImageEntry({LMS_DEV_STREAM, 3, 8, "STREAM-USB_HW_1.1_r8.0.img", 1, 2, "STREAM-USB_HW_1.3_r1.2.rbf"})};
for(const auto &iter : imageEntries)
{
if (info.device == iter.dev and info.hardware == iter.hw_rev)
{
return iter;
}
}
return imageEntries.front(); //the -1 unknown entry
}
void ConnectionSTREAM::VersionCheck(void)
{
const auto info = this->GetInfo();
const auto &entry = lookupImageEntry(info);
//an entry match was not found
if (entry.dev == LMS_DEV_UNKNOWN)
{
std::cerr << "Unsupported hardware connected: " << GetDeviceName(info.device) << "[HW=" << info.hardware << "]" << std::endl;
return;
}
//check and warn about firmware mismatch problems
if (info.firmware != entry.fw_ver)
std::cerr << std::endl
<< "########################################################" << std::endl
<< "## !!! Warning: firmware version mismatch !!!" << std::endl
<< "## Expected firmware version " << entry.fw_ver << ", but found version " << info.firmware << std::endl
<< "## Follow the FW and FPGA upgrade instructions:" << std::endl
<< "## http://wiki.myriadrf.org/Lime_Suite#Flashing_images" << std::endl
<< "## Or run update on the command line: LimeUtil --update" << std::endl
<< "########################################################" << std::endl
<< std::endl;
//check and warn about gateware mismatch problems
const auto fpgaInfo = this->GetFPGAInfo();
if (fpgaInfo.gatewareVersion != entry.gw_ver
|| fpgaInfo.gatewareRevision != entry.gw_rev)
std::cerr << std::endl
<< "########################################################" << std::endl
<< "## !!! Warning: gateware version mismatch !!!" << std::endl
<< "## Expected gateware version " << entry.gw_ver << ", revision " << entry.gw_rev << std::endl
<< "## But found version " << fpgaInfo.gatewareVersion << ", revision " << fpgaInfo.gatewareRevision<< std::endl
<< "## Follow the FW and FPGA upgrade instructions:" << std::endl
<< "## http://wiki.myriadrf.org/Lime_Suite#Flashing_images" << std::endl
<< "## Or run update on the command line: LimeUtil --update" << std::endl
<< "########################################################" << std::endl
<< std::endl;
}
int ConnectionSTREAM::ProgramUpdate(const bool download, IConnection::ProgrammingCallback callback)
{
const auto info = this->GetInfo();
const auto &entry = lookupImageEntry(info);
//an entry match was not found
if (entry.dev == LMS_DEV_UNKNOWN)
{
return lime::ReportError("Unsupported hardware connected: %s[HW=%d]", GetDeviceName(info.device), info.hardware);
}
//download images when missing
if (download)
{
const std::vector<std::string> images = {entry.fw_img, entry.gw_rbf};
for (const auto &image : images)
{
if (not lime::locateImageResource(image).empty()) continue;
const std::string msg("Downloading: " + image);
if (callback) callback(0, 1, msg.c_str());
int ret = lime::downloadImageResource(image);
if (ret != 0) return ret; //error set by download call
if (callback) callback(1, 1, "Done!");
}
}
//load firmware into flash
{
//open file
std::ifstream file;
const auto path = lime::locateImageResource(entry.fw_img);
file.open(path.c_str(), std::ios::in | std::ios::binary);
if (not file.good()) return lime::ReportError("Error opening %s", path.c_str());
//read file
std::streampos fileSize;
file.seekg(0, std::ios::end);
fileSize = file.tellg();
file.seekg(0, std::ios::beg);
std::vector<char> progData(fileSize, 0);
file.read(progData.data(), fileSize);
int device = LMS64CProtocol::FX3; //FX3
int progMode = 2; //Firmware to FLASH
auto status = this->ProgramWrite(progData.data(), progData.size(), progMode, device, callback);
if (status != 0) return status;
}
//load gateware into flash
{
//open file
std::ifstream file;
const auto path = lime::locateImageResource(entry.gw_rbf);
file.open(path.c_str(), std::ios::in | std::ios::binary);
if (not file.good()) return lime::ReportError("Error opening %s", path.c_str());
//read file
std::streampos fileSize;
file.seekg(0, std::ios::end);
fileSize = file.tellg();
file.seekg(0, std::ios::beg);
std::vector<char> progData(fileSize, 0);
file.read(progData.data(), fileSize);
int device = LMS64CProtocol::FPGA; //Altera FPGA
int progMode = 1; //Bitstream to FLASH
auto status = this->ProgramWrite(progData.data(), progData.size(), progMode, device, callback);
if (status != 0) return status;
}
//Reset FX3, FPGA should be reloaded on boot
{
int device = LMS64CProtocol::FX3; //FX3
auto status = this->ProgramWrite(nullptr, 0, 0, device, nullptr);
if (status != 0) return status;
}
return 0;
}
<commit_msg>print image path in program update<commit_after>/**
@file ConnectionSTREAMImages.cpp
@author Lime Microsystems
@brief Image updating and version checking
*/
#include "ConnectionSTREAM.h"
#include "ErrorReporting.h"
#include "SystemResources.h"
#include "LMS64CProtocol.h"
#include "LMSBoards.h"
#include <iostream>
#include <fstream>
#include <ciso646>
using namespace lime;
/*!
* The entry structure that describes a board revision and its fw/gw images
*/
struct ConnectionSTREAMImageEntry
{
eLMS_DEV dev;
int hw_rev;
int fw_ver;
const char *fw_img;
int gw_ver;
int gw_rev;
const char *gw_rbf;
};
/*!
* Lookup the board information given hardware type and revision.
* Edit each entry for supported hardware and image updates.
*/
static const ConnectionSTREAMImageEntry &lookupImageEntry(const LMS64CProtocol::LMSinfo &info)
{
static const std::vector<ConnectionSTREAMImageEntry> imageEntries = {
ConnectionSTREAMImageEntry({LMS_DEV_UNKNOWN, -1, -1, "Unknown-USB.img", -1, -1, "Unknown-USB.rbf"}),
ConnectionSTREAMImageEntry({LMS_DEV_LIMESDR, 4, 3, "LimeSDR-USB_HW_1.3_r3.0.img", 2, 2, "LimeSDR-USB_HW_1.4_r2.2.rbf"}),
ConnectionSTREAMImageEntry({LMS_DEV_LIMESDR, 3, 3, "LimeSDR-USB_HW_1.3_r3.0.img", 1, 20, "LimeSDR-USB_HW_1.1_r1.20.rbf"}),
ConnectionSTREAMImageEntry({LMS_DEV_LIMESDR, 2, 3, "LimeSDR-USB_HW_1.2_r3.0.img", 1, 20, "LimeSDR-USB_HW_1.1_r1.20.rbf"}),
ConnectionSTREAMImageEntry({LMS_DEV_LIMESDR, 1, 7, "LimeSDR-USB_HW_1.1_r7.0.img", 1, 20, "LimeSDR-USB_HW_1.1_r1.20.rbf"}),
ConnectionSTREAMImageEntry({LMS_DEV_STREAM, 3, 8, "STREAM-USB_HW_1.1_r8.0.img", 1, 2, "STREAM-USB_HW_1.3_r1.2.rbf"})};
for(const auto &iter : imageEntries)
{
if (info.device == iter.dev and info.hardware == iter.hw_rev)
{
return iter;
}
}
return imageEntries.front(); //the -1 unknown entry
}
void ConnectionSTREAM::VersionCheck(void)
{
const auto info = this->GetInfo();
const auto &entry = lookupImageEntry(info);
//an entry match was not found
if (entry.dev == LMS_DEV_UNKNOWN)
{
std::cerr << "Unsupported hardware connected: " << GetDeviceName(info.device) << "[HW=" << info.hardware << "]" << std::endl;
return;
}
//check and warn about firmware mismatch problems
if (info.firmware != entry.fw_ver)
std::cerr << std::endl
<< "########################################################" << std::endl
<< "## !!! Warning: firmware version mismatch !!!" << std::endl
<< "## Expected firmware version " << entry.fw_ver << ", but found version " << info.firmware << std::endl
<< "## Follow the FW and FPGA upgrade instructions:" << std::endl
<< "## http://wiki.myriadrf.org/Lime_Suite#Flashing_images" << std::endl
<< "## Or run update on the command line: LimeUtil --update" << std::endl
<< "########################################################" << std::endl
<< std::endl;
//check and warn about gateware mismatch problems
const auto fpgaInfo = this->GetFPGAInfo();
if (fpgaInfo.gatewareVersion != entry.gw_ver
|| fpgaInfo.gatewareRevision != entry.gw_rev)
std::cerr << std::endl
<< "########################################################" << std::endl
<< "## !!! Warning: gateware version mismatch !!!" << std::endl
<< "## Expected gateware version " << entry.gw_ver << ", revision " << entry.gw_rev << std::endl
<< "## But found version " << fpgaInfo.gatewareVersion << ", revision " << fpgaInfo.gatewareRevision<< std::endl
<< "## Follow the FW and FPGA upgrade instructions:" << std::endl
<< "## http://wiki.myriadrf.org/Lime_Suite#Flashing_images" << std::endl
<< "## Or run update on the command line: LimeUtil --update" << std::endl
<< "########################################################" << std::endl
<< std::endl;
}
static bool programmingCallbackStream(
int bsent, int btotal, const char* progressMsg,
const std::string &image,
IConnection::ProgrammingCallback callback)
{
const auto msg = std::string(progressMsg) + " (" + image + ")";
return callback(bsent, btotal, msg.c_str());
}
int ConnectionSTREAM::ProgramUpdate(const bool download, IConnection::ProgrammingCallback callback)
{
const auto info = this->GetInfo();
const auto &entry = lookupImageEntry(info);
//an entry match was not found
if (entry.dev == LMS_DEV_UNKNOWN)
{
return lime::ReportError("Unsupported hardware connected: %s[HW=%d]", GetDeviceName(info.device), info.hardware);
}
//download images when missing
if (download)
{
const std::vector<std::string> images = {entry.fw_img, entry.gw_rbf};
for (const auto &image : images)
{
if (not lime::locateImageResource(image).empty()) continue;
const std::string msg("Downloading: " + image);
if (callback) callback(0, 1, msg.c_str());
int ret = lime::downloadImageResource(image);
if (ret != 0) return ret; //error set by download call
if (callback) callback(1, 1, "Done!");
}
}
//load firmware into flash
{
//open file
std::ifstream file;
const auto path = lime::locateImageResource(entry.fw_img);
file.open(path.c_str(), std::ios::in | std::ios::binary);
if (not file.good()) return lime::ReportError("Error opening %s", path.c_str());
//read file
std::streampos fileSize;
file.seekg(0, std::ios::end);
fileSize = file.tellg();
file.seekg(0, std::ios::beg);
std::vector<char> progData(fileSize, 0);
file.read(progData.data(), fileSize);
int device = LMS64CProtocol::FX3; //FX3
int progMode = 2; //Firmware to FLASH
using namespace std::placeholders;
const auto cb = std::bind(&programmingCallbackStream, _1, _2, _3, path, callback);
auto status = this->ProgramWrite(progData.data(), progData.size(), progMode, device, cb);
if (status != 0) return status;
}
//load gateware into flash
{
//open file
std::ifstream file;
const auto path = lime::locateImageResource(entry.gw_rbf);
file.open(path.c_str(), std::ios::in | std::ios::binary);
if (not file.good()) return lime::ReportError("Error opening %s", path.c_str());
//read file
std::streampos fileSize;
file.seekg(0, std::ios::end);
fileSize = file.tellg();
file.seekg(0, std::ios::beg);
std::vector<char> progData(fileSize, 0);
file.read(progData.data(), fileSize);
int device = LMS64CProtocol::FPGA; //Altera FPGA
int progMode = 1; //Bitstream to FLASH
using namespace std::placeholders;
const auto cb = std::bind(&programmingCallbackStream, _1, _2, _3, path, callback);
auto status = this->ProgramWrite(progData.data(), progData.size(), progMode, device, cb);
if (status != 0) return status;
}
//Reset FX3, FPGA should be reloaded on boot
{
int device = LMS64CProtocol::FX3; //FX3
auto status = this->ProgramWrite(nullptr, 0, 0, device, nullptr);
if (status != 0) return status;
}
return 0;
}
<|endoftext|> |
<commit_before>/*!
@file
@copyright Edouard Alligand and Joel Falcou 2015-2017
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
#ifndef BOOST_BRIGAND_SEQUENCES_FRONT_HPP
#define BOOST_BRIGAND_SEQUENCES_FRONT_HPP
#include <brigand/sequences/filled_list.hpp>
#include <brigand/types/integral_constant.hpp>
#include <brigand/types/type.hpp>
namespace brigand
{
// push_front
namespace detail
{
template <class L, class... T>
struct push_front_impl;
template <template <class...> class L, class... U, class... T>
struct push_front_impl<L<U...>, T...>
{
using type = L<T..., U...>;
};
}
namespace lazy
{
template <class L, class... T>
struct push_front : detail::push_front_impl<L, T...>
{
};
}
template <class L, class... T>
using push_front = typename detail::push_front_impl<L, T...>::type;
// front
namespace detail
{
template <class L>
struct front_impl;
template <template <class...> class L, class T, class... U>
struct front_impl<L<T, U...>>
{
using type = T;
};
}
template <class L>
using front = typename detail::front_impl<L>::type;
// pop front
namespace detail
{
template <class L, unsigned int N>
struct pop_front_impl;
template <template <class...> class L, class T, class... U>
struct pop_front_impl<L<T, U...>, 1>
{
using type = L<U...>;
};
template <template <class...> class L, class>
struct pop_front_element;
template <template <class...> class L, class... Ts>
struct pop_front_element<L, list<Ts...>>
{
template <class... Us>
static L<Us...> impl(Ts..., type_<Us> *...);
};
template <template <class...> class L, class... Ts, unsigned int N>
struct pop_front_impl<L<Ts...>, N>
{
using type = decltype(pop_front_element<L, filled_list<void const *, N>>::impl(
static_cast<type_<Ts> *>(nullptr)...));
};
}
namespace lazy
{
template <class L, class N = brigand::integral_constant<unsigned int, 1>>
struct pop_front : detail::pop_front_impl<L, N::value>
{
};
}
template <class L, class N = brigand::integral_constant<unsigned int, 1>>
using pop_front = typename detail::pop_front_impl<L, N::value>::type;
}
#endif
<commit_msg>Delete front.hpp<commit_after><|endoftext|> |
<commit_before>
#include <mpi.h>
#include "adios2.h"
#include <cstdint>
#include <iomanip>
#include <iostream>
#include <math.h>
#include <memory>
#include <stdexcept>
#include <string>
#include <vector>
#include "PrintData.h"
int main(int argc, char *argv[])
{
MPI_Init(&argc, &argv);
if (argc < 2)
{
std::cout << "Not enough arguments: need an input file\n";
return 1;
}
const char *inputfile = argv[1];
/* World comm spans all applications started with the same aprun command
on a Cray XK6. So we have to split and create the local
'world' communicator for the reader only.
In normal start-up, the communicator will just equal the MPI_COMM_WORLD.
*/
int wrank, wnproc;
MPI_Comm_rank(MPI_COMM_WORLD, &wrank);
MPI_Comm_size(MPI_COMM_WORLD, &wnproc);
MPI_Barrier(MPI_COMM_WORLD);
const unsigned int color = 2;
MPI_Comm mpiReaderComm;
MPI_Comm_split(MPI_COMM_WORLD, color, wrank, &mpiReaderComm);
int rank, nproc;
MPI_Comm_rank(mpiReaderComm, &rank);
MPI_Comm_size(mpiReaderComm, &nproc);
adios2::ADIOS ad("adios2.xml", mpiReaderComm, adios2::DebugON);
// Define method for engine creation
// 1. Get method def from config file or define new one
adios2::IO &bpReaderIO = ad.DeclareIO("input");
if (!bpReaderIO.InConfigFile())
{
// if not defined by user, we can change the default settings
// BPFileWriter is the default engine
bpReaderIO.SetEngine("ADIOS1Reader");
bpReaderIO.SetParameters({{"num_threads", "2"}});
// ISO-POSIX file is the default transport
// Passing parameters to the transport
bpReaderIO.AddTransport("File", {{"verbose", "4"}});
}
auto bpReader =
bpReaderIO.Open(inputfile, adios2::OpenMode::Read, mpiReaderComm);
if (!bpReader)
{
throw std::ios_base::failure("ERROR: failed to open " +
std::string(inputfile) + "\n");
}
unsigned int gndx;
unsigned int gndy;
// bpReader->Read<unsigned int>("gndx", &gndx);
// bpReader->Read<unsigned int>("gndy", &gndy);
adios2::Variable<unsigned int> *vgndx =
bpReader->InquireVariable<unsigned int>("gndx");
gndx = vgndx->m_Data[0];
adios2::Variable<unsigned int> *vgndy =
bpReader->InquireVariable<unsigned int>("gndy");
gndy = vgndy->m_Data[0];
if (rank == 0)
{
std::cout << "gndx = " << gndx << std::endl;
std::cout << "gndy = " << gndy << std::endl;
std::cout << "# of steps = " << vgndy->m_AvailableSteps << std::endl;
}
// 1D decomposition of the columns, which is inefficient for reading!
std::vector<uint64_t> readsize({gndx, gndy / nproc});
std::vector<uint64_t> offset({0LL, rank * readsize[1]});
if (rank == nproc - 1)
{
// last process should read all the rest of columns
readsize[1] = gndy - readsize[1] * (nproc - 1);
}
std::cout << "rank " << rank << " reads " << readsize[1]
<< " columns from offset " << offset[1] << std::endl;
adios2::Variable<double> *vT = bpReader->InquireVariable<double>("T");
double *T = new double[vT->m_AvailableSteps * readsize[0] * readsize[1]];
// Create a 2D selection for the subset
vT->SetSelection(offset, readsize);
vT->SetStepSelection(0, vT->m_AvailableSteps);
// Arrays are read by scheduling one or more of them
// and performing the reads at once
bpReader->ScheduleRead<double>(*vT, T);
bpReader->PerformReads(adios2::ReadMode::Blocking);
printData(T, readsize.data(), offset.data(), rank, vT->m_AvailableSteps);
bpReader->Close();
delete[] T;
MPI_Finalize();
return 0;
}
<commit_msg>fixed a size_t / uint64_t problem for macOS 10.12 and Clang 8.1.0<commit_after>
#include <mpi.h>
#include "adios2.h"
#include <cstdint>
#include <iomanip>
#include <iostream>
#include <math.h>
#include <memory>
#include <stdexcept>
#include <string>
#include <vector>
#include "PrintData.h"
int main(int argc, char *argv[])
{
MPI_Init(&argc, &argv);
if (argc < 2)
{
std::cout << "Not enough arguments: need an input file\n";
return 1;
}
const char *inputfile = argv[1];
/* World comm spans all applications started with the same aprun command
on a Cray XK6. So we have to split and create the local
'world' communicator for the reader only.
In normal start-up, the communicator will just equal the MPI_COMM_WORLD.
*/
int wrank, wnproc;
MPI_Comm_rank(MPI_COMM_WORLD, &wrank);
MPI_Comm_size(MPI_COMM_WORLD, &wnproc);
MPI_Barrier(MPI_COMM_WORLD);
const unsigned int color = 2;
MPI_Comm mpiReaderComm;
MPI_Comm_split(MPI_COMM_WORLD, color, wrank, &mpiReaderComm);
int rank, nproc;
MPI_Comm_rank(mpiReaderComm, &rank);
MPI_Comm_size(mpiReaderComm, &nproc);
adios2::ADIOS ad("adios2.xml", mpiReaderComm, adios2::DebugON);
// Define method for engine creation
// 1. Get method def from config file or define new one
adios2::IO &bpReaderIO = ad.DeclareIO("input");
if (!bpReaderIO.InConfigFile())
{
// if not defined by user, we can change the default settings
// BPFileWriter is the default engine
bpReaderIO.SetEngine("ADIOS1Reader");
bpReaderIO.SetParameters({{"num_threads", "2"}});
// ISO-POSIX file is the default transport
// Passing parameters to the transport
bpReaderIO.AddTransport("File", {{"verbose", "4"}});
}
auto bpReader =
bpReaderIO.Open(inputfile, adios2::OpenMode::Read, mpiReaderComm);
if (!bpReader)
{
throw std::ios_base::failure("ERROR: failed to open " +
std::string(inputfile) + "\n");
}
unsigned int gndx;
unsigned int gndy;
// bpReader->Read<unsigned int>("gndx", &gndx);
// bpReader->Read<unsigned int>("gndy", &gndy);
adios2::Variable<unsigned int> *vgndx =
bpReader->InquireVariable<unsigned int>("gndx");
gndx = vgndx->m_Data[0];
adios2::Variable<unsigned int> *vgndy =
bpReader->InquireVariable<unsigned int>("gndy");
gndy = vgndy->m_Data[0];
if (rank == 0)
{
std::cout << "gndx = " << gndx << std::endl;
std::cout << "gndy = " << gndy << std::endl;
std::cout << "# of steps = " << vgndy->m_AvailableSteps << std::endl;
}
// 1D decomposition of the columns, which is inefficient for reading!
std::vector<uint64_t> readsize({gndx, gndy / nproc});
std::vector<uint64_t> offset({0LL, rank * readsize[1]});
std::vector<size_t> readsize_size_t({gndx, gndy / nproc});
std::vector<size_t> offset_size_t({0LL, rank * readsize[1]});
if (rank == nproc - 1)
{
// last process should read all the rest of columns
readsize[1] = gndy - readsize[1] * (nproc - 1);
}
std::cout << "rank " << rank << " reads " << readsize[1]
<< " columns from offset " << offset[1] << std::endl;
adios2::Variable<double> *vT = bpReader->InquireVariable<double>("T");
double *T = new double[vT->m_AvailableSteps * readsize[0] * readsize[1]];
// Create a 2D selection for the subset
vT->SetSelection(offset_size_t, readsize_size_t);
vT->SetStepSelection(0, vT->m_AvailableSteps);
// Arrays are read by scheduling one or more of them
// and performing the reads at once
bpReader->ScheduleRead<double>(*vT, T);
bpReader->PerformReads(adios2::ReadMode::Blocking);
printData(T, readsize.data(), offset.data(), rank, vT->m_AvailableSteps);
bpReader->Close();
delete[] T;
MPI_Finalize();
return 0;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2015 Andrew Sutton
// All rights reserved
#ifndef LINGO_LEXING_HPP
#define LINGO_LEXING_HPP
// The lexing module provides support for writing lexers
// by providing a number of generic scanners for different
// character sequences.
//
// These algorithms are based on a Lexer concept. Every
// lexer must expose a number of operations.
#include "lingo/string.hpp"
#include "lingo/location.hpp"
#include "lingo/token.hpp"
#include "lingo/algorithm.hpp"
#include "lingo/error.hpp"
namespace lingo
{
// -------------------------------------------------------------------------- //
// Character classes
// Returns true if c is white space.
inline bool
is_space(char c)
{
return std::isspace(c);
}
// Returns true if c is alphabetical.
inline bool
is_alpha(char c)
{
return std::isalpha(c);
}
// Returns true if c is a binary digit.
inline bool
is_binary_digit(char c)
{
return c == '0' || c == '1';
}
// Returns true if c is an octal digit.
inline bool
is_octal_digit(char c)
{
return '0' <= c && c <= '7';
}
// Returns true if c is a decimial digit.
inline bool
is_decimal_digit(char c)
{
return std::isdigit(c);
}
// Returns true if c is a hexadecimal digit.
inline bool
is_hexadecimal_digit(char c)
{
return std::isxdigit(c);
}
// Returns true if c starts an identifier.
inline bool
is_ident_head(char c)
{
return is_alpha(c) || c == '_';
}
// Returns true if c can appear in the rest of an identifier.
inline bool
is_ident_tail(char c)
{
return is_ident_tail(c) || is_decimal_digit(c);
}
// -------------------------------------------------------------------------- //
// Integer lexers
//
// TODO: Conditionally support a character as a digit separator
// in integer values.
//
// Note that an integer value like '0x' is an error. Note that the
// lexers for prefixed integer values require the lexer to define
// the following functions:
//
// cxt.on_expected(loc, t)
// cxt.on_expected(loc, str)
// Lexically analyze a decimal integer. The current character
// is `s` must be in the set of decimal digits.
template<typename Lexer, typename Stream>
inline Result_type<Lexer>
lex_decimal_integer(Lexer& lex, Stream& s, Location loc)
{
auto pred = [](Stream& s) { return next_element_if(s, is_decimal_digit); };
auto range = match_range_after_first(s, pred);
return lex.on_decimal_integer(loc, range.begin(), range.end());
}
namespace
{
// A helper function for lexing integers with a specified
// base prefix. If successful, returns a character range
// that includes the 2-character prefix.
template<typename Stream, typename P>
inline Range_over<Stream>
match_integer_in_base(Stream& s, P pred)
{
auto first = get_n(s, 2);
auto range = match_range_after_first(s, pred);
if (range)
return {first, range.end()};
else
return range;
}
} // namespace
// Lex a binary integer where the first two characters are
// known to be '0b' or '0B'
template<typename Lexer, typename Stream>
inline Result_type<Lexer>
lex_binary_integer(Lexer& lex, Stream& s, Location loc)
{
auto pred = [](Stream& s) { return next_element_if(s, is_binary_digit); };
auto range = match_integer_in_base(s, pred);
if (!range) {
lex.on_expected(loc, "binary-digit");
return {};
}
return lex.on_binary_integer(loc, range.begin(), range.end());
}
// Lex an octal integer where the first two characters are
// known to be '0o' or '0O' (that's a 0 and an O).
template<typename Lexer, typename Stream>
inline Result_type<Lexer>
lex_octal_integer(Lexer& lex, Stream& s, Location loc)
{
auto pred = [](Stream& s) { return next_element_if(s, is_octal_digit); };
auto range = match_integer_in_base(s, pred);
if (!range) {
lex.on_expected(loc, "octal-digit");
return {};
}
return lex.on_octal_integer(loc, range.begin(), range.end());
}
// Lex a hexadecimal integer where the first two characters are
// known to be '0x' or '0X'.
template<typename Lexer, typename Stream>
inline Result_type<Lexer>
lex_hexadecimal_integer(Lexer& lex, Stream& s, Location loc)
{
auto pred = [](Stream& s) { return next_element_if(s, is_hexadecimal_digit); };
auto range = match_integer_in_base(s, pred);
if (!range) {
lex.on_expected(loc, "hexadecimal-digit");
return {};
}
return lex.on_hexadecimal_integer(loc, range.begin(), range.end());
}
// Lex a numeric literal.
//
// TODO: If we know that we start with 0, then we can skip the
// first comparison. This could be two algorithms.
//
// TODO: Repeated comparisons for nth_element may repeatedly
// check for eof. This could be optimized.
//
// TODO: Add support for floating point values.
template<typename Lexer, typename Stream>
inline Result_type<Lexer>
lex_number(Lexer& l, Stream& s, Location loc)
{
if (s.peek() == '0') {
if (nth_element_is(s, 1, 'b'))
return lex_binary_integer(l, s, loc);
if (nth_element_is(s, 1, 'o'))
return lex_octal_integer(l, s, loc);
if (nth_element_is(s, 1, 'x'))
return lex_hexadecimal_integer(l, s, loc);
}
return lex_decimal_integer(l, s, loc);
}
template<typename Lexer, typename Stream>
inline Result_type<Lexer>
lex_identifier(Lexer& l, Stream& s, Location loc)
{
auto first = s.begin();
while (!s.eof() && is_ident_tail(s.peek()))
s.get();
return l.on_identifier(loc, first, s.begin());
}
} // namespace lingo
#endif
<commit_msg>Fix infinite recursion in identifier lex.<commit_after>// Copyright (c) 2015 Andrew Sutton
// All rights reserved
#ifndef LINGO_LEXING_HPP
#define LINGO_LEXING_HPP
// The lexing module provides support for writing lexers
// by providing a number of generic scanners for different
// character sequences.
//
// These algorithms are based on a Lexer concept. Every
// lexer must expose a number of operations.
#include "lingo/string.hpp"
#include "lingo/location.hpp"
#include "lingo/token.hpp"
#include "lingo/algorithm.hpp"
#include "lingo/error.hpp"
namespace lingo
{
// -------------------------------------------------------------------------- //
// Character classes
// Returns true if c is white space.
inline bool
is_space(char c)
{
return std::isspace(c);
}
// Returns true if c is alphabetical.
inline bool
is_alpha(char c)
{
return std::isalpha(c);
}
// Returns true if c is a binary digit.
inline bool
is_binary_digit(char c)
{
return c == '0' || c == '1';
}
// Returns true if c is an octal digit.
inline bool
is_octal_digit(char c)
{
return '0' <= c && c <= '7';
}
// Returns true if c is a decimial digit.
inline bool
is_decimal_digit(char c)
{
return std::isdigit(c);
}
// Returns true if c is a hexadecimal digit.
inline bool
is_hexadecimal_digit(char c)
{
return std::isxdigit(c);
}
// Returns true if c starts an identifier.
inline bool
is_ident_head(char c)
{
return is_alpha(c) || c == '_';
}
// Returns true if c can appear in the rest of an identifier.
inline bool
is_ident_tail(char c)
{
return is_ident_head(c) || is_decimal_digit(c);
}
// -------------------------------------------------------------------------- //
// Integer lexers
//
// TODO: Conditionally support a character as a digit separator
// in integer values.
//
// Note that an integer value like '0x' is an error. Note that the
// lexers for prefixed integer values require the lexer to define
// the following functions:
//
// cxt.on_expected(loc, t)
// cxt.on_expected(loc, str)
// Lexically analyze a decimal integer. The current character
// is `s` must be in the set of decimal digits.
template<typename Lexer, typename Stream>
inline Result_type<Lexer>
lex_decimal_integer(Lexer& lex, Stream& s, Location loc)
{
auto pred = [](Stream& s) { return next_element_if(s, is_decimal_digit); };
auto range = match_range_after_first(s, pred);
return lex.on_decimal_integer(loc, range.begin(), range.end());
}
namespace
{
// A helper function for lexing integers with a specified
// base prefix. If successful, returns a character range
// that includes the 2-character prefix.
template<typename Stream, typename P>
inline Range_over<Stream>
match_integer_in_base(Stream& s, P pred)
{
auto first = get_n(s, 2);
auto range = match_range_after_first(s, pred);
if (range)
return {first, range.end()};
else
return range;
}
} // namespace
// Lex a binary integer where the first two characters are
// known to be '0b' or '0B'
template<typename Lexer, typename Stream>
inline Result_type<Lexer>
lex_binary_integer(Lexer& lex, Stream& s, Location loc)
{
auto pred = [](Stream& s) { return next_element_if(s, is_binary_digit); };
auto range = match_integer_in_base(s, pred);
if (!range) {
lex.on_expected(loc, "binary-digit");
return {};
}
return lex.on_binary_integer(loc, range.begin(), range.end());
}
// Lex an octal integer where the first two characters are
// known to be '0o' or '0O' (that's a 0 and an O).
template<typename Lexer, typename Stream>
inline Result_type<Lexer>
lex_octal_integer(Lexer& lex, Stream& s, Location loc)
{
auto pred = [](Stream& s) { return next_element_if(s, is_octal_digit); };
auto range = match_integer_in_base(s, pred);
if (!range) {
lex.on_expected(loc, "octal-digit");
return {};
}
return lex.on_octal_integer(loc, range.begin(), range.end());
}
// Lex a hexadecimal integer where the first two characters are
// known to be '0x' or '0X'.
template<typename Lexer, typename Stream>
inline Result_type<Lexer>
lex_hexadecimal_integer(Lexer& lex, Stream& s, Location loc)
{
auto pred = [](Stream& s) { return next_element_if(s, is_hexadecimal_digit); };
auto range = match_integer_in_base(s, pred);
if (!range) {
lex.on_expected(loc, "hexadecimal-digit");
return {};
}
return lex.on_hexadecimal_integer(loc, range.begin(), range.end());
}
// Lex a numeric literal.
//
// TODO: If we know that we start with 0, then we can skip the
// first comparison. This could be two algorithms.
//
// TODO: Repeated comparisons for nth_element may repeatedly
// check for eof. This could be optimized.
//
// TODO: Add support for floating point values.
template<typename Lexer, typename Stream>
inline Result_type<Lexer>
lex_number(Lexer& l, Stream& s, Location loc)
{
if (s.peek() == '0') {
if (nth_element_is(s, 1, 'b'))
return lex_binary_integer(l, s, loc);
if (nth_element_is(s, 1, 'o'))
return lex_octal_integer(l, s, loc);
if (nth_element_is(s, 1, 'x'))
return lex_hexadecimal_integer(l, s, loc);
}
return lex_decimal_integer(l, s, loc);
}
template<typename Lexer, typename Stream>
inline Result_type<Lexer>
lex_identifier(Lexer& l, Stream& s, Location loc)
{
auto first = s.begin();
while (!s.eof() && is_ident_tail(s.peek()))
s.get();
return l.on_identifier(loc, first, s.begin());
}
} // namespace lingo
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: myucp_resultset.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-08 13:32:08 $
*
* 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 DBA_UCPRESULTSET_HXX
#define DBA_UCPRESULTSET_HXX
#ifndef _RTL_REF_HXX_
#include <rtl/ref.hxx>
#endif
#ifndef _UCBHELPER_RESULTSETHELPER_HXX
#include <ucbhelper/resultsethelper.hxx>
#endif
#ifndef _DBA_COREDATAACCESS_DOCUMENTCONTAINER_HXX_
#include "documentcontainer.hxx"
#endif
// @@@ Adjust namespace name.
namespace dbaccess {
class DynamicResultSet : public ::ucb::ResultSetImplHelper
{
rtl::Reference< ODocumentContainer > m_xContent;
com::sun::star::uno::Reference<
com::sun::star::ucb::XCommandEnvironment > m_xEnv;
private:
virtual void initStatic();
virtual void initDynamic();
public:
DynamicResultSet(
const com::sun::star::uno::Reference<
com::sun::star::lang::XMultiServiceFactory >& rxSMgr,
const rtl::Reference< ODocumentContainer >& rxContent,
const com::sun::star::ucb::OpenCommandArgument2& rCommand,
const com::sun::star::uno::Reference<
com::sun::star::ucb::XCommandEnvironment >& rxEnv );
};
}
#endif // DBA_UCPRESULTSET_HXX
<commit_msg>INTEGRATION: CWS bgdlremove (1.3.278); FILE MERGED 2007/05/18 09:03:13 kso 1.3.278.1: #i77419# - cleanup of ucbhelper namespaces.<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: myucp_resultset.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: ihi $ $Date: 2007-06-05 14:40:12 $
*
* 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 DBA_UCPRESULTSET_HXX
#define DBA_UCPRESULTSET_HXX
#ifndef _RTL_REF_HXX_
#include <rtl/ref.hxx>
#endif
#ifndef _UCBHELPER_RESULTSETHELPER_HXX
#include <ucbhelper/resultsethelper.hxx>
#endif
#ifndef _DBA_COREDATAACCESS_DOCUMENTCONTAINER_HXX_
#include "documentcontainer.hxx"
#endif
// @@@ Adjust namespace name.
namespace dbaccess {
class DynamicResultSet : public ::ucbhelper::ResultSetImplHelper
{
rtl::Reference< ODocumentContainer > m_xContent;
com::sun::star::uno::Reference<
com::sun::star::ucb::XCommandEnvironment > m_xEnv;
private:
virtual void initStatic();
virtual void initDynamic();
public:
DynamicResultSet(
const com::sun::star::uno::Reference<
com::sun::star::lang::XMultiServiceFactory >& rxSMgr,
const rtl::Reference< ODocumentContainer >& rxContent,
const com::sun::star::ucb::OpenCommandArgument2& rCommand,
const com::sun::star::uno::Reference<
com::sun::star::ucb::XCommandEnvironment >& rxEnv );
};
}
#endif // DBA_UCPRESULTSET_HXX
<|endoftext|> |
<commit_before>#include "nucleus/HighPerformanceTimer.h"
#include "nucleus/Config.h"
#include "nucleus/Logging.h"
#if OS(WIN)
#include "nucleus/Win/WindowsMixin.h"
#elif OS(MACOSX)
#include <mach/mach_time.h>
#elif OS(POSIX)
#include <time.h>
#ifdef CLOCK_MONOTONIC
#define CLOCKID CLOCK_MONOTONIC
#else
#define CLOCKID CLOCK_REALTIME
#endif
#else
#error Operating system not supported
#endif
namespace nu {
namespace {
struct FrequencyStorage {
F64 ticksPerSecond;
FrequencyStorage() noexcept {
#if OS(WIN)
LARGE_INTEGER frequency;
QueryPerformanceFrequency(&frequency);
ticksPerSecond = static_cast<F64>(frequency.QuadPart);
#elif OS(MACOSX)
mach_timebase_info_data_t rate;
mach_timebase_info(&rate);
ticksPerSecond = static_cast<F64>(rate.numer) * 1000.0 / static_cast<F64>(rate.denom);
#elif OS(POSIX)
struct timespec rate;
clock_getres(CLOCKID, &rate);
ticksPerSecond = static_cast<F64>(rate.tv_nsec) * 1000.0;
#else
#error Operating system not supported
#endif
}
};
FrequencyStorage s_frequencyStorage;
} // namespace
F64 getCurrentHighPerformanceTick() {
#if OS(WIN)
LARGE_INTEGER counter;
QueryPerformanceCounter(&counter);
return static_cast<F64>(counter.QuadPart) * 1000.0 * 1000.0 / s_frequencyStorage.ticksPerSecond;
#elif OS(MACOSX)
auto time = mach_absolute_time();
return static_cast<F64>(time) / s_frequencyStorage.ticksPerSecond;
#elif OS(POSIX)
struct timespec specTime;
clock_gettime(CLOCKID, &specTime);
F64 now = static_cast<F64>(specTime.tv_sec) * 1000000.0 + static_cast<F64>(specTime.tv_nsec);
#else
#error Operating system not supported
#endif
}
} // namespace nu
<commit_msg>Fix posix compilation error.<commit_after>#include "nucleus/HighPerformanceTimer.h"
#include "nucleus/Config.h"
#include "nucleus/Logging.h"
#if OS(WIN)
#include "nucleus/Win/WindowsMixin.h"
#elif OS(MACOSX)
#include <mach/mach_time.h>
#elif OS(POSIX)
#include <time.h>
#ifdef CLOCK_MONOTONIC
#define CLOCKID CLOCK_MONOTONIC
#else
#define CLOCKID CLOCK_REALTIME
#endif
#else
#error Operating system not supported
#endif
namespace nu {
namespace {
struct FrequencyStorage {
F64 ticksPerSecond;
FrequencyStorage() noexcept {
#if OS(WIN)
LARGE_INTEGER frequency;
QueryPerformanceFrequency(&frequency);
ticksPerSecond = static_cast<F64>(frequency.QuadPart);
#elif OS(MACOSX)
mach_timebase_info_data_t rate;
mach_timebase_info(&rate);
ticksPerSecond = static_cast<F64>(rate.numer) * 1000.0 / static_cast<F64>(rate.denom);
#elif OS(POSIX)
struct timespec rate;
clock_getres(CLOCKID, &rate);
ticksPerSecond = static_cast<F64>(rate.tv_nsec) * 1000.0;
#else
#error Operating system not supported
#endif
}
};
FrequencyStorage s_frequencyStorage;
} // namespace
F64 getCurrentHighPerformanceTick() {
#if OS(WIN)
LARGE_INTEGER counter;
QueryPerformanceCounter(&counter);
return static_cast<F64>(counter.QuadPart) * 1000.0 * 1000.0 / s_frequencyStorage.ticksPerSecond;
#elif OS(MACOSX)
auto time = mach_absolute_time();
return static_cast<F64>(time) / s_frequencyStorage.ticksPerSecond;
#elif OS(POSIX)
struct timespec time;
clock_gettime(CLOCKID, &time);
return static_cast<F64>(time.tv_sec) * 1000000.0 + static_cast<F64>(time.tv_nsec);
#else
#error Operating system not supported
#endif
}
} // namespace nu
<|endoftext|> |
<commit_before>/* OpenSceneGraph example, osgtexture3D.
*
* 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 SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <osg/Node>
#include <osg/Geometry>
#include <osg/Notify>
#include <osg/Texture1D>
#include <osg/Texture2D>
#include <osg/Texture3D>
#include <osg/TextureRectangle>
#include <osg/ImageSequence>
#include <osg/Geode>
#include <osgDB/Registry>
#include <osgDB/ReadFile>
#include <osgDB/WriteFile>
#include <osgDB/FileNameUtils>
#include <osgDB/FileUtils>
#include <osgViewer/Viewer>
#include <osgViewer/ViewerEventHandlers>
#include <iostream>
static osgDB::DirectoryContents getSuitableFiles(osg::ArgumentParser& arguments)
{
osgDB::DirectoryContents files;
for(int i=1; i<arguments.argc(); ++i)
{
if (osgDB::fileType(arguments[i]) == osgDB::DIRECTORY)
{
const std::string& directory = arguments[i];
osgDB::DirectoryContents dc = osgDB::getSortedDirectoryContents(directory);
for(osgDB::DirectoryContents::iterator itr = dc.begin(); itr != dc.end(); ++itr)
{
std::string full_file_name = directory + "/" + (*itr);
std::string ext = osgDB::getLowerCaseFileExtension(full_file_name);
if ((ext == "jpg") || (ext == "png") || (ext == "gif") || (ext == "rgb") || (ext == "dds") )
{
files.push_back(full_file_name);
}
}
}
else {
files.push_back(arguments[i]);
}
}
return files;
}
//
// A simple demo demonstrating how to set on an animated texture using an osg::ImageSequence
//
osg::StateSet* createState(osg::ArgumentParser& arguments)
{
osg::ref_ptr<osg::ImageSequence> imageSequence = new osg::ImageSequence;
bool preLoad = true;
while (arguments.read("--page-and-discard"))
{
imageSequence->setMode(osg::ImageSequence::PAGE_AND_DISCARD_USED_IMAGES);
preLoad = false;
}
while (arguments.read("--page-and-retain"))
{
imageSequence->setMode(osg::ImageSequence::PAGE_AND_RETAIN_IMAGES);
preLoad = false;
}
while (arguments.read("--preload"))
{
imageSequence->setMode(osg::ImageSequence::PRE_LOAD_ALL_IMAGES);
preLoad = true;
}
double length = -1.0;
while (arguments.read("--length",length)) {}
double fps = 30.0;
while (arguments.read("--fps",fps)) {}
osgDB::DirectoryContents files = getSuitableFiles(arguments);
if (!files.empty())
{
for(osgDB::DirectoryContents::iterator itr = files.begin();
itr != files.end();
++itr)
{
const std::string& filename = *itr;
if (preLoad)
{
osg::ref_ptr<osg::Image> image = osgDB::readRefImageFile(filename);
if (image.valid())
{
imageSequence->addImage(image.get());
}
}
else
{
imageSequence->addImageFile(filename);
}
}
if (length>0.0)
{
imageSequence->setLength(length);
}
else
{
unsigned int maxNum = imageSequence->getNumImageData();
imageSequence->setLength(double(maxNum)*(1.0/fps));
}
}
else
{
if (length>0.0)
{
imageSequence->setLength(length);
}
else
{
imageSequence->setLength(4.0);
}
imageSequence->addImage(osgDB::readRefImageFile("Cubemap_axis/posx.png"));
imageSequence->addImage(osgDB::readRefImageFile("Cubemap_axis/negx.png"));
imageSequence->addImage(osgDB::readRefImageFile("Cubemap_axis/posy.png"));
imageSequence->addImage(osgDB::readRefImageFile("Cubemap_axis/negy.png"));
imageSequence->addImage(osgDB::readRefImageFile("Cubemap_axis/posz.png"));
imageSequence->addImage(osgDB::readRefImageFile("Cubemap_axis/negz.png"));
}
// start the image sequence playing
imageSequence->play();
#if 1
osg::Texture2D* texture = new osg::Texture2D;
texture->setFilter(osg::Texture::MIN_FILTER,osg::Texture::LINEAR);
texture->setFilter(osg::Texture::MAG_FILTER,osg::Texture::LINEAR);
texture->setWrap(osg::Texture::WRAP_R,osg::Texture::REPEAT);
texture->setResizeNonPowerOfTwoHint(false);
texture->setImage(imageSequence.get());
//texture->setTextureSize(512,512);
#else
osg::TextureRectangle* texture = new osg::TextureRectangle;
texture->setFilter(osg::Texture::MIN_FILTER,osg::Texture::LINEAR);
texture->setFilter(osg::Texture::MAG_FILTER,osg::Texture::LINEAR);
texture->setWrap(osg::Texture::WRAP_R,osg::Texture::REPEAT);
texture->setImage(imageSequence.get());
//texture->setTextureSize(512,512);
#endif
// create the StateSet to store the texture data
osg::StateSet* stateset = new osg::StateSet;
stateset->setTextureAttributeAndModes(0,texture,osg::StateAttribute::ON);
return stateset;
}
osg::Node* createModel(osg::ArgumentParser& arguments)
{
// create the geometry of the model, just a simple 2d quad right now.
osg::Geode* geode = new osg::Geode;
geode->addDrawable(osg::createTexturedQuadGeometry(osg::Vec3(0.0f,0.0f,0.0), osg::Vec3(1.0f,0.0f,0.0), osg::Vec3(0.0f,0.0f,1.0f)));
geode->setStateSet(createState(arguments));
return geode;
}
osg::ImageStream* s_imageStream = 0;
class MovieEventHandler : public osgGA::GUIEventHandler
{
public:
MovieEventHandler():_playToggle(true),_trackMouse(false) {}
void setMouseTracking(bool track) { _trackMouse = track; }
bool getMouseTracking() const { return _trackMouse; }
void set(osg::Node* node);
void setTrackMouse(bool tm)
{
if (tm==_trackMouse) return;
_trackMouse = tm;
std::cout << "tracking mouse: " << (_trackMouse ? "ON" : "OFF") << std::endl;
for(ImageStreamList::iterator itr=_imageStreamList.begin();
itr!=_imageStreamList.end();
++itr)
{
if ((*itr)->getStatus()==osg::ImageStream::PLAYING)
{
(*itr)->pause();
}
else
{
(*itr)->play();
}
}
}
bool getTrackMouse() const { return _trackMouse; }
virtual bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter& aa, osg::Object*, osg::NodeVisitor* nv);
virtual void getUsage(osg::ApplicationUsage& usage) const;
typedef std::vector< osg::observer_ptr<osg::ImageStream> > ImageStreamList;
struct ImageStreamPlaybackSpeedData {
double fps;
unsigned char* lastData;
double timeStamp, lastOutput;
ImageStreamPlaybackSpeedData() : fps(0), lastData(NULL), timeStamp(0), lastOutput(0) {}
};
typedef std::vector< ImageStreamPlaybackSpeedData > ImageStreamPlayBackSpeedList;
protected:
virtual ~MovieEventHandler() {}
class FindImageStreamsVisitor : public osg::NodeVisitor
{
public:
FindImageStreamsVisitor(ImageStreamList& imageStreamList):
_imageStreamList(imageStreamList) {}
virtual void apply(osg::Geode& geode)
{
apply(geode.getStateSet());
for(unsigned int i=0;i<geode.getNumDrawables();++i)
{
apply(geode.getDrawable(i)->getStateSet());
}
traverse(geode);
}
virtual void apply(osg::Node& node)
{
apply(node.getStateSet());
traverse(node);
}
inline void apply(osg::StateSet* stateset)
{
if (!stateset) return;
osg::StateAttribute* attr = stateset->getTextureAttribute(0,osg::StateAttribute::TEXTURE);
if (attr)
{
osg::Texture2D* texture2D = dynamic_cast<osg::Texture2D*>(attr);
if (texture2D) apply(dynamic_cast<osg::ImageStream*>(texture2D->getImage()));
osg::TextureRectangle* textureRec = dynamic_cast<osg::TextureRectangle*>(attr);
if (textureRec) apply(dynamic_cast<osg::ImageStream*>(textureRec->getImage()));
}
}
inline void apply(osg::ImageStream* imagestream)
{
if (imagestream)
{
_imageStreamList.push_back(imagestream);
s_imageStream = imagestream;
}
}
ImageStreamList& _imageStreamList;
protected:
FindImageStreamsVisitor& operator = (const FindImageStreamsVisitor&) { return *this; }
};
bool _playToggle;
bool _trackMouse;
ImageStreamList _imageStreamList;
ImageStreamPlayBackSpeedList _imageStreamPlayBackSpeedList;
};
void MovieEventHandler::set(osg::Node* node)
{
_imageStreamList.clear();
if (node)
{
FindImageStreamsVisitor fisv(_imageStreamList);
node->accept(fisv);
}
_imageStreamPlayBackSpeedList.resize(_imageStreamList.size());
}
bool MovieEventHandler::handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter& aa, osg::Object*, osg::NodeVisitor* nv)
{
switch(ea.getEventType())
{
case(osgGA::GUIEventAdapter::FRAME):
{
double t = ea.getTime();
bool printed(false);
ImageStreamPlayBackSpeedList::iterator fps_itr = _imageStreamPlayBackSpeedList.begin();
for(ImageStreamList::iterator itr=_imageStreamList.begin();
itr!=_imageStreamList.end();
++itr, ++fps_itr)
{
if (((*itr)->getStatus()==osg::ImageStream::PLAYING) && ((*itr)->data() != (*fps_itr).lastData))
{
ImageStreamPlaybackSpeedData& data(*fps_itr);
double dt = (data.timeStamp > 0) ? t - data.timeStamp : 1/60.0;
data.lastData = (*itr)->data();
data.fps = (*fps_itr).fps * 0.8 + 0.2 * (1/dt);
data.timeStamp = t;
if (t-data.lastOutput > 1)
{
std::cout << data.fps << " ";
data.lastOutput = t;
printed = true;
}
}
}
if (printed)
std::cout << std::endl;
}
break;
case(osgGA::GUIEventAdapter::MOVE):
{
if (_trackMouse)
{
for(ImageStreamList::iterator itr=_imageStreamList.begin();
itr!=_imageStreamList.end();
++itr)
{
double dt = (*itr)->getLength() * ((1.0+ea.getXnormalized()) / 2.0);
(*itr)->seek(dt);
std::cout << "seeking to " << dt << " length: " <<(*itr)->getLength() << std::endl;
}
}
return false;
}
case(osgGA::GUIEventAdapter::KEYDOWN):
{
if (ea.getKey()=='p')
{
for(ImageStreamList::iterator itr=_imageStreamList.begin();
itr!=_imageStreamList.end();
++itr)
{
if ((*itr)->getStatus()==osg::ImageStream::PLAYING)
{
// playing, so pause
std::cout<<"Pause"<<std::endl;
(*itr)->pause();
}
else
{
// playing, so pause
std::cout<<"Play"<<std::endl;
(*itr)->play();
}
}
return true;
}
else if (ea.getKey()=='r')
{
for(ImageStreamList::iterator itr=_imageStreamList.begin();
itr!=_imageStreamList.end();
++itr)
{
std::cout<<"Restart"<<std::endl;
(*itr)->rewind();
}
return true;
}
else if (ea.getKey()=='L')
{
for(ImageStreamList::iterator itr=_imageStreamList.begin();
itr!=_imageStreamList.end();
++itr)
{
if ( (*itr)->getLoopingMode() == osg::ImageStream::LOOPING)
{
std::cout<<"Toggle Looping Off"<<std::endl;
(*itr)->setLoopingMode( osg::ImageStream::NO_LOOPING );
}
else
{
std::cout<<"Toggle Looping On"<<std::endl;
(*itr)->setLoopingMode( osg::ImageStream::LOOPING );
}
}
return true;
}
else if (ea.getKey() == 'i')
{
setTrackMouse(!_trackMouse);
}
return false;
}
default:
return false;
}
return false;
}
void MovieEventHandler::getUsage(osg::ApplicationUsage& usage) const
{
usage.addKeyboardMouseBinding("i","toggle interactive mode, scrub via mouse-move");
usage.addKeyboardMouseBinding("p","Play/Pause movie");
usage.addKeyboardMouseBinding("r","Restart movie");
usage.addKeyboardMouseBinding("l","Toggle looping of movie");
}
int main(int argc, char **argv)
{
osg::ArgumentParser arguments(&argc,argv);
// construct the viewer.
osgViewer::Viewer viewer(arguments);
std::string filename;
arguments.read("-o",filename);
// create a model from the images and pass it to the viewer.
viewer.setSceneData(createModel(arguments));
// pass the model to the MovieEventHandler so it can pick out ImageStream's to manipulate.
MovieEventHandler* meh = new MovieEventHandler();
meh->set( viewer.getSceneData() );
if (arguments.read("--track-mouse")) meh->setTrackMouse(true);
viewer.addEventHandler( meh );
viewer.addEventHandler( new osgViewer::StatsHandler());
if (!filename.empty())
{
osgDB::writeNodeFile(*viewer.getSceneData(),filename);
}
return viewer.run();
}
<commit_msg>Fixed unused parameter warning.<commit_after>/* OpenSceneGraph example, osgtexture3D.
*
* 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 SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <osg/Node>
#include <osg/Geometry>
#include <osg/Notify>
#include <osg/Texture1D>
#include <osg/Texture2D>
#include <osg/Texture3D>
#include <osg/TextureRectangle>
#include <osg/ImageSequence>
#include <osg/Geode>
#include <osgDB/Registry>
#include <osgDB/ReadFile>
#include <osgDB/WriteFile>
#include <osgDB/FileNameUtils>
#include <osgDB/FileUtils>
#include <osgViewer/Viewer>
#include <osgViewer/ViewerEventHandlers>
#include <iostream>
static osgDB::DirectoryContents getSuitableFiles(osg::ArgumentParser& arguments)
{
osgDB::DirectoryContents files;
for(int i=1; i<arguments.argc(); ++i)
{
if (osgDB::fileType(arguments[i]) == osgDB::DIRECTORY)
{
const std::string& directory = arguments[i];
osgDB::DirectoryContents dc = osgDB::getSortedDirectoryContents(directory);
for(osgDB::DirectoryContents::iterator itr = dc.begin(); itr != dc.end(); ++itr)
{
std::string full_file_name = directory + "/" + (*itr);
std::string ext = osgDB::getLowerCaseFileExtension(full_file_name);
if ((ext == "jpg") || (ext == "png") || (ext == "gif") || (ext == "rgb") || (ext == "dds") )
{
files.push_back(full_file_name);
}
}
}
else {
files.push_back(arguments[i]);
}
}
return files;
}
//
// A simple demo demonstrating how to set on an animated texture using an osg::ImageSequence
//
osg::StateSet* createState(osg::ArgumentParser& arguments)
{
osg::ref_ptr<osg::ImageSequence> imageSequence = new osg::ImageSequence;
bool preLoad = true;
while (arguments.read("--page-and-discard"))
{
imageSequence->setMode(osg::ImageSequence::PAGE_AND_DISCARD_USED_IMAGES);
preLoad = false;
}
while (arguments.read("--page-and-retain"))
{
imageSequence->setMode(osg::ImageSequence::PAGE_AND_RETAIN_IMAGES);
preLoad = false;
}
while (arguments.read("--preload"))
{
imageSequence->setMode(osg::ImageSequence::PRE_LOAD_ALL_IMAGES);
preLoad = true;
}
double length = -1.0;
while (arguments.read("--length",length)) {}
double fps = 30.0;
while (arguments.read("--fps",fps)) {}
osgDB::DirectoryContents files = getSuitableFiles(arguments);
if (!files.empty())
{
for(osgDB::DirectoryContents::iterator itr = files.begin();
itr != files.end();
++itr)
{
const std::string& filename = *itr;
if (preLoad)
{
osg::ref_ptr<osg::Image> image = osgDB::readRefImageFile(filename);
if (image.valid())
{
imageSequence->addImage(image.get());
}
}
else
{
imageSequence->addImageFile(filename);
}
}
if (length>0.0)
{
imageSequence->setLength(length);
}
else
{
unsigned int maxNum = imageSequence->getNumImageData();
imageSequence->setLength(double(maxNum)*(1.0/fps));
}
}
else
{
if (length>0.0)
{
imageSequence->setLength(length);
}
else
{
imageSequence->setLength(4.0);
}
imageSequence->addImage(osgDB::readRefImageFile("Cubemap_axis/posx.png"));
imageSequence->addImage(osgDB::readRefImageFile("Cubemap_axis/negx.png"));
imageSequence->addImage(osgDB::readRefImageFile("Cubemap_axis/posy.png"));
imageSequence->addImage(osgDB::readRefImageFile("Cubemap_axis/negy.png"));
imageSequence->addImage(osgDB::readRefImageFile("Cubemap_axis/posz.png"));
imageSequence->addImage(osgDB::readRefImageFile("Cubemap_axis/negz.png"));
}
// start the image sequence playing
imageSequence->play();
#if 1
osg::Texture2D* texture = new osg::Texture2D;
texture->setFilter(osg::Texture::MIN_FILTER,osg::Texture::LINEAR);
texture->setFilter(osg::Texture::MAG_FILTER,osg::Texture::LINEAR);
texture->setWrap(osg::Texture::WRAP_R,osg::Texture::REPEAT);
texture->setResizeNonPowerOfTwoHint(false);
texture->setImage(imageSequence.get());
//texture->setTextureSize(512,512);
#else
osg::TextureRectangle* texture = new osg::TextureRectangle;
texture->setFilter(osg::Texture::MIN_FILTER,osg::Texture::LINEAR);
texture->setFilter(osg::Texture::MAG_FILTER,osg::Texture::LINEAR);
texture->setWrap(osg::Texture::WRAP_R,osg::Texture::REPEAT);
texture->setImage(imageSequence.get());
//texture->setTextureSize(512,512);
#endif
// create the StateSet to store the texture data
osg::StateSet* stateset = new osg::StateSet;
stateset->setTextureAttributeAndModes(0,texture,osg::StateAttribute::ON);
return stateset;
}
osg::Node* createModel(osg::ArgumentParser& arguments)
{
// create the geometry of the model, just a simple 2d quad right now.
osg::Geode* geode = new osg::Geode;
geode->addDrawable(osg::createTexturedQuadGeometry(osg::Vec3(0.0f,0.0f,0.0), osg::Vec3(1.0f,0.0f,0.0), osg::Vec3(0.0f,0.0f,1.0f)));
geode->setStateSet(createState(arguments));
return geode;
}
osg::ImageStream* s_imageStream = 0;
class MovieEventHandler : public osgGA::GUIEventHandler
{
public:
MovieEventHandler():_playToggle(true),_trackMouse(false) {}
void setMouseTracking(bool track) { _trackMouse = track; }
bool getMouseTracking() const { return _trackMouse; }
void set(osg::Node* node);
void setTrackMouse(bool tm)
{
if (tm==_trackMouse) return;
_trackMouse = tm;
std::cout << "tracking mouse: " << (_trackMouse ? "ON" : "OFF") << std::endl;
for(ImageStreamList::iterator itr=_imageStreamList.begin();
itr!=_imageStreamList.end();
++itr)
{
if ((*itr)->getStatus()==osg::ImageStream::PLAYING)
{
(*itr)->pause();
}
else
{
(*itr)->play();
}
}
}
bool getTrackMouse() const { return _trackMouse; }
virtual bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter& aa, osg::Object*, osg::NodeVisitor* nv);
virtual void getUsage(osg::ApplicationUsage& usage) const;
typedef std::vector< osg::observer_ptr<osg::ImageStream> > ImageStreamList;
struct ImageStreamPlaybackSpeedData {
double fps;
unsigned char* lastData;
double timeStamp, lastOutput;
ImageStreamPlaybackSpeedData() : fps(0), lastData(NULL), timeStamp(0), lastOutput(0) {}
};
typedef std::vector< ImageStreamPlaybackSpeedData > ImageStreamPlayBackSpeedList;
protected:
virtual ~MovieEventHandler() {}
class FindImageStreamsVisitor : public osg::NodeVisitor
{
public:
FindImageStreamsVisitor(ImageStreamList& imageStreamList):
_imageStreamList(imageStreamList) {}
virtual void apply(osg::Geode& geode)
{
apply(geode.getStateSet());
for(unsigned int i=0;i<geode.getNumDrawables();++i)
{
apply(geode.getDrawable(i)->getStateSet());
}
traverse(geode);
}
virtual void apply(osg::Node& node)
{
apply(node.getStateSet());
traverse(node);
}
inline void apply(osg::StateSet* stateset)
{
if (!stateset) return;
osg::StateAttribute* attr = stateset->getTextureAttribute(0,osg::StateAttribute::TEXTURE);
if (attr)
{
osg::Texture2D* texture2D = dynamic_cast<osg::Texture2D*>(attr);
if (texture2D) apply(dynamic_cast<osg::ImageStream*>(texture2D->getImage()));
osg::TextureRectangle* textureRec = dynamic_cast<osg::TextureRectangle*>(attr);
if (textureRec) apply(dynamic_cast<osg::ImageStream*>(textureRec->getImage()));
}
}
inline void apply(osg::ImageStream* imagestream)
{
if (imagestream)
{
_imageStreamList.push_back(imagestream);
s_imageStream = imagestream;
}
}
ImageStreamList& _imageStreamList;
protected:
FindImageStreamsVisitor& operator = (const FindImageStreamsVisitor&) { return *this; }
};
bool _playToggle;
bool _trackMouse;
ImageStreamList _imageStreamList;
ImageStreamPlayBackSpeedList _imageStreamPlayBackSpeedList;
};
void MovieEventHandler::set(osg::Node* node)
{
_imageStreamList.clear();
if (node)
{
FindImageStreamsVisitor fisv(_imageStreamList);
node->accept(fisv);
}
_imageStreamPlayBackSpeedList.resize(_imageStreamList.size());
}
bool MovieEventHandler::handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter&, osg::Object*, osg::NodeVisitor*)
{
switch(ea.getEventType())
{
case(osgGA::GUIEventAdapter::FRAME):
{
double t = ea.getTime();
bool printed(false);
ImageStreamPlayBackSpeedList::iterator fps_itr = _imageStreamPlayBackSpeedList.begin();
for(ImageStreamList::iterator itr=_imageStreamList.begin();
itr!=_imageStreamList.end();
++itr, ++fps_itr)
{
if (((*itr)->getStatus()==osg::ImageStream::PLAYING) && ((*itr)->data() != (*fps_itr).lastData))
{
ImageStreamPlaybackSpeedData& data(*fps_itr);
double dt = (data.timeStamp > 0) ? t - data.timeStamp : 1/60.0;
data.lastData = (*itr)->data();
data.fps = (*fps_itr).fps * 0.8 + 0.2 * (1/dt);
data.timeStamp = t;
if (t-data.lastOutput > 1)
{
std::cout << data.fps << " ";
data.lastOutput = t;
printed = true;
}
}
}
if (printed)
std::cout << std::endl;
}
break;
case(osgGA::GUIEventAdapter::MOVE):
{
if (_trackMouse)
{
for(ImageStreamList::iterator itr=_imageStreamList.begin();
itr!=_imageStreamList.end();
++itr)
{
double dt = (*itr)->getLength() * ((1.0+ea.getXnormalized()) / 2.0);
(*itr)->seek(dt);
std::cout << "seeking to " << dt << " length: " <<(*itr)->getLength() << std::endl;
}
}
return false;
}
case(osgGA::GUIEventAdapter::KEYDOWN):
{
if (ea.getKey()=='p')
{
for(ImageStreamList::iterator itr=_imageStreamList.begin();
itr!=_imageStreamList.end();
++itr)
{
if ((*itr)->getStatus()==osg::ImageStream::PLAYING)
{
// playing, so pause
std::cout<<"Pause"<<std::endl;
(*itr)->pause();
}
else
{
// playing, so pause
std::cout<<"Play"<<std::endl;
(*itr)->play();
}
}
return true;
}
else if (ea.getKey()=='r')
{
for(ImageStreamList::iterator itr=_imageStreamList.begin();
itr!=_imageStreamList.end();
++itr)
{
std::cout<<"Restart"<<std::endl;
(*itr)->rewind();
}
return true;
}
else if (ea.getKey()=='L')
{
for(ImageStreamList::iterator itr=_imageStreamList.begin();
itr!=_imageStreamList.end();
++itr)
{
if ( (*itr)->getLoopingMode() == osg::ImageStream::LOOPING)
{
std::cout<<"Toggle Looping Off"<<std::endl;
(*itr)->setLoopingMode( osg::ImageStream::NO_LOOPING );
}
else
{
std::cout<<"Toggle Looping On"<<std::endl;
(*itr)->setLoopingMode( osg::ImageStream::LOOPING );
}
}
return true;
}
else if (ea.getKey() == 'i')
{
setTrackMouse(!_trackMouse);
}
return false;
}
default:
return false;
}
return false;
}
void MovieEventHandler::getUsage(osg::ApplicationUsage& usage) const
{
usage.addKeyboardMouseBinding("i","toggle interactive mode, scrub via mouse-move");
usage.addKeyboardMouseBinding("p","Play/Pause movie");
usage.addKeyboardMouseBinding("r","Restart movie");
usage.addKeyboardMouseBinding("l","Toggle looping of movie");
}
int main(int argc, char **argv)
{
osg::ArgumentParser arguments(&argc,argv);
// construct the viewer.
osgViewer::Viewer viewer(arguments);
std::string filename;
arguments.read("-o",filename);
// create a model from the images and pass it to the viewer.
viewer.setSceneData(createModel(arguments));
// pass the model to the MovieEventHandler so it can pick out ImageStream's to manipulate.
MovieEventHandler* meh = new MovieEventHandler();
meh->set( viewer.getSceneData() );
if (arguments.read("--track-mouse")) meh->setTrackMouse(true);
viewer.addEventHandler( meh );
viewer.addEventHandler( new osgViewer::StatsHandler());
if (!filename.empty())
{
osgDB::writeNodeFile(*viewer.getSceneData(),filename);
}
return viewer.run();
}
<|endoftext|> |
<commit_before><commit_msg>Alphabetized file format lists<commit_after><|endoftext|> |
<commit_before>#include <iostream>
#include <pcl/io/pcd_io.h>
#include <pcl/point_types.h>
using namespace pcl;
int
main (int argc, char** argv)
{
PointCloud<PointXYZ>::Ptr cloud (new PointCloud<PointXYZ>);
if (io::loadPCDFile<PointXYZ> ("test_pcd.pcd", *cloud) == -1) //* load the file
{
PCL_ERROR ("Couldn't read file test_pcd.pcd \n");
return (-1);
}
std::cerr << "Loaded "
<< cloud->width * cloud->height
<< " data points from test_pcd.pcd with the following fields: "
<< std::endl;
for (size_t i = 0; i < cloud->points.size (); ++i)
std::cerr << " " << cloud->points[i].x
<< " " << cloud->points[i].y
<< " " << cloud->points[i].z << std::endl;
return (0);
}<commit_msg>removed using namespace pcl from code<commit_after>#include <iostream>
#include <pcl/io/pcd_io.h>
#include <pcl/point_types.h>
//using namespace pcl;
int
main (int argc, char** argv)
{
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZ>);
if (pcl::io::loadPCDFile<pcl::PointXYZ> ("test_pcd.pcd", *cloud) == -1) //* load the file
{
PCL_ERROR ("Couldn't read file test_pcd.pcd \n");
return (-1);
}
std::cerr << "Loaded "
<< cloud->width * cloud->height
<< " data points from test_pcd.pcd with the following fields: "
<< std::endl;
for (size_t i = 0; i < cloud->points.size (); ++i)
std::cerr << " " << cloud->points[i].x
<< " " << cloud->points[i].y
<< " " << cloud->points[i].z << std::endl;
return (0);
}
<|endoftext|> |
<commit_before>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999-2001 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 "Xalan" 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/>.
*/
// Class header file...
#include "XalanDOMStringHashTable.hpp"
#include <algorithm>
#include "DOMStringHelper.hpp"
XalanDOMStringHashTable::XalanDOMStringHashTable(
unsigned int theBucketCount,
unsigned int theBucketSize) :
m_bucketCount(theBucketCount),
m_bucketSize(theBucketSize),
m_buckets(new BucketType[theBucketCount]),
m_count(0),
m_collisions(0)
{
}
void
XalanDOMStringHashTable::clear()
{
for(unsigned int i = 0; i < m_bucketCount; ++i)
{
m_buckets[i].clear();
}
#if !defined(NDEBUG)
m_collisions = 0;
#endif
m_count = 0;
}
void
XalanDOMStringHashTable::getBucketCounts(BucketCountsType& theVector) const
{
for(unsigned int i = 0; i < m_bucketCount; ++i)
{
theVector.push_back(m_buckets[i].size());
}
}
struct
equalsXalanDOMString
{
equalsXalanDOMString(
const XalanDOMChar* theString,
unsigned int theLength) :
m_string(theString),
m_length(theLength)
{
}
bool
operator()(const XalanDOMString* theString) const
{
if (m_length != length(*theString))
{
return false;
}
else
{
return equals(m_string, c_wstr(*theString), m_length);
}
}
private:
const XalanDOMChar* const m_string;
const unsigned int m_length;
};
const XalanDOMString*
XalanDOMStringHashTable::find(
const XalanDOMString& theString,
unsigned int* theBucketIndex) const
{
return find(c_wstr(theString), length(theString), theBucketIndex);
}
inline unsigned int
hash(
const XalanDOMChar* theString,
unsigned int theLength)
{
assert(theString != 0);
unsigned int theResult = 0;
const XalanDOMChar* const theEnd = theString + theLength;
while (theString != theEnd)
{
theResult += (theResult * 37) + (theResult >> 24) + unsigned(*theString);
++theString;
}
return theResult;
}
const XalanDOMString*
XalanDOMStringHashTable::find(
const XalanDOMChar* theString,
unsigned int theLength,
unsigned int* theBucketIndex) const
{
assert(theString != 0);
const unsigned int theActualLength =
theLength == unsigned(-1) ? length(theString) : theLength;
const unsigned int theHash = hash(theString, theActualLength);
const unsigned int theLocalBucketIndex = theHash % m_bucketCount;
assert(theLocalBucketIndex < m_bucketCount);
const BucketType& theBucket = m_buckets[theLocalBucketIndex];
if (theBucketIndex != 0)
{
*theBucketIndex = theLocalBucketIndex;
}
#if !defined(XALAN_NO_NAMESPACES)
using std::find_if;
#endif
const BucketType::const_iterator i =
find_if(
theBucket.begin(),
theBucket.end(),
equalsXalanDOMString(theString, theActualLength));
if (i == theBucket.end())
{
return 0;
}
else
{
return *i;
}
}
void
XalanDOMStringHashTable::insert(const XalanDOMString& theString)
{
const unsigned int theHash = hash(c_wstr(theString), length(theString));
const unsigned int theBucketIndex = theHash % m_bucketCount;
assert(theBucketIndex < m_bucketCount);
BucketType& theBucket = m_buckets[theBucketIndex];
#if !defined(NDEBUG)
if (theBucket.size() > 0)
{
++m_collisions;
}
#endif
theBucket.reserve(m_bucketSize);
theBucket.push_back(&theString);
++m_count;
}
void
XalanDOMStringHashTable::insert(
const XalanDOMString& theString,
unsigned int theBucketIndex)
{
assert(theBucketIndex == hash(c_wstr(theString), length(theString)) % m_bucketCount);
assert(theBucketIndex < m_bucketCount);
BucketType& theBucket = m_buckets[theBucketIndex];
#if !defined(NDEBUG)
if (theBucket.size() > 0)
{
++m_collisions;
}
#endif
theBucket.reserve(m_bucketSize);
theBucket.push_back(&theString);
++m_count;
}
<commit_msg>Changed hash to hashString since Solaris seems to have a conflicting hash() function. The evils of global functions...<commit_after>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999-2001 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 "Xalan" 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/>.
*/
// Class header file...
#include "XalanDOMStringHashTable.hpp"
#include <algorithm>
#include "DOMStringHelper.hpp"
XalanDOMStringHashTable::XalanDOMStringHashTable(
unsigned int theBucketCount,
unsigned int theBucketSize) :
m_bucketCount(theBucketCount),
m_bucketSize(theBucketSize),
m_buckets(new BucketType[theBucketCount]),
m_count(0),
m_collisions(0)
{
}
void
XalanDOMStringHashTable::clear()
{
for(unsigned int i = 0; i < m_bucketCount; ++i)
{
m_buckets[i].clear();
}
#if !defined(NDEBUG)
m_collisions = 0;
#endif
m_count = 0;
}
void
XalanDOMStringHashTable::getBucketCounts(BucketCountsType& theVector) const
{
for(unsigned int i = 0; i < m_bucketCount; ++i)
{
theVector.push_back(m_buckets[i].size());
}
}
struct
equalsXalanDOMString
{
equalsXalanDOMString(
const XalanDOMChar* theString,
unsigned int theLength) :
m_string(theString),
m_length(theLength)
{
}
bool
operator()(const XalanDOMString* theString) const
{
if (m_length != length(*theString))
{
return false;
}
else
{
return equals(m_string, c_wstr(*theString), m_length);
}
}
private:
const XalanDOMChar* const m_string;
const unsigned int m_length;
};
const XalanDOMString*
XalanDOMStringHashTable::find(
const XalanDOMString& theString,
unsigned int* theBucketIndex) const
{
return find(c_wstr(theString), length(theString), theBucketIndex);
}
inline unsigned int
hashString(
const XalanDOMChar* theString,
unsigned int theLength)
{
assert(theString != 0);
unsigned int theResult = 0;
const XalanDOMChar* const theEnd = theString + theLength;
while (theString != theEnd)
{
theResult += (theResult * 37) + (theResult >> 24) + unsigned(*theString);
++theString;
}
return theResult;
}
const XalanDOMString*
XalanDOMStringHashTable::find(
const XalanDOMChar* theString,
unsigned int theLength,
unsigned int* theBucketIndex) const
{
assert(theString != 0);
const unsigned int theActualLength =
theLength == unsigned(-1) ? length(theString) : theLength;
const unsigned int theHash = hashString(theString, theActualLength);
const unsigned int theLocalBucketIndex = theHash % m_bucketCount;
assert(theLocalBucketIndex < m_bucketCount);
const BucketType& theBucket = m_buckets[theLocalBucketIndex];
if (theBucketIndex != 0)
{
*theBucketIndex = theLocalBucketIndex;
}
#if !defined(XALAN_NO_NAMESPACES)
using std::find_if;
#endif
const BucketType::const_iterator i =
find_if(
theBucket.begin(),
theBucket.end(),
equalsXalanDOMString(theString, theActualLength));
if (i == theBucket.end())
{
return 0;
}
else
{
return *i;
}
}
void
XalanDOMStringHashTable::insert(const XalanDOMString& theString)
{
const unsigned int theHash = hashString(c_wstr(theString), length(theString));
const unsigned int theBucketIndex = theHash % m_bucketCount;
assert(theBucketIndex < m_bucketCount);
BucketType& theBucket = m_buckets[theBucketIndex];
#if !defined(NDEBUG)
if (theBucket.size() > 0)
{
++m_collisions;
}
#endif
theBucket.reserve(m_bucketSize);
theBucket.push_back(&theString);
++m_count;
}
void
XalanDOMStringHashTable::insert(
const XalanDOMString& theString,
unsigned int theBucketIndex)
{
assert(theBucketIndex == hashString(c_wstr(theString), length(theString)) % m_bucketCount);
assert(theBucketIndex < m_bucketCount);
BucketType& theBucket = m_buckets[theBucketIndex];
#if !defined(NDEBUG)
if (theBucket.size() > 0)
{
++m_collisions;
}
#endif
theBucket.reserve(m_bucketSize);
theBucket.push_back(&theString);
++m_count;
}
<|endoftext|> |
<commit_before>
/*
* Copyright (C) 2010, Victor Semionov
* 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.
*
* 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 <climits>
#include <string>
#include <vector>
#include <set>
#include <ostream>
#include <iostream>
#include "Poco/Util/ServerApplication.h"
#include "Poco/URI.h"
#include "Poco/File.h"
#include "Poco/DirectoryIterator.h"
#include "Poco/NumberFormatter.h"
#include "IndigoRequestHandler.h"
#include "IndigoConfiguration.h"
using namespace std;
using namespace Poco;
using namespace Poco::Util;
using namespace Poco::Net;
POCO_DECLARE_EXCEPTION(, ShareNotFoundException, ApplicationException)
POCO_IMPLEMENT_EXCEPTION(ShareNotFoundException, ApplicationException, "ShareNotFoundException")
IndigoRequestHandler::IndigoRequestHandler()
{
}
void IndigoRequestHandler::handleRequest(HTTPServerRequest &request, HTTPServerResponse &response)
{
logRequest(request);
const string &method = request.getMethod();
if (method != HTTPRequest::HTTP_GET)
{
sendMethodNotAllowed(response);
return;
}
URI uri;
try
{
uri = request.getURI();
}
catch (SyntaxException &se)
{
sendBadRequest(response);
return;
}
Path uriPath(uri.getPath(), Path::PATH_UNIX);
if (!uriPath.isAbsolute())
{
sendBadRequest(response);
return;
}
const IndigoConfiguration &configuration = IndigoConfiguration::get();
try
{
if (uriPath.isDirectory() && uriPath.depth() == 0)
{
if (configuration.virtualRoot())
{
sendVirtualIndex(response);
return;
}
}
const Path &fsPath = resolveFSPath(uriPath);
const string &target = fsPath.toString();
File f(target);
if (f.isDirectory())
{
if (uriPath.isDirectory())
{
sendDirectoryIndex(response, target, uriPath.toString(Path::PATH_UNIX));
}
else
{
Path uriDirPath = uriPath;
uriDirPath.makeDirectory();
redirectToDirectory(response, uriDirPath.toString(Path::PATH_UNIX), false);
}
}
else
{
sendFile(response, target);
}
}
catch (ShareNotFoundException &snfe)
{
sendNotFound(response);
}
catch (FileNotFoundException &fnfe)
{
sendNotFound(response);
}
catch (FileAccessDeniedException &fade)
{
sendForbidden(response);
}
catch (FileException &fe)
{
sendInternalServerError(response);
}
catch (PathSyntaxException &pse)
{
sendNotImplemented(response);
}
catch (...)
{
sendInternalServerError(response);
}
}
Path IndigoRequestHandler::resolveFSPath(const Path &uriPath)
{
const IndigoConfiguration &configuration = IndigoConfiguration::get();
const string &shareName = uriPath[0];
string base = configuration.getSharePath(shareName);
bool share = true;
if (base.empty())
{
base = configuration.getRoot();
if (base.empty())
throw ShareNotFoundException();
share = false;
}
Path fsPath(base);
if (share)
{
fsPath.makeDirectory();
const int d = uriPath.depth();
for (int i = 1; i <= d; i++)
fsPath.pushDirectory(uriPath[i]);
}
else
{
fsPath.append(uriPath);
}
fsPath.makeFile();
return fsPath;
}
void IndigoRequestHandler::sendFile(HTTPServerResponse &response, const string &path)
{
const string &ext = Path(path).getExtension();
const string &mediaType = IndigoConfiguration::get().getMimeType(ext);
response.sendFile(path, mediaType);
}
void IndigoRequestHandler::sendDirectoryListing(HTTPServerResponse &response, const string &dirURI, const vector<string> &entries)
{
bool root = (dirURI == "/");
response.setContentType("text/html");
response.setContentLength(HTTPResponse::UNKNOWN_CONTENT_LENGTH);
response.setChunkedTransferEncoding(true);
ostream &out = response.send();
out << "<html>" << endl;
out << "<head>" << endl;
out << "<title>";
out << "Index of " << dirURI;
out << "</title>" << endl;
out << "</head>" << endl;
out << "<body>" << endl;
out << "<h1>";
out << "Index of " << dirURI;
out << "</h1>" << endl;
if (!root)
{
out << "<a href=\"../\"><Parent Directory></a><br>" << endl;
}
const int l = entries.size();
for (int i = 0; i < l; i++)
{
out << "<a href=\"" << entries[i] << "\">" << entries[i] << "</a>" << "<br>" << endl;
}
out << "</body>" << endl;
out << "</html>" << endl;
}
string IndigoRequestHandler::findVirtualIndex()
{
const IndigoConfiguration &configuration = IndigoConfiguration::get();
const set<string> indexes = configuration.getIndexes();
set<string>::const_iterator it;
set<string>::const_iterator end = indexes.end();
for (it = indexes.begin(); it != end; ++it)
{
try
{
const Path &index = resolveFSPath(Path("/" + *it, Path::PATH_UNIX));
File f(index);
if (!f.isDirectory())
{
return index.toString();
}
}
catch (ShareNotFoundException &snfe)
{
}
catch (FileException &fe)
{
}
catch (PathSyntaxException &pse)
{
}
}
return "";
}
void IndigoRequestHandler::sendVirtualIndex(HTTPServerResponse &response)
{
const IndigoConfiguration &configuration = IndigoConfiguration::get();
const string &index = findVirtualIndex();
if (!index.empty())
{
sendFile(response, index);
return;
}
if (!configuration.getAutoIndex())
throw ShareNotFoundException();
const set<string> &shares = configuration.getShares();
vector<string> entries;
set<string>::const_iterator it;
const set<string>::const_iterator &end = shares.end();
for (it = shares.begin(); it != end; ++it)
{
const string &shareName = *it;
try
{
const Path &fsPath = resolveFSPath(Path("/" + shareName, Path::PATH_UNIX));
File f(fsPath);
if (!f.isHidden())
{
string entry = shareName;
if (f.isDirectory())
entry += '/';
entries.push_back(entry);
}
}
catch (ShareNotFoundException &snfe)
{
}
catch (FileException &fe)
{
}
catch (PathSyntaxException &pse)
{
}
}
sendDirectoryListing(response, "/", entries);
}
string IndigoRequestHandler::findDirectoryIndex(const string &base)
{
const IndigoConfiguration &configuration = IndigoConfiguration::get();
const set<string> indexes = configuration.getIndexes(true);
set<string>::const_iterator it;
set<string>::const_iterator end = indexes.end();
for (it = indexes.begin(); it != end; ++it)
{
try
{
string index = base;
if (index[index.length() - 1] != Path::separator())
index += Path::separator();
index += *it;
File f(index);
if (!f.isDirectory())
{
return index;
}
}
catch (FileException &fe)
{
}
catch (PathSyntaxException &pse)
{
}
}
return "";
}
void IndigoRequestHandler::sendDirectoryIndex(HTTPServerResponse &response, const string &path, const string &dirURI)
{
const IndigoConfiguration &configuration = IndigoConfiguration::get();
const string &index = findDirectoryIndex(path);
if (!index.empty())
{
sendFile(response, index);
return;
}
if (!configuration.getAutoIndex())
throw FileNotFoundException();
vector<string> entries;
DirectoryIterator it(path);
DirectoryIterator end;
while (it != end)
{
try
{
if (!it->isHidden())
{
string entry = it.name();
if (it->isDirectory())
entry += '/';
entries.push_back(entry);
}
}
catch (FileException &fe)
{
}
catch (PathSyntaxException &pse)
{
}
++it;
}
sendDirectoryListing(response, dirURI, entries);
}
void IndigoRequestHandler::redirectToDirectory(HTTPServerResponse &response, const string &dirURI, bool permanent)
{
if (!permanent)
{
response.redirect(dirURI);
}
else
{
response.setStatusAndReason(HTTPResponse::HTTP_MOVED_PERMANENTLY);
response.setContentLength(0);
response.setChunkedTransferEncoding(false);
response.set("Location", dirURI);
response.send();
}
}
void IndigoRequestHandler::logRequest(const HTTPServerRequest &request)
{
const ServerApplication &app = dynamic_cast<ServerApplication &>(Application::instance());
if (app.isInteractive())
{
const string &method = request.getMethod();
const string &uri = request.getURI();
const string &host = request.clientAddress().host().toString();
string logString = host + " - " + method + " " + uri;
app.logger().information(logString);
}
}
void IndigoRequestHandler::sendError(HTTPServerResponse &response, int code)
{
if (response.sent())
return;
response.setStatusAndReason(HTTPResponse::HTTPStatus(code));
response.setChunkedTransferEncoding(true);
response.setContentType("text/html");
const string &reason = response.getReason();
ostream &out = response.send();
out << "<html>";
out << "<head><title>" + NumberFormatter::format(code) + " " + reason + "</title></head>";
out << "<body><h1>" + reason + "</h1></body>";
out << "</html>";
}
void IndigoRequestHandler::sendMethodNotAllowed(HTTPServerResponse &response)
{
sendError(response, HTTPResponse::HTTP_METHOD_NOT_ALLOWED);
}
void IndigoRequestHandler::sendRequestURITooLong(HTTPServerResponse &response)
{
sendError(response, HTTPResponse::HTTP_REQUESTURITOOLONG);
}
void IndigoRequestHandler::sendBadRequest(HTTPServerResponse &response)
{
sendError(response, HTTPResponse::HTTP_BAD_REQUEST);
}
void IndigoRequestHandler::sendNotImplemented(HTTPServerResponse &response)
{
sendError(response, HTTPResponse::HTTP_NOT_IMPLEMENTED);
}
void IndigoRequestHandler::sendNotFound(HTTPServerResponse &response)
{
sendError(response, HTTPResponse::HTTP_NOT_FOUND);
}
void IndigoRequestHandler::sendForbidden(HTTPServerResponse &response)
{
sendError(response, HTTPResponse::HTTP_FORBIDDEN);
}
void IndigoRequestHandler::sendInternalServerError(HTTPServerResponse &response)
{
sendError(response, HTTPResponse::HTTP_INTERNAL_SERVER_ERROR);
}
<commit_msg>Check if the file is a regular file before treating it as a directory index.<commit_after>
/*
* Copyright (C) 2010, Victor Semionov
* 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.
*
* 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 <climits>
#include <string>
#include <vector>
#include <set>
#include <ostream>
#include <iostream>
#include "Poco/Util/ServerApplication.h"
#include "Poco/URI.h"
#include "Poco/File.h"
#include "Poco/DirectoryIterator.h"
#include "Poco/NumberFormatter.h"
#include "IndigoRequestHandler.h"
#include "IndigoConfiguration.h"
using namespace std;
using namespace Poco;
using namespace Poco::Util;
using namespace Poco::Net;
POCO_DECLARE_EXCEPTION(, ShareNotFoundException, ApplicationException)
POCO_IMPLEMENT_EXCEPTION(ShareNotFoundException, ApplicationException, "ShareNotFoundException")
IndigoRequestHandler::IndigoRequestHandler()
{
}
void IndigoRequestHandler::handleRequest(HTTPServerRequest &request, HTTPServerResponse &response)
{
logRequest(request);
const string &method = request.getMethod();
if (method != HTTPRequest::HTTP_GET)
{
sendMethodNotAllowed(response);
return;
}
URI uri;
try
{
uri = request.getURI();
}
catch (SyntaxException &se)
{
sendBadRequest(response);
return;
}
Path uriPath(uri.getPath(), Path::PATH_UNIX);
if (!uriPath.isAbsolute())
{
sendBadRequest(response);
return;
}
const IndigoConfiguration &configuration = IndigoConfiguration::get();
try
{
if (uriPath.isDirectory() && uriPath.depth() == 0)
{
if (configuration.virtualRoot())
{
sendVirtualIndex(response);
return;
}
}
const Path &fsPath = resolveFSPath(uriPath);
const string &target = fsPath.toString();
File f(target);
if (f.isDirectory())
{
if (uriPath.isDirectory())
{
sendDirectoryIndex(response, target, uriPath.toString(Path::PATH_UNIX));
}
else
{
Path uriDirPath = uriPath;
uriDirPath.makeDirectory();
redirectToDirectory(response, uriDirPath.toString(Path::PATH_UNIX), false);
}
}
else
{
sendFile(response, target);
}
}
catch (ShareNotFoundException &snfe)
{
sendNotFound(response);
}
catch (FileNotFoundException &fnfe)
{
sendNotFound(response);
}
catch (FileAccessDeniedException &fade)
{
sendForbidden(response);
}
catch (FileException &fe)
{
sendInternalServerError(response);
}
catch (PathSyntaxException &pse)
{
sendNotImplemented(response);
}
catch (...)
{
sendInternalServerError(response);
}
}
Path IndigoRequestHandler::resolveFSPath(const Path &uriPath)
{
const IndigoConfiguration &configuration = IndigoConfiguration::get();
const string &shareName = uriPath[0];
string base = configuration.getSharePath(shareName);
bool share = true;
if (base.empty())
{
base = configuration.getRoot();
if (base.empty())
throw ShareNotFoundException();
share = false;
}
Path fsPath(base);
if (share)
{
fsPath.makeDirectory();
const int d = uriPath.depth();
for (int i = 1; i <= d; i++)
fsPath.pushDirectory(uriPath[i]);
}
else
{
fsPath.append(uriPath);
}
fsPath.makeFile();
return fsPath;
}
void IndigoRequestHandler::sendFile(HTTPServerResponse &response, const string &path)
{
const string &ext = Path(path).getExtension();
const string &mediaType = IndigoConfiguration::get().getMimeType(ext);
response.sendFile(path, mediaType);
}
void IndigoRequestHandler::sendDirectoryListing(HTTPServerResponse &response, const string &dirURI, const vector<string> &entries)
{
bool root = (dirURI == "/");
response.setContentType("text/html");
response.setContentLength(HTTPResponse::UNKNOWN_CONTENT_LENGTH);
response.setChunkedTransferEncoding(true);
ostream &out = response.send();
out << "<html>" << endl;
out << "<head>" << endl;
out << "<title>";
out << "Index of " << dirURI;
out << "</title>" << endl;
out << "</head>" << endl;
out << "<body>" << endl;
out << "<h1>";
out << "Index of " << dirURI;
out << "</h1>" << endl;
if (!root)
{
out << "<a href=\"../\"><Parent Directory></a><br>" << endl;
}
const int l = entries.size();
for (int i = 0; i < l; i++)
{
out << "<a href=\"" << entries[i] << "\">" << entries[i] << "</a>" << "<br>" << endl;
}
out << "</body>" << endl;
out << "</html>" << endl;
}
string IndigoRequestHandler::findVirtualIndex()
{
const IndigoConfiguration &configuration = IndigoConfiguration::get();
const set<string> indexes = configuration.getIndexes();
set<string>::const_iterator it;
set<string>::const_iterator end = indexes.end();
for (it = indexes.begin(); it != end; ++it)
{
try
{
const Path &index = resolveFSPath(Path("/" + *it, Path::PATH_UNIX));
File f(index);
if (f.isFile())
{
return index.toString();
}
}
catch (ShareNotFoundException &snfe)
{
}
catch (FileException &fe)
{
}
catch (PathSyntaxException &pse)
{
}
}
return "";
}
void IndigoRequestHandler::sendVirtualIndex(HTTPServerResponse &response)
{
const IndigoConfiguration &configuration = IndigoConfiguration::get();
const string &index = findVirtualIndex();
if (!index.empty())
{
sendFile(response, index);
return;
}
if (!configuration.getAutoIndex())
throw ShareNotFoundException();
const set<string> &shares = configuration.getShares();
vector<string> entries;
set<string>::const_iterator it;
const set<string>::const_iterator &end = shares.end();
for (it = shares.begin(); it != end; ++it)
{
const string &shareName = *it;
try
{
const Path &fsPath = resolveFSPath(Path("/" + shareName, Path::PATH_UNIX));
File f(fsPath);
if (!f.isHidden())
{
string entry = shareName;
if (f.isDirectory())
entry += '/';
entries.push_back(entry);
}
}
catch (ShareNotFoundException &snfe)
{
}
catch (FileException &fe)
{
}
catch (PathSyntaxException &pse)
{
}
}
sendDirectoryListing(response, "/", entries);
}
string IndigoRequestHandler::findDirectoryIndex(const string &base)
{
const IndigoConfiguration &configuration = IndigoConfiguration::get();
const set<string> indexes = configuration.getIndexes(true);
set<string>::const_iterator it;
set<string>::const_iterator end = indexes.end();
for (it = indexes.begin(); it != end; ++it)
{
try
{
string index = base;
if (index[index.length() - 1] != Path::separator())
index += Path::separator();
index += *it;
File f(index);
if (f.isFile())
{
return index;
}
}
catch (FileException &fe)
{
}
catch (PathSyntaxException &pse)
{
}
}
return "";
}
void IndigoRequestHandler::sendDirectoryIndex(HTTPServerResponse &response, const string &path, const string &dirURI)
{
const IndigoConfiguration &configuration = IndigoConfiguration::get();
const string &index = findDirectoryIndex(path);
if (!index.empty())
{
sendFile(response, index);
return;
}
if (!configuration.getAutoIndex())
throw FileNotFoundException();
vector<string> entries;
DirectoryIterator it(path);
DirectoryIterator end;
while (it != end)
{
try
{
if (!it->isHidden())
{
string entry = it.name();
if (it->isDirectory())
entry += '/';
entries.push_back(entry);
}
}
catch (FileException &fe)
{
}
catch (PathSyntaxException &pse)
{
}
++it;
}
sendDirectoryListing(response, dirURI, entries);
}
void IndigoRequestHandler::redirectToDirectory(HTTPServerResponse &response, const string &dirURI, bool permanent)
{
if (!permanent)
{
response.redirect(dirURI);
}
else
{
response.setStatusAndReason(HTTPResponse::HTTP_MOVED_PERMANENTLY);
response.setContentLength(0);
response.setChunkedTransferEncoding(false);
response.set("Location", dirURI);
response.send();
}
}
void IndigoRequestHandler::logRequest(const HTTPServerRequest &request)
{
const ServerApplication &app = dynamic_cast<ServerApplication &>(Application::instance());
if (app.isInteractive())
{
const string &method = request.getMethod();
const string &uri = request.getURI();
const string &host = request.clientAddress().host().toString();
string logString = host + " - " + method + " " + uri;
app.logger().information(logString);
}
}
void IndigoRequestHandler::sendError(HTTPServerResponse &response, int code)
{
if (response.sent())
return;
response.setStatusAndReason(HTTPResponse::HTTPStatus(code));
response.setChunkedTransferEncoding(true);
response.setContentType("text/html");
const string &reason = response.getReason();
ostream &out = response.send();
out << "<html>";
out << "<head><title>" + NumberFormatter::format(code) + " " + reason + "</title></head>";
out << "<body><h1>" + reason + "</h1></body>";
out << "</html>";
}
void IndigoRequestHandler::sendMethodNotAllowed(HTTPServerResponse &response)
{
sendError(response, HTTPResponse::HTTP_METHOD_NOT_ALLOWED);
}
void IndigoRequestHandler::sendRequestURITooLong(HTTPServerResponse &response)
{
sendError(response, HTTPResponse::HTTP_REQUESTURITOOLONG);
}
void IndigoRequestHandler::sendBadRequest(HTTPServerResponse &response)
{
sendError(response, HTTPResponse::HTTP_BAD_REQUEST);
}
void IndigoRequestHandler::sendNotImplemented(HTTPServerResponse &response)
{
sendError(response, HTTPResponse::HTTP_NOT_IMPLEMENTED);
}
void IndigoRequestHandler::sendNotFound(HTTPServerResponse &response)
{
sendError(response, HTTPResponse::HTTP_NOT_FOUND);
}
void IndigoRequestHandler::sendForbidden(HTTPServerResponse &response)
{
sendError(response, HTTPResponse::HTTP_FORBIDDEN);
}
void IndigoRequestHandler::sendInternalServerError(HTTPServerResponse &response)
{
sendError(response, HTTPResponse::HTTP_INTERNAL_SERVER_ERROR);
}
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <mpi.h>
#define MASTER 0
#define TAG 0
#define MAX 25
const long long MSGSIZE = 99999999;
int main(int argc, char *argv[]) {
int my_rank, source, num_nodes;
char *message = new char[MSGSIZE];
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
MPI_Comm_size(MPI_COMM_WORLD, &num_nodes);
double program_start = MPI_Wtime();
if (my_rank != MASTER) {
double message_sent = MPI_Wtime();
for (long long i = 0; i < MSGSIZE; i++) {
message[i] = 'a' + std::rand() % 26;
}
MPI_Send(&message, MSGSIZE, MPI_CHAR, MASTER, TAG, MPI_COMM_WORLD);
} else {
printf("Num_nodes: %d\n", num_nodes);
printf("Hello from Master (process %d)!\n", my_rank);
MPI_Status status;
for (source = 1; source < num_nodes; source++) {
MPI_Recv(&message, MSGSIZE, MPI_CHAR, source, TAG, MPI_COMM_WORLD,
&status);
}
double program_end = MPI_Wtime();
double program_elapsed = program_end - program_start;
printf("Nodes, Message Size, Program Execution Time, %d,%lld,%f\n",
num_nodes, MSGSIZE, program_elapsed);
}
MPI_Finalize();
return 0;
}
<commit_msg>try lowering message size<commit_after>#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <mpi.h>
#define MASTER 0
#define TAG 0
#define MAX 25
const long long MSGSIZE = 9999999;
int main(int argc, char *argv[]) {
int my_rank, source, num_nodes;
char *message = new char[MSGSIZE];
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
MPI_Comm_size(MPI_COMM_WORLD, &num_nodes);
double program_start = MPI_Wtime();
if (my_rank != MASTER) {
double message_sent = MPI_Wtime();
for (long long i = 0; i < MSGSIZE; i++) {
message[i] = 'a' + std::rand() % 26;
}
MPI_Send(&message, MSGSIZE, MPI_CHAR, MASTER, TAG, MPI_COMM_WORLD);
} else {
printf("Num_nodes: %d\n", num_nodes);
printf("Hello from Master (process %d)!\n", my_rank);
MPI_Status status;
for (source = 1; source < num_nodes; source++) {
MPI_Recv(&message, MSGSIZE, MPI_CHAR, source, TAG, MPI_COMM_WORLD,
&status);
}
double program_end = MPI_Wtime();
double program_elapsed = program_end - program_start;
printf("Nodes, Message Size, Program Execution Time, %d,%lld,%f\n",
num_nodes, MSGSIZE, program_elapsed);
}
MPI_Finalize();
return 0;
}
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <mpi.h>
#define MASTER 0
#define TAG 0
#define MAX 25
const long long MSGSIZE = 999999;
int main(int argc, char *argv[]) {
int my_rank, source, num_nodes;
char message[MSGSIZE];
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
MPI_Comm_size(MPI_COMM_WORLD, &num_nodes);
double program_start = MPI_Wtime();
if (my_rank != MASTER) {
double message_sent = MPI_Wtime();
for (long long i = 0; i < MSGSIZE; i++) {
message[i] = 'a' + rand() % 26;
}
MPI_Send(&message, MSGSIZE, MPI_CHAR, MASTER, TAG, MPI_COMM_WORLD);
} else {
printf("Num_nodes: %d\n", num_nodes);
printf("Hello from Master (process %d)!\n", my_rank);
char message[MSGSIZE];
MPI_Status status;
for (source = 1; source < num_nodes; source++) {
MPI_Recv(&message, MSGSIZE, MPI_CHAR, source, TAG, MPI_COMM_WORLD,
&status);
}
double program_end = MPI_Wtime();
double program_elapsed = program_end - program_start;
printf("Nodes, Message Size, Program Execution Time, %d,%lld,%f\n",
num_nodes, MSGSIZE, program_elapsed);
}
MPI_Finalize();
return 0;
}
<commit_msg>increase message size<commit_after>#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <mpi.h>
#define MASTER 0
#define TAG 0
#define MAX 25
const long long MSGSIZE = 999999999;
int main(int argc, char *argv[]) {
int my_rank, source, num_nodes;
char message[MSGSIZE];
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
MPI_Comm_size(MPI_COMM_WORLD, &num_nodes);
double program_start = MPI_Wtime();
if (my_rank != MASTER) {
double message_sent = MPI_Wtime();
for (long long i = 0; i < MSGSIZE; i++) {
message[i] = 'a' + rand() % 26;
}
MPI_Send(&message, MSGSIZE, MPI_CHAR, MASTER, TAG, MPI_COMM_WORLD);
} else {
printf("Num_nodes: %d\n", num_nodes);
printf("Hello from Master (process %d)!\n", my_rank);
char message[MSGSIZE];
MPI_Status status;
for (source = 1; source < num_nodes; source++) {
MPI_Recv(&message, MSGSIZE, MPI_CHAR, source, TAG, MPI_COMM_WORLD,
&status);
}
double program_end = MPI_Wtime();
double program_elapsed = program_end - program_start;
printf("Nodes, Message Size, Program Execution Time, %d,%lld,%f\n",
num_nodes, MSGSIZE, program_elapsed);
}
MPI_Finalize();
return 0;
}
<|endoftext|> |
<commit_before>// Copyright (2015) Gustav
#include "finans/core/commandline.h"
#include "gtest/gtest.h"
#include "gmock/gmock.h"
using namespace testing;
struct CommandlineTest : public Test {
std::ostringstream output;
std::ostringstream error;
};
#define GTEST(x) TEST_F(CommandlineTest, x)
/*
void main(int argc, char* argv[])
{
enum MyEnum
{
MyVal, MyVal2
};
std::string compiler;
int i;
int op = 2;
std::vector<std::string> strings;
//MyEnum v;
bool ok = argparse::Parser::ParseComplete ==
argparse::Parser("description")
("compiler", compiler)
("int", i)
("-op", op)
.add<std::vector<std::string>, std::string>("-strings", strings, argparse::Extra().count(argparse::Count::MoreThanOne).metavar("string"), argparse::PushBackVector<std::string>) // todo: is this beautifiable?
//("-enum", &v, Convert<MyEnum>("MyVal", MyEnum::MyVal)("MyVal2", MyEnum::MyVal2) )
.parseArgs(argc, argv);
if (ok == false) return;
std::cout << compiler << " " << i << " " << op << std::endl;
BOOST_FOREACH(const std::string& s, strings)
{
std::cout << s << " " << std::endl;
}
}
*/
GTEST(TestEmpty) {
const bool ok = argparse::Parser::ParseComplete ==
argparse::Parser("description")
.ParseArgs(argparse::Arguments("app.exe", {}), output, error);
EXPECT_EQ(true, ok);
}
GTEST(TestError) {
const bool ok = argparse::Parser::ParseComplete ==
argparse::Parser("description")
.ParseArgs(argparse::Arguments("app.exe", { "hello", "world" }), output, error);
EXPECT_EQ(false, ok);
}
GTEST(TestOptionalDefault) {
int op = 2;
const bool ok = argparse::Parser::ParseComplete ==
argparse::Parser("description")
("-op", op)
.ParseArgs(argparse::Arguments("app.exe", {}), output, error);
EXPECT_EQ(true, ok);
EXPECT_EQ(2, op);
}
GTEST(TestOptionalValue) {
int op = 2;
const bool ok = argparse::Parser::ParseComplete ==
argparse::Parser("description")
("-op", op)
.ParseArgs(argparse::Arguments("app.exe", {"-op", "42"}), output, error);
EXPECT_EQ(true, ok);
EXPECT_EQ(42, op);
}
GTEST(TestPositionalValue) {
int op = 2;
const bool ok = argparse::Parser::ParseComplete ==
argparse::Parser("description")
("op", op)
.ParseArgs(argparse::Arguments("app.exe", { "42" }), output, error);
EXPECT_EQ(true, ok);
EXPECT_EQ(42, op);
}
GTEST(TestPositionalValueErr) {
int op = 42;
const bool ok = argparse::Parser::ParseComplete ==
argparse::Parser("description")
("op", op)
.ParseArgs(argparse::Arguments("app.exe", {}), output, error);
EXPECT_EQ(false, ok);
EXPECT_EQ(42, op); // not touched
}
GTEST(TestStdVector) {
std::vector<std::string> strings;
const bool ok = argparse::Parser::ParseComplete ==
argparse::Parser("description")
.AddGreedy("-strings", strings, "string")
.ParseArgs(argparse::Arguments("app.exe", {"-strings", "cat", "dog", "fish"}), output, error);
EXPECT_EQ(true, ok);
EXPECT_THAT(strings, ElementsAre("cat", "dog", "fish"));
}
GTEST(TestStdVectorInts) {
std::vector<int> ints;
const bool ok = argparse::Parser::ParseComplete ==
argparse::Parser("description")
.AddGreedy("-ints", ints, "string")
.ParseArgs(argparse::Arguments("app.exe", { "-ints", "2", "3", "-5", "4" }), output, error);
EXPECT_EQ(true, ok);
EXPECT_THAT(ints, ElementsAre(2, 3, -5, 4));
}
GTEST(TestNonGreedyVector) {
std::vector<std::string> strings;
const bool ok = argparse::Parser::ParseComplete ==
argparse::Parser("description")
("-s", strings)
.ParseArgs(argparse::Arguments("app.exe", { "-s", "cat", "-s", "dog", "-s", "fish" }), output, error);
EXPECT_EQ(true, ok);
EXPECT_THAT(strings, ElementsAre("cat", "dog", "fish"));
}
enum class Day
{
TODAY, YESTERDAY, TOMORROW
};
ARGPARSE_DEFINE_ENUM(Day, "day", ("Today", Day::TODAY)("Tomorrow", Day::TOMORROW)("Yesterday", Day::YESTERDAY) )
GTEST(TestEnum) {
Day op = Day::TOMORROW;
const bool ok = argparse::Parser::ParseComplete ==
argparse::Parser("description")
("op", op)
.ParseArgs(argparse::Arguments("app.exe", { "tod" }), output, error);
EXPECT_EQ(true, ok);
EXPECT_EQ(Day::TODAY, op);
}
GTEST(TestCommaOp) {
int op = 2;
const bool ok = argparse::Parser::ParseComplete ==
argparse::Parser("description")
("-int,-i", op)
.ParseArgs(argparse::Arguments("app.exe", { "-int", "42" }), output, error);
EXPECT_EQ(true, ok);
EXPECT_EQ(42, op);
}
<commit_msg>commented away failing tests<commit_after>// Copyright (2015) Gustav
#include "finans/core/commandline.h"
#include "gtest/gtest.h"
#include "gmock/gmock.h"
using namespace testing;
struct CommandlineTest : public Test {
std::ostringstream output;
std::ostringstream error;
argparse::Parser parser;
std::string animal;
std::string another;
CommandlineTest() : parser("description") {
parser("pos", animal)("-op", another);
}
};
#define GTEST(x) TEST_F(CommandlineTest, x)
/*
void main(int argc, char* argv[])
{
enum MyEnum
{
MyVal, MyVal2
};
std::string compiler;
int i;
int op = 2;
std::vector<std::string> strings;
//MyEnum v;
bool ok = argparse::Parser::ParseComplete ==
argparse::Parser("description")
("compiler", compiler)
("int", i)
("-op", op)
.add<std::vector<std::string>, std::string>("-strings", strings, argparse::Extra().count(argparse::Count::MoreThanOne).metavar("string"), argparse::PushBackVector<std::string>) // todo: is this beautifiable?
//("-enum", &v, Convert<MyEnum>("MyVal", MyEnum::MyVal)("MyVal2", MyEnum::MyVal2) )
.parseArgs(argc, argv);
if (ok == false) return;
std::cout << compiler << " " << i << " " << op << std::endl;
BOOST_FOREACH(const std::string& s, strings)
{
std::cout << s << " " << std::endl;
}
}
*/
GTEST(TestEmpty) {
const bool ok = argparse::Parser::ParseComplete ==
argparse::Parser("description")
.ParseArgs(argparse::Arguments("app.exe", {}), output, error);
EXPECT_EQ(true, ok);
}
GTEST(TestError) {
const bool ok = argparse::Parser::ParseComplete ==
argparse::Parser("description")
.ParseArgs(argparse::Arguments("app.exe", { "hello", "world" }), output, error);
EXPECT_EQ(false, ok);
}
GTEST(TestOptionalDefault) {
int op = 2;
const bool ok = argparse::Parser::ParseComplete ==
argparse::Parser("description")
("-op", op)
.ParseArgs(argparse::Arguments("app.exe", {}), output, error);
EXPECT_EQ(true, ok);
EXPECT_EQ(2, op);
}
GTEST(TestOptionalValue) {
int op = 2;
const bool ok = argparse::Parser::ParseComplete ==
argparse::Parser("description")
("-op", op)
.ParseArgs(argparse::Arguments("app.exe", {"-op", "42"}), output, error);
EXPECT_EQ(true, ok);
EXPECT_EQ(42, op);
}
GTEST(TestPositionalValue) {
int op = 2;
const bool ok = argparse::Parser::ParseComplete ==
argparse::Parser("description")
("op", op)
.ParseArgs(argparse::Arguments("app.exe", { "42" }), output, error);
EXPECT_EQ(true, ok);
EXPECT_EQ(42, op);
}
GTEST(TestPositionalValueErr) {
int op = 42;
const bool ok = argparse::Parser::ParseComplete ==
argparse::Parser("description")
("op", op)
.ParseArgs(argparse::Arguments("app.exe", {}), output, error);
EXPECT_EQ(false, ok);
EXPECT_EQ(42, op); // not touched
}
GTEST(TestStdVector) {
std::vector<std::string> strings;
const bool ok = argparse::Parser::ParseComplete ==
argparse::Parser("description")
.AddGreedy("-strings", strings, "string")
.ParseArgs(argparse::Arguments("app.exe", {"-strings", "cat", "dog", "fish"}), output, error);
EXPECT_EQ(true, ok);
EXPECT_THAT(strings, ElementsAre("cat", "dog", "fish"));
}
GTEST(TestStdVectorInts) {
std::vector<int> ints;
const bool ok = argparse::Parser::ParseComplete ==
argparse::Parser("description")
.AddGreedy("-ints", ints, "string")
.ParseArgs(argparse::Arguments("app.exe", { "-ints", "2", "3", "-5", "4" }), output, error);
EXPECT_EQ(true, ok);
EXPECT_THAT(ints, ElementsAre(2, 3, -5, 4));
}
GTEST(TestNonGreedyVector) {
std::vector<std::string> strings;
const bool ok = argparse::Parser::ParseComplete ==
argparse::Parser("description")
("-s", strings)
.ParseArgs(argparse::Arguments("app.exe", { "-s", "cat", "-s", "dog", "-s", "fish" }), output, error);
EXPECT_EQ(true, ok);
EXPECT_THAT(strings, ElementsAre("cat", "dog", "fish"));
}
enum class Day
{
TODAY, YESTERDAY, TOMORROW
};
ARGPARSE_DEFINE_ENUM(Day, "day", ("Today", Day::TODAY)("Tomorrow", Day::TOMORROW)("Yesterday", Day::YESTERDAY) )
GTEST(TestEnum) {
Day op = Day::TOMORROW;
const bool ok = argparse::Parser::ParseComplete ==
argparse::Parser("description")
("op", op)
.ParseArgs(argparse::Arguments("app.exe", { "tod" }), output, error);
EXPECT_EQ(true, ok);
EXPECT_EQ(Day::TODAY, op);
}
GTEST(TestCommaOp) {
int op = 2;
const bool ok = argparse::Parser::ParseComplete ==
argparse::Parser("description")
("-int,-i", op)
.ParseArgs(argparse::Arguments("app.exe", { "-int", "42" }), output, error);
EXPECT_EQ(true, ok);
EXPECT_EQ(42, op);
}
GTEST(TestPrecedencePos) {
const bool ok = argparse::Parser::ParseComplete ==
parser.ParseArgs(argparse::Arguments("app.exe", {"dog"}), output, error);
EXPECT_EQ(true, ok);
EXPECT_EQ("dog", animal);
EXPECT_EQ("", another);
}
/*
// currently failing. fix this
GTEST(TestPrecedencePosOp) {
const bool ok = argparse::Parser::ParseComplete ==
parser.ParseArgs(argparse::Arguments("app.exe", { "-dog", "-op", "cat" }), output, error);
EXPECT_EQ(true, ok);
EXPECT_EQ("-dog", animal);
EXPECT_EQ("cat", another);
}
*/
// should optional be allowed before positional? How does help work with positional?
/*
// currently failing. fix this
GTEST(TestPrecedenceOpPos) {
const bool ok = argparse::Parser::ParseComplete ==
parser.ParseArgs(argparse::Arguments("app.exe", { "-op", "cat", "dog" }), output, error);
EXPECT_EQ(true, ok);
EXPECT_EQ("dog", animal);
EXPECT_EQ("cat", another);
}
*/<|endoftext|> |
<commit_before>/*
Copyright (c) 2009-2010 Ilmar 'Ingaras' Kruis (seaeagle1@users.sourceforge.net)
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 Mumble Developers 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 FOUNDATION 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 "../mumble_plugin_win32.h"
static int fetch(float *avatar_pos, float *avatar_front, float *avatar_top, float *camera_pos, float *camera_front, float *camera_top, std::string &context, std::wstring &identity) {
for (int i=0;i<3;i++)
avatar_pos[i] = avatar_front[i] = avatar_top[i] = camera_pos[i] = camera_front[i] = camera_top[i] = 0.0f;
bool ok;
byte l[2];
byte r,i;
float o[3];
BYTE *hPtr;
float h;
/*
Position as represented by /loc command
lx, ly = 8 * (byte)l;
ox, oy, oz = (float)o;
0 < ox < 160
x = west
y = north
z = altitude
r = region
i = instance nr
*/
ok = peekProc((BYTE *) 0x010A18F0, o, 12) &&
peekProc((BYTE *) 0x010A18E8, l, 2) &&
peekProc((BYTE *) 0x010A18E4, &r, 1) &&
peekProc((BYTE *) 0x010A18EC, &i, 1) &&
peekProc((BYTE *)(pModule + 0x00D87EC0), &hPtr, 4);
if (! ok)
return false;
ok = peekProc((BYTE *)(hPtr + 0x00000034), &h, 4);
if (! ok)
return false;
// Use region as context since each region has its own coordinate system
if (r == 1)
context = "Eriador";
else if (r == 2)
context = "Rhovannion";
else
return true;
// If we're in an instance, append the instance id
if (i != 0)
context += i;
// Heading should be between 0 and 360
if (h < 0 || h > 360)
return true;
// Limit coordinates to byte-values, otherwise we probably have a read error
if (l[0] == 255 && l[1] == 255)
return true;
avatar_pos[0] = (float)l[0] * 160.0f + o[0];
avatar_pos[1] = o[2];
avatar_pos[2] = (float)l[1] * 160.0f + o[1];
avatar_front[0] = sinf(h * M_PI / 180.0f);
avatar_front[1] = 0.0f;
avatar_front[2] = cosf(h * M_PI / 180.0f);
avatar_top[0] = 0.0;
avatar_top[1] = 1.0;
avatar_top[2] = 0.0;
// TODO: 3rd person camera support
for (int i=0;i<3;i++) {
camera_pos[i] = avatar_pos[i];
camera_front[i] = avatar_front[i];
camera_top[i] = avatar_top[i];
}
//qDebug("P %f %f %f -- %f %f %f -- h %f \n", avatar_pos[0], avatar_pos[1], avatar_pos[2], avatar_front[0], avatar_front[1], avatar_front[2], h);
return true;
}
static int trylock(const std::multimap<std::wstring, unsigned long long int> &pids) {
if (! initialize(pids, L"lotroclient.exe"))
return false;
float apos[3], afront[3], atop[3], cpos[3], cfront[3], ctop[3];
std::string context;
std::wstring identity;
if (fetch(apos, afront, atop, cpos, cfront, ctop, context, identity)) {
return true;
} else {
generic_unlock();
return false;
}
}
static const std::wstring longdesc() {
return std::wstring(L"Supports Lord of the Rings Online (Codemasters Edition, Vol II Book 9 Patch1, v3.0.6.8015). Context support based on region and instance. No Identity support.");
}
static std::wstring description(L"Lord of the Rings Online (EU), Vol II Book 9 Patch1");
static std::wstring shortname(L"Lord of the Rings Online");
static int trylock1() {
return trylock(std::multimap<std::wstring, unsigned long long int>());
}
static MumblePlugin lotroplug = {
MUMBLE_PLUGIN_MAGIC,
description,
shortname,
NULL,
NULL,
trylock1,
generic_unlock,
longdesc,
fetch
};
static MumblePlugin2 lotroplug2 = {
MUMBLE_PLUGIN_MAGIC_2,
MUMBLE_PLUGIN_VERSION,
trylock
};
extern "C" __declspec(dllexport) MumblePlugin *getMumblePlugin() {
return &lotroplug;
}
extern "C" __declspec(dllexport) MumblePlugin2 *getMumblePlugin2() {
return &lotroplug2;
}
<commit_msg>Update lotro to Vol 3, Book 1<commit_after>/*
Copyright (c) 2009-2010 Ilmar 'Ingaras' Kruis (seaeagle1@users.sourceforge.net)
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 Mumble Developers 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 FOUNDATION 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 "../mumble_plugin_win32.h"
#include <QtCore/QtCore>
static int fetch(float *avatar_pos, float *avatar_front, float *avatar_top, float *camera_pos, float *camera_front, float *camera_top, std::string &context, std::wstring &identity) {
for (int i=0;i<3;i++)
avatar_pos[i] = avatar_front[i] = avatar_top[i] = camera_pos[i] = camera_front[i] = camera_top[i] = 0.0f;
bool ok;
byte l[2];
byte r,i;
float o[3];
BYTE *hPtr;
float h;
BYTE *nPtr;
BYTE *nPtr2;
wchar_t* nPtr3;
/*
Position as represented by /loc command
lx, ly = 8 * (byte)l;
ox, oy, oz = (float)o;
0 < ox < 160
x = west
y = north
z = altitude
r = region
i = instance nr
nPtr = pointer to character name (unique on a server)
*/
ok = peekProc((BYTE *) 0x010A9DC0, o, 12) &&
peekProc((BYTE *) 0x010A9DB8, l, 2) &&
peekProc((BYTE *) 0x010A9DB4, &r, 1) &&
peekProc((BYTE *) 0x010A9DBC, &i, 1) &&
peekProc((BYTE *)(pModule + 0x00DA0864), &hPtr, 4);
if (! ok)
return false;
ok = peekProc((BYTE *)(hPtr + 0x000007DC), &h, 4);
if (! ok)
return false;
// Set identity
//if(nPtr3 > 0)
// identity.assign(nPtr3);
// Use region as context since each region has its own coordinate system
if (r == 1)
context = "Eriador";
else if (r == 2)
context = "Rhovannion";
else
return true;
// If we're in an instance, append the instance id
if (i != 0)
context += i;
// Heading should be between 0 and 360
if (h < 0 || h > 360)
return true;
// Limit coordinates to byte-values, otherwise we probably have a read error
if (l[0] == 255 && l[1] == 255)
return true;
avatar_pos[0] = (float)l[0] * 160.0f + o[0];
avatar_pos[1] = o[2];
avatar_pos[2] = (float)l[1] * 160.0f + o[1];
avatar_front[0] = sinf(h * M_PI / 180.0f);
avatar_front[1] = 0.0f;
avatar_front[2] = cosf(h * M_PI / 180.0f);
avatar_top[0] = 0.0;
avatar_top[1] = 1.0;
avatar_top[2] = 0.0;
// TODO: 3rd person camera support
for (int i=0;i<3;i++) {
camera_pos[i] = avatar_pos[i];
camera_front[i] = avatar_front[i];
camera_top[i] = avatar_top[i];
}
//qDebug("I %s", identity);
//qDebug("P %f %f %f -- %f %f %f -- h %f \n", avatar_pos[0], avatar_pos[1], avatar_pos[2], avatar_front[0], avatar_front[1], avatar_front[2], h);
return true;
}
static int trylock(const std::multimap<std::wstring, unsigned long long int> &pids) {
if (! initialize(pids, L"lotroclient.exe"))
return false;
float apos[3], afront[3], atop[3], cpos[3], cfront[3], ctop[3];
std::string context;
std::wstring identity;
if (fetch(apos, afront, atop, cpos, cfront, ctop, context, identity)) {
return true;
} else {
generic_unlock();
return false;
}
}
static const std::wstring longdesc() {
return std::wstring(L"Supports Lord of the Rings Online (Codemasters Edition, Vol III Book 1, v3.1.0.8026). Context support based on region and instance. No Identity support.");
}
static std::wstring description(L"Lord of the Rings Online (EU), Vol III Book 1");
static std::wstring shortname(L"Lord of the Rings Online");
static int trylock1() {
return trylock(std::multimap<std::wstring, unsigned long long int>());
}
static MumblePlugin lotroplug = {
MUMBLE_PLUGIN_MAGIC,
description,
shortname,
NULL,
NULL,
trylock1,
generic_unlock,
longdesc,
fetch
};
static MumblePlugin2 lotroplug2 = {
MUMBLE_PLUGIN_MAGIC_2,
MUMBLE_PLUGIN_VERSION,
trylock
};
extern "C" __declspec(dllexport) MumblePlugin *getMumblePlugin() {
return &lotroplug;
}
extern "C" __declspec(dllexport) MumblePlugin2 *getMumblePlugin2() {
return &lotroplug2;
}
<|endoftext|> |
<commit_before>#include <nodelet/nodelet.h>
#include <pluginlib/class_list_macros.h>
#include "OpenniWrapperNode.h"
#include "OpenniWrapperNodelet.h"
void OpenniWrapperNodelet::onInit()
{
NODELET_DEBUG("Initializing nodelet");
inst_.reset(new OpenniWrapperNode(getNodeHandle(),getPrivateNodeHandle()));
inst_->initializeOpenni();
}
OpenniWrapperNodelet::~OpenniWrapperNodelet()
{
inst_->terminateOpenni();
}
PLUGINLIB_DECLARE_CLASS(openni_wrapper,OpenniWrapperNodelet, OpenniWrapperNodelet, nodelet::Nodelet)
<commit_msg>new export class<commit_after>#include <nodelet/nodelet.h>
#include <pluginlib/class_list_macros.h>
#include "OpenniWrapperNode.h"
#include "OpenniWrapperNodelet.h"
void OpenniWrapperNodelet::onInit()
{
NODELET_DEBUG("Initializing nodelet");
inst_.reset(new OpenniWrapperNode(getNodeHandle(),getPrivateNodeHandle()));
inst_->initializeOpenni();
}
OpenniWrapperNodelet::~OpenniWrapperNodelet()
{
inst_->terminateOpenni();
}
PLUGINLIB_EXPORT_CLASS(OpenniWrapperNodelet, nodelet::Nodelet)
<|endoftext|> |
<commit_before>#include "input/input_state.h"
#include "input/keycodes.h"
#include "ui/ui_screen.h"
#include "ui/ui_context.h"
#include "ui/screen.h"
#include "i18n/i18n.h"
#include "gfx_es2/draw_buffer.h"
UIScreen::UIScreen()
: Screen(), root_(0), recreateViews_(true), hatDown_(0) {
}
UIScreen::~UIScreen() {
delete root_;
}
void UIScreen::DoRecreateViews() {
if (recreateViews_) {
delete root_;
root_ = 0;
CreateViews();
if (root_ && root_->GetDefaultFocusView()) {
root_->GetDefaultFocusView()->SetFocus();
}
recreateViews_ = false;
}
}
void UIScreen::update(InputState &input) {
DoRecreateViews();
if (root_) {
UpdateViewHierarchy(input, root_);
}
}
void UIScreen::render() {
DoRecreateViews();
if (root_) {
UI::LayoutViewHierarchy(*screenManager()->getUIContext(), root_);
screenManager()->getUIContext()->Begin();
DrawBackground(*screenManager()->getUIContext());
root_->Draw(*screenManager()->getUIContext());
screenManager()->getUIContext()->End();
screenManager()->getUIContext()->Flush();
}
}
void UIScreen::touch(const TouchInput &touch) {
if (root_) {
UI::TouchEvent(touch, root_);
}
}
void UIScreen::key(const KeyInput &key) {
if (root_) {
UI::KeyEvent(key, root_);
}
}
void UIDialogScreen::key(const KeyInput &key) {
if ((key.flags & KEY_DOWN) && UI::IsEscapeKeyCode(key.keyCode)) {
if (finished_) {
ELOG("Screen already finished");
} else {
finished_ = true;
screenManager()->finishDialog(this, DR_BACK);
}
} else {
UIScreen::key(key);
}
}
void UIScreen::axis(const AxisInput &axis) {
// Simple translation of hat to keys for Shield and other modern pads.
// TODO: Use some variant of keymap?
int flags = 0;
if (axis.axisId == JOYSTICK_AXIS_HAT_X) {
if (axis.value < -0.7f)
flags |= PAD_BUTTON_LEFT;
if (axis.value > 0.7f)
flags |= PAD_BUTTON_RIGHT;
}
if (axis.axisId == JOYSTICK_AXIS_HAT_Y) {
if (axis.value < -0.7f)
flags |= PAD_BUTTON_UP;
if (axis.value > 0.7f)
flags |= PAD_BUTTON_DOWN;
}
// Yeah yeah, this should be table driven..
int pressed = flags & ~hatDown_;
int released = ~flags & hatDown_;
if (pressed & PAD_BUTTON_LEFT) key(KeyInput(DEVICE_ID_KEYBOARD, NKCODE_DPAD_LEFT, KEY_DOWN));
if (pressed & PAD_BUTTON_RIGHT) key(KeyInput(DEVICE_ID_KEYBOARD, NKCODE_DPAD_RIGHT, KEY_DOWN));
if (pressed & PAD_BUTTON_UP) key(KeyInput(DEVICE_ID_KEYBOARD, NKCODE_DPAD_UP, KEY_DOWN));
if (pressed & PAD_BUTTON_DOWN) key(KeyInput(DEVICE_ID_KEYBOARD, NKCODE_DPAD_DOWN, KEY_DOWN));
if (released & PAD_BUTTON_LEFT) key(KeyInput(DEVICE_ID_KEYBOARD, NKCODE_DPAD_LEFT, KEY_UP));
if (released & PAD_BUTTON_RIGHT) key(KeyInput(DEVICE_ID_KEYBOARD, NKCODE_DPAD_RIGHT, KEY_UP));
if (released & PAD_BUTTON_UP) key(KeyInput(DEVICE_ID_KEYBOARD, NKCODE_DPAD_UP, KEY_UP));
if (released & PAD_BUTTON_DOWN) key(KeyInput(DEVICE_ID_KEYBOARD, NKCODE_DPAD_DOWN, KEY_UP));
hatDown_ = flags;
if (root_) {
UI::AxisEvent(axis, root_);
}
}
UI::EventReturn UIScreen::OnBack(UI::EventParams &e) {
screenManager()->finishDialog(this, DR_BACK);
return UI::EVENT_DONE;
}
UI::EventReturn UIScreen::OnOK(UI::EventParams &e) {
screenManager()->finishDialog(this, DR_OK);
return UI::EVENT_DONE;
}
UI::EventReturn UIScreen::OnCancel(UI::EventParams &e) {
screenManager()->finishDialog(this, DR_CANCEL);
return UI::EVENT_DONE;
}
PopupScreen::PopupScreen(std::string title, std::string button1, std::string button2)
: box_(0), title_(title) {
I18NCategory *d = GetI18NCategory("Dialog");
if (!button1.empty())
button1_ = d->T(button1.c_str());
if (!button2.empty())
button2_ = d->T(button2.c_str());
}
void PopupScreen::touch(const TouchInput &touch) {
if (!box_ || (touch.flags & TOUCH_DOWN) == 0 || touch.id != 0) {
UIDialogScreen::touch(touch);
return;
}
if (!box_->GetBounds().Contains(touch.x, touch.y))
screenManager()->finishDialog(this, DR_BACK);
UIDialogScreen::touch(touch);
}
void PopupScreen::CreateViews() {
using namespace UI;
UIContext &dc = *screenManager()->getUIContext();
root_ = new AnchorLayout(new LayoutParams(FILL_PARENT, FILL_PARENT));
float yres = screenManager()->getUIContext()->GetBounds().h;
box_ = new LinearLayout(ORIENT_VERTICAL,
new AnchorLayoutParams(550, FillVertical() ? yres - 30 : WRAP_CONTENT, dc.GetBounds().centerX(), dc.GetBounds().centerY(), NONE, NONE, true));
root_->Add(box_);
box_->SetBG(UI::Drawable(0xFF303030));
box_->SetHasDropShadow(true);
View *title = new PopupHeader(title_);
box_->Add(title);
CreatePopupContents(box_);
if (ShowButtons() && !button1_.empty()) {
// And the two buttons at the bottom.
LinearLayout *buttonRow = new LinearLayout(ORIENT_HORIZONTAL, new LinearLayoutParams(200, WRAP_CONTENT));
buttonRow->SetSpacing(0);
Margins buttonMargins(5, 5);
// Adjust button order to the platform default.
#if defined(_WIN32)
buttonRow->Add(new Button(button1_, new LinearLayoutParams(1.0f, buttonMargins)))->OnClick.Handle(this, &PopupScreen::OnOK);
if (!button2_.empty())
buttonRow->Add(new Button(button2_, new LinearLayoutParams(1.0f, buttonMargins)))->OnClick.Handle(this, &PopupScreen::OnCancel);
#else
if (!button2_.empty())
buttonRow->Add(new Button(button2_, new LinearLayoutParams(1.0f)))->OnClick.Handle(this, &PopupScreen::OnCancel);
buttonRow->Add(new Button(button1_, new LinearLayoutParams(1.0f)))->OnClick.Handle(this, &PopupScreen::OnOK);
#endif
box_->Add(buttonRow);
}
}
void MessagePopupScreen::CreatePopupContents(UI::ViewGroup *parent) {
parent->Add(new UI::TextView(message_));
}
UI::EventReturn PopupScreen::OnOK(UI::EventParams &e) {
OnCompleted(DR_OK);
screenManager()->finishDialog(this, DR_OK);
return UI::EVENT_DONE;
}
UI::EventReturn PopupScreen::OnCancel(UI::EventParams &e) {
OnCompleted(DR_CANCEL);
screenManager()->finishDialog(this, DR_CANCEL);
return UI::EVENT_DONE;
}
void ListPopupScreen::CreatePopupContents(UI::ViewGroup *parent) {
using namespace UI;
listView_ = parent->Add(new ListView(&adaptor_)); //, new LinearLayoutParams(1.0)));
listView_->SetMaxHeight(screenManager()->getUIContext()->GetBounds().h - 140);
listView_->OnChoice.Handle(this, &ListPopupScreen::OnListChoice);
}
UI::EventReturn ListPopupScreen::OnListChoice(UI::EventParams &e) {
adaptor_.SetSelected(e.a);
if (callback_)
callback_(adaptor_.GetSelected());
screenManager()->finishDialog(this, DR_OK);
OnCompleted(DR_OK);
OnChoice.Dispatch(e);
return UI::EVENT_DONE;
}
namespace UI {
UI::EventReturn PopupMultiChoice::HandleClick(UI::EventParams &e) {
std::vector<std::string> choices;
for (int i = 0; i < numChoices_; i++) {
choices.push_back(category_ ? category_->T(choices_[i]) : choices_[i]);
}
Screen *popupScreen = new ListPopupScreen(text_, choices, *value_ - minVal_,
std::bind(&PopupMultiChoice::ChoiceCallback, this, placeholder::_1));
screenManager_->push(popupScreen);
return UI::EVENT_DONE;
}
void PopupMultiChoice::UpdateText() {
// Clamp the value to be safe.
if (*value_ < minVal_ || *value_ > minVal_ + numChoices_ - 1) {
valueText_ = "(invalid choice)"; // Shouldn't happen. Should be no need to translate this.
} else {
valueText_ = category_ ? category_->T(choices_[*value_ - minVal_]) : choices_[*value_ - minVal_];
}
}
void PopupMultiChoice::ChoiceCallback(int num) {
if (num != -1) {
*value_ = num + minVal_;
UpdateText();
UI::EventParams e;
e.v = this;
e.a = num;
OnChoice.Trigger(e);
}
}
void PopupMultiChoice::Draw(UIContext &dc) {
Style style = dc.theme->itemStyle;
if (!IsEnabled()) {
style = dc.theme->itemDisabledStyle;
}
Choice::Draw(dc);
int paddingX = 12;
dc.SetFontStyle(dc.theme->uiFont);
dc.DrawText(valueText_.c_str(), bounds_.x2() - paddingX, bounds_.centerY(), style.fgColor, ALIGN_RIGHT | ALIGN_VCENTER);
}
PopupSliderChoice::PopupSliderChoice(int *value, int minValue, int maxValue, const std::string &text, ScreenManager *screenManager, LayoutParams *layoutParams)
: Choice(text, "", false, layoutParams), value_(value), minValue_(minValue), maxValue_(maxValue), screenManager_(screenManager) {
OnClick.Handle(this, &PopupSliderChoice::HandleClick);
}
PopupSliderChoiceFloat::PopupSliderChoiceFloat(float *value, float minValue, float maxValue, const std::string &text, ScreenManager *screenManager, LayoutParams *layoutParams)
: Choice(text, "", false, layoutParams), value_(value), minValue_(minValue), maxValue_(maxValue), screenManager_(screenManager) {
OnClick.Handle(this, &PopupSliderChoiceFloat::HandleClick);
}
EventReturn PopupSliderChoice::HandleClick(EventParams &e) {
SliderPopupScreen *popupScreen = new SliderPopupScreen(value_, minValue_, maxValue_, text_);
popupScreen->OnChange.Handle(this, &PopupSliderChoice::HandleChange);
screenManager_->push(popupScreen);
return EVENT_DONE;
}
EventReturn PopupSliderChoice::HandleChange(EventParams &e) {
e.v = this;
OnChange.Trigger(e);
return EVENT_DONE;
}
void PopupSliderChoice::Draw(UIContext &dc) {
Style style = dc.theme->itemStyle;
if (!IsEnabled()) {
style = dc.theme->itemDisabledStyle;
}
Choice::Draw(dc);
char temp[32];
sprintf(temp, "%i", *value_);
dc.SetFontStyle(dc.theme->uiFont);
dc.DrawText(temp, bounds_.x2() - 12, bounds_.centerY(), style.fgColor, ALIGN_RIGHT | ALIGN_VCENTER);
}
EventReturn PopupSliderChoiceFloat::HandleClick(EventParams &e) {
SliderFloatPopupScreen *popupScreen = new SliderFloatPopupScreen(value_, minValue_, maxValue_, text_);
popupScreen->OnChange.Handle(this, &PopupSliderChoiceFloat::HandleChange);
screenManager_->push(popupScreen);
return EVENT_DONE;
}
EventReturn PopupSliderChoiceFloat::HandleChange(EventParams &e) {
e.v = this;
OnChange.Trigger(e);
return EVENT_DONE;
}
void PopupSliderChoiceFloat::Draw(UIContext &dc) {
Style style = dc.theme->itemStyle;
if (!IsEnabled()) {
style = dc.theme->itemDisabledStyle;
}
Choice::Draw(dc);
char temp[32];
sprintf(temp, "%2.2f", *value_);
dc.SetFontStyle(dc.theme->uiFont);
dc.DrawText(temp, bounds_.x2() - 12, bounds_.centerY(), style.fgColor, ALIGN_RIGHT | ALIGN_VCENTER);
}
EventReturn SliderPopupScreen::OnDecrease(EventParams ¶ms) {
sliderValue_--;
slider_->Clamp();
return EVENT_DONE;
}
EventReturn SliderPopupScreen::OnIncrease(EventParams ¶ms) {
sliderValue_++;
slider_->Clamp();
return EVENT_DONE;
}
void SliderPopupScreen::CreatePopupContents(UI::ViewGroup *parent) {
using namespace UI;
sliderValue_ = *value_;
LinearLayout *lin = parent->Add(new LinearLayout(ORIENT_HORIZONTAL, new LinearLayoutParams(UI::Margins(10, 5))));
slider_ = new Slider(&sliderValue_, minValue_, maxValue_, new LinearLayoutParams(1.0f));
lin->Add(slider_);
lin->Add(new Button(" - "))->OnClick.Handle(this, &SliderPopupScreen::OnDecrease);
lin->Add(new Button(" + "))->OnClick.Handle(this, &SliderPopupScreen::OnIncrease);
UI::SetFocusedView(slider_);
}
void SliderFloatPopupScreen::CreatePopupContents(UI::ViewGroup *parent) {
using namespace UI;
sliderValue_ = *value_;
slider_ = parent->Add(new SliderFloat(&sliderValue_, minValue_, maxValue_, new LinearLayoutParams(UI::Margins(10, 5))));
UI::SetFocusedView(slider_);
}
void SliderPopupScreen::OnCompleted(DialogResult result) {
if (result == DR_OK) {
*value_ = sliderValue_;
EventParams e;
e.v = 0;
e.a = *value_;
OnChange.Trigger(e);
}
}
void SliderFloatPopupScreen::OnCompleted(DialogResult result) {
if (result == DR_OK) {
*value_ = sliderValue_;
EventParams e;
e.v = 0;
e.a = (int)*value_;
e.f = *value_;
OnChange.Trigger(e);
}
}
} // namespace UI
<commit_msg>Focus the contents of popup screens<commit_after>#include "input/input_state.h"
#include "input/keycodes.h"
#include "ui/ui_screen.h"
#include "ui/ui_context.h"
#include "ui/screen.h"
#include "i18n/i18n.h"
#include "gfx_es2/draw_buffer.h"
UIScreen::UIScreen()
: Screen(), root_(0), recreateViews_(true), hatDown_(0) {
}
UIScreen::~UIScreen() {
delete root_;
}
void UIScreen::DoRecreateViews() {
if (recreateViews_) {
delete root_;
root_ = 0;
CreateViews();
if (root_ && root_->GetDefaultFocusView()) {
root_->GetDefaultFocusView()->SetFocus();
}
recreateViews_ = false;
}
}
void UIScreen::update(InputState &input) {
DoRecreateViews();
if (root_) {
UpdateViewHierarchy(input, root_);
}
}
void UIScreen::render() {
DoRecreateViews();
if (root_) {
UI::LayoutViewHierarchy(*screenManager()->getUIContext(), root_);
screenManager()->getUIContext()->Begin();
DrawBackground(*screenManager()->getUIContext());
root_->Draw(*screenManager()->getUIContext());
screenManager()->getUIContext()->End();
screenManager()->getUIContext()->Flush();
}
}
void UIScreen::touch(const TouchInput &touch) {
if (root_) {
UI::TouchEvent(touch, root_);
}
}
void UIScreen::key(const KeyInput &key) {
if (root_) {
UI::KeyEvent(key, root_);
}
}
void UIDialogScreen::key(const KeyInput &key) {
if ((key.flags & KEY_DOWN) && UI::IsEscapeKeyCode(key.keyCode)) {
if (finished_) {
ELOG("Screen already finished");
} else {
finished_ = true;
screenManager()->finishDialog(this, DR_BACK);
}
} else {
UIScreen::key(key);
}
}
void UIScreen::axis(const AxisInput &axis) {
// Simple translation of hat to keys for Shield and other modern pads.
// TODO: Use some variant of keymap?
int flags = 0;
if (axis.axisId == JOYSTICK_AXIS_HAT_X) {
if (axis.value < -0.7f)
flags |= PAD_BUTTON_LEFT;
if (axis.value > 0.7f)
flags |= PAD_BUTTON_RIGHT;
}
if (axis.axisId == JOYSTICK_AXIS_HAT_Y) {
if (axis.value < -0.7f)
flags |= PAD_BUTTON_UP;
if (axis.value > 0.7f)
flags |= PAD_BUTTON_DOWN;
}
// Yeah yeah, this should be table driven..
int pressed = flags & ~hatDown_;
int released = ~flags & hatDown_;
if (pressed & PAD_BUTTON_LEFT) key(KeyInput(DEVICE_ID_KEYBOARD, NKCODE_DPAD_LEFT, KEY_DOWN));
if (pressed & PAD_BUTTON_RIGHT) key(KeyInput(DEVICE_ID_KEYBOARD, NKCODE_DPAD_RIGHT, KEY_DOWN));
if (pressed & PAD_BUTTON_UP) key(KeyInput(DEVICE_ID_KEYBOARD, NKCODE_DPAD_UP, KEY_DOWN));
if (pressed & PAD_BUTTON_DOWN) key(KeyInput(DEVICE_ID_KEYBOARD, NKCODE_DPAD_DOWN, KEY_DOWN));
if (released & PAD_BUTTON_LEFT) key(KeyInput(DEVICE_ID_KEYBOARD, NKCODE_DPAD_LEFT, KEY_UP));
if (released & PAD_BUTTON_RIGHT) key(KeyInput(DEVICE_ID_KEYBOARD, NKCODE_DPAD_RIGHT, KEY_UP));
if (released & PAD_BUTTON_UP) key(KeyInput(DEVICE_ID_KEYBOARD, NKCODE_DPAD_UP, KEY_UP));
if (released & PAD_BUTTON_DOWN) key(KeyInput(DEVICE_ID_KEYBOARD, NKCODE_DPAD_DOWN, KEY_UP));
hatDown_ = flags;
if (root_) {
UI::AxisEvent(axis, root_);
}
}
UI::EventReturn UIScreen::OnBack(UI::EventParams &e) {
screenManager()->finishDialog(this, DR_BACK);
return UI::EVENT_DONE;
}
UI::EventReturn UIScreen::OnOK(UI::EventParams &e) {
screenManager()->finishDialog(this, DR_OK);
return UI::EVENT_DONE;
}
UI::EventReturn UIScreen::OnCancel(UI::EventParams &e) {
screenManager()->finishDialog(this, DR_CANCEL);
return UI::EVENT_DONE;
}
PopupScreen::PopupScreen(std::string title, std::string button1, std::string button2)
: box_(0), title_(title) {
I18NCategory *d = GetI18NCategory("Dialog");
if (!button1.empty())
button1_ = d->T(button1.c_str());
if (!button2.empty())
button2_ = d->T(button2.c_str());
}
void PopupScreen::touch(const TouchInput &touch) {
if (!box_ || (touch.flags & TOUCH_DOWN) == 0 || touch.id != 0) {
UIDialogScreen::touch(touch);
return;
}
if (!box_->GetBounds().Contains(touch.x, touch.y))
screenManager()->finishDialog(this, DR_BACK);
UIDialogScreen::touch(touch);
}
void PopupScreen::CreateViews() {
using namespace UI;
UIContext &dc = *screenManager()->getUIContext();
root_ = new AnchorLayout(new LayoutParams(FILL_PARENT, FILL_PARENT));
float yres = screenManager()->getUIContext()->GetBounds().h;
box_ = new LinearLayout(ORIENT_VERTICAL,
new AnchorLayoutParams(550, FillVertical() ? yres - 30 : WRAP_CONTENT, dc.GetBounds().centerX(), dc.GetBounds().centerY(), NONE, NONE, true));
root_->Add(box_);
box_->SetBG(UI::Drawable(0xFF303030));
box_->SetHasDropShadow(true);
View *title = new PopupHeader(title_);
box_->Add(title);
CreatePopupContents(box_);
root_->SetDefaultFocusView(box_);
if (ShowButtons() && !button1_.empty()) {
// And the two buttons at the bottom.
LinearLayout *buttonRow = new LinearLayout(ORIENT_HORIZONTAL, new LinearLayoutParams(200, WRAP_CONTENT));
buttonRow->SetSpacing(0);
Margins buttonMargins(5, 5);
// Adjust button order to the platform default.
#if defined(_WIN32)
buttonRow->Add(new Button(button1_, new LinearLayoutParams(1.0f, buttonMargins)))->OnClick.Handle(this, &PopupScreen::OnOK);
if (!button2_.empty())
buttonRow->Add(new Button(button2_, new LinearLayoutParams(1.0f, buttonMargins)))->OnClick.Handle(this, &PopupScreen::OnCancel);
#else
if (!button2_.empty())
buttonRow->Add(new Button(button2_, new LinearLayoutParams(1.0f)))->OnClick.Handle(this, &PopupScreen::OnCancel);
buttonRow->Add(new Button(button1_, new LinearLayoutParams(1.0f)))->OnClick.Handle(this, &PopupScreen::OnOK);
#endif
box_->Add(buttonRow);
}
}
void MessagePopupScreen::CreatePopupContents(UI::ViewGroup *parent) {
parent->Add(new UI::TextView(message_));
}
UI::EventReturn PopupScreen::OnOK(UI::EventParams &e) {
OnCompleted(DR_OK);
screenManager()->finishDialog(this, DR_OK);
return UI::EVENT_DONE;
}
UI::EventReturn PopupScreen::OnCancel(UI::EventParams &e) {
OnCompleted(DR_CANCEL);
screenManager()->finishDialog(this, DR_CANCEL);
return UI::EVENT_DONE;
}
void ListPopupScreen::CreatePopupContents(UI::ViewGroup *parent) {
using namespace UI;
listView_ = parent->Add(new ListView(&adaptor_)); //, new LinearLayoutParams(1.0)));
listView_->SetMaxHeight(screenManager()->getUIContext()->GetBounds().h - 140);
listView_->OnChoice.Handle(this, &ListPopupScreen::OnListChoice);
}
UI::EventReturn ListPopupScreen::OnListChoice(UI::EventParams &e) {
adaptor_.SetSelected(e.a);
if (callback_)
callback_(adaptor_.GetSelected());
screenManager()->finishDialog(this, DR_OK);
OnCompleted(DR_OK);
OnChoice.Dispatch(e);
return UI::EVENT_DONE;
}
namespace UI {
UI::EventReturn PopupMultiChoice::HandleClick(UI::EventParams &e) {
std::vector<std::string> choices;
for (int i = 0; i < numChoices_; i++) {
choices.push_back(category_ ? category_->T(choices_[i]) : choices_[i]);
}
Screen *popupScreen = new ListPopupScreen(text_, choices, *value_ - minVal_,
std::bind(&PopupMultiChoice::ChoiceCallback, this, placeholder::_1));
screenManager_->push(popupScreen);
return UI::EVENT_DONE;
}
void PopupMultiChoice::UpdateText() {
// Clamp the value to be safe.
if (*value_ < minVal_ || *value_ > minVal_ + numChoices_ - 1) {
valueText_ = "(invalid choice)"; // Shouldn't happen. Should be no need to translate this.
} else {
valueText_ = category_ ? category_->T(choices_[*value_ - minVal_]) : choices_[*value_ - minVal_];
}
}
void PopupMultiChoice::ChoiceCallback(int num) {
if (num != -1) {
*value_ = num + minVal_;
UpdateText();
UI::EventParams e;
e.v = this;
e.a = num;
OnChoice.Trigger(e);
}
}
void PopupMultiChoice::Draw(UIContext &dc) {
Style style = dc.theme->itemStyle;
if (!IsEnabled()) {
style = dc.theme->itemDisabledStyle;
}
Choice::Draw(dc);
int paddingX = 12;
dc.SetFontStyle(dc.theme->uiFont);
dc.DrawText(valueText_.c_str(), bounds_.x2() - paddingX, bounds_.centerY(), style.fgColor, ALIGN_RIGHT | ALIGN_VCENTER);
}
PopupSliderChoice::PopupSliderChoice(int *value, int minValue, int maxValue, const std::string &text, ScreenManager *screenManager, LayoutParams *layoutParams)
: Choice(text, "", false, layoutParams), value_(value), minValue_(minValue), maxValue_(maxValue), screenManager_(screenManager) {
OnClick.Handle(this, &PopupSliderChoice::HandleClick);
}
PopupSliderChoiceFloat::PopupSliderChoiceFloat(float *value, float minValue, float maxValue, const std::string &text, ScreenManager *screenManager, LayoutParams *layoutParams)
: Choice(text, "", false, layoutParams), value_(value), minValue_(minValue), maxValue_(maxValue), screenManager_(screenManager) {
OnClick.Handle(this, &PopupSliderChoiceFloat::HandleClick);
}
EventReturn PopupSliderChoice::HandleClick(EventParams &e) {
SliderPopupScreen *popupScreen = new SliderPopupScreen(value_, minValue_, maxValue_, text_);
popupScreen->OnChange.Handle(this, &PopupSliderChoice::HandleChange);
screenManager_->push(popupScreen);
return EVENT_DONE;
}
EventReturn PopupSliderChoice::HandleChange(EventParams &e) {
e.v = this;
OnChange.Trigger(e);
return EVENT_DONE;
}
void PopupSliderChoice::Draw(UIContext &dc) {
Style style = dc.theme->itemStyle;
if (!IsEnabled()) {
style = dc.theme->itemDisabledStyle;
}
Choice::Draw(dc);
char temp[32];
sprintf(temp, "%i", *value_);
dc.SetFontStyle(dc.theme->uiFont);
dc.DrawText(temp, bounds_.x2() - 12, bounds_.centerY(), style.fgColor, ALIGN_RIGHT | ALIGN_VCENTER);
}
EventReturn PopupSliderChoiceFloat::HandleClick(EventParams &e) {
SliderFloatPopupScreen *popupScreen = new SliderFloatPopupScreen(value_, minValue_, maxValue_, text_);
popupScreen->OnChange.Handle(this, &PopupSliderChoiceFloat::HandleChange);
screenManager_->push(popupScreen);
return EVENT_DONE;
}
EventReturn PopupSliderChoiceFloat::HandleChange(EventParams &e) {
e.v = this;
OnChange.Trigger(e);
return EVENT_DONE;
}
void PopupSliderChoiceFloat::Draw(UIContext &dc) {
Style style = dc.theme->itemStyle;
if (!IsEnabled()) {
style = dc.theme->itemDisabledStyle;
}
Choice::Draw(dc);
char temp[32];
sprintf(temp, "%2.2f", *value_);
dc.SetFontStyle(dc.theme->uiFont);
dc.DrawText(temp, bounds_.x2() - 12, bounds_.centerY(), style.fgColor, ALIGN_RIGHT | ALIGN_VCENTER);
}
EventReturn SliderPopupScreen::OnDecrease(EventParams ¶ms) {
sliderValue_--;
slider_->Clamp();
return EVENT_DONE;
}
EventReturn SliderPopupScreen::OnIncrease(EventParams ¶ms) {
sliderValue_++;
slider_->Clamp();
return EVENT_DONE;
}
void SliderPopupScreen::CreatePopupContents(UI::ViewGroup *parent) {
using namespace UI;
sliderValue_ = *value_;
LinearLayout *lin = parent->Add(new LinearLayout(ORIENT_HORIZONTAL, new LinearLayoutParams(UI::Margins(10, 5))));
slider_ = new Slider(&sliderValue_, minValue_, maxValue_, new LinearLayoutParams(1.0f));
lin->Add(slider_);
lin->Add(new Button(" - "))->OnClick.Handle(this, &SliderPopupScreen::OnDecrease);
lin->Add(new Button(" + "))->OnClick.Handle(this, &SliderPopupScreen::OnIncrease);
UI::SetFocusedView(slider_);
}
void SliderFloatPopupScreen::CreatePopupContents(UI::ViewGroup *parent) {
using namespace UI;
sliderValue_ = *value_;
slider_ = parent->Add(new SliderFloat(&sliderValue_, minValue_, maxValue_, new LinearLayoutParams(UI::Margins(10, 5))));
UI::SetFocusedView(slider_);
}
void SliderPopupScreen::OnCompleted(DialogResult result) {
if (result == DR_OK) {
*value_ = sliderValue_;
EventParams e;
e.v = 0;
e.a = *value_;
OnChange.Trigger(e);
}
}
void SliderFloatPopupScreen::OnCompleted(DialogResult result) {
if (result == DR_OK) {
*value_ = sliderValue_;
EventParams e;
e.v = 0;
e.a = (int)*value_;
e.f = *value_;
OnChange.Trigger(e);
}
}
} // namespace UI
<|endoftext|> |
<commit_before>// Copyright (c) 2020 by Robert Bosch GmbH. 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 "iceoryx_posh/iceoryx_posh_types.hpp"
#include "iceoryx_posh/internal/popo/ports/publisher_port_roudi.hpp"
#include "iceoryx_posh/internal/popo/ports/publisher_port_user.hpp"
#include "iceoryx_posh/internal/popo/ports/subscriber_port_multi_producer.hpp"
#include "iceoryx_posh/internal/popo/ports/subscriber_port_single_producer.hpp"
#include "iceoryx_posh/internal/popo/ports/subscriber_port_user.hpp"
#include "iceoryx_posh/mepoo/mepoo_config.hpp"
#include "iceoryx_utils/cxx/generic_raii.hpp"
#include "iceoryx_utils/error_handling/error_handling.hpp"
#include "iceoryx_utils/internal/concurrent/smart_lock.hpp"
#include "test.hpp"
#include <chrono>
#include <sstream>
#include <thread>
using namespace ::testing;
using namespace iox::popo;
using namespace iox::capro;
using namespace iox::cxx;
using namespace iox::mepoo;
using namespace iox::posix;
using ::testing::Return;
struct DummySample
{
uint64_t m_dummy{42};
};
static const ServiceDescription TEST_SERVICE_DESCRIPTION("x", "y", "z");
static const iox::ProcessName_t TEST_SUBSCRIBER_APP_NAME("mySubscriberApp");
static const iox::ProcessName_t TEST_PUBLISHER_APP_NAME("myPublisherApp");
static constexpr uint32_t NUMBER_OF_PUBLISHERS = 27u;
static constexpr uint32_t ITERATIONS = 1000u;
static constexpr uint32_t NUM_CHUNKS_IN_POOL = NUMBER_OF_PUBLISHERS * ITERATIONS;
static constexpr uint32_t SMALL_CHUNK = 128u;
static constexpr uint32_t CHUNK_META_INFO_SIZE = 256u;
static constexpr size_t MEMORY_SIZE = NUM_CHUNKS_IN_POOL * (SMALL_CHUNK + CHUNK_META_INFO_SIZE);
alignas(64) static uint8_t g_memory[MEMORY_SIZE];
class PortUser_IntegrationTest : public Test
{
public:
PortUser_IntegrationTest()
{
m_mempoolConfig.addMemPool({SMALL_CHUNK, NUM_CHUNKS_IN_POOL});
m_memoryManager.configureMemoryManager(m_mempoolConfig, &m_memoryAllocator, &m_memoryAllocator);
}
~PortUser_IntegrationTest()
{
}
void SetUp()
{
for (uint32_t i = 0; i < NUMBER_OF_PUBLISHERS; i++)
{
std::stringstream publisherAppName;
publisherAppName << TEST_PUBLISHER_APP_NAME << i;
iox::cxx::string<100> processName(TruncateToCapacity, publisherAppName.str().c_str());
m_publisherPortDataVector.emplace_back(TEST_SERVICE_DESCRIPTION, processName, &m_memoryManager);
m_publisherPortUserVector.emplace_back(&m_publisherPortDataVector.back());
m_publisherPortRouDiVector.emplace_back(&m_publisherPortDataVector.back());
}
}
void TearDown()
{
for (uint32_t i = 0; i < NUMBER_OF_PUBLISHERS; i++)
{
m_publisherPortUserVector[i].stopOffer();
static_cast<void>(m_publisherPortRouDiVector[i].getCaProMessage());
}
m_subscriberPortUserSingleProducer.unsubscribe();
m_subscriberPortUserMultiProducer.unsubscribe();
static_cast<void>(m_subscriberPortRouDiSingleProducer.getCaProMessage());
static_cast<void>(m_subscriberPortRouDiMultiProducer.getCaProMessage());
}
GenericRAII m_uniqueRouDiId{[] { iox::popo::internal::setUniqueRouDiId(0); },
[] { iox::popo::internal::unsetUniqueRouDiId(); }};
uint64_t m_receiveCounter{0};
std::atomic<uint64_t> m_sendCounter{0};
std::atomic<uint64_t> m_publisherRunFinished{0};
// Memory objects
Allocator m_memoryAllocator{g_memory, MEMORY_SIZE};
MePooConfig m_mempoolConfig;
MemoryManager m_memoryManager;
using ConcurrentCaproMessageVector_t = iox::concurrent::smart_lock<vector<CaproMessage, 1>>;
ConcurrentCaproMessageVector_t m_concurrentCaproMessageExchange;
ConcurrentCaproMessageVector_t m_concurrentCaproMessageRx;
// subscriber port for single producer
SubscriberPortData m_subscriberPortDataSingleProducer{
TEST_SERVICE_DESCRIPTION, TEST_SUBSCRIBER_APP_NAME, VariantQueueTypes::SoFi_SingleProducerSingleConsumer};
SubscriberPortUser m_subscriberPortUserSingleProducer{&m_subscriberPortDataSingleProducer};
SubscriberPortSingleProducer m_subscriberPortRouDiSingleProducer{&m_subscriberPortDataSingleProducer};
// subscriber port for multi producer
SubscriberPortData m_subscriberPortDataMultiProducer{
TEST_SERVICE_DESCRIPTION, TEST_SUBSCRIBER_APP_NAME, VariantQueueTypes::SoFi_MultiProducerSingleConsumer};
SubscriberPortUser m_subscriberPortUserMultiProducer{&m_subscriberPortDataMultiProducer};
SubscriberPortMultiProducer m_subscriberPortRouDiMultiProducer{&m_subscriberPortDataMultiProducer};
// publisher port
vector<PublisherPortData, NUMBER_OF_PUBLISHERS> m_publisherPortDataVector;
vector<PublisherPortUser, NUMBER_OF_PUBLISHERS> m_publisherPortUserVector;
vector<PublisherPortRouDi, NUMBER_OF_PUBLISHERS> m_publisherPortRouDiVector;
inline CaproMessage waitForCaproMessage(const ConcurrentCaproMessageVector_t& concurrentCaproMessageVector,
const CaproMessageType& caproMessageType)
{
bool finished{false};
CaproMessage caproMessage;
// Wait until the expected CaPro message has arrived in the shared message vector between subscriber and the
// first publisher thread
do
{
// Add delay to allow other thread accessing the shared resource
std::this_thread::sleep_for(std::chrono::microseconds(10));
{
auto guardedVector = concurrentCaproMessageVector.GetScopeGuard();
if (guardedVector->size() != 0)
{
caproMessage = guardedVector->back();
if (caproMessage.m_type == caproMessageType)
{
guardedVector->pop_back();
finished = true;
}
}
}
} while (!finished);
return caproMessage;
}
template <typename SubscriberPortProducerType>
void subscriberThread(uint32_t numberOfPublishers,
SubscriberPortProducerType& subscriberPortRouDi,
SubscriberPortUser& subscriberPortUser)
{
bool finished{false};
// Wait for publisher to be ready
auto caproMessage = waitForCaproMessage(m_concurrentCaproMessageExchange, CaproMessageType::OFFER);
// Subscribe to publisher
subscriberPortUser.subscribe();
auto maybeCaproMessage = subscriberPortRouDi.getCaProMessage();
if (maybeCaproMessage.has_value())
{
caproMessage = maybeCaproMessage.value();
m_concurrentCaproMessageExchange->push_back(caproMessage);
}
else
{
// Error shall never occur
FAIL() << "Error in subscriber SUB CaPro message!";
}
// Wait for subscription ACK from publisher
caproMessage = waitForCaproMessage(m_concurrentCaproMessageExchange, CaproMessageType::ACK);
// Let RouDi change state to finish subscription
static_cast<void>(subscriberPortRouDi.dispatchCaProMessage(caproMessage));
// Subscription done and ready to receive samples
while (!finished)
{
// Try to receive chunk
subscriberPortUser.getChunk()
.and_then([&](optional<const ChunkHeader*>& maybeChunkHeader) {
if (maybeChunkHeader.has_value())
{
auto chunkHeader = maybeChunkHeader.value();
m_receiveCounter++;
subscriberPortUser.releaseChunk(chunkHeader);
}
else
{
// Nothing received -> check if publisher(s) still running
if (m_publisherRunFinished.load(std::memory_order_relaxed) == numberOfPublishers)
{
finished = true;
}
}
})
.or_else([](ChunkReceiveError error) {
// Errors shall never occur
FAIL() << "Error in getChunk(): " << static_cast<uint32_t>(error);
});
}
}
void publisherThread(uint32_t publisherThreadIndex,
PublisherPortRouDi& publisherPortRouDi,
PublisherPortUser& publisherPortUser)
{
CaproMessage caproMessage;
// Publisher offers its service
publisherPortUser.offer();
// Let RouDi change state and send OFFER to subscriber
auto maybeCaproMessage = publisherPortRouDi.getCaProMessage();
if (publisherThreadIndex == 0)
{
// First publisher thread will sync with subscriber
if (maybeCaproMessage.has_value())
{
caproMessage = maybeCaproMessage.value();
m_concurrentCaproMessageExchange->push_back(caproMessage);
}
else
{
// Error shall never occur
FAIL() << "Error in publisher OFFER CaPro message!";
}
// Wait for subscriber to subscribe
caproMessage = waitForCaproMessage(m_concurrentCaproMessageExchange, CaproMessageType::SUB);
m_concurrentCaproMessageRx->push_back(caproMessage);
// Send ACK to subscriber
maybeCaproMessage = publisherPortRouDi.dispatchCaProMessage(m_concurrentCaproMessageRx->back());
if (maybeCaproMessage.has_value())
{
caproMessage = maybeCaproMessage.value();
m_concurrentCaproMessageExchange->push_back(caproMessage);
}
else
{
// Error shall never occur
FAIL() << "Error in publisher ACK CaPro message!";
}
}
else
{
// All other publisher threads wait for the first thread to be synced with subscriber (indicated by
// receiving a SUB message) to continue
CaproMessage caproMessageRouDi(CaproMessageType::UNSUB, TEST_SERVICE_DESCRIPTION);
do
{
std::this_thread::sleep_for(std::chrono::microseconds(10));
if (m_concurrentCaproMessageRx->size() != 0)
{
caproMessageRouDi = m_concurrentCaproMessageRx->back();
}
} while (caproMessageRouDi.m_type != CaproMessageType::SUB);
static_cast<void>(publisherPortRouDi.dispatchCaProMessage(caproMessageRouDi));
}
// Subscriber is ready to receive -> start sending samples
for (size_t i = 0; i < ITERATIONS; i++)
{
publisherPortUser.allocateChunk(sizeof(DummySample))
.and_then([&](ChunkHeader* chunkHeader) {
auto sample = chunkHeader->payload();
new (sample) DummySample();
static_cast<DummySample*>(sample)->m_dummy = i;
publisherPortUser.sendChunk(chunkHeader);
m_sendCounter++;
})
.or_else([](AllocationError error) {
// Errors shall never occur
FAIL() << "Error in allocateChunk(): " << static_cast<uint32_t>(error);
});
/// Add some jitter to make thread breathe
std::this_thread::sleep_for(std::chrono::microseconds(rand() % 750));
}
// Signal the subscriber thread we're done
m_publisherRunFinished++;
}
};
TEST_F(PortUser_IntegrationTest, SingleProducer)
{
std::thread subscribingThread(std::bind(&PortUser_IntegrationTest::subscriberThread<SubscriberPortSingleProducer>,
this,
1,
std::ref(PortUser_IntegrationTest::m_subscriberPortRouDiSingleProducer),
std::ref(PortUser_IntegrationTest::m_subscriberPortUserSingleProducer)));
std::thread publishingThread(std::bind(&PortUser_IntegrationTest::publisherThread,
this,
0,
std::ref(PortUser_IntegrationTest::m_publisherPortRouDiVector.front()),
std::ref(PortUser_IntegrationTest::m_publisherPortUserVector.front())));
if (subscribingThread.joinable())
{
subscribingThread.join();
}
if (publishingThread.joinable())
{
publishingThread.join();
}
EXPECT_EQ(m_sendCounter.load(std::memory_order_relaxed), m_receiveCounter);
EXPECT_EQ(PortUser_IntegrationTest::m_subscriberPortUserMultiProducer.hasLostChunks(), false);
}
TEST_F(PortUser_IntegrationTest, MultiProducer)
{
std::thread subscribingThread(std::bind(&PortUser_IntegrationTest::subscriberThread<SubscriberPortMultiProducer>,
this,
NUMBER_OF_PUBLISHERS,
std::ref(PortUser_IntegrationTest::m_subscriberPortRouDiMultiProducer),
std::ref(PortUser_IntegrationTest::m_subscriberPortUserMultiProducer)));
vector<std::thread, NUMBER_OF_PUBLISHERS> publisherThreadVector;
for (uint32_t i = 0; i < NUMBER_OF_PUBLISHERS; i++)
{
publisherThreadVector.emplace_back(std::bind(&PortUser_IntegrationTest::publisherThread,
this,
i,
std::ref(PortUser_IntegrationTest::m_publisherPortRouDiVector[i]),
std::ref(PortUser_IntegrationTest::m_publisherPortUserVector[i])));
}
if (subscribingThread.joinable())
{
subscribingThread.join();
}
for (uint32_t i = 0; i < NUMBER_OF_PUBLISHERS; i++)
{
if (publisherThreadVector[i].joinable())
{
publisherThreadVector[i].join();
}
}
EXPECT_EQ(m_sendCounter.load(std::memory_order_relaxed), m_receiveCounter);
EXPECT_EQ(PortUser_IntegrationTest::m_subscriberPortUserMultiProducer.hasLostChunks(), false);
}
<commit_msg>iox-#25: Add constexpr for some numbers<commit_after>// Copyright (c) 2020 by Robert Bosch GmbH. 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 "iceoryx_posh/iceoryx_posh_types.hpp"
#include "iceoryx_posh/internal/popo/ports/publisher_port_roudi.hpp"
#include "iceoryx_posh/internal/popo/ports/publisher_port_user.hpp"
#include "iceoryx_posh/internal/popo/ports/subscriber_port_multi_producer.hpp"
#include "iceoryx_posh/internal/popo/ports/subscriber_port_single_producer.hpp"
#include "iceoryx_posh/internal/popo/ports/subscriber_port_user.hpp"
#include "iceoryx_posh/mepoo/mepoo_config.hpp"
#include "iceoryx_utils/cxx/generic_raii.hpp"
#include "iceoryx_utils/error_handling/error_handling.hpp"
#include "iceoryx_utils/internal/concurrent/smart_lock.hpp"
#include "test.hpp"
#include <chrono>
#include <sstream>
#include <thread>
using namespace ::testing;
using namespace iox::popo;
using namespace iox::capro;
using namespace iox::cxx;
using namespace iox::mepoo;
using namespace iox::posix;
using ::testing::Return;
struct DummySample
{
uint64_t m_dummy{42};
};
static const ServiceDescription TEST_SERVICE_DESCRIPTION("x", "y", "z");
static const iox::ProcessName_t TEST_SUBSCRIBER_APP_NAME("mySubscriberApp");
static const iox::ProcessName_t TEST_PUBLISHER_APP_NAME("myPublisherApp");
static constexpr uint32_t NUMBER_OF_PUBLISHERS = 27u;
static constexpr uint32_t ITERATIONS = 1000u;
static constexpr uint32_t NUM_CHUNKS_IN_POOL = NUMBER_OF_PUBLISHERS * ITERATIONS;
static constexpr uint32_t SMALL_CHUNK = 128u;
static constexpr uint32_t CHUNK_META_INFO_SIZE = 256u;
static constexpr size_t MEMORY_SIZE = NUM_CHUNKS_IN_POOL * (SMALL_CHUNK + CHUNK_META_INFO_SIZE);
alignas(64) static uint8_t g_memory[MEMORY_SIZE];
class PortUser_IntegrationTest : public Test
{
public:
PortUser_IntegrationTest()
{
m_mempoolConfig.addMemPool({SMALL_CHUNK, NUM_CHUNKS_IN_POOL});
m_memoryManager.configureMemoryManager(m_mempoolConfig, &m_memoryAllocator, &m_memoryAllocator);
}
~PortUser_IntegrationTest()
{
}
void SetUp()
{
for (uint32_t i = 0; i < NUMBER_OF_PUBLISHERS; i++)
{
std::stringstream publisherAppName;
publisherAppName << TEST_PUBLISHER_APP_NAME << i;
iox::cxx::string<100> processName(TruncateToCapacity, publisherAppName.str().c_str());
m_publisherPortDataVector.emplace_back(TEST_SERVICE_DESCRIPTION, processName, &m_memoryManager);
m_publisherPortUserVector.emplace_back(&m_publisherPortDataVector.back());
m_publisherPortRouDiVector.emplace_back(&m_publisherPortDataVector.back());
}
}
void TearDown()
{
for (uint32_t i = 0; i < NUMBER_OF_PUBLISHERS; i++)
{
m_publisherPortUserVector[i].stopOffer();
static_cast<void>(m_publisherPortRouDiVector[i].getCaProMessage());
}
m_subscriberPortUserSingleProducer.unsubscribe();
m_subscriberPortUserMultiProducer.unsubscribe();
static_cast<void>(m_subscriberPortRouDiSingleProducer.getCaProMessage());
static_cast<void>(m_subscriberPortRouDiMultiProducer.getCaProMessage());
}
GenericRAII m_uniqueRouDiId{[] { iox::popo::internal::setUniqueRouDiId(0); },
[] { iox::popo::internal::unsetUniqueRouDiId(); }};
uint64_t m_receiveCounter{0};
std::atomic<uint64_t> m_sendCounter{0};
std::atomic<uint64_t> m_publisherRunFinished{0};
// Memory objects
Allocator m_memoryAllocator{g_memory, MEMORY_SIZE};
MePooConfig m_mempoolConfig;
MemoryManager m_memoryManager;
using ConcurrentCaproMessageVector_t = iox::concurrent::smart_lock<vector<CaproMessage, 1>>;
ConcurrentCaproMessageVector_t m_concurrentCaproMessageExchange;
ConcurrentCaproMessageVector_t m_concurrentCaproMessageRx;
// subscriber port for single producer
SubscriberPortData m_subscriberPortDataSingleProducer{
TEST_SERVICE_DESCRIPTION, TEST_SUBSCRIBER_APP_NAME, VariantQueueTypes::SoFi_SingleProducerSingleConsumer};
SubscriberPortUser m_subscriberPortUserSingleProducer{&m_subscriberPortDataSingleProducer};
SubscriberPortSingleProducer m_subscriberPortRouDiSingleProducer{&m_subscriberPortDataSingleProducer};
// subscriber port for multi producer
SubscriberPortData m_subscriberPortDataMultiProducer{
TEST_SERVICE_DESCRIPTION, TEST_SUBSCRIBER_APP_NAME, VariantQueueTypes::SoFi_MultiProducerSingleConsumer};
SubscriberPortUser m_subscriberPortUserMultiProducer{&m_subscriberPortDataMultiProducer};
SubscriberPortMultiProducer m_subscriberPortRouDiMultiProducer{&m_subscriberPortDataMultiProducer};
// publisher port
vector<PublisherPortData, NUMBER_OF_PUBLISHERS> m_publisherPortDataVector;
vector<PublisherPortUser, NUMBER_OF_PUBLISHERS> m_publisherPortUserVector;
vector<PublisherPortRouDi, NUMBER_OF_PUBLISHERS> m_publisherPortRouDiVector;
inline CaproMessage waitForCaproMessage(const ConcurrentCaproMessageVector_t& concurrentCaproMessageVector,
const CaproMessageType& caproMessageType)
{
bool finished{false};
CaproMessage caproMessage;
// Wait until the expected CaPro message has arrived in the shared message vector between subscriber and the
// first publisher thread
do
{
// Add delay to allow other thread accessing the shared resource
std::this_thread::sleep_for(std::chrono::microseconds(10));
{
auto guardedVector = concurrentCaproMessageVector.GetScopeGuard();
if (guardedVector->size() != 0)
{
caproMessage = guardedVector->back();
if (caproMessage.m_type == caproMessageType)
{
guardedVector->pop_back();
finished = true;
}
}
}
} while (!finished);
return caproMessage;
}
template <typename SubscriberPortProducerType>
void subscriberThread(uint32_t numberOfPublishers,
SubscriberPortProducerType& subscriberPortRouDi,
SubscriberPortUser& subscriberPortUser)
{
bool finished{false};
// Wait for publisher to be ready
auto caproMessage = waitForCaproMessage(m_concurrentCaproMessageExchange, CaproMessageType::OFFER);
// Subscribe to publisher
subscriberPortUser.subscribe();
auto maybeCaproMessage = subscriberPortRouDi.getCaProMessage();
if (maybeCaproMessage.has_value())
{
caproMessage = maybeCaproMessage.value();
m_concurrentCaproMessageExchange->push_back(caproMessage);
}
else
{
// Error shall never occur
FAIL() << "Error in subscriber SUB CaPro message!";
}
// Wait for subscription ACK from publisher
caproMessage = waitForCaproMessage(m_concurrentCaproMessageExchange, CaproMessageType::ACK);
// Let RouDi change state to finish subscription
static_cast<void>(subscriberPortRouDi.dispatchCaProMessage(caproMessage));
// Subscription done and ready to receive samples
while (!finished)
{
// Try to receive chunk
subscriberPortUser.getChunk()
.and_then([&](optional<const ChunkHeader*>& maybeChunkHeader) {
if (maybeChunkHeader.has_value())
{
auto chunkHeader = maybeChunkHeader.value();
m_receiveCounter++;
subscriberPortUser.releaseChunk(chunkHeader);
}
else
{
// Nothing received -> check if publisher(s) still running
if (m_publisherRunFinished.load(std::memory_order_relaxed) == numberOfPublishers)
{
finished = true;
}
}
})
.or_else([](ChunkReceiveError error) {
// Errors shall never occur
FAIL() << "Error in getChunk(): " << static_cast<uint32_t>(error);
});
}
}
void publisherThread(uint32_t publisherThreadIndex,
PublisherPortRouDi& publisherPortRouDi,
PublisherPortUser& publisherPortUser)
{
CaproMessage caproMessage;
// Publisher offers its service
publisherPortUser.offer();
// Let RouDi change state and send OFFER to subscriber
auto maybeCaproMessage = publisherPortRouDi.getCaProMessage();
if (publisherThreadIndex == 0)
{
// First publisher thread will sync with subscriber
if (maybeCaproMessage.has_value())
{
caproMessage = maybeCaproMessage.value();
m_concurrentCaproMessageExchange->push_back(caproMessage);
}
else
{
// Error shall never occur
FAIL() << "Error in publisher OFFER CaPro message!";
}
// Wait for subscriber to subscribe
caproMessage = waitForCaproMessage(m_concurrentCaproMessageExchange, CaproMessageType::SUB);
m_concurrentCaproMessageRx->push_back(caproMessage);
// Send ACK to subscriber
maybeCaproMessage = publisherPortRouDi.dispatchCaProMessage(m_concurrentCaproMessageRx->back());
if (maybeCaproMessage.has_value())
{
caproMessage = maybeCaproMessage.value();
m_concurrentCaproMessageExchange->push_back(caproMessage);
}
else
{
// Error shall never occur
FAIL() << "Error in publisher ACK CaPro message!";
}
}
else
{
// All other publisher threads wait for the first thread to be synced with subscriber (indicated by
// receiving a SUB message) to continue
CaproMessage caproMessageRouDi(CaproMessageType::UNSUB, TEST_SERVICE_DESCRIPTION);
do
{
std::this_thread::sleep_for(std::chrono::microseconds(10));
if (m_concurrentCaproMessageRx->size() != 0)
{
caproMessageRouDi = m_concurrentCaproMessageRx->back();
}
} while (caproMessageRouDi.m_type != CaproMessageType::SUB);
static_cast<void>(publisherPortRouDi.dispatchCaProMessage(caproMessageRouDi));
}
// Subscriber is ready to receive -> start sending samples
for (size_t i = 0; i < ITERATIONS; i++)
{
publisherPortUser.allocateChunk(sizeof(DummySample))
.and_then([&](ChunkHeader* chunkHeader) {
auto sample = chunkHeader->payload();
new (sample) DummySample();
static_cast<DummySample*>(sample)->m_dummy = i;
publisherPortUser.sendChunk(chunkHeader);
m_sendCounter++;
})
.or_else([](AllocationError error) {
// Errors shall never occur
FAIL() << "Error in allocateChunk(): " << static_cast<uint32_t>(error);
});
/// Add some jitter to make thread breathe
std::this_thread::sleep_for(std::chrono::microseconds(rand() % 750));
}
// Signal the subscriber thread we're done
m_publisherRunFinished++;
}
};
TEST_F(PortUser_IntegrationTest, SingleProducer)
{
constexpr uint32_t NUMBER_OF_PUBLISHERS_SINGLE_PRODUCER = 1u;
constexpr uint32_t INDEX_OF_PUBLISHER_SINGLE_PRODUCER = 0u;
std::thread subscribingThread(std::bind(&PortUser_IntegrationTest::subscriberThread<SubscriberPortSingleProducer>,
this,
NUMBER_OF_PUBLISHERS_SINGLE_PRODUCER,
std::ref(PortUser_IntegrationTest::m_subscriberPortRouDiSingleProducer),
std::ref(PortUser_IntegrationTest::m_subscriberPortUserSingleProducer)));
std::thread publishingThread(std::bind(&PortUser_IntegrationTest::publisherThread,
this,
INDEX_OF_PUBLISHER_SINGLE_PRODUCER,
std::ref(PortUser_IntegrationTest::m_publisherPortRouDiVector.front()),
std::ref(PortUser_IntegrationTest::m_publisherPortUserVector.front())));
if (subscribingThread.joinable())
{
subscribingThread.join();
}
if (publishingThread.joinable())
{
publishingThread.join();
}
EXPECT_EQ(m_sendCounter.load(std::memory_order_relaxed), m_receiveCounter);
EXPECT_EQ(PortUser_IntegrationTest::m_subscriberPortUserMultiProducer.hasLostChunks(), false);
}
TEST_F(PortUser_IntegrationTest, MultiProducer)
{
std::thread subscribingThread(std::bind(&PortUser_IntegrationTest::subscriberThread<SubscriberPortMultiProducer>,
this,
NUMBER_OF_PUBLISHERS,
std::ref(PortUser_IntegrationTest::m_subscriberPortRouDiMultiProducer),
std::ref(PortUser_IntegrationTest::m_subscriberPortUserMultiProducer)));
vector<std::thread, NUMBER_OF_PUBLISHERS> publisherThreadVector;
for (uint32_t i = 0; i < NUMBER_OF_PUBLISHERS; i++)
{
publisherThreadVector.emplace_back(std::bind(&PortUser_IntegrationTest::publisherThread,
this,
i,
std::ref(PortUser_IntegrationTest::m_publisherPortRouDiVector[i]),
std::ref(PortUser_IntegrationTest::m_publisherPortUserVector[i])));
}
if (subscribingThread.joinable())
{
subscribingThread.join();
}
for (uint32_t i = 0; i < NUMBER_OF_PUBLISHERS; i++)
{
if (publisherThreadVector[i].joinable())
{
publisherThreadVector[i].join();
}
}
EXPECT_EQ(m_sendCounter.load(std::memory_order_relaxed), m_receiveCounter);
EXPECT_EQ(PortUser_IntegrationTest::m_subscriberPortUserMultiProducer.hasLostChunks(), false);
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: propertysethelper.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-08 19:25:24 $
*
* 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
*
************************************************************************/
#include "propertysethelper.hxx"
#ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_
#include <com/sun/star/lang/XTypeProvider.hpp>
#endif
#include <cppuhelper/typeprovider.hxx>
//..........................................................................
namespace extensions {
namespace apihelper {
//..........................................................................
namespace uno = com::sun::star::uno;
namespace lang = com::sun::star::lang;
namespace beans = com::sun::star::beans;
//..........................................................................
PropertySetHelper::PropertySetHelper()
: BroadcasterBase()
, cppu::OWeakObject()
, cppu::OPropertySetHelper( BroadcasterBase::getBroadcastHelper() )
, m_pHelper(0)
{
}
//..........................................................................
PropertySetHelper::~PropertySetHelper()
{
delete m_pHelper;
}
//..........................................................................
// XInterface
uno::Any SAL_CALL PropertySetHelper::queryInterface( uno::Type const & rType ) throw (uno::RuntimeException)
{
uno::Any aResult = cppu::OPropertySetHelper::queryInterface(rType);
if (!aResult.hasValue())
aResult = OWeakObject::queryInterface(rType);
return aResult;
}
void SAL_CALL PropertySetHelper::acquire() throw ()
{
OWeakObject::acquire();
}
void SAL_CALL PropertySetHelper::release() throw ()
{
if (m_refCount == 1)
this->disposing();
OWeakObject::release();
}
//..........................................................................
// XTypeProvider
uno::Sequence< uno::Type > SAL_CALL PropertySetHelper::getTypes() throw (uno::RuntimeException)
{
// could be static instance
cppu::OTypeCollection aTypes(
::getCppuType( static_cast< uno::Reference< beans::XPropertySet > const * >(0) ),
::getCppuType( static_cast< uno::Reference< beans::XMultiPropertySet > const * >(0) ),
::getCppuType( static_cast< uno::Reference< beans::XFastPropertySet > const * >(0) ),
::getCppuType( static_cast< uno::Reference< lang::XTypeProvider > const * >(0) ) );
return aTypes.getTypes();
}
//..........................................................................
// cppu::OPropertySetHelper
uno::Reference< beans::XPropertySetInfo > SAL_CALL PropertySetHelper::getPropertySetInfo( )
throw (uno::RuntimeException)
{
return createPropertySetInfo(getInfoHelper());
}
//..........................................................................
cppu::IPropertyArrayHelper & SAL_CALL PropertySetHelper::getInfoHelper()
{
osl::MutexGuard aGuard( getBroadcastMutex() );
if (!m_pHelper)
m_pHelper = newInfoHelper();
OSL_ENSURE(m_pHelper,"Derived class did not create new PropertyInfoHelper");
if (!m_pHelper)
throw uno::RuntimeException(rtl::OUString::createFromAscii("No PropertyArrayHelper available"),*this);
return *m_pHelper;
}
//..........................................................................
sal_Bool SAL_CALL PropertySetHelper::convertFastPropertyValue(
uno::Any & rConvertedValue, uno::Any & rOldValue, sal_Int32 nHandle, const uno::Any& rValue )
throw (lang::IllegalArgumentException)
{
this->getFastPropertyValue(rOldValue, nHandle);
rConvertedValue = rValue;
return rValue.isExtractableTo( rOldValue.getValueType() );
}
//..........................................................................
void SAL_CALL ReadOnlyPropertySetHelper::setFastPropertyValue_NoBroadcast(
sal_Int32 nHandle, const uno::Any& rValue )
throw (uno::Exception)
{
OSL_ENSURE(false, "Attempt to set value in read-only property set");
throw beans::PropertyVetoException(rtl::OUString::createFromAscii("Attempt to set value in Read-Only property set"),*this);
}
//..........................................................................
sal_Bool SAL_CALL ReadOnlyPropertySetHelper::convertFastPropertyValue(
uno::Any & rConvertedValue, uno::Any & rOldValue, sal_Int32 nHandle, const uno::Any& rValue )
throw (lang::IllegalArgumentException)
{
OSL_ENSURE(false, "Attempt to convert value in read-only property set");
return false;
}
//..........................................................................
//..........................................................................
} // namespace apihelper
} // namespace extensions
//..........................................................................
<commit_msg>INTEGRATION: CWS pchfix02 (1.3.186); FILE MERGED 2006/09/01 17:26:28 kaib 1.3.186.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: propertysethelper.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: obo $ $Date: 2006-09-16 12:58:28 $
*
* 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_extensions.hxx"
#include "propertysethelper.hxx"
#ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_
#include <com/sun/star/lang/XTypeProvider.hpp>
#endif
#include <cppuhelper/typeprovider.hxx>
//..........................................................................
namespace extensions {
namespace apihelper {
//..........................................................................
namespace uno = com::sun::star::uno;
namespace lang = com::sun::star::lang;
namespace beans = com::sun::star::beans;
//..........................................................................
PropertySetHelper::PropertySetHelper()
: BroadcasterBase()
, cppu::OWeakObject()
, cppu::OPropertySetHelper( BroadcasterBase::getBroadcastHelper() )
, m_pHelper(0)
{
}
//..........................................................................
PropertySetHelper::~PropertySetHelper()
{
delete m_pHelper;
}
//..........................................................................
// XInterface
uno::Any SAL_CALL PropertySetHelper::queryInterface( uno::Type const & rType ) throw (uno::RuntimeException)
{
uno::Any aResult = cppu::OPropertySetHelper::queryInterface(rType);
if (!aResult.hasValue())
aResult = OWeakObject::queryInterface(rType);
return aResult;
}
void SAL_CALL PropertySetHelper::acquire() throw ()
{
OWeakObject::acquire();
}
void SAL_CALL PropertySetHelper::release() throw ()
{
if (m_refCount == 1)
this->disposing();
OWeakObject::release();
}
//..........................................................................
// XTypeProvider
uno::Sequence< uno::Type > SAL_CALL PropertySetHelper::getTypes() throw (uno::RuntimeException)
{
// could be static instance
cppu::OTypeCollection aTypes(
::getCppuType( static_cast< uno::Reference< beans::XPropertySet > const * >(0) ),
::getCppuType( static_cast< uno::Reference< beans::XMultiPropertySet > const * >(0) ),
::getCppuType( static_cast< uno::Reference< beans::XFastPropertySet > const * >(0) ),
::getCppuType( static_cast< uno::Reference< lang::XTypeProvider > const * >(0) ) );
return aTypes.getTypes();
}
//..........................................................................
// cppu::OPropertySetHelper
uno::Reference< beans::XPropertySetInfo > SAL_CALL PropertySetHelper::getPropertySetInfo( )
throw (uno::RuntimeException)
{
return createPropertySetInfo(getInfoHelper());
}
//..........................................................................
cppu::IPropertyArrayHelper & SAL_CALL PropertySetHelper::getInfoHelper()
{
osl::MutexGuard aGuard( getBroadcastMutex() );
if (!m_pHelper)
m_pHelper = newInfoHelper();
OSL_ENSURE(m_pHelper,"Derived class did not create new PropertyInfoHelper");
if (!m_pHelper)
throw uno::RuntimeException(rtl::OUString::createFromAscii("No PropertyArrayHelper available"),*this);
return *m_pHelper;
}
//..........................................................................
sal_Bool SAL_CALL PropertySetHelper::convertFastPropertyValue(
uno::Any & rConvertedValue, uno::Any & rOldValue, sal_Int32 nHandle, const uno::Any& rValue )
throw (lang::IllegalArgumentException)
{
this->getFastPropertyValue(rOldValue, nHandle);
rConvertedValue = rValue;
return rValue.isExtractableTo( rOldValue.getValueType() );
}
//..........................................................................
void SAL_CALL ReadOnlyPropertySetHelper::setFastPropertyValue_NoBroadcast(
sal_Int32 nHandle, const uno::Any& rValue )
throw (uno::Exception)
{
OSL_ENSURE(false, "Attempt to set value in read-only property set");
throw beans::PropertyVetoException(rtl::OUString::createFromAscii("Attempt to set value in Read-Only property set"),*this);
}
//..........................................................................
sal_Bool SAL_CALL ReadOnlyPropertySetHelper::convertFastPropertyValue(
uno::Any & rConvertedValue, uno::Any & rOldValue, sal_Int32 nHandle, const uno::Any& rValue )
throw (lang::IllegalArgumentException)
{
OSL_ENSURE(false, "Attempt to convert value in read-only property set");
return false;
}
//..........................................................................
//..........................................................................
} // namespace apihelper
} // namespace extensions
//..........................................................................
<|endoftext|> |
<commit_before>template <size_t maxSets>
inline DescriptorSetPool<maxSets>::DescriptorSetPool(Renderer& renderer) : _renderer(renderer) {}
template <size_t maxSets>
inline DescriptorSetPool<maxSets>::~DescriptorSetPool() {
descriptorPool.destroy();
}
template <size_t maxSets>
inline bool DescriptorSetPool<maxSets>::init() {
if (static_cast<VkDescriptorPool>(descriptorPool) == VK_NULL_HANDLE) {
API::Builder::DescriptorPool descriptorPoolBuilder(_renderer.getDevice());
// Use VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT to individually free descritors sets
descriptorPoolBuilder.setFlags(0);
descriptorPoolBuilder.setMaxSets(42); // TODO: Replace this arbitrary number
std::vector<VkDescriptorPoolSize> poolSizes{ // TODO: Replace this initialization
{
/* poolSize.type */ VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC,
/* poolSize.descriptorCount */ 42
},
{
/* poolSize.type */ VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
/* poolSize.descriptorCount */ 42
}
};
descriptorPoolBuilder.setPoolSizes(poolSizes);
VkResult result{VK_SUCCESS};
if (!descriptorPoolBuilder.build(descriptorPool, &result)) {
LUG_LOG.error("DescriptorSetPool: Can't create the descriptor pool: {}", result);
return false;
}
}
return true;
}
template <size_t maxSets>
inline std::tuple<bool, const DescriptorSet*> DescriptorSetPool<maxSets>::allocate(size_t hash, const API::DescriptorSetLayout& descriptorSetLayout) {
auto it = _descriptorSetsInUse.find(hash);
if (it == _descriptorSetsInUse.end()) {
DescriptorSet* descriptorSet = allocateNewDescriptorSet(descriptorSetLayout);
if (!descriptorSet) {
return std::make_tuple(false, nullptr);
}
descriptorSet->setHash(hash);
_descriptorSetsInUse[hash] = descriptorSet;
return std::make_tuple(true, descriptorSet);
}
it->second->_referenceCount += 1;
return std::make_tuple(false, it->second);
}
template <size_t maxSets>
inline void DescriptorSetPool<maxSets>::free(const DescriptorSet* descriptorSet) {
if (!descriptorSet) {
return;
}
const_cast<DescriptorSet*>(descriptorSet)->_referenceCount -= 1;
const auto it = _descriptorSetsInUse.find(descriptorSet->getHash());
if (descriptorSet->_referenceCount == 0) {
if (it != _descriptorSetsInUse.end() && it->second == descriptorSet) {
_descriptorSetsInUse.erase(descriptorSet->getHash());
} else {
_freeDescriptorSets[_freeDescriptorSetsCount++] = const_cast<DescriptorSet*>(descriptorSet);
}
}
}
template <size_t maxSets>
inline DescriptorSet* DescriptorSetPool<maxSets>::allocateNewDescriptorSet(const API::DescriptorSetLayout& descriptorSetLayout) {
if (_freeDescriptorSetsCount) {
DescriptorSet* tmp = _freeDescriptorSets[_freeDescriptorSetsCount];
_freeDescriptorSets[_freeDescriptorSetsCount--] = nullptr;
tmp->_referenceCount += 1;
return tmp;
} else if (_descriptorSetsCount < maxSets) {
API::Builder::DescriptorSet descriptorSetBuilder(_renderer.getDevice(), descriptorPool);
descriptorSetBuilder.setDescriptorSetLayouts({static_cast<VkDescriptorSetLayout>(descriptorSetLayout)});
API::DescriptorSet descriptorSet;
VkResult result{VK_SUCCESS};
if (!descriptorSetBuilder.build(_descriptorSets[_descriptorSetsCount]._descriptorSet, &result)) {
LUG_LOG.error("DescriptorSetPool: Can't create descriptor set: {}", result);
return nullptr;
}
return &_descriptorSets[_descriptorSetsCount++];
} else {
LUG_LOG.error("DescriptorSetPool: Can't create descriptor set: Maximum number of sets reached");
}
return nullptr;
}
<commit_msg>Fix a fail of reference counting in DescriptorSetPool<commit_after>template <size_t maxSets>
inline DescriptorSetPool<maxSets>::DescriptorSetPool(Renderer& renderer) : _renderer(renderer) {}
template <size_t maxSets>
inline DescriptorSetPool<maxSets>::~DescriptorSetPool() {
descriptorPool.destroy();
}
template <size_t maxSets>
inline bool DescriptorSetPool<maxSets>::init() {
if (static_cast<VkDescriptorPool>(descriptorPool) == VK_NULL_HANDLE) {
API::Builder::DescriptorPool descriptorPoolBuilder(_renderer.getDevice());
// Use VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT to individually free descritors sets
descriptorPoolBuilder.setFlags(0);
descriptorPoolBuilder.setMaxSets(42); // TODO: Replace this arbitrary number
std::vector<VkDescriptorPoolSize> poolSizes{ // TODO: Replace this initialization
{
/* poolSize.type */ VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC,
/* poolSize.descriptorCount */ 42
},
{
/* poolSize.type */ VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
/* poolSize.descriptorCount */ 42
}
};
descriptorPoolBuilder.setPoolSizes(poolSizes);
VkResult result{VK_SUCCESS};
if (!descriptorPoolBuilder.build(descriptorPool, &result)) {
LUG_LOG.error("DescriptorSetPool: Can't create the descriptor pool: {}", result);
return false;
}
}
return true;
}
template <size_t maxSets>
inline std::tuple<bool, const DescriptorSet*> DescriptorSetPool<maxSets>::allocate(size_t hash, const API::DescriptorSetLayout& descriptorSetLayout) {
auto it = _descriptorSetsInUse.find(hash);
if (it == _descriptorSetsInUse.end()) {
DescriptorSet* descriptorSet = allocateNewDescriptorSet(descriptorSetLayout);
if (!descriptorSet) {
return std::make_tuple(false, nullptr);
}
descriptorSet->setHash(hash);
descriptorSet->_referenceCount += 1;
_descriptorSetsInUse[hash] = descriptorSet;
return std::make_tuple(true, descriptorSet);
}
it->second->_referenceCount += 1;
return std::make_tuple(false, it->second);
}
template <size_t maxSets>
inline void DescriptorSetPool<maxSets>::free(const DescriptorSet* descriptorSet) {
if (!descriptorSet) {
return;
}
const_cast<DescriptorSet*>(descriptorSet)->_referenceCount -= 1;
const auto it = _descriptorSetsInUse.find(descriptorSet->getHash());
if (descriptorSet->_referenceCount == 0) {
if (it != _descriptorSetsInUse.end() && it->second == descriptorSet) {
_descriptorSetsInUse.erase(descriptorSet->getHash());
} else {
_freeDescriptorSets[_freeDescriptorSetsCount++] = const_cast<DescriptorSet*>(descriptorSet);
}
}
}
template <size_t maxSets>
inline DescriptorSet* DescriptorSetPool<maxSets>::allocateNewDescriptorSet(const API::DescriptorSetLayout& descriptorSetLayout) {
if (_freeDescriptorSetsCount) {
DescriptorSet* tmp = _freeDescriptorSets[_freeDescriptorSetsCount];
_freeDescriptorSets[_freeDescriptorSetsCount--] = nullptr;
return tmp;
} else if (_descriptorSetsCount < maxSets) {
API::Builder::DescriptorSet descriptorSetBuilder(_renderer.getDevice(), descriptorPool);
descriptorSetBuilder.setDescriptorSetLayouts({static_cast<VkDescriptorSetLayout>(descriptorSetLayout)});
VkResult result{VK_SUCCESS};
if (!descriptorSetBuilder.build(_descriptorSets[_descriptorSetsCount]._descriptorSet, &result)) {
LUG_LOG.error("DescriptorSetPool: Can't create descriptor set: {}", result);
return nullptr;
}
return &_descriptorSets[_descriptorSetsCount++];
} else {
LUG_LOG.error("DescriptorSetPool: Can't create descriptor set: Maximum number of sets reached");
}
return nullptr;
}
<|endoftext|> |
<commit_before>#include "ns3/core-module.h"
#include "ns3/network-module.h"
#include "ns3/csma-module.h"
#include "ns3/internet-module.h"
#include "ns3/applications-module.h"
#include "ns3/ipv4-global-routing-helper.h"
using namespace ns3;
/*
Example Topology: 2 levels, each node connected to 2 leaves per level.
Client
+------------+
| Root |
+------------+
/ \
/ \
+-------------+ +-------------+
| leftRouther | | rightRouter |
+-------------+ +-------------+
/ \ / \
/ \ / \
+----+ +----+ +----+ +----+
| n1 | | n2 | | n3 | | n4 |
+----+ +----+ +----+ +----+
Server Server Server Server
*/
/**
* Function to generate network topology as shown above, with an arbitrary number of
* levels or leave nodes. This function is recursive.
*
* Ptr<Node> parent is the node to the network topology, it is equivalent to the motherNode
* illustrated above
*
* int numLeaves is the number of leaves each parent node should be connected with.
* Ipv4InterfaceContainer* ipInterfaces is a variable to keep track of the server nodes addresses
* (explained more in the main function)
*
* int level is the level of the network topology, level = 1 would be a parent node connected with
* numLeaves
*/
void networkTree(Ptr<Node> parent, int numLeaves, Ipv4InterfaceContainer* ipInterfaces, int level);
/**
* Function to install a UDP server application on each server node that echo's back the
* packet it receives.
*
* NodeContainer* leaves is a reference to the nodes to install the server application onto.
*
* int port is the port number which all server nodes listen to.
*
* float start, end is the start and end of the application
*/
void installUdpEchoServers(NodeContainer* leaves, int port, float start, float end);
/**
* Function to install several UDP client applications to send to all the server nodes
* and expect a echo packet reply
*
* Ptr<Node> node, node to intall the several UDP client apps onto
*
* int port is the port number the server nodes are supposed to listen to
*
* Ipv4InterfaceContainer* ipInterfaces is the variable that contains all the addresses
* of the server nodes, and is used for the client app to send a packet to them
*
* float start, end is the start and end of the application
*/
void installUdpEchoClient(Ptr<Node> node, int port, Ipv4InterfaceContainer* ipInterfaces,
float start, float end);
// Since this code uses recursion, using a global variable to specify a branch was useful
static int branch = 1;
NS_LOG_COMPONENT_DEFINE ("networkTree"); // Naming this script to enable logging (debugging)
int main (int argc, char *argv[])
{
LogComponentEnable ("networkTree", LOG_LEVEL_INFO); // Enable logging or debugging at the info level
NS_LOG_INFO ("Testing"); // Code reached here, should output "testing" on the shell
// We need to log packet info of client node, which contains a UDP application
LogComponentEnable ("UdpEchoClientApplication", LOG_LEVEL_INFO);
// uncomment line below to log server applications listening to packets and echoing them back
//LogComponentEnable ("UdpEchoServerApplication", LOG_LEVEL_INFO);
// There is a lot of congestion in this network topology, we need to increase the buffer size,
// otherwise packets will be dropped, we need to do this at the IP layer and the link layer,
// below increases buffer size to 1000 at the IP layer, as in, 1000 packets can be queued up
Config::SetDefault("ns3::ArpCache::PendingQueueSize", UintegerValue(1000));
Ptr<Node> client = CreateObject<Node> ();
InternetStackHelper stack;
stack.Install (client);
// We need to keep track of the IP addresses of the server nodes for the client to send
// packets to them, this can be done using a Ipv4InterfaceContainer var. The var ipInterfaces
// will be used to contain all the IP addresses of the server nodes.
Ipv4InterfaceContainer ipInterfaces;
// Generate the topology with connections and IPv4 addresses
// here, each node has 3 leaves, and it is 2 levels long, so there should be 3*2 = 6 server nodes
// at the bottom, modify them to create the appropriate topology
networkTree(client, 3, &ipInterfaces, 2);
// Install the UDP application on the client node and have these applications send a packet to
// all the server nodes
installUdpEchoClient(client, 9, &ipInterfaces, 2.0, 2000.0);
// Since this is dynamic routing and with a large network topology, populating the routing tables
// can take quite a long time. To simulate topology with 2 levels and 32 leaves at each level,
// there would be 32*32 = 1024 server nodes, it takes about 30 minutes to populate the tables.
NS_LOG_INFO ("Populating table");
Ipv4GlobalRoutingHelper::PopulateRoutingTables ();
NS_LOG_INFO ("Populating table done");
Simulator::Stop (Seconds (200));
NS_LOG_INFO ("Simulation begins now");
Simulator::Run ();
NS_LOG_INFO ("Simulation ends");
Simulator::Destroy ();
return 0;
}
void networkTree(Ptr<Node> parent, int numLeaves, Ipv4InterfaceContainer* ipInterfaces, int level) {
if (level > 0) { // Base case, only recursively create more connections if level > 0
// Create the nodes to be connected as leaves
NodeContainer leaves;
leaves.Create(numLeaves);
// Create the net devices on the nodes and a network channel connecting them
// according to the topology
// Create the variable to help create the net devices and connect nodes to channels
CsmaHelper csma;
// Increase the buffer size at the link layer
csma.SetQueue ("ns3::DropTailQueue", "MaxPackets", UintegerValue(1000));
// Set the typical Data Centre standard values
csma.SetChannelAttribute ("DataRate", StringValue ("1Gbps"));
csma.SetChannelAttribute ("Delay", StringValue ("1ms"));
// Connect the parent node to its leave nodes
std::vector<NetDeviceContainer> netC; // save them to assign IP addresses
for (int leaf = 0; leaf < leaves.GetN(); leaf++) {
netC.push_back( csma.Install( NodeContainer( parent, leaves.Get(leaf) ) ) );
}
// Set up the IP addresses to the leaves
InternetStackHelper stack;
stack.Install (leaves);
// Make sure level == 1 to ensure server nodes are installed at the bottom of the topology
if (level == 1) installUdpEchoServers(&leaves, 9, 1.0, 2000.0);
// Assign IP addresses to the leaves
char buffer [15];
Ipv4AddressHelper address;
for (int netDev = 0; netDev < netC.size(); netDev++) {
// Specify the address using string formating
sprintf (buffer, "%d.%d.%d.0", 9 + level, branch, netDev + 1);
address.SetBase (buffer, "255.255.255.0");
Ipv4InterfaceContainer tempContainer = address.Assign( netC.at(netDev) );
// Make sure we only obtain the addresses of the leaves nodes at the bottom of the topology
if (level == 1) ipInterfaces->Add(tempContainer);
// Recursion, connect each leaf to more nodes
int leaf = netDev;
networkTree(leaves.Get(leaf), numLeaves, ipInterfaces, level - 1);
}
branch++; // next branch in topology
}
}
void installUdpEchoServers(NodeContainer* leaves, int port, float start, float end) {
for (int leaf = 0; leaf < leaves->GetN(); leaf++) {
Ptr<UdpEchoServer> serverApp = CreateObject<UdpEchoServer>();
serverApp->SetAttribute("Port", UintegerValue(port)); // server apps listen to this port
leaves->Get(leaf)->AddApplication(serverApp);
serverApp->SetStartTime (Seconds (start));
serverApp->SetStopTime (Seconds (end));
}
}
void installUdpEchoClient(Ptr<Node> node, int port, Ipv4InterfaceContainer* ipInterfaces,
float start, float end) {
// ipInterfaces contains the address of the net device of the server node and the
// address of the net device connected to the server node (parent node).
// In order to obtain only the server node addresses, the first address is parent
// second is server, so start with ip = 1, and incumbent twice to obtain only server addresses
for (int ip = 1; ip < ipInterfaces->GetN(); ip+=2) {
Ptr<UdpEchoClient> echoClient = CreateObject<UdpEchoClient>();
echoClient->SetRemote(ipInterfaces->GetAddress(ip), port);
echoClient->SetAttribute ("MaxPackets", UintegerValue (1)); // send only 1 packet
echoClient->SetAttribute ("PacketSize", UintegerValue (1 << 10)); // 1 KB
node->AddApplication(echoClient);
// Start each application and have each send a packet with a delay of 100 micro seconds
int delay = 10000; // in terms of seconds, so if delay = 1 ms, it is 1000, or 1000th of a second
echoClient->SetStartTime (Seconds (start + (ip - 1.0)/(2*delay) )); // formula to create delay using ip
echoClient->SetStopTime (Seconds (end));
}
}<commit_msg>Rename to networkTree.cc<commit_after><|endoftext|> |
<commit_before>// Copyright 2020 The Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Graphs (influence maximization, coverage function)
//
// Class that stores a graph (e.g. a social network)
// with special support for DBLP.
// Input format:
// For normal graphs we expect on edge per line. Each edge is expected to be two
// space separated integers.
// For DBLP, each line is expected to be an edge followed by the year.
#include "graph.h"
#include "absl/container/node_hash_map.h"
#include "absl/container/node_hash_set.h"
using std::vector;
Graph::Graph(const std::string& name) : name_(name) {
// Technical comment: would prefer to make this constructor private,
// but this breaks a crucial line in getGraph.
// Update this part with the file name.
static const absl::node_hash_map<std::string, std::string> name_to_filename =
{{"amazon", "../datasets/amazon/graph-relabeled-big-amazon.txt"},
{"enron", "../datasets/enron/Email-Enron.txt"},
{"twitter", "../datasets/twitter/graph-relabel-twitter.txt"},
{"dblp", "../datasets/dblp/dblp-graph.txt"},
{"pokec", "../datasets/pokec/soc-pokec-relationships.txt"},
{"friendster", "../datasets/friendster/friendster.txt"}};
if (!name_to_filename.count(name_)) {
Fail("unknown graph name");
}
const std::string& file_name = name_to_filename.at(name_);
std::cerr << "reading graph from " << file_name << "..." << std::endl;
std::ifstream input(file_name);
if (!input) {
Fail("graph file does not exist");
}
// renumber[x] = new number of x
unordered_map<int64_t, int> renumber;
numVertices_ = 0;
numEdges_ = 0;
const bool is_dblp = (name_ == "dblp");
int64_t first_endpoint, second_endpoint;
unordered_set<int> leftVertices, rightVertices;
while (input >> first_endpoint >> second_endpoint) {
if (!renumber.count(first_endpoint)) {
renumber[first_endpoint] = numVertices_;
++numVertices_;
neighbors_.push_back({});
}
leftVertices.insert(renumber[first_endpoint]);
if (!renumber.count(second_endpoint)) {
renumber[second_endpoint] = numVertices_;
++numVertices_;
neighbors_.push_back({});
}
rightVertices.insert(renumber[second_endpoint]);
numEdges_++;
neighbors_[renumber[first_endpoint]].push_back(renumber[second_endpoint]);
// Note: our graphs are directed.
// But in some cases you may want to also add the reverse edge.
if (is_dblp) {
int year;
input >> year;
publicationDates_[renumber[first_endpoint]].insert(year);
}
}
leftVertices_.assign(leftVertices.begin(), leftVertices.end());
rightVertices_.assign(rightVertices.begin(), rightVertices.end());
std::cerr << "read graph with " << numVertices_ << " vertices "
<< "and " << numEdges_ << " edges" << std::endl;
}
const vector<int>& Graph::GetCoverableVertices() const {
return rightVertices_;
}
const vector<int>& Graph::GetUniverseVertices() const { return leftVertices_; }
const vector<int>& Graph::GetNeighbors(int vertex_i) const {
return neighbors_[vertex_i];
}
const std::string& Graph::GetName() const { return name_; }
<commit_msg>Internal change<commit_after>// Copyright 2020 The Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Graphs (influence maximization, coverage function)
//
// Class that stores a graph (e.g. a social network)
// with special support for DBLP.
// Input format:
// For normal graphs we expect on edge per line. Each edge is expected to be two
// space separated integers.
// For DBLP, each line is expected to be an edge followed by the year.
#include "graph.h"
#include "absl/container/node_hash_map.h"
#include "absl/container/node_hash_set.h"
using std::unordered_set;
using std::vector;
Graph::Graph(const std::string& name) : name_(name) {
// Technical comment: would prefer to make this constructor private,
// but this breaks a crucial line in getGraph.
// Update this part with the file name.
static const unordered_map<std::string, std::string> name_to_filename =
{{"amazon", "../datasets/amazon/graph-relabeled-big-amazon.txt"},
{"enron", "../datasets/enron/Email-Enron.txt"},
{"twitter", "../datasets/twitter/graph-relabel-twitter.txt"},
{"dblp", "../datasets/dblp/dblp-graph.txt"},
{"pokec", "../datasets/pokec/soc-pokec-relationships.txt"},
{"friendster", "../datasets/friendster/friendster.txt"}};
if (!name_to_filename.count(name_)) {
Fail("unknown graph name");
}
const std::string& file_name = name_to_filename.at(name_);
std::cerr << "reading graph from " << file_name << "..." << std::endl;
std::ifstream input(file_name);
if (!input) {
Fail("graph file does not exist");
}
// renumber[x] = new number of x
unordered_map<int64_t, int> renumber;
numVertices_ = 0;
numEdges_ = 0;
const bool is_dblp = (name_ == "dblp");
int64_t first_endpoint, second_endpoint;
absl::node_hash_set<int> leftVertices, rightVertices;
while (input >> first_endpoint >> second_endpoint) {
if (!renumber.count(first_endpoint)) {
renumber[first_endpoint] = numVertices_;
++numVertices_;
neighbors_.push_back({});
}
leftVertices.insert(renumber[first_endpoint]);
if (!renumber.count(second_endpoint)) {
renumber[second_endpoint] = numVertices_;
++numVertices_;
neighbors_.push_back({});
}
rightVertices.insert(renumber[second_endpoint]);
numEdges_++;
neighbors_[renumber[first_endpoint]].push_back(renumber[second_endpoint]);
// Note: our graphs are directed.
// But in some cases you may want to also add the reverse edge.
if (is_dblp) {
int year;
input >> year;
publicationDates_[renumber[first_endpoint]].insert(year);
}
}
leftVertices_.assign(leftVertices.begin(), leftVertices.end());
rightVertices_.assign(rightVertices.begin(), rightVertices.end());
std::cerr << "read graph with " << numVertices_ << " vertices "
<< "and " << numEdges_ << " edges" << std::endl;
}
const vector<int>& Graph::GetCoverableVertices() const {
return rightVertices_;
}
const vector<int>& Graph::GetUniverseVertices() const { return leftVertices_; }
const vector<int>& Graph::GetNeighbors(int vertex_i) const {
return neighbors_[vertex_i];
}
const std::string& Graph::GetName() const { return name_; }
<|endoftext|> |
<commit_before>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/path_service.h"
#include "base/process/launch.h"
#include "base/strings/string_util.h"
#include "testing/gtest/include/gtest/gtest.h"
base::FilePath GinShellPath() {
base::FilePath dir;
PathService::Get(base::DIR_EXE, &dir);
return dir.AppendASCII("gin_shell");
}
base::FilePath HelloWorldPath() {
base::FilePath path;
PathService::Get(base::DIR_SOURCE_ROOT, &path);
return path
.AppendASCII("gin")
.AppendASCII("shell")
.AppendASCII("hello_world.js");
}
TEST(GinShellTest, HelloWorld) {
CommandLine cmd(GinShellPath());
cmd.AppendArgPath(HelloWorldPath());
std::string output;
ASSERT_TRUE(base::GetAppOutput(cmd, &output));
base::TrimWhitespaceASCII(output, base::TRIM_ALL, &output);
ASSERT_EQ("Hello World", output);
}
<commit_msg>Verify that gin_shell and hello_world.js exist.<commit_after>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/process/launch.h"
#include "base/strings/string_util.h"
#include "testing/gtest/include/gtest/gtest.h"
base::FilePath GinShellPath() {
base::FilePath dir;
PathService::Get(base::DIR_EXE, &dir);
return dir.AppendASCII("gin_shell");
}
base::FilePath HelloWorldPath() {
base::FilePath path;
PathService::Get(base::DIR_SOURCE_ROOT, &path);
return path
.AppendASCII("gin")
.AppendASCII("shell")
.AppendASCII("hello_world.js");
}
TEST(GinShellTest, HelloWorld) {
base::FilePath gin_shell_path(GinShellPath());
base::FilePath hello_world_path(HelloWorldPath());
ASSERT_TRUE(base::PathExists(gin_shell_path));
ASSERT_TRUE(base::PathExists(hello_world_path));
CommandLine cmd(gin_shell_path);
cmd.AppendArgPath(hello_world_path);
std::string output;
ASSERT_TRUE(base::GetAppOutput(cmd, &output));
base::TrimWhitespaceASCII(output, base::TRIM_ALL, &output);
ASSERT_EQ("Hello World", output);
}
<|endoftext|> |
<commit_before>/******************************************************************************
*
* Module : HaskinoRuntimeScheduler
* Copyright : (c) University of Kansas
* License : BSD3
* Stability : experimental
*
* Haskino Runtime Scheduler module
*****************************************************************************/
#include <Arduino.h>
#include "HaskinoRuntime.h"
// Scheduling routines
static void reschedule();
static void switchTo(TCB *newTask);
static bool minWait(TCB *task);
static void reschedule();
static TCB *firstTask = NULL;
static TCB *runningTask = NULL;
static int taskCount = 0;
static SEMAPHORE_C semaphores[NUM_SEMAPHORES];
// Temp variables used for C/Assembly transfer
volatile uint32_t taskStack;
volatile uint32_t taskFunction;
// Macros to save and restore context
#define SAVE_TASK_CONTEXT()\
asm volatile (\
"push r0 \n\t"\
"in r0, __SREG__ \n\t"\
"cli \n\t"\
"push r0 \n\t"\
"push r1 \n\t"\
"clr r1 \n\t"\
"push r2 \n\t"\
"push r3 \n\t"\
"push r4 \n\t"\
"push r5 \n\t"\
"push r6 \n\t"\
"push r7 \n\t"\
"push r8 \n\t"\
"push r9 \n\t"\
"push r10 \n\t"\
"push r11 \n\t"\
"push r12 \n\t"\
"push r13 \n\t"\
"push r14 \n\t"\
"push r15 \n\t"\
"push r16 \n\t"\
"push r17 \n\t"\
"push r18 \n\t"\
"push r19 \n\t"\
"push r20 \n\t"\
"push r21 \n\t"\
"push r22 \n\t"\
"push r23 \n\t"\
"push r24 \n\t"\
"push r25 \n\t"\
"push r26 \n\t"\
"push r27 \n\t"\
"push r28 \n\t"\
"push r29 \n\t"\
"push r30 \n\t"\
"push r31 \n\t"\
"in r26, __SP_L__ \n\t"\
"in r27, __SP_H__ \n\t"\
"sts taskStack+1, r27 \n\t"\
"sts taskStack, r26 \n\t"\
"sei \n\t" : :);
#define LOAD_TASK_CONTEXT()\
asm volatile (\
"cli \n\t"\
"out __SP_L__, %A0 \n\t"\
"out __SP_H__, %B0 \n\t"\
"pop r31 \n\t"\
"pop r30 \n\t"\
"pop r29 \n\t"\
"pop r28 \n\t"\
"pop r27 \n\t"\
"pop r26 \n\t"\
"pop r25 \n\t"\
"pop r24 \n\t"\
"pop r23 \n\t"\
"pop r22 \n\t"\
"pop r21 \n\t"\
"pop r20 \n\t"\
"pop r19 \n\t"\
"pop r18 \n\t"\
"pop r17 \n\t"\
"pop r16 \n\t"\
"pop r15 \n\t"\
"pop r14 \n\t"\
"pop r13 \n\t"\
"pop r12 \n\t"\
"pop r11 \n\t"\
"pop r10 \n\t"\
"pop r9 \n\t"\
"pop r8 \n\t"\
"pop r7 \n\t"\
"pop r6 \n\t"\
"pop r5 \n\t"\
"pop r4 \n\t"\
"pop r3 \n\t"\
"pop r2 \n\t"\
"pop r1 \n\t"\
"pop r0 \n\t"\
"sei \n\t"\
"out __SREG__, r0 \n\t"\
"pop r0 \n\t": : "r" (taskStack))
#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
#define INIT_TASK_STACK_FUNC()\
asm volatile(\
"out __SP_L__, %A0 \n\t"\
"out __SP_H__, %B0 \n\t"\
"mov r0, %A1 \n\t"\
"push r0 \n\t"\
"mov r0, %B1 \n\t"\
"push r0 \n\t"\
"mov r0, %C1 \n\t"\
"push r0 \n\t" : : "r" (taskStack), "r" (taskFunction))
#else
#define INIT_TASK_STACK_FUNC()\
asm volatile(\
"out __SP_L__, %A0 \n\t"\
"out __SP_H__, %B0 \n\t"\
"mov r0, %A1 \n\t"\
"push r0 \n\t"\
"mov r0, %B1 \n\t"\
"push r0 \n\t" : : "r" (taskStack), "r" (taskFunction))
#endif
static TCB *findTask(int id)
{
TCB *task = firstTask;
while (task != NULL)
{
if (id == task->id)
return task;
task = task->next;
}
return NULL;
}
void delayMilliseconds(uint32_t ms)
{
#if 1
runningTask->millis = millis() + ms;
reschedule();
#else
delay(ms);
#endif
}
void createTask(uint8_t tid, void *tcb, int stackSize, void (*task)())
{
TCB *newTask = (TCB *) tcb;
if (findTask(tid) == NULL)
{
newTask->next = firstTask;
firstTask = newTask;
newTask->id = tid;
newTask->stackSize = stackSize;
newTask->millis = 0;
newTask->ready = false;
newTask->hasRan = false;
newTask->entry = task;
newTask->stackPointer =
(uint16_t) &newTask->stack[stackSize-sizeof(unsigned long)];
taskCount++;
}
}
void deleteTask(uint8_t tid)
{
TCB *task;
if ((task = findTask(tid)) != NULL)
{
task->ready = false;
if (task == runningTask)
reschedule();
}
}
void scheduleTask(uint8_t tid, uint32_t tt)
{
TCB *task;
if ((task = findTask(tid)) != NULL)
{
task->millis = millis() + tt;
task->ready = true;
}
}
void scheduleReset()
{
TCB *task = firstTask;
// Set all tasks except for running one to false
while (task != NULL)
{
if (task != runningTask)
task->ready = false;
task = task->next;
}
}
void taskComplete()
{
runningTask->ready = false;
reschedule();
}
static void switchTo(TCB *newTask)
{
SAVE_TASK_CONTEXT();
runningTask->stackPointer = taskStack;
runningTask = newTask;
if(!runningTask->hasRan)
{
runningTask->hasRan = true;
taskStack = (uint32_t) runningTask->stackPointer;
taskFunction = (uint32_t) runningTask->entry;
INIT_TASK_STACK_FUNC();
}
else
{
taskStack = (uint32_t) runningTask->stackPointer;
LOAD_TASK_CONTEXT();
}
asm("ret");
}
void startScheduler()
{
TCB *task;
task = findTask(255);
runningTask = task;
switchTo(task);
}
static bool minWait(TCB *task)
{
uint32_t now = millis();
uint32_t minTime = 0x80000000UL;
TCB *currTask = task;
TCB *minTask = NULL;
// Find the task that is ready to run and has the shortest delay
do {
if (currTask->ready)
{
uint32_t timeDiff = currTask->millis - now;
if (timeDiff >= 0x80000000UL)
timeDiff = 0;
if (timeDiff < minTime)
{
minTime = timeDiff;
minTask = currTask;
}
}
if (currTask->next == NULL)
currTask = firstTask;
else
currTask = currTask->next;
} while (currTask != task);
// If one was found, then delay until its delay would time out
// and switch to that task.
if (minTask)
{
delay(minTime);
if (minTask != runningTask)
switchTo(minTask);
return false;
}
else
{
return true;
}
}
static void reschedule()
{
TCB *next = runningTask->next;
if (next == NULL)
next = firstTask;
// Loop while no tasks are ready.
// Start the search with the task after the current one, so that
// if all tasks used delayMillis(0), they would proceed in a
// round robin fashion.
while (minWait(next))
{
delay(1);
}
}
// Semphore routines
void giveSem(uint8_t id)
{
if (id < NUM_SEMAPHORES)
{
// Semaphore is already full, do nothing
if (semaphores[id].full)
{
}
// Semaphore has a task waiting, ready it to run
else if (semaphores[id].waiting)
{
TCB *task = semaphores[id].waiting;
task->ready = true;
task->millis = millis();
semaphores[id].waiting = NULL;
}
// Otherwise mark the semphore as full
else
{
semaphores[id].full = true;
}
}
}
void takeSem(uint8_t id)
{
if (id < NUM_SEMAPHORES)
{
// Semaphore is already full, take it and do not reschedule
if (semaphores[id].full)
{
semaphores[id].full = false;
}
else
// Semaphore is not full, we need to add ourselves to waiting
// and reschedule
{
semaphores[id].waiting = runningTask;
runningTask->ready = false;
reschedule();
}
}
}
<commit_msg>Added critical section global lock for use in semaphore routines<commit_after>/******************************************************************************
*
* Module : HaskinoRuntimeScheduler
* Copyright : (c) University of Kansas
* License : BSD3
* Stability : experimental
*
* Haskino Runtime Scheduler module
*****************************************************************************/
#include <Arduino.h>
#include "HaskinoRuntime.h"
// Scheduling routines
static void reschedule();
static void switchTo(TCB *newTask);
static bool minWait(TCB *task);
static void reschedule();
static TCB *firstTask = NULL;
static TCB *runningTask = NULL;
static int taskCount = 0;
static SEMAPHORE_C semaphores[NUM_SEMAPHORES];
// Temp variables used for C/Assembly transfer
volatile uint32_t taskStack;
volatile uint32_t taskFunction;
// Macros to save and restore context
#define SAVE_TASK_CONTEXT()\
asm volatile (\
"push r0 \n\t"\
"in r0, __SREG__ \n\t"\
"cli \n\t"\
"push r0 \n\t"\
"push r1 \n\t"\
"clr r1 \n\t"\
"push r2 \n\t"\
"push r3 \n\t"\
"push r4 \n\t"\
"push r5 \n\t"\
"push r6 \n\t"\
"push r7 \n\t"\
"push r8 \n\t"\
"push r9 \n\t"\
"push r10 \n\t"\
"push r11 \n\t"\
"push r12 \n\t"\
"push r13 \n\t"\
"push r14 \n\t"\
"push r15 \n\t"\
"push r16 \n\t"\
"push r17 \n\t"\
"push r18 \n\t"\
"push r19 \n\t"\
"push r20 \n\t"\
"push r21 \n\t"\
"push r22 \n\t"\
"push r23 \n\t"\
"push r24 \n\t"\
"push r25 \n\t"\
"push r26 \n\t"\
"push r27 \n\t"\
"push r28 \n\t"\
"push r29 \n\t"\
"push r30 \n\t"\
"push r31 \n\t"\
"in r26, __SP_L__ \n\t"\
"in r27, __SP_H__ \n\t"\
"sts taskStack+1, r27 \n\t"\
"sts taskStack, r26 \n\t"\
"sei \n\t" : :);
#define LOAD_TASK_CONTEXT()\
asm volatile (\
"cli \n\t"\
"out __SP_L__, %A0 \n\t"\
"out __SP_H__, %B0 \n\t"\
"pop r31 \n\t"\
"pop r30 \n\t"\
"pop r29 \n\t"\
"pop r28 \n\t"\
"pop r27 \n\t"\
"pop r26 \n\t"\
"pop r25 \n\t"\
"pop r24 \n\t"\
"pop r23 \n\t"\
"pop r22 \n\t"\
"pop r21 \n\t"\
"pop r20 \n\t"\
"pop r19 \n\t"\
"pop r18 \n\t"\
"pop r17 \n\t"\
"pop r16 \n\t"\
"pop r15 \n\t"\
"pop r14 \n\t"\
"pop r13 \n\t"\
"pop r12 \n\t"\
"pop r11 \n\t"\
"pop r10 \n\t"\
"pop r9 \n\t"\
"pop r8 \n\t"\
"pop r7 \n\t"\
"pop r6 \n\t"\
"pop r5 \n\t"\
"pop r4 \n\t"\
"pop r3 \n\t"\
"pop r2 \n\t"\
"pop r1 \n\t"\
"pop r0 \n\t"\
"sei \n\t"\
"out __SREG__, r0 \n\t"\
"pop r0 \n\t": : "r" (taskStack))
#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
#define INIT_TASK_STACK_FUNC()\
asm volatile(\
"out __SP_L__, %A0 \n\t"\
"out __SP_H__, %B0 \n\t"\
"mov r0, %A1 \n\t"\
"push r0 \n\t"\
"mov r0, %B1 \n\t"\
"push r0 \n\t"\
"mov r0, %C1 \n\t"\
"push r0 \n\t" : : "r" (taskStack), "r" (taskFunction))
#else
#define INIT_TASK_STACK_FUNC()\
asm volatile(\
"out __SP_L__, %A0 \n\t"\
"out __SP_H__, %B0 \n\t"\
"mov r0, %A1 \n\t"\
"push r0 \n\t"\
"mov r0, %B1 \n\t"\
"push r0 \n\t" : : "r" (taskStack), "r" (taskFunction))
#endif
static TCB *findTask(int id)
{
TCB *task = firstTask;
while (task != NULL)
{
if (id == task->id)
return task;
task = task->next;
}
return NULL;
}
void delayMilliseconds(uint32_t ms)
{
#if 1
runningTask->millis = millis() + ms;
reschedule();
#else
delay(ms);
#endif
}
void createTask(uint8_t tid, void *tcb, int stackSize, void (*task)())
{
TCB *newTask = (TCB *) tcb;
if (findTask(tid) == NULL)
{
newTask->next = firstTask;
firstTask = newTask;
newTask->id = tid;
newTask->stackSize = stackSize;
newTask->millis = 0;
newTask->ready = false;
newTask->hasRan = false;
newTask->entry = task;
newTask->stackPointer =
(uint16_t) &newTask->stack[stackSize-sizeof(unsigned long)];
taskCount++;
}
}
void deleteTask(uint8_t tid)
{
TCB *task;
if ((task = findTask(tid)) != NULL)
{
task->ready = false;
if (task == runningTask)
reschedule();
}
}
void scheduleTask(uint8_t tid, uint32_t tt)
{
TCB *task;
if ((task = findTask(tid)) != NULL)
{
task->millis = millis() + tt;
task->ready = true;
}
}
void scheduleReset()
{
TCB *task = firstTask;
// Set all tasks except for running one to false
while (task != NULL)
{
if (task != runningTask)
task->ready = false;
task = task->next;
}
}
void taskComplete()
{
runningTask->ready = false;
reschedule();
}
static void switchTo(TCB *newTask)
{
SAVE_TASK_CONTEXT();
runningTask->stackPointer = taskStack;
runningTask = newTask;
if(!runningTask->hasRan)
{
runningTask->hasRan = true;
taskStack = (uint32_t) runningTask->stackPointer;
taskFunction = (uint32_t) runningTask->entry;
INIT_TASK_STACK_FUNC();
}
else
{
taskStack = (uint32_t) runningTask->stackPointer;
LOAD_TASK_CONTEXT();
}
asm("ret");
}
void startScheduler()
{
TCB *task;
task = findTask(255);
runningTask = task;
switchTo(task);
}
static bool minWait(TCB *task)
{
uint32_t now = millis();
uint32_t minTime = 0x80000000UL;
TCB *currTask = task;
TCB *minTask = NULL;
// Find the task that is ready to run and has the shortest delay
do {
if (currTask->ready)
{
uint32_t timeDiff = currTask->millis - now;
if (timeDiff >= 0x80000000UL)
timeDiff = 0;
if (timeDiff < minTime)
{
minTime = timeDiff;
minTask = currTask;
}
}
if (currTask->next == NULL)
currTask = firstTask;
else
currTask = currTask->next;
} while (currTask != task);
// If one was found, then delay until its delay would time out
// and switch to that task.
if (minTask)
{
delay(minTime);
if (minTask != runningTask)
switchTo(minTask);
return false;
}
else
{
return true;
}
}
static void reschedule()
{
TCB *next = runningTask->next;
if (next == NULL)
next = firstTask;
// Loop while no tasks are ready.
// Start the search with the task after the current one, so that
// if all tasks used delayMillis(0), they would proceed in a
// round robin fashion.
while (minWait(next))
{
delay(1);
}
}
// Critical Region global lock routines
static inline uint8_t lock()
{
uint8_t statReg = SREG;
cli();
return statReg;
}
static inline void unlock(uint8_t statReg)
{
SREG = statReg;
}
// Semphore routines
void giveSem(uint8_t id)
{
if (id < NUM_SEMAPHORES)
{
uint8_t reg;
reg = lock();
// Semaphore is already full, do nothing
if (semaphores[id].full)
{
}
// Semaphore has a task waiting, ready it to run
else if (semaphores[id].waiting)
{
TCB *task = semaphores[id].waiting;
task->ready = true;
task->millis = millis();
semaphores[id].waiting = NULL;
}
// Otherwise mark the semphore as full
else
{
semaphores[id].full = true;
}
unlock(reg);
}
}
void takeSem(uint8_t id)
{
if (id < NUM_SEMAPHORES)
{
uint8_t reg;
reg = lock();
// Semaphore is already full, take it and do not reschedule
if (semaphores[id].full)
{
semaphores[id].full = false;
unlock(reg);
}
else
// Semaphore is not full, we need to add ourselves to waiting
// and reschedule
{
semaphores[id].waiting = runningTask;
runningTask->ready = false;
unlock(reg);
reschedule();
}
}
}
<|endoftext|> |
<commit_before>/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */
// vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4:
#ident "$Id$"
/*======
This file is part of PerconaFT.
Copyright (c) 2006, 2015, Percona and/or its affiliates. All rights reserved.
PerconaFT is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2,
as published by the Free Software Foundation.
PerconaFT 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 PerconaFT. If not, see <http://www.gnu.org/licenses/>.
----------------------------------------
PerconaFT is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License, version 3,
as published by the Free Software Foundation.
PerconaFT 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with PerconaFT. If not, see <http://www.gnu.org/licenses/>.
======= */
#ident "Copyright (c) 2006, 2015, Percona and/or its affiliates. All rights reserved."
#include "test.h"
static void
flush (CACHEFILE f __attribute__((__unused__)),
int UU(fd),
CACHEKEY k __attribute__((__unused__)),
void *v __attribute__((__unused__)),
void** UU(dd),
void *e __attribute__((__unused__)),
PAIR_ATTR s __attribute__((__unused__)),
PAIR_ATTR* new_size __attribute__((__unused__)),
bool w __attribute__((__unused__)),
bool keep __attribute__((__unused__)),
bool c __attribute__((__unused__)),
bool UU(is_clone)
) {
if (w) {
assert(c);
assert(keep);
}
}
static void kibbutz_work(void *fe_v)
{
CACHEFILE CAST_FROM_VOIDP(f1, fe_v);
sleep(2);
int r = toku_test_cachetable_unpin(f1, make_blocknum(1), 1, CACHETABLE_CLEAN, make_pair_attr(8));
assert(r==0);
remove_background_job_from_cf(f1);
}
static void
unlock_dummy (void* UU(v)) {
}
static void reset_unlockers(UNLOCKERS unlockers) {
unlockers->locked = true;
}
static void
run_case_that_should_succeed(CACHEFILE f1, pair_lock_type first_lock, pair_lock_type second_lock) {
void* v1;
CACHETABLE_WRITE_CALLBACK wc = def_write_callback(NULL);
wc.flush_callback = flush;
struct unlockers unlockers = {true, unlock_dummy, NULL, NULL};
int r = toku_cachetable_get_and_pin_nonblocking(f1, make_blocknum(1), 1, &v1, wc, def_fetch, def_pf_req_callback, def_pf_callback, first_lock, NULL, NULL);
assert(r==0);
cachefile_kibbutz_enq(f1, kibbutz_work, f1);
reset_unlockers(&unlockers);
r = toku_cachetable_get_and_pin_nonblocking(f1, make_blocknum(1), 1, &v1, wc, def_fetch, def_pf_req_callback, def_pf_callback, second_lock, NULL, &unlockers);
assert(r==0); assert(unlockers.locked);
r = toku_test_cachetable_unpin(f1, make_blocknum(1), 1, CACHETABLE_CLEAN, make_pair_attr(8)); assert(r==0);
}
static void
run_case_that_should_fail(CACHEFILE f1, pair_lock_type first_lock, pair_lock_type second_lock) {
void* v1;
CACHETABLE_WRITE_CALLBACK wc = def_write_callback(NULL);
wc.flush_callback = flush;
struct unlockers unlockers = {true, unlock_dummy, NULL, NULL};
int r = toku_cachetable_get_and_pin_nonblocking(f1, make_blocknum(1), 1, &v1, wc, def_fetch, def_pf_req_callback, def_pf_callback, first_lock, NULL, NULL);
assert(r==0);
cachefile_kibbutz_enq(f1, kibbutz_work, f1);
reset_unlockers(&unlockers);
r = toku_cachetable_get_and_pin_nonblocking(f1, make_blocknum(1), 1, &v1, wc, def_fetch, def_pf_req_callback, def_pf_callback, second_lock, NULL, &unlockers);
assert(r == TOKUDB_TRY_AGAIN); assert(!unlockers.locked);
}
static void
run_test (void) {
const int test_limit = 12;
int r;
CACHETABLE ct;
toku_cachetable_create(&ct, test_limit, ZERO_LSN, nullptr);
const char *fname1 = TOKU_TEST_FILENAME;
unlink(fname1);
CACHEFILE f1;
r = toku_cachetable_openf(&f1, ct, fname1, O_RDWR|O_CREAT, S_IRWXU|S_IRWXG|S_IRWXO); assert(r == 0);
void* v1;
CACHETABLE_WRITE_CALLBACK wc = def_write_callback(NULL);
wc.flush_callback = flush;
//
// test that if we are getting a PAIR for the first time that TOKUDB_TRY_AGAIN is returned
// because the PAIR was not in the cachetable.
//
r = toku_cachetable_get_and_pin_nonblocking(f1, make_blocknum(1), 1, &v1, wc, def_fetch, def_pf_req_callback, def_pf_callback, PL_WRITE_EXPENSIVE, NULL, NULL);
assert(r==TOKUDB_TRY_AGAIN);
run_case_that_should_succeed(f1, PL_READ, PL_WRITE_CHEAP);
run_case_that_should_succeed(f1, PL_READ, PL_WRITE_EXPENSIVE);
run_case_that_should_succeed(f1, PL_WRITE_CHEAP, PL_READ);
run_case_that_should_succeed(f1, PL_WRITE_CHEAP, PL_WRITE_CHEAP);
run_case_that_should_succeed(f1, PL_WRITE_CHEAP, PL_WRITE_EXPENSIVE);
run_case_that_should_fail(f1, PL_WRITE_EXPENSIVE, PL_READ);
run_case_that_should_fail(f1, PL_WRITE_EXPENSIVE, PL_WRITE_CHEAP);
run_case_that_should_fail(f1, PL_WRITE_EXPENSIVE, PL_WRITE_EXPENSIVE);
toku_cachetable_verify(ct);
toku_cachefile_close(&f1, false, ZERO_LSN);
toku_cachetable_close(&ct);
}
int
test_main(int argc, const char *argv[]) {
default_parse_args(argc, argv);
run_test();
return 0;
}
<commit_msg>The cachetable-simple-pin-noblocking-cheap test occasionally fails due to a TOKUDB_TRY_AGAIN error being kicked out of the cachetable to the test. The test does not expect this error so it crashes. The TOKUDB_TRY_AGAIN error was caused by a locking conflict between the test and the cachetable evictor which periodically runs on a background thread. Since the evictor is not an important part of this test, its execution was removed by setting the cachetable size larger than the test's cachetable footprint.<commit_after>/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */
// vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4:
#ident "$Id$"
/*======
This file is part of PerconaFT.
Copyright (c) 2006, 2015, Percona and/or its affiliates. All rights reserved.
PerconaFT is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2,
as published by the Free Software Foundation.
PerconaFT 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 PerconaFT. If not, see <http://www.gnu.org/licenses/>.
----------------------------------------
PerconaFT is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License, version 3,
as published by the Free Software Foundation.
PerconaFT 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with PerconaFT. If not, see <http://www.gnu.org/licenses/>.
======= */
#ident "Copyright (c) 2006, 2015, Percona and/or its affiliates. All rights reserved."
#include "test.h"
static void
flush (CACHEFILE f __attribute__((__unused__)),
int UU(fd),
CACHEKEY k __attribute__((__unused__)),
void *v __attribute__((__unused__)),
void** UU(dd),
void *e __attribute__((__unused__)),
PAIR_ATTR s __attribute__((__unused__)),
PAIR_ATTR* new_size __attribute__((__unused__)),
bool w __attribute__((__unused__)),
bool keep __attribute__((__unused__)),
bool c __attribute__((__unused__)),
bool UU(is_clone)
) {
if (w) {
assert(c);
assert(keep);
}
}
static void kibbutz_work(void *fe_v)
{
CACHEFILE CAST_FROM_VOIDP(f1, fe_v);
sleep(2);
int r = toku_test_cachetable_unpin(f1, make_blocknum(1), 1, CACHETABLE_CLEAN, make_pair_attr(8));
assert(r==0);
remove_background_job_from_cf(f1);
}
static void
unlock_dummy (void* UU(v)) {
}
static void reset_unlockers(UNLOCKERS unlockers) {
unlockers->locked = true;
}
static void
run_case_that_should_succeed(CACHEFILE f1, pair_lock_type first_lock, pair_lock_type second_lock) {
void* v1;
CACHETABLE_WRITE_CALLBACK wc = def_write_callback(NULL);
wc.flush_callback = flush;
struct unlockers unlockers = {true, unlock_dummy, NULL, NULL};
int r = toku_cachetable_get_and_pin_nonblocking(f1, make_blocknum(1), 1, &v1, wc, def_fetch, def_pf_req_callback, def_pf_callback, first_lock, NULL, NULL);
assert(r==0);
cachefile_kibbutz_enq(f1, kibbutz_work, f1);
reset_unlockers(&unlockers);
r = toku_cachetable_get_and_pin_nonblocking(f1, make_blocknum(1), 1, &v1, wc, def_fetch, def_pf_req_callback, def_pf_callback, second_lock, NULL, &unlockers);
assert(r==0); assert(unlockers.locked);
r = toku_test_cachetable_unpin(f1, make_blocknum(1), 1, CACHETABLE_CLEAN, make_pair_attr(8)); assert(r==0);
}
static void
run_case_that_should_fail(CACHEFILE f1, pair_lock_type first_lock, pair_lock_type second_lock) {
void* v1;
CACHETABLE_WRITE_CALLBACK wc = def_write_callback(NULL);
wc.flush_callback = flush;
struct unlockers unlockers = {true, unlock_dummy, NULL, NULL};
int r = toku_cachetable_get_and_pin_nonblocking(f1, make_blocknum(1), 1, &v1, wc, def_fetch, def_pf_req_callback, def_pf_callback, first_lock, NULL, NULL);
assert(r==0);
cachefile_kibbutz_enq(f1, kibbutz_work, f1);
reset_unlockers(&unlockers);
r = toku_cachetable_get_and_pin_nonblocking(f1, make_blocknum(1), 1, &v1, wc, def_fetch, def_pf_req_callback, def_pf_callback, second_lock, NULL, &unlockers);
assert(r == TOKUDB_TRY_AGAIN); assert(!unlockers.locked);
}
static void
run_test (void) {
// sometimes the cachetable evictor runs during the test. this sometimes causes cachetable pair locking contention,
// which results with a TOKUDB_TRY_AGAIN error occurring. unfortunately, the test does not expect this and fails.
// set cachetable size limit to a value big enough so that the cachetable evictor is not triggered during the test.
const int test_limit = 100;
int r;
CACHETABLE ct;
toku_cachetable_create(&ct, test_limit, ZERO_LSN, nullptr);
const char *fname1 = TOKU_TEST_FILENAME;
unlink(fname1);
CACHEFILE f1;
r = toku_cachetable_openf(&f1, ct, fname1, O_RDWR|O_CREAT, S_IRWXU|S_IRWXG|S_IRWXO); assert(r == 0);
void* v1;
CACHETABLE_WRITE_CALLBACK wc = def_write_callback(NULL);
wc.flush_callback = flush;
//
// test that if we are getting a PAIR for the first time that TOKUDB_TRY_AGAIN is returned
// because the PAIR was not in the cachetable.
//
r = toku_cachetable_get_and_pin_nonblocking(f1, make_blocknum(1), 1, &v1, wc, def_fetch, def_pf_req_callback, def_pf_callback, PL_WRITE_EXPENSIVE, NULL, NULL);
assert(r==TOKUDB_TRY_AGAIN);
run_case_that_should_succeed(f1, PL_READ, PL_WRITE_CHEAP);
run_case_that_should_succeed(f1, PL_READ, PL_WRITE_EXPENSIVE);
run_case_that_should_succeed(f1, PL_WRITE_CHEAP, PL_READ);
run_case_that_should_succeed(f1, PL_WRITE_CHEAP, PL_WRITE_CHEAP);
run_case_that_should_succeed(f1, PL_WRITE_CHEAP, PL_WRITE_EXPENSIVE);
run_case_that_should_fail(f1, PL_WRITE_EXPENSIVE, PL_READ);
run_case_that_should_fail(f1, PL_WRITE_EXPENSIVE, PL_WRITE_CHEAP);
run_case_that_should_fail(f1, PL_WRITE_EXPENSIVE, PL_WRITE_EXPENSIVE);
toku_cachetable_verify(ct);
toku_cachefile_close(&f1, false, ZERO_LSN);
toku_cachetable_close(&ct);
}
int
test_main(int argc, const char *argv[]) {
default_parse_args(argc, argv);
run_test();
return 0;
}
<|endoftext|> |
<commit_before>
#pragma once
#include <gloperate/base/make_unique.hpp>
#include <gloperate/pipeline/AbstractPipeline.h>
#include "DummyStage.hpp"
using namespace gloperate;
class TestPipeline : public AbstractPipeline
{
public:
TestPipeline()
{
auto stage0 = make_unique<DummyStage>("", std::vector<std::string>{}, std::vector<std::string>{"output0", "output1"});
auto stage1 = make_unique<DummyStage>("", std::vector<std::string>{"input0"}, std::vector<std::string>{"output0"});
auto stage2 = make_unique<DummyStage>("", std::vector<std::string>{"input0"}, std::vector<std::string>{"output0"});
auto stage3 = make_unique<DummyStage>("", std::vector<std::string>{"input0", "input1"}, std::vector<std::string>{"output0"});
auto stage4 = make_unique<DummyStage>("", std::vector<std::string>{"input0"}, std::vector<std::string>{"output0"});
auto stage5 = make_unique<DummyStage>("", std::vector<std::string>{"input0", "input1"}, std::vector<std::string>{"output0"});
auto stage6 = make_unique<DummyStage>("", std::vector<std::string>{"input0", "input1"}, std::vector<std::string>{"output0"});
auto stage7 = make_unique<DummyStage>("", std::vector<std::string>{"input0", "input1"}, std::vector<std::string>{"output0"});
auto stage8 = make_unique<DummyStage>("", std::vector<std::string>{"input0", "input1", "input2"}, std::vector<std::string>{"output0"});
auto stage9 = make_unique<DummyStage>("", std::vector<std::string>{"input0", "input1", "input2"}, std::vector<std::string>{"output0"});
auto stage10 = make_unique<DummyStage>("", std::vector<std::string>{"input0", "input1", "input2"}, std::vector<std::string>{"output0"});
auto stage11 = make_unique<DummyStage>("", std::vector<std::string>{"input0"}, std::vector<std::string>{"output0"});
auto stage12 = make_unique<DummyStage>("", std::vector<std::string>{"input0", "input1", "input2"}, std::vector<std::string>{"output0"});
auto stage13 = make_unique<DummyStage>("", std::vector<std::string>{"input0", "input1", "input2", "input3", "input4"}, std::vector<std::string>{"output0"});
auto stage14 = make_unique<DummyStage>("", std::vector<std::string>{"input0"}, std::vector<std::string>{"output0", "output1", "output2", "output3", "output4"});
auto stage15 = make_unique<DummyStage>("", std::vector<std::string>{"input0", "input1", "input2", "input3", "input4", "input5"}, std::vector<std::string>{"output0"});
auto stage16 = make_unique<DummyStage>("", std::vector<std::string>{"input0"}, std::vector<std::string>{});
stage1->inputs.at("input0") = stage0->outputs.at("output0");
stage2->inputs.at("input0") = stage1->outputs.at("output0");
stage3->inputs.at("input0") = stage0->outputs.at("output0");
stage3->inputs.at("input1") = stage2->outputs.at("output0");
stage4->inputs.at("input0") = stage3->outputs.at("output0");
stage5->inputs.at("input0") = stage3->outputs.at("output0");
stage5->inputs.at("input1") = stage4->outputs.at("output0");
stage6->inputs.at("input0") = stage3->outputs.at("output0");
stage6->inputs.at("input1") = stage4->outputs.at("output0");
stage7->inputs.at("input0") = stage3->outputs.at("output0");
stage7->inputs.at("input0") = stage4->outputs.at("output0");
stage8->inputs.at("input0") = stage3->outputs.at("output0");
stage8->inputs.at("input1") = stage4->outputs.at("output0");
stage8->inputs.at("input2") = stage5->outputs.at("output0");
stage9->inputs.at("input0") = stage3->outputs.at("output0");
stage9->inputs.at("input1") = stage4->outputs.at("output0");
stage9->inputs.at("input2") = stage6->outputs.at("output0");
stage10->inputs.at("input0") = stage3->outputs.at("output0");
stage10->inputs.at("input1") = stage4->outputs.at("output0");
stage10->inputs.at("input2") = stage7->outputs.at("output0");
stage11->inputs.at("input0") = stage10->outputs.at("output0");
stage12->inputs.at("input0") = stage3->outputs.at("output0");
stage12->inputs.at("input1") = stage4->outputs.at("output0");
stage12->inputs.at("input2") = stage8->outputs.at("output0");
stage13->inputs.at("input0") = stage3->outputs.at("output0");
stage13->inputs.at("input1") = stage4->outputs.at("output0");
stage13->inputs.at("input2") = stage12->outputs.at("output0");
stage13->inputs.at("input3") = stage9->outputs.at("output0");
stage13->inputs.at("input4") = stage11->outputs.at("output0");
stage14->inputs.at("input0") = stage13->outputs.at("output0");
stage15->inputs.at("input0") = stage14->outputs.at("output0");
stage15->inputs.at("input1") = stage14->outputs.at("output1");
stage15->inputs.at("input2") = stage14->outputs.at("output2");
stage15->inputs.at("input3") = stage14->outputs.at("output3");
stage15->inputs.at("input4") = stage14->outputs.at("output4");
stage15->inputs.at("input5") = stage0->outputs.at("output1");
stage16->inputs.at("input0") = stage15->outputs.at("output0");
addStages(
std::move(stage0),
std::move(stage1),
std::move(stage2),
std::move(stage3),
std::move(stage4),
std::move(stage5),
std::move(stage6),
std::move(stage7),
std::move(stage8),
std::move(stage9),
std::move(stage10),
std::move(stage11),
std::move(stage12),
std::move(stage13),
std::move(stage14),
std::move(stage15),
std::move(stage16));
}
};
<commit_msg>fix ambiguous make_unique call<commit_after>
#pragma once
#include <gloperate/base/make_unique.hpp>
#include <gloperate/pipeline/AbstractPipeline.h>
#include "DummyStage.hpp"
using namespace gloperate;
using gloperate::make_unique;
class TestPipeline : public AbstractPipeline
{
public:
TestPipeline()
{
auto stage0 = make_unique<DummyStage>("", std::vector<std::string>{}, std::vector<std::string>{"output0", "output1"});
auto stage1 = make_unique<DummyStage>("", std::vector<std::string>{"input0"}, std::vector<std::string>{"output0"});
auto stage2 = make_unique<DummyStage>("", std::vector<std::string>{"input0"}, std::vector<std::string>{"output0"});
auto stage3 = make_unique<DummyStage>("", std::vector<std::string>{"input0", "input1"}, std::vector<std::string>{"output0"});
auto stage4 = make_unique<DummyStage>("", std::vector<std::string>{"input0"}, std::vector<std::string>{"output0"});
auto stage5 = make_unique<DummyStage>("", std::vector<std::string>{"input0", "input1"}, std::vector<std::string>{"output0"});
auto stage6 = make_unique<DummyStage>("", std::vector<std::string>{"input0", "input1"}, std::vector<std::string>{"output0"});
auto stage7 = make_unique<DummyStage>("", std::vector<std::string>{"input0", "input1"}, std::vector<std::string>{"output0"});
auto stage8 = make_unique<DummyStage>("", std::vector<std::string>{"input0", "input1", "input2"}, std::vector<std::string>{"output0"});
auto stage9 = make_unique<DummyStage>("", std::vector<std::string>{"input0", "input1", "input2"}, std::vector<std::string>{"output0"});
auto stage10 = make_unique<DummyStage>("", std::vector<std::string>{"input0", "input1", "input2"}, std::vector<std::string>{"output0"});
auto stage11 = make_unique<DummyStage>("", std::vector<std::string>{"input0"}, std::vector<std::string>{"output0"});
auto stage12 = make_unique<DummyStage>("", std::vector<std::string>{"input0", "input1", "input2"}, std::vector<std::string>{"output0"});
auto stage13 = make_unique<DummyStage>("", std::vector<std::string>{"input0", "input1", "input2", "input3", "input4"}, std::vector<std::string>{"output0"});
auto stage14 = make_unique<DummyStage>("", std::vector<std::string>{"input0"}, std::vector<std::string>{"output0", "output1", "output2", "output3", "output4"});
auto stage15 = make_unique<DummyStage>("", std::vector<std::string>{"input0", "input1", "input2", "input3", "input4", "input5"}, std::vector<std::string>{"output0"});
auto stage16 = make_unique<DummyStage>("", std::vector<std::string>{"input0"}, std::vector<std::string>{});
stage1->inputs.at("input0") = stage0->outputs.at("output0");
stage2->inputs.at("input0") = stage1->outputs.at("output0");
stage3->inputs.at("input0") = stage0->outputs.at("output0");
stage3->inputs.at("input1") = stage2->outputs.at("output0");
stage4->inputs.at("input0") = stage3->outputs.at("output0");
stage5->inputs.at("input0") = stage3->outputs.at("output0");
stage5->inputs.at("input1") = stage4->outputs.at("output0");
stage6->inputs.at("input0") = stage3->outputs.at("output0");
stage6->inputs.at("input1") = stage4->outputs.at("output0");
stage7->inputs.at("input0") = stage3->outputs.at("output0");
stage7->inputs.at("input0") = stage4->outputs.at("output0");
stage8->inputs.at("input0") = stage3->outputs.at("output0");
stage8->inputs.at("input1") = stage4->outputs.at("output0");
stage8->inputs.at("input2") = stage5->outputs.at("output0");
stage9->inputs.at("input0") = stage3->outputs.at("output0");
stage9->inputs.at("input1") = stage4->outputs.at("output0");
stage9->inputs.at("input2") = stage6->outputs.at("output0");
stage10->inputs.at("input0") = stage3->outputs.at("output0");
stage10->inputs.at("input1") = stage4->outputs.at("output0");
stage10->inputs.at("input2") = stage7->outputs.at("output0");
stage11->inputs.at("input0") = stage10->outputs.at("output0");
stage12->inputs.at("input0") = stage3->outputs.at("output0");
stage12->inputs.at("input1") = stage4->outputs.at("output0");
stage12->inputs.at("input2") = stage8->outputs.at("output0");
stage13->inputs.at("input0") = stage3->outputs.at("output0");
stage13->inputs.at("input1") = stage4->outputs.at("output0");
stage13->inputs.at("input2") = stage12->outputs.at("output0");
stage13->inputs.at("input3") = stage9->outputs.at("output0");
stage13->inputs.at("input4") = stage11->outputs.at("output0");
stage14->inputs.at("input0") = stage13->outputs.at("output0");
stage15->inputs.at("input0") = stage14->outputs.at("output0");
stage15->inputs.at("input1") = stage14->outputs.at("output1");
stage15->inputs.at("input2") = stage14->outputs.at("output2");
stage15->inputs.at("input3") = stage14->outputs.at("output3");
stage15->inputs.at("input4") = stage14->outputs.at("output4");
stage15->inputs.at("input5") = stage0->outputs.at("output1");
stage16->inputs.at("input0") = stage15->outputs.at("output0");
addStages(
std::move(stage0),
std::move(stage1),
std::move(stage2),
std::move(stage3),
std::move(stage4),
std::move(stage5),
std::move(stage6),
std::move(stage7),
std::move(stage8),
std::move(stage9),
std::move(stage10),
std::move(stage11),
std::move(stage12),
std::move(stage13),
std::move(stage14),
std::move(stage15),
std::move(stage16));
}
};
<|endoftext|> |
<commit_before>//============================================================================
// Name : CubemapRenderer.h
// Author : Duarte Peixinho
// Version :
// Copyright : ;)
// Description : Dynamic Cube Map aka Environment Map
//============================================================================
#include "CubemapRenderer.h"
#include <GL/glew.h>
namespace p3d {
CubemapRenderer::CubemapRenderer(const uint32& Width, const uint32& Height) : IRenderer(Width,Height)
{
echo("SUCCESS: Forward Renderer Created");
ActivateCulling(CullingMode::FrustumCulling);
// Create Texture (CubeMap), Frame Buffer and Set the Texture as Attachment
environmentMap=AssetManager::CreateTexture(TextureType::CubemapNegative_X,TextureDataType::RGB,Width,Height,false);
environmentMap->CreateTexture(TextureType::CubemapNegative_Y,TextureDataType::RGB,Width,Height,false);
environmentMap->CreateTexture(TextureType::CubemapNegative_Z,TextureDataType::RGB,Width,Height,false);
environmentMap->CreateTexture(TextureType::CubemapPositive_X,TextureDataType::RGB,Width,Height,false);
environmentMap->CreateTexture(TextureType::CubemapPositive_Y,TextureDataType::RGB,Width,Height,false);
environmentMap->CreateTexture(TextureType::CubemapPositive_Z,TextureDataType::RGB,Width,Height,false);
environmentMap->SetRepeat(TextureRepeat::ClampToEdge,TextureRepeat::ClampToEdge,TextureRepeat::ClampToEdge);
// Initialize Frame Buffer
fbo = new FrameBuffer();
fbo->Init(FrameBufferAttachmentFormat::Color_Attachment0,TextureType::CubemapPositive_X,environmentMap,true);
}
CubemapRenderer::~CubemapRenderer()
{
if (IsCulling)
{
delete culling;
}
AssetManager::DeleteTexture(environmentMap);
delete fbo;
}
std::vector<RenderingMesh*> CubemapRenderer::GroupAndSortAssets(SceneGraph* Scene, GameObject* Camera)
{
// Sort and Group Objects From Scene
std::vector<RenderingMesh*> _OpaqueMeshes;
std::map<f32,RenderingMesh*> _TranslucidMeshes;
std::vector<RenderingMesh*> rmeshes = RenderingComponent::GetRenderingMeshes(Scene);
for (std::vector<RenderingMesh*>::iterator k=rmeshes.begin();k!=rmeshes.end();k++)
{
if ((*k)->Material->IsTransparent())
{
f32 index = Camera->GetWorldPosition().distanceSQR((*k)->renderingComponent->GetOwner()->GetWorldPosition());
while(_TranslucidMeshes.find(index)!=_TranslucidMeshes.end()) index+=1.f;
_TranslucidMeshes[index] = (*k);
}
else _OpaqueMeshes.push_back((*k));
}
for (std::map<f32,RenderingMesh*>::iterator i=_TranslucidMeshes.begin();i!=_TranslucidMeshes.end();i++)
{
_OpaqueMeshes.push_back((*i).second);
}
return _OpaqueMeshes;
}
void CubemapRenderer::RenderCubeMap(SceneGraph* Scene, GameObject* AllSeeingEye, const f32 &Near, const f32 &Far)
{
InitRender();
this->AllSeeingEye = AllSeeingEye;
ProjectionMatrix = Matrix::PerspectiveMatrix(90.f, 1.0, Near, Far);
// Universal Cache
NearFarPlane = Vec2(Near, Far);
CameraPosition = AllSeeingEye->GetWorldPosition();
// Flags
ViewMatrixInverseIsDirty = true;
ProjectionMatrixInverseIsDirty = true;
ViewProjectionMatrixIsDirty = true;
// Group and Sort Meshes
std::vector<RenderingMesh*> rmesh = GroupAndSortAssets(Scene,AllSeeingEye);
// Get Lights List
std::vector<IComponent*> lcomps = ILightComponent::GetLightsOnScene(Scene);
if (rmesh.size()>0)
{
// Prepare and Pack Lights to Send to Shaders
Lights.clear();
// ShadowMaps
DirectionalShadowMapsTextures.clear();
DirectionalShadowMatrix.clear();
NumberOfDirectionalShadows = 0;
PointShadowMapsTextures.clear();
PointShadowMatrix.clear();
NumberOfPointShadows = 0;
SpotShadowMapsTextures.clear();
SpotShadowMatrix.clear();
NumberOfSpotShadows = 0;
if (lcomps.size()>0)
{
for (std::vector<IComponent*>::iterator i = lcomps.begin();i!=lcomps.end();i++)
{
if (DirectionalLight* d = dynamic_cast<DirectionalLight*>((*i))) {
// Directional Lights
Vec4 color = d->GetLightColor();
Vec3 position;
Vec3 LDirection = d->GetOwner()->GetWorldPosition().normalize();
Vec4 direction = ViewMatrix * Vec4(LDirection.x,LDirection.y,LDirection.z,0.f);
f32 attenuation = 1.f;
Vec2 cones;
int32 type = 1;
Matrix directionalLight = Matrix();
directionalLight.m[0] = color.x; directionalLight.m[1] = color.y; directionalLight.m[2] = color.z; directionalLight.m[3] = color.w;
directionalLight.m[4] = position.x; directionalLight.m[5] = position.y; directionalLight.m[6] = position.z;
directionalLight.m[7] = direction.x; directionalLight.m[8] = direction.y; directionalLight.m[9] = direction.z;
directionalLight.m[10] = attenuation; //directionalLight.m[11] = attenuation.y; directionalLight.m[12] = attenuation.z;
directionalLight.m[13] = cones.x; directionalLight.m[14] = cones.y;
directionalLight.m[15] = type;
Lights.push_back(directionalLight);
} else if (PointLight* p = dynamic_cast<PointLight*>((*i))) {
// Point Lights
Vec4 color = p->GetLightColor();
Vec3 position = ViewMatrix * (p->GetOwner()->GetWorldPosition());
Vec3 direction;
f32 attenuation = p->GetLightRadius();
Vec2 cones;
int32 type = 2;
Matrix pointLight = Matrix();
pointLight.m[0] = color.x; pointLight.m[1] = color.y; pointLight.m[2] = color.z; pointLight.m[3] = color.w;
pointLight.m[4] = position.x; pointLight.m[5] = position.y; pointLight.m[6] = position.z;
pointLight.m[7] = direction.x; pointLight.m[8] = direction.y; pointLight.m[9] = direction.z;
pointLight.m[10] = attenuation; //pointLight.m[11] = attenuation.y; pointLight.m[12] = attenuation.z;
pointLight.m[13] = cones.x; pointLight.m[14] = cones.y;
pointLight.m[15] = type;
Lights.push_back(pointLight);
} else if (SpotLight* s = dynamic_cast<SpotLight*>((*i))) {
// Spot Lights
Vec4 color = s->GetLightColor();
Vec3 position = ViewMatrix * (s->GetOwner()->GetWorldPosition());
Vec3 LDirection = s->GetLightDirection().normalize();
Vec4 direction = ViewMatrix * Vec4(LDirection.x,LDirection.y,LDirection.z,0.f);
f32 attenuation = s->GetLightRadius();
Vec2 cones = Vec2(s->GetLightCosInnerCone(),s->GetLightCosOutterCone());
int32 type = 3;
Matrix spotLight = Matrix();
spotLight.m[0] = color.x; spotLight.m[1] = color.y; spotLight.m[2] = color.z; spotLight.m[3] = color.w;
spotLight.m[4] = position.x; spotLight.m[5] = position.y; spotLight.m[6] = position.z;
spotLight.m[7] = direction.x; spotLight.m[8] = direction.y; spotLight.m[9] = direction.z;
spotLight.m[10] = attenuation; //spotLight.m[11] = attenuation.y; spotLight.m[12] = attenuation.z;
spotLight.m[13] = cones.x; spotLight.m[14] = cones.y;
spotLight.m[15] = type;
Lights.push_back(spotLight);
}
}
}
// Save Time
Timer = Scene->GetTime();
// Update Lights Position and Direction to ViewSpace
NumberOfLights = Lights.size();
// Bind FBO
fbo->Bind();
for (uint32 i=0;i<6;i++)
{
// Clean View Matrix
ViewMatrix.identity();
// Create Light View Matrix For Rendering Each Face of the Cubemap
if (i==0)
ViewMatrix.LookAt(Vec3::ZERO, Vec3(1.0, 0.0, 0.0), Vec3(0.0,-1.0,0.0)); // +X
if (i==1)
ViewMatrix.LookAt(Vec3::ZERO, Vec3(-1.0, 0.0, 0.0), Vec3(0.0,-1.0,0.0)); // -X
if (i==2)
ViewMatrix.LookAt(Vec3::ZERO, Vec3(0.0, -1.0, 0.0), Vec3(0.0,0.0,1.0)); // +Y
if (i==3)
ViewMatrix.LookAt(Vec3::ZERO, Vec3(0.0, 1.0, 0.0), Vec3(0.0,0.0,-1.0)); // -Y
if (i==4)
ViewMatrix.LookAt(Vec3::ZERO, Vec3(0.0, 0.0, 1.0), Vec3(0.0,-1.0,0.0)); // +Z
if (i==5)
ViewMatrix.LookAt(Vec3::ZERO, Vec3(0.0, 0.0, -1.0), Vec3(0.0,-1.0,0.0)); // -Z
// Translate Light View Matrix
ViewMatrix*=AllSeeingEye->GetWorldTransformation().Inverse();
// Frame Buffer Attachment
fbo->AddAttach(FrameBufferAttachmentFormat::Color_Attachment0,TextureType::CubemapPositive_X+i,environmentMap);
// Set Viewport
SetViewPort(0,0, Width, Height);
// Clear Screen
ClearScreen(Buffer_Bit::Color | Buffer_Bit::Depth);
SetBackground(Vec4::ZERO);
EnableDepthTest();
// Update Culling
UpdateCulling(ProjectionMatrix*ViewMatrix);
// Render Scene with Objects Material
for (std::vector<RenderingMesh*>::iterator k=rmesh.begin();k!=rmesh.end();k++)
{
if ((*k)->renderingComponent->GetOwner()!=NULL)
{
// Culling Test
bool cullingTest = false;
switch((*k)->CullingGeometry)
{
case CullingGeometry::Box:
cullingTest = CullingBoxTest(*k);
break;
case CullingGeometry::Sphere:
default:
cullingTest = CullingSphereTest(*k);
break;
}
if (cullingTest && (*k)->renderingComponent->IsActive())
RenderObject((*k),(*k)->Material);
}
}
}
fbo->UnBind();
EndRender();
}
}
Texture* CubemapRenderer::GetTexture()
{
return environmentMap;
}
};<commit_msg>Fixed minore issue when creating view matrix, it was flipped on Y (on purpose for testing :P)<commit_after>//============================================================================
// Name : CubemapRenderer.h
// Author : Duarte Peixinho
// Version :
// Copyright : ;)
// Description : Dynamic Cube Map aka Environment Map
//============================================================================
#include "CubemapRenderer.h"
#include <GL/glew.h>
namespace p3d {
CubemapRenderer::CubemapRenderer(const uint32& Width, const uint32& Height) : IRenderer(Width,Height)
{
echo("SUCCESS: Forward Renderer Created");
ActivateCulling(CullingMode::FrustumCulling);
// Create Texture (CubeMap), Frame Buffer and Set the Texture as Attachment
environmentMap=AssetManager::CreateTexture(TextureType::CubemapNegative_X,TextureDataType::RGB,Width,Height,false);
environmentMap->CreateTexture(TextureType::CubemapNegative_Y,TextureDataType::RGB,Width,Height,false);
environmentMap->CreateTexture(TextureType::CubemapNegative_Z,TextureDataType::RGB,Width,Height,false);
environmentMap->CreateTexture(TextureType::CubemapPositive_X,TextureDataType::RGB,Width,Height,false);
environmentMap->CreateTexture(TextureType::CubemapPositive_Y,TextureDataType::RGB,Width,Height,false);
environmentMap->CreateTexture(TextureType::CubemapPositive_Z,TextureDataType::RGB,Width,Height,false);
environmentMap->SetRepeat(TextureRepeat::ClampToEdge,TextureRepeat::ClampToEdge,TextureRepeat::ClampToEdge);
// Initialize Frame Buffer
fbo = new FrameBuffer();
fbo->Init(FrameBufferAttachmentFormat::Color_Attachment0,TextureType::CubemapPositive_X,environmentMap,true);
}
CubemapRenderer::~CubemapRenderer()
{
if (IsCulling)
{
delete culling;
}
AssetManager::DeleteTexture(environmentMap);
delete fbo;
}
std::vector<RenderingMesh*> CubemapRenderer::GroupAndSortAssets(SceneGraph* Scene, GameObject* Camera)
{
// Sort and Group Objects From Scene
std::vector<RenderingMesh*> _OpaqueMeshes;
std::map<f32,RenderingMesh*> _TranslucidMeshes;
std::vector<RenderingMesh*> rmeshes = RenderingComponent::GetRenderingMeshes(Scene);
for (std::vector<RenderingMesh*>::iterator k=rmeshes.begin();k!=rmeshes.end();k++)
{
if ((*k)->Material->IsTransparent())
{
f32 index = Camera->GetWorldPosition().distanceSQR((*k)->renderingComponent->GetOwner()->GetWorldPosition());
while(_TranslucidMeshes.find(index)!=_TranslucidMeshes.end()) index+=1.f;
_TranslucidMeshes[index] = (*k);
}
else _OpaqueMeshes.push_back((*k));
}
for (std::map<f32,RenderingMesh*>::iterator i=_TranslucidMeshes.begin();i!=_TranslucidMeshes.end();i++)
{
_OpaqueMeshes.push_back((*i).second);
}
return _OpaqueMeshes;
}
void CubemapRenderer::RenderCubeMap(SceneGraph* Scene, GameObject* AllSeeingEye, const f32 &Near, const f32 &Far)
{
InitRender();
this->AllSeeingEye = AllSeeingEye;
ProjectionMatrix = Matrix::PerspectiveMatrix(90.f, 1.0, Near, Far);
// Universal Cache
NearFarPlane = Vec2(Near, Far);
CameraPosition = AllSeeingEye->GetWorldPosition();
// Flags
ViewMatrixInverseIsDirty = true;
ProjectionMatrixInverseIsDirty = true;
ViewProjectionMatrixIsDirty = true;
// Group and Sort Meshes
std::vector<RenderingMesh*> rmesh = GroupAndSortAssets(Scene,AllSeeingEye);
// Get Lights List
std::vector<IComponent*> lcomps = ILightComponent::GetLightsOnScene(Scene);
if (rmesh.size()>0)
{
// Prepare and Pack Lights to Send to Shaders
Lights.clear();
// ShadowMaps
DirectionalShadowMapsTextures.clear();
DirectionalShadowMatrix.clear();
NumberOfDirectionalShadows = 0;
PointShadowMapsTextures.clear();
PointShadowMatrix.clear();
NumberOfPointShadows = 0;
SpotShadowMapsTextures.clear();
SpotShadowMatrix.clear();
NumberOfSpotShadows = 0;
if (lcomps.size()>0)
{
for (std::vector<IComponent*>::iterator i = lcomps.begin();i!=lcomps.end();i++)
{
if (DirectionalLight* d = dynamic_cast<DirectionalLight*>((*i))) {
// Directional Lights
Vec4 color = d->GetLightColor();
Vec3 position;
Vec3 LDirection = d->GetOwner()->GetWorldPosition().normalize();
Vec4 direction = ViewMatrix * Vec4(LDirection.x,LDirection.y,LDirection.z,0.f);
f32 attenuation = 1.f;
Vec2 cones;
int32 type = 1;
Matrix directionalLight = Matrix();
directionalLight.m[0] = color.x; directionalLight.m[1] = color.y; directionalLight.m[2] = color.z; directionalLight.m[3] = color.w;
directionalLight.m[4] = position.x; directionalLight.m[5] = position.y; directionalLight.m[6] = position.z;
directionalLight.m[7] = direction.x; directionalLight.m[8] = direction.y; directionalLight.m[9] = direction.z;
directionalLight.m[10] = attenuation; //directionalLight.m[11] = attenuation.y; directionalLight.m[12] = attenuation.z;
directionalLight.m[13] = cones.x; directionalLight.m[14] = cones.y;
directionalLight.m[15] = type;
Lights.push_back(directionalLight);
} else if (PointLight* p = dynamic_cast<PointLight*>((*i))) {
// Point Lights
Vec4 color = p->GetLightColor();
Vec3 position = ViewMatrix * (p->GetOwner()->GetWorldPosition());
Vec3 direction;
f32 attenuation = p->GetLightRadius();
Vec2 cones;
int32 type = 2;
Matrix pointLight = Matrix();
pointLight.m[0] = color.x; pointLight.m[1] = color.y; pointLight.m[2] = color.z; pointLight.m[3] = color.w;
pointLight.m[4] = position.x; pointLight.m[5] = position.y; pointLight.m[6] = position.z;
pointLight.m[7] = direction.x; pointLight.m[8] = direction.y; pointLight.m[9] = direction.z;
pointLight.m[10] = attenuation; //pointLight.m[11] = attenuation.y; pointLight.m[12] = attenuation.z;
pointLight.m[13] = cones.x; pointLight.m[14] = cones.y;
pointLight.m[15] = type;
Lights.push_back(pointLight);
} else if (SpotLight* s = dynamic_cast<SpotLight*>((*i))) {
// Spot Lights
Vec4 color = s->GetLightColor();
Vec3 position = ViewMatrix * (s->GetOwner()->GetWorldPosition());
Vec3 LDirection = s->GetLightDirection().normalize();
Vec4 direction = ViewMatrix * Vec4(LDirection.x,LDirection.y,LDirection.z,0.f);
f32 attenuation = s->GetLightRadius();
Vec2 cones = Vec2(s->GetLightCosInnerCone(),s->GetLightCosOutterCone());
int32 type = 3;
Matrix spotLight = Matrix();
spotLight.m[0] = color.x; spotLight.m[1] = color.y; spotLight.m[2] = color.z; spotLight.m[3] = color.w;
spotLight.m[4] = position.x; spotLight.m[5] = position.y; spotLight.m[6] = position.z;
spotLight.m[7] = direction.x; spotLight.m[8] = direction.y; spotLight.m[9] = direction.z;
spotLight.m[10] = attenuation; //spotLight.m[11] = attenuation.y; spotLight.m[12] = attenuation.z;
spotLight.m[13] = cones.x; spotLight.m[14] = cones.y;
spotLight.m[15] = type;
Lights.push_back(spotLight);
}
}
}
// Save Time
Timer = Scene->GetTime();
// Update Lights Position and Direction to ViewSpace
NumberOfLights = Lights.size();
// Bind FBO
fbo->Bind();
for (uint32 i=0;i<6;i++)
{
// Clean View Matrix
ViewMatrix.identity();
// Create Light View Matrix For Rendering Each Face of the Cubemap
if (i==0)
ViewMatrix.LookAt(Vec3::ZERO, Vec3(1.0, 0.0, 0.0), Vec3(0.0,-1.0,0.0)); // +X
if (i==1)
ViewMatrix.LookAt(Vec3::ZERO, Vec3(-1.0, 0.0, 0.0), Vec3(0.0,-1.0,0.0)); // -X
if (i==2)
ViewMatrix.LookAt(Vec3::ZERO, Vec3(0.0, 1.0, 0.0), Vec3(0.0,0.0,1.0)); // +Y
if (i==3)
ViewMatrix.LookAt(Vec3::ZERO, Vec3(0.0, -1.0, 0.0), Vec3(0.0,0.0,-1.0)); // -Y
if (i==4)
ViewMatrix.LookAt(Vec3::ZERO, Vec3(0.0, 0.0, 1.0), Vec3(0.0,-1.0,0.0)); // +Z
if (i==5)
ViewMatrix.LookAt(Vec3::ZERO, Vec3(0.0, 0.0, -1.0), Vec3(0.0,-1.0,0.0)); // -Z
// Translate Light View Matrix
ViewMatrix*=AllSeeingEye->GetWorldTransformation().Inverse();
// Frame Buffer Attachment
fbo->AddAttach(FrameBufferAttachmentFormat::Color_Attachment0,TextureType::CubemapPositive_X+i,environmentMap);
// Set Viewport
SetViewPort(0,0, Width, Height);
// Clear Screen
ClearScreen(Buffer_Bit::Color | Buffer_Bit::Depth);
SetBackground(Vec4::ZERO);
EnableDepthTest();
// Update Culling
UpdateCulling(ProjectionMatrix*ViewMatrix);
// Render Scene with Objects Material
for (std::vector<RenderingMesh*>::iterator k=rmesh.begin();k!=rmesh.end();k++)
{
if ((*k)->renderingComponent->GetOwner()!=NULL)
{
// Culling Test
bool cullingTest = false;
switch((*k)->CullingGeometry)
{
case CullingGeometry::Box:
cullingTest = CullingBoxTest(*k);
break;
case CullingGeometry::Sphere:
default:
cullingTest = CullingSphereTest(*k);
break;
}
if (cullingTest && (*k)->renderingComponent->IsActive())
RenderObject((*k),(*k)->Material);
}
}
}
fbo->UnBind();
EndRender();
}
}
Texture* CubemapRenderer::GetTexture()
{
return environmentMap;
}
};<|endoftext|> |
<commit_before>#include "stan/math/functions/binomial_coefficient_log.hpp"
#include <gtest/gtest.h>
TEST(MathFunctions, binomial_coefficient_log) {
using stan::math::binomial_coefficient_log;
EXPECT_FLOAT_EQ(1.0, exp(binomial_coefficient_log(2.0,2.0)));
EXPECT_FLOAT_EQ(2.0, exp(binomial_coefficient_log(2.0,1.0)));
EXPECT_FLOAT_EQ(3.0, exp(binomial_coefficient_log(3.0,1.0)));
EXPECT_NEAR(3.0, exp(binomial_coefficient_log(3.0,2.0)),0.0001);
}
<commit_msg>added NaN test for binomial_coefficient_log<commit_after>#include <stan/math/functions/binomial_coefficient_log.hpp>
#include <boost/math/special_functions/fpclassify.hpp>
#include <gtest/gtest.h>
TEST(MathFunctions, binomial_coefficient_log) {
using stan::math::binomial_coefficient_log;
EXPECT_FLOAT_EQ(1.0, exp(binomial_coefficient_log(2.0,2.0)));
EXPECT_FLOAT_EQ(2.0, exp(binomial_coefficient_log(2.0,1.0)));
EXPECT_FLOAT_EQ(3.0, exp(binomial_coefficient_log(3.0,1.0)));
EXPECT_NEAR(3.0, exp(binomial_coefficient_log(3.0,2.0)),0.0001);
}
TEST(MathFunctions, binomial_coefficient_log_nan) {
double nan = std::numeric_limits<double>::quiet_NaN();
EXPECT_PRED1(boost::math::isnan<double>,
stan::math::binomial_coefficient_log(2.0, nan));
EXPECT_PRED1(boost::math::isnan<double>,
stan::math::binomial_coefficient_log(nan, 2.0));
EXPECT_PRED1(boost::math::isnan<double>,
stan::math::binomial_coefficient_log(nan, nan));
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.