text
stringlengths
54
60.6k
<commit_before>#include <algorithm> #include "command.hh" #include "common-args.hh" #include "eval.hh" #include "globals.hh" #include "legacy.hh" #include "shared.hh" #include "store-api.hh" #include "progress-bar.hh" #include "download.hh" #include "finally.hh" #include <sys/types.h> #include <sys/socket.h> #include <ifaddrs.h> #include <netdb.h> #include <netinet/in.h> extern std::string chrootHelperName; void chrootHelper(int argc, char * * argv); namespace nix { /* Check if we have a non-loopback/link-local network interface. */ static bool haveInternet() { struct ifaddrs * addrs; if (getifaddrs(&addrs)) return true; Finally free([&]() { freeifaddrs(addrs); }); for (auto i = addrs; i; i = i->ifa_next) { if (!i->ifa_addr) continue; if (i->ifa_addr->sa_family == AF_INET) { if (ntohl(((sockaddr_in *) i->ifa_addr)->sin_addr.s_addr) != INADDR_LOOPBACK) { return true; } } else if (i->ifa_addr->sa_family == AF_INET6) { if (!IN6_IS_ADDR_LOOPBACK(&((sockaddr_in6 *) i->ifa_addr)->sin6_addr) && !IN6_IS_ADDR_LINKLOCAL(&((sockaddr_in6 *) i->ifa_addr)->sin6_addr)) return true; } } return false; } std::string programPath; struct NixArgs : virtual MultiCommand, virtual MixCommonArgs { bool printBuildLogs = false; bool useNet = true; NixArgs() : MultiCommand(*RegisterCommand::commands), MixCommonArgs("nix") { mkFlag() .longName("help") .description("show usage information") .handler([&]() { showHelpAndExit(); }); mkFlag() .longName("help-config") .description("show configuration options") .handler([&]() { std::cout << "The following configuration options are available:\n\n"; Table2 tbl; std::map<std::string, Config::SettingInfo> settings; globalConfig.getSettings(settings); for (const auto & s : settings) tbl.emplace_back(s.first, s.second.description); printTable(std::cout, tbl); throw Exit(); }); mkFlag() .longName("print-build-logs") .shortName('L') .description("print full build logs on stderr") .set(&printBuildLogs, true); mkFlag() .longName("version") .description("show version information") .handler([&]() { printVersion(programName); }); mkFlag() .longName("no-net") .description("disable substituters and consider all previously downloaded files up-to-date") .handler([&]() { useNet = false; }); mkFlag() .longName("refresh") .description("consider all previously downloaded files out-of-date") .handler([&]() { settings.tarballTtl = 0; }); } void printFlags(std::ostream & out) override { Args::printFlags(out); std::cout << "\n" "In addition, most configuration settings can be overriden using '--<name> <value>'.\n" "Boolean settings can be overriden using '--<name>' or '--no-<name>'. See 'nix\n" "--help-config' for a list of configuration settings.\n"; } void printHelp(const string & programName, std::ostream & out) override { MultiCommand::printHelp(programName, out); #if 0 out << "\nFor full documentation, run 'man " << programName << "' or 'man " << programName << "-<COMMAND>'.\n"; #endif std::cout << "\nNote: this program is EXPERIMENTAL and subject to change.\n"; } void showHelpAndExit() { printHelp(programName, std::cout); throw Exit(); } }; void mainWrapped(int argc, char * * argv) { /* The chroot helper needs to be run before any threads have been started. */ if (argc > 0 && argv[0] == chrootHelperName) { chrootHelper(argc, argv); return; } initNix(); initGC(); programPath = argv[0]; auto programName = std::string(baseNameOf(programPath)); { auto legacy = (*RegisterLegacyCommand::commands)[programName]; if (legacy) return legacy(argc, argv); } verbosity = lvlWarn; settings.verboseBuild = false; NixArgs args; args.parseCmdline(argvToStrings(argc, argv)); settings.requireExperimentalFeature("nix-command"); initPlugins(); if (!args.command) args.showHelpAndExit(); Finally f([]() { stopProgressBar(); }); startProgressBar(args.printBuildLogs); if (args.useNet && !haveInternet()) { warn("you don't have Internet access; disabling some network-dependent features"); args.useNet = false; } if (!args.useNet) { // FIXME: should check for command line overrides only. if (!settings.useSubstitutes.overriden) settings.useSubstitutes = false; if (!settings.tarballTtl.overriden) settings.tarballTtl = std::numeric_limits<unsigned int>::max(); if (!downloadSettings.tries.overriden) downloadSettings.tries = 0; if (!downloadSettings.connectTimeout.overriden) downloadSettings.connectTimeout = 1; } args.command->prepare(); args.command->run(); } } int main(int argc, char * * argv) { return nix::handleExceptions(argv[0], [&]() { nix::mainWrapped(argc, argv); }); } <commit_msg>Fix --refresh with --no-net<commit_after>#include <algorithm> #include "command.hh" #include "common-args.hh" #include "eval.hh" #include "globals.hh" #include "legacy.hh" #include "shared.hh" #include "store-api.hh" #include "progress-bar.hh" #include "download.hh" #include "finally.hh" #include <sys/types.h> #include <sys/socket.h> #include <ifaddrs.h> #include <netdb.h> #include <netinet/in.h> extern std::string chrootHelperName; void chrootHelper(int argc, char * * argv); namespace nix { /* Check if we have a non-loopback/link-local network interface. */ static bool haveInternet() { struct ifaddrs * addrs; if (getifaddrs(&addrs)) return true; Finally free([&]() { freeifaddrs(addrs); }); for (auto i = addrs; i; i = i->ifa_next) { if (!i->ifa_addr) continue; if (i->ifa_addr->sa_family == AF_INET) { if (ntohl(((sockaddr_in *) i->ifa_addr)->sin_addr.s_addr) != INADDR_LOOPBACK) { return true; } } else if (i->ifa_addr->sa_family == AF_INET6) { if (!IN6_IS_ADDR_LOOPBACK(&((sockaddr_in6 *) i->ifa_addr)->sin6_addr) && !IN6_IS_ADDR_LINKLOCAL(&((sockaddr_in6 *) i->ifa_addr)->sin6_addr)) return true; } } return false; } std::string programPath; struct NixArgs : virtual MultiCommand, virtual MixCommonArgs { bool printBuildLogs = false; bool useNet = true; bool refresh = false; NixArgs() : MultiCommand(*RegisterCommand::commands), MixCommonArgs("nix") { mkFlag() .longName("help") .description("show usage information") .handler([&]() { showHelpAndExit(); }); mkFlag() .longName("help-config") .description("show configuration options") .handler([&]() { std::cout << "The following configuration options are available:\n\n"; Table2 tbl; std::map<std::string, Config::SettingInfo> settings; globalConfig.getSettings(settings); for (const auto & s : settings) tbl.emplace_back(s.first, s.second.description); printTable(std::cout, tbl); throw Exit(); }); mkFlag() .longName("print-build-logs") .shortName('L') .description("print full build logs on stderr") .set(&printBuildLogs, true); mkFlag() .longName("version") .description("show version information") .handler([&]() { printVersion(programName); }); mkFlag() .longName("no-net") .description("disable substituters and consider all previously downloaded files up-to-date") .handler([&]() { useNet = false; }); mkFlag() .longName("refresh") .description("consider all previously downloaded files out-of-date") .handler([&]() { refresh = true; }); } void printFlags(std::ostream & out) override { Args::printFlags(out); std::cout << "\n" "In addition, most configuration settings can be overriden using '--<name> <value>'.\n" "Boolean settings can be overriden using '--<name>' or '--no-<name>'. See 'nix\n" "--help-config' for a list of configuration settings.\n"; } void printHelp(const string & programName, std::ostream & out) override { MultiCommand::printHelp(programName, out); #if 0 out << "\nFor full documentation, run 'man " << programName << "' or 'man " << programName << "-<COMMAND>'.\n"; #endif std::cout << "\nNote: this program is EXPERIMENTAL and subject to change.\n"; } void showHelpAndExit() { printHelp(programName, std::cout); throw Exit(); } }; void mainWrapped(int argc, char * * argv) { /* The chroot helper needs to be run before any threads have been started. */ if (argc > 0 && argv[0] == chrootHelperName) { chrootHelper(argc, argv); return; } initNix(); initGC(); programPath = argv[0]; auto programName = std::string(baseNameOf(programPath)); { auto legacy = (*RegisterLegacyCommand::commands)[programName]; if (legacy) return legacy(argc, argv); } verbosity = lvlWarn; settings.verboseBuild = false; NixArgs args; args.parseCmdline(argvToStrings(argc, argv)); settings.requireExperimentalFeature("nix-command"); initPlugins(); if (!args.command) args.showHelpAndExit(); Finally f([]() { stopProgressBar(); }); startProgressBar(args.printBuildLogs); if (args.useNet && !haveInternet()) { warn("you don't have Internet access; disabling some network-dependent features"); args.useNet = false; } if (!args.useNet) { // FIXME: should check for command line overrides only. if (!settings.useSubstitutes.overriden) settings.useSubstitutes = false; if (!settings.tarballTtl.overriden) settings.tarballTtl = std::numeric_limits<unsigned int>::max(); if (!downloadSettings.tries.overriden) downloadSettings.tries = 0; if (!downloadSettings.connectTimeout.overriden) downloadSettings.connectTimeout = 1; } if (args.refresh) settings.tarballTtl = 0; args.command->prepare(); args.command->run(); } } int main(int argc, char * * argv) { return nix::handleExceptions(argv[0], [&]() { nix::mainWrapped(argc, argv); }); } <|endoftext|>
<commit_before>/* Kopete Latex Plugin Copyright (c) 2004 by Duncan Mac-Vicar Prett <duncan@kde.org> Copyright (c) 2004-2005 by Olivier Goffart <ogoffart@kde. org> Kopete (c) 2001-2004 by the Kopete developers <kopete-devel@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. * * * ************************************************************************* */ #include <qregexp.h> #include <qimage.h> #include <qbuffer.h> #include <qcstring.h> #include <qstylesheet.h> #include <kgenericfactory.h> #include <kdebug.h> #include <kstandarddirs.h> #include <kprocess.h> #include <ktempfile.h> #include <kmdcodec.h> #include <kmessagebox.h> #include "kopetemessagemanagerfactory.h" #include "kopeteuiglobal.h" #include "latexplugin.h" #include "latexconfig.h" #define ENCODED_IMAGE_MODE 0 typedef KGenericFactory<LatexPlugin> LatexPluginFactory; K_EXPORT_COMPONENT_FACTORY( kopete_latex, LatexPluginFactory( "kopete_latex" ) ) LatexPlugin::LatexPlugin( QObject *parent, const char *name, const QStringList &/*args*/ ) : Kopete::Plugin( LatexPluginFactory::instance(), parent, name ) { // kdDebug() << k_funcinfo << endl; if( !s_pluginStatic ) s_pluginStatic = this; mMagickNotFoundShown = false; connect( Kopete::ChatSessionManager::self(), SIGNAL( aboutToDisplay( Kopete::Message & ) ), SLOT( slotMessageAboutToShow( Kopete::Message & ) ) ); connect( Kopete::ChatSessionManager::self(), SIGNAL( aboutToSend(Kopete::Message& ) ), this, SLOT(slotMessageAboutToSend(Kopete::Message& ) ) ); connect ( this , SIGNAL( settingsChanged() ) , this , SLOT( slotSettingsChanged() ) ); m_convScript = KStandardDirs::findExe("kopete_latexconvert.sh"); slotSettingsChanged(); } LatexPlugin::~LatexPlugin() { s_pluginStatic = 0L; } LatexPlugin* LatexPlugin::plugin() { return s_pluginStatic ; } LatexPlugin* LatexPlugin::s_pluginStatic = 0L; void LatexPlugin::slotMessageAboutToShow( Kopete::Message& msg ) { QString mMagick = KStandardDirs::findExe("convert"); if ( mMagick.isEmpty() ) { // show just once if ( !mMagickNotFoundShown ) { KMessageBox::queuedMessageBox( Kopete::UI::Global::mainWidget(), KMessageBox::Error, i18n("I cannot find the Magick convert program.\nconvert is required to render the Latex formulas.\nPlease go to www.imagemagick.org or to your distribution site and get the right package.") ); mMagickNotFoundShown = true; } // dont try to parse if convert is not installed return; } QString messageText = msg.plainBody(); if( !messageText.contains("$$")) return; //kdDebug() << k_funcinfo << " Using converter: " << m_convScript << endl; // /\[([^]]).*?\[/$1\]/ // \$\$.+?\$\$ // this searches for $$formula$$ QRegExp rg("\\$\\$.+\\$\\$"); rg.setMinimal(true); // this searches for [latex]formula[/latex] //QRegExp rg("\\[([^]\]).*?\\[/$1\\]"); int pos = 0; QMap<QString, QString> replaceMap; while (pos >= 0 && (unsigned int)pos < messageText.length()) { // kdDebug() << k_funcinfo << " searching pos: " << pos << endl; pos = rg.search(messageText, pos); if (pos >= 0 ) { QString match = rg.cap(0); pos += rg.matchedLength(); QString formul=match; if(!securityCheck(formul)) continue; QString fileName=handleLatex(formul.replace("$$","")); // get the image and encode it with base64 #if ENCODED_IMAGE_MODE QImage renderedImage( fileName ); if ( !renderedImage.isNull() ) { QByteArray ba; QBuffer buffer( ba ); buffer.open( IO_WriteOnly ); renderedImage.save( &buffer, "PNG" ); QString imageURL = QString::fromLatin1("data:image/png;base64,%1").arg( KCodecs::base64Encode( ba ) ); replaceMap[Kopete::Message::escape(match)] = imageURL; } #else replaceMap[Kopete::Message::escape(match)] = fileName; #endif } } if(replaceMap.isEmpty()) //we haven't found any latex strings return; messageText=Kopete::Message::escape(messageText); for (QMap<QString,QString>::ConstIterator it = replaceMap.begin(); it != replaceMap.end(); ++it) { QString escapedLATEX=it.key(); escapedLATEX.replace("\"","&quot;"); //we need the escape quotes because that string will be in a title="" argument messageText.replace(it.key(), " <img src=\"" + (*it) + "\" alt=\"" + escapedLATEX +"\" title=\"" + escapedLATEX +"\" /> "); } msg.setBody( messageText, Kopete::Message::RichText ); } void LatexPlugin::slotMessageAboutToSend( Kopete::Message& msg) { //disabled because to work correctly, we need to find what special has the gif we can send over MSN #if 0 KConfig *config = KGlobal::config(); config->setGroup("Latex Plugin"); if(!config->readBoolEntry("ParseOutgoing", false)) return; QString messageText = msg.plainBody(); if( !messageText.contains("$$")) return; /* if( msg.from()->protocol()->pluginId()!="MSNProtocol" ) return;*/ // this searches for $$formula$$ QRegExp rg("^\\s*\\$\\$([^$]+)\\$\\$\\s*$"); if( rg.search(messageText) != -1 ) { QString latexFormula = rg.cap(1); if(!securityCheck( latexFormula )) return; QString url = handleLatex(latexFormula); if(!url.isNull()) { QString escapedLATEX= QStyleSheet::escape(messageText).replace("\"","&quot;"); QString messageText="<img src=\"" + url + "\" alt=\"" + escapedLATEX + "\" title=\"" + escapedLATEX +"\" />"; msg.setBody( messageText, Kopete::Message::RichText ); } } #endif } QString LatexPlugin::handleLatex(const QString &latexFormula) { KTempFile *tempFile=new KTempFile( locateLocal( "tmp", "kopetelatex-" ), ".png" ); tempFile->setAutoDelete(true); m_tempFiles.append(tempFile); m_tempFiles.setAutoDelete(true); QString fileName = tempFile->name(); KProcess p; QString argumentRes = "-r %1x%2"; QString argumentOut = "-o %1"; //QString argumentFormat = "-fgif"; //we uses gif format because MSN only handle gif int hDPI, vDPI; hDPI = LatexConfig::self()->horizontalDPI(); vDPI = LatexConfig::self()->verticalDPI(); p << m_convScript << argumentRes.arg(QString::number(hDPI), QString::number(vDPI)) << argumentOut.arg(fileName) /*<< argumentFormat*/ << latexFormula ; kdDebug() << k_funcinfo << " Rendering " << m_convScript << " " << argumentRes.arg(QString::number(hDPI), QString::number(vDPI)) << " " << argumentOut.arg(fileName) << endl; // FIXME our sucky sync filter API limitations :-) p.start(KProcess::Block); return fileName; } bool LatexPlugin::securityCheck(const QString &latexFormula) { return !latexFormula.contains(QRegExp("\\\\(def|let|futurelet|newcommand|renewcomment|if[a-z]*|else|fi|write|input|include" "|chardef|catcode|makeatletter|noexpand|toksdef|every|errhelp|errorstopmode|scrollmode|nonstopmode|batchmode" "|read|csname|newhelp|relax|afterground|afterassignment|expandafter|noexpand|special|command|loop|repeat|toks" "|output|line|mathcode|name|item|section|mbox|DeclareRobustCommand)[^a-zA-Z]")); } void LatexPlugin::slotSettingsChanged() { LatexConfig::self()->readConfig(); } #include "latexplugin.moc" // vim: set noet ts=4 sts=4 sw=4: <commit_msg>don't blacklist \iff<commit_after>/* Kopete Latex Plugin Copyright (c) 2004 by Duncan Mac-Vicar Prett <duncan@kde.org> Copyright (c) 2004-2005 by Olivier Goffart <ogoffart@kde. org> Kopete (c) 2001-2004 by the Kopete developers <kopete-devel@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. * * * ************************************************************************* */ #include <qregexp.h> #include <qimage.h> #include <qbuffer.h> #include <qcstring.h> #include <qstylesheet.h> #include <kgenericfactory.h> #include <kdebug.h> #include <kstandarddirs.h> #include <kprocess.h> #include <ktempfile.h> #include <kmdcodec.h> #include <kmessagebox.h> #include "kopetemessagemanagerfactory.h" #include "kopeteuiglobal.h" #include "latexplugin.h" #include "latexconfig.h" #define ENCODED_IMAGE_MODE 0 typedef KGenericFactory<LatexPlugin> LatexPluginFactory; K_EXPORT_COMPONENT_FACTORY( kopete_latex, LatexPluginFactory( "kopete_latex" ) ) LatexPlugin::LatexPlugin( QObject *parent, const char *name, const QStringList &/*args*/ ) : Kopete::Plugin( LatexPluginFactory::instance(), parent, name ) { // kdDebug() << k_funcinfo << endl; if( !s_pluginStatic ) s_pluginStatic = this; mMagickNotFoundShown = false; connect( Kopete::ChatSessionManager::self(), SIGNAL( aboutToDisplay( Kopete::Message & ) ), SLOT( slotMessageAboutToShow( Kopete::Message & ) ) ); connect( Kopete::ChatSessionManager::self(), SIGNAL( aboutToSend(Kopete::Message& ) ), this, SLOT(slotMessageAboutToSend(Kopete::Message& ) ) ); connect ( this , SIGNAL( settingsChanged() ) , this , SLOT( slotSettingsChanged() ) ); m_convScript = KStandardDirs::findExe("kopete_latexconvert.sh"); slotSettingsChanged(); } LatexPlugin::~LatexPlugin() { s_pluginStatic = 0L; } LatexPlugin* LatexPlugin::plugin() { return s_pluginStatic ; } LatexPlugin* LatexPlugin::s_pluginStatic = 0L; void LatexPlugin::slotMessageAboutToShow( Kopete::Message& msg ) { QString mMagick = KStandardDirs::findExe("convert"); if ( mMagick.isEmpty() ) { // show just once if ( !mMagickNotFoundShown ) { KMessageBox::queuedMessageBox( Kopete::UI::Global::mainWidget(), KMessageBox::Error, i18n("I cannot find the Magick convert program.\nconvert is required to render the Latex formulas.\nPlease go to www.imagemagick.org or to your distribution site and get the right package.") ); mMagickNotFoundShown = true; } // dont try to parse if convert is not installed return; } QString messageText = msg.plainBody(); if( !messageText.contains("$$")) return; //kdDebug() << k_funcinfo << " Using converter: " << m_convScript << endl; // /\[([^]]).*?\[/$1\]/ // \$\$.+?\$\$ // this searches for $$formula$$ QRegExp rg("\\$\\$.+\\$\\$"); rg.setMinimal(true); // this searches for [latex]formula[/latex] //QRegExp rg("\\[([^]\]).*?\\[/$1\\]"); int pos = 0; QMap<QString, QString> replaceMap; while (pos >= 0 && (unsigned int)pos < messageText.length()) { // kdDebug() << k_funcinfo << " searching pos: " << pos << endl; pos = rg.search(messageText, pos); if (pos >= 0 ) { QString match = rg.cap(0); pos += rg.matchedLength(); QString formul=match; if(!securityCheck(formul)) continue; QString fileName=handleLatex(formul.replace("$$","")); // get the image and encode it with base64 #if ENCODED_IMAGE_MODE QImage renderedImage( fileName ); if ( !renderedImage.isNull() ) { QByteArray ba; QBuffer buffer( ba ); buffer.open( IO_WriteOnly ); renderedImage.save( &buffer, "PNG" ); QString imageURL = QString::fromLatin1("data:image/png;base64,%1").arg( KCodecs::base64Encode( ba ) ); replaceMap[Kopete::Message::escape(match)] = imageURL; } #else replaceMap[Kopete::Message::escape(match)] = fileName; #endif } } if(replaceMap.isEmpty()) //we haven't found any latex strings return; messageText=Kopete::Message::escape(messageText); for (QMap<QString,QString>::ConstIterator it = replaceMap.begin(); it != replaceMap.end(); ++it) { QString escapedLATEX=it.key(); escapedLATEX.replace("\"","&quot;"); //we need the escape quotes because that string will be in a title="" argument messageText.replace(it.key(), " <img src=\"" + (*it) + "\" alt=\"" + escapedLATEX +"\" title=\"" + escapedLATEX +"\" /> "); } msg.setBody( messageText, Kopete::Message::RichText ); } void LatexPlugin::slotMessageAboutToSend( Kopete::Message& msg) { //disabled because to work correctly, we need to find what special has the gif we can send over MSN #if 0 KConfig *config = KGlobal::config(); config->setGroup("Latex Plugin"); if(!config->readBoolEntry("ParseOutgoing", false)) return; QString messageText = msg.plainBody(); if( !messageText.contains("$$")) return; /* if( msg.from()->protocol()->pluginId()!="MSNProtocol" ) return;*/ // this searches for $$formula$$ QRegExp rg("^\\s*\\$\\$([^$]+)\\$\\$\\s*$"); if( rg.search(messageText) != -1 ) { QString latexFormula = rg.cap(1); if(!securityCheck( latexFormula )) return; QString url = handleLatex(latexFormula); if(!url.isNull()) { QString escapedLATEX= QStyleSheet::escape(messageText).replace("\"","&quot;"); QString messageText="<img src=\"" + url + "\" alt=\"" + escapedLATEX + "\" title=\"" + escapedLATEX +"\" />"; msg.setBody( messageText, Kopete::Message::RichText ); } } #endif } QString LatexPlugin::handleLatex(const QString &latexFormula) { KTempFile *tempFile=new KTempFile( locateLocal( "tmp", "kopetelatex-" ), ".png" ); tempFile->setAutoDelete(true); m_tempFiles.append(tempFile); m_tempFiles.setAutoDelete(true); QString fileName = tempFile->name(); KProcess p; QString argumentRes = "-r %1x%2"; QString argumentOut = "-o %1"; //QString argumentFormat = "-fgif"; //we uses gif format because MSN only handle gif int hDPI, vDPI; hDPI = LatexConfig::self()->horizontalDPI(); vDPI = LatexConfig::self()->verticalDPI(); p << m_convScript << argumentRes.arg(QString::number(hDPI), QString::number(vDPI)) << argumentOut.arg(fileName) /*<< argumentFormat*/ << latexFormula ; kdDebug() << k_funcinfo << " Rendering " << m_convScript << " " << argumentRes.arg(QString::number(hDPI), QString::number(vDPI)) << " " << argumentOut.arg(fileName) << endl; // FIXME our sucky sync filter API limitations :-) p.start(KProcess::Block); return fileName; } bool LatexPlugin::securityCheck(const QString &latexFormula) { return !latexFormula.contains(QRegExp("\\\\(def|let|futurelet|newcommand|renewcomment|else|fi|write|input|include" "|chardef|catcode|makeatletter|noexpand|toksdef|every|errhelp|errorstopmode|scrollmode|nonstopmode|batchmode" "|read|csname|newhelp|relax|afterground|afterassignment|expandafter|noexpand|special|command|loop|repeat|toks" "|output|line|mathcode|name|item|section|mbox|DeclareRobustCommand)[^a-zA-Z]")); } void LatexPlugin::slotSettingsChanged() { LatexConfig::self()->readConfig(); } #include "latexplugin.moc" // vim: set noet ts=4 sts=4 sw=4: <|endoftext|>
<commit_before>#include "taichi/backends/vulkan/aot_module_builder_impl.h" #include <fstream> #include <type_traits> #include "taichi/codegen/spirv/spirv_codegen.h" namespace taichi { namespace lang { namespace vulkan { AotModuleBuilderImpl::AotModuleBuilderImpl( const std::vector<CompiledSNodeStructs> &compiled_structs) : compiled_structs_(compiled_structs) { aot_target_device_ = std::make_unique<AotTargetDevice>(Arch::vulkan); } uint32_t AotModuleBuilderImpl::to_vk_dtype_enum(DataType dt) { if (dt == PrimitiveType::u64) { return 0; } else if (dt == PrimitiveType::i64) { return 1; } else if (dt == PrimitiveType::u32) { return 2; } else if (dt == PrimitiveType::i32) { return 3; } else if (dt == PrimitiveType::u16) { return 4; } else if (dt == PrimitiveType::i16) { return 5; } else if (dt == PrimitiveType::u8) { return 6; } else if (dt == PrimitiveType::i8) { return 7; } else if (dt == PrimitiveType::f64) { return 8; } else if (dt == PrimitiveType::f32) { return 9; } else { TI_NOT_IMPLEMENTED } } void AotModuleBuilderImpl::write_spv_file( const std::string &output_dir, const TaskAttributes &k, const std::vector<uint32_t> &source_code) const { const std::string spv_path = fmt::format("{}/{}.spv", output_dir, k.name); std::ofstream fs(spv_path, std::ios_base::binary | std::ios::trunc); fs.write((char *)source_code.data(), source_code.size() * sizeof(uint32_t)); fs.close(); } std::vector<uint32_t> AotModuleBuilderImpl::read_spv_file( const std::string &output_dir, const TaskAttributes &k) { const std::string spv_path = fmt::format("{}/{}.spv", output_dir, k.name); std::vector<uint32_t> source_code; std::ifstream fs(spv_path, std::ios_base::binary | std::ios::ate); size_t size = fs.tellg(); fs.seekg(0, std::ios::beg); source_code.resize(size / sizeof(uint32_t)); fs.read((char *)source_code.data(), size); fs.close(); return source_code; } void AotModuleBuilderImpl::dump(const std::string &output_dir, const std::string &filename) const { TI_WARN_IF(!filename.empty(), "Filename prefix is ignored on vulkan backend."); const std::string bin_path = fmt::format("{}/metadata.tcb", output_dir); write_to_binary_file(ti_aot_data_, bin_path); // Json format doesn't support multiple line strings. for (int i = 0; i < ti_aot_data_.kernels.size(); ++i) { auto k = ti_aot_data_.kernels[i]; for (int j = 0; j < k.tasks_attribs.size(); ++j) { write_spv_file(output_dir, k.tasks_attribs[j], ti_aot_data_.spirv_codes[i][j]); } } const std::string txt_path = fmt::format("{}/metadata.json", output_dir); TextSerializer ts; ts.serialize_to_json("aot_data", ti_aot_data_); ts.write_to_file(txt_path); } void AotModuleBuilderImpl::load(const std::string &output_dir) { const std::string bin_path = fmt::format("{}/metadata.tcb", output_dir); read_from_binary_file(ti_aot_data_, bin_path); for (int i = 0; i < ti_aot_data_.kernels.size(); ++i) { auto k = ti_aot_data_.kernels[i]; std::vector<std::vector<uint32_t>> spirv_sources_codes; for (int j = 0; j < k.tasks_attribs.size(); ++j) { std::vector<uint32_t> res = read_spv_file(output_dir, k.tasks_attribs[j]); spirv_sources_codes.push_back(res); } VkRuntime::RegisterParams params; params.kernel_attribs = ti_aot_data_.kernels[i]; params.task_spirv_source_codes = spirv_sources_codes; runtime_->register_taichi_kernel(params); } } void AotModuleBuilderImpl::add_per_backend(const std::string &identifier, Kernel *kernel) { spirv::lower(kernel); auto compiled = run_codegen(kernel, aot_target_device_.get(), compiled_structs_); ti_aot_data_.kernels.push_back(compiled.kernel_attribs); ti_aot_data_.spirv_codes.push_back(compiled.task_spirv_source_codes); } void AotModuleBuilderImpl::add_field_per_backend(const std::string &identifier, const SNode *rep_snode, bool is_scalar, DataType dt, std::vector<int> shape, int row_num, int column_num) { // Note that currently we only support adding dense fields in AOT for all // backends. In opengl backend we only error out when a non dense field is // added to the aot module, but in metal backend we error out earlier when // constructing aot module. Ideally we will unify this behavior but it doesn't // matter too much for now. TI_ERROR_IF(!all_fields_are_dense_in_container(rep_snode->parent), "AOT: only supports dense field"); const auto &dense_desc = compiled_structs_[0].snode_descriptors.at(rep_snode->parent->id); CompiledFieldData field_data; field_data.field_name = identifier; field_data.is_scalar = is_scalar; field_data.dtype = to_vk_dtype_enum(dt); field_data.dtype_name = dt.to_string(); field_data.shape = shape; field_data.mem_offset_in_parent = dense_desc.mem_offset_in_parent_cell; field_data.row_num = row_num; field_data.column_num = column_num; ti_aot_data_.fields.push_back(field_data); } void AotModuleBuilderImpl::add_per_backend_tmpl(const std::string &identifier, const std::string &key, Kernel *kernel) { } } // namespace vulkan } // namespace lang } // namespace taichi <commit_msg>[bug] Temporarily remove runtime_ usage in aot_module_builder. (#3746)<commit_after>#include "taichi/backends/vulkan/aot_module_builder_impl.h" #include <fstream> #include <type_traits> #include "taichi/codegen/spirv/spirv_codegen.h" namespace taichi { namespace lang { namespace vulkan { AotModuleBuilderImpl::AotModuleBuilderImpl( const std::vector<CompiledSNodeStructs> &compiled_structs) : compiled_structs_(compiled_structs) { aot_target_device_ = std::make_unique<AotTargetDevice>(Arch::vulkan); } uint32_t AotModuleBuilderImpl::to_vk_dtype_enum(DataType dt) { if (dt == PrimitiveType::u64) { return 0; } else if (dt == PrimitiveType::i64) { return 1; } else if (dt == PrimitiveType::u32) { return 2; } else if (dt == PrimitiveType::i32) { return 3; } else if (dt == PrimitiveType::u16) { return 4; } else if (dt == PrimitiveType::i16) { return 5; } else if (dt == PrimitiveType::u8) { return 6; } else if (dt == PrimitiveType::i8) { return 7; } else if (dt == PrimitiveType::f64) { return 8; } else if (dt == PrimitiveType::f32) { return 9; } else { TI_NOT_IMPLEMENTED } } void AotModuleBuilderImpl::write_spv_file( const std::string &output_dir, const TaskAttributes &k, const std::vector<uint32_t> &source_code) const { const std::string spv_path = fmt::format("{}/{}.spv", output_dir, k.name); std::ofstream fs(spv_path, std::ios_base::binary | std::ios::trunc); fs.write((char *)source_code.data(), source_code.size() * sizeof(uint32_t)); fs.close(); } std::vector<uint32_t> AotModuleBuilderImpl::read_spv_file( const std::string &output_dir, const TaskAttributes &k) { const std::string spv_path = fmt::format("{}/{}.spv", output_dir, k.name); std::vector<uint32_t> source_code; std::ifstream fs(spv_path, std::ios_base::binary | std::ios::ate); size_t size = fs.tellg(); fs.seekg(0, std::ios::beg); source_code.resize(size / sizeof(uint32_t)); fs.read((char *)source_code.data(), size); fs.close(); return source_code; } void AotModuleBuilderImpl::dump(const std::string &output_dir, const std::string &filename) const { TI_WARN_IF(!filename.empty(), "Filename prefix is ignored on vulkan backend."); const std::string bin_path = fmt::format("{}/metadata.tcb", output_dir); write_to_binary_file(ti_aot_data_, bin_path); // Json format doesn't support multiple line strings. for (int i = 0; i < ti_aot_data_.kernels.size(); ++i) { auto k = ti_aot_data_.kernels[i]; for (int j = 0; j < k.tasks_attribs.size(); ++j) { write_spv_file(output_dir, k.tasks_attribs[j], ti_aot_data_.spirv_codes[i][j]); } } const std::string txt_path = fmt::format("{}/metadata.json", output_dir); TextSerializer ts; ts.serialize_to_json("aot_data", ti_aot_data_); ts.write_to_file(txt_path); } void AotModuleBuilderImpl::load(const std::string &output_dir) { const std::string bin_path = fmt::format("{}/metadata.tcb", output_dir); read_from_binary_file(ti_aot_data_, bin_path); for (int i = 0; i < ti_aot_data_.kernels.size(); ++i) { auto k = ti_aot_data_.kernels[i]; std::vector<std::vector<uint32_t>> spirv_sources_codes; for (int j = 0; j < k.tasks_attribs.size(); ++j) { std::vector<uint32_t> res = read_spv_file(output_dir, k.tasks_attribs[j]); spirv_sources_codes.push_back(res); } VkRuntime::RegisterParams params; params.kernel_attribs = ti_aot_data_.kernels[i]; params.task_spirv_source_codes = spirv_sources_codes; } } void AotModuleBuilderImpl::add_per_backend(const std::string &identifier, Kernel *kernel) { spirv::lower(kernel); auto compiled = run_codegen(kernel, aot_target_device_.get(), compiled_structs_); ti_aot_data_.kernels.push_back(compiled.kernel_attribs); ti_aot_data_.spirv_codes.push_back(compiled.task_spirv_source_codes); } void AotModuleBuilderImpl::add_field_per_backend(const std::string &identifier, const SNode *rep_snode, bool is_scalar, DataType dt, std::vector<int> shape, int row_num, int column_num) { // Note that currently we only support adding dense fields in AOT for all // backends. In opengl backend we only error out when a non dense field is // added to the aot module, but in metal backend we error out earlier when // constructing aot module. Ideally we will unify this behavior but it doesn't // matter too much for now. TI_ERROR_IF(!all_fields_are_dense_in_container(rep_snode->parent), "AOT: only supports dense field"); const auto &dense_desc = compiled_structs_[0].snode_descriptors.at(rep_snode->parent->id); CompiledFieldData field_data; field_data.field_name = identifier; field_data.is_scalar = is_scalar; field_data.dtype = to_vk_dtype_enum(dt); field_data.dtype_name = dt.to_string(); field_data.shape = shape; field_data.mem_offset_in_parent = dense_desc.mem_offset_in_parent_cell; field_data.row_num = row_num; field_data.column_num = column_num; ti_aot_data_.fields.push_back(field_data); } void AotModuleBuilderImpl::add_per_backend_tmpl(const std::string &identifier, const std::string &key, Kernel *kernel) { } } // namespace vulkan } // namespace lang } // namespace taichi <|endoftext|>
<commit_before>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ // See docs in ../ops/math_ops.cc. // This file uses oneDNN library for acceleration of Batch Matrix-Matrix // Multiplication (MatMul) operations. We currently register this kernel only // for oneDNN supported data types (float, bfloat16). The maximum number of // dimensions (rank) for output tensor is 12 in oneDNN. If output tensor rank // exceeds 12, we fallback to Eigen library based kernel. #define EIGEN_USE_THREADS #if defined(INTEL_MKL) #include "tensorflow/core/framework/op.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/register_types.h" #include "tensorflow/core/framework/tensor.h" #include "tensorflow/core/framework/tensor_shape.h" #include "tensorflow/core/framework/type_traits.h" #include "tensorflow/core/framework/types.h" #include "tensorflow/core/kernels/batch_matmul_op_impl.h" #include "tensorflow/core/kernels/fill_functor.h" #include "tensorflow/core/kernels/mkl/mkl_matmul_ops_common.h" #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/platform/types.h" #include "tensorflow/core/util/matmul_bcast.h" #include "tensorflow/core/util/mkl_util.h" #include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor" namespace tensorflow { typedef Eigen::ThreadPoolDevice CPUDevice; // The third parameter v2_bcast is set to true if we are using V2 otherwise // we set it to false. template <typename Device, typename Scalar, bool v2_bcast> class BatchMatMulMkl : public OpKernel { public: explicit BatchMatMulMkl(OpKernelConstruction* context) : OpKernel(context), eigen_batch_mm_v2_(context) { OP_REQUIRES_OK(context, context->GetAttr("adj_x", &adj_x_)); OP_REQUIRES_OK(context, context->GetAttr("adj_y", &adj_y_)); } virtual ~BatchMatMulMkl() {} void Compute(OpKernelContext* ctx) override { const Tensor& lhs = ctx->input(0); const Tensor& rhs = ctx->input(1); if (!v2_bcast) { // Using V1, so check to make sure lhs and rhs dimensions are correct and // no broadcasting is needed. OP_REQUIRES(ctx, lhs.dims() == rhs.dims(), errors::InvalidArgument("lhs and rhs has different ndims: ", lhs.shape().DebugString(), " vs. ", rhs.shape().DebugString())); const int ndims = lhs.dims(); OP_REQUIRES( ctx, ndims >= 2, errors::InvalidArgument("lhs and rhs ndims must be >= 2: ", ndims)); for (int i = 0; i < ndims - 2; ++i) { OP_REQUIRES(ctx, lhs.dim_size(i) == rhs.dim_size(i), errors::InvalidArgument( "lhs.dim(", i, ") and rhs.dim(", i, ") must be the same: ", lhs.shape().DebugString(), " vs ", rhs.shape().DebugString())); } } else { OP_REQUIRES( ctx, lhs.dims() >= 2, errors::InvalidArgument("In[0] ndims must be >= 2: ", lhs.dims())); OP_REQUIRES( ctx, rhs.dims() >= 2, errors::InvalidArgument("In[1] ndims must be >= 2: ", rhs.dims())); } // lhs and rhs can have different dimensions const auto ndims_lhs = lhs.dims(); const auto ndims_rhs = rhs.dims(); // Get broadcast info MatMulBCast bcast(lhs.shape().dim_sizes(), rhs.shape().dim_sizes()); OP_REQUIRES( ctx, bcast.IsValid(), errors::InvalidArgument( "In[0] and In[1] must have compatible batch dimensions: ", lhs.shape().DebugString(), " vs. ", rhs.shape().DebugString())); TensorShape out_shape = bcast.output_batch_shape(); auto lhs_rows = lhs.dim_size(ndims_lhs - 2); auto lhs_cols = lhs.dim_size(ndims_lhs - 1); auto rhs_rows = rhs.dim_size(ndims_rhs - 2); auto rhs_cols = rhs.dim_size(ndims_rhs - 1); if (adj_x_) std::swap(lhs_rows, lhs_cols); if (adj_y_) std::swap(rhs_rows, rhs_cols); OP_REQUIRES(ctx, lhs_cols == rhs_rows, errors::InvalidArgument( "lhs mismatch rhs shape: ", lhs_cols, " vs. ", rhs_rows, ": ", lhs.shape().DebugString(), " ", rhs.shape().DebugString(), " ", adj_x_, " ", adj_y_)); out_shape.AddDim(lhs_rows); out_shape.AddDim(rhs_cols); // The maximum number of dimensions for a tensor in DNNL is 12. OP_REQUIRES(ctx, out_shape.dims() <= 12, errors::InvalidArgument( "Rank of output tensor is required as <= 12, ", "but is ", out_shape.dims(), ". Current implementation supports upto ", "rank 12 tensors.")); Tensor* out = nullptr; OP_REQUIRES_OK(ctx, ctx->allocate_output(0, out_shape, &out)); if (out->NumElements() == 0) { return; } if (lhs.NumElements() == 0 || rhs.NumElements() == 0) { functor::SetZeroFunctor<Device, Scalar> f; f(ctx->eigen_device<Device>(), out->flat<Scalar>()); return; } // Compute parameters for DNNL matmul primitive. auto params = CreateMatMulParams(lhs.shape(), rhs.shape(), out_shape); // Create or retrieve matmul primitive from cache. MklMatMulPrimitive<Scalar>* matmul_prim = MklMatMulPrimitiveFactory<Scalar>::Get( *params, false /* value for do_not_cache */); // Execute matmul primitive. std::shared_ptr<stream> cpu_stream; cpu_stream.reset(CreateStream(ctx, matmul_prim->GetEngine())); matmul_prim->Execute(lhs.flat<Scalar>().data(), rhs.flat<Scalar>().data(), out->flat<Scalar>().data(), cpu_stream); } private: bool adj_x_; bool adj_y_; BatchMatMulV2Op<CPUDevice, Scalar> eigen_batch_mm_v2_; using dims = dnnl::memory::dims; // This method makes the rank (ndims) of input same as the output by creating // new axes to the input. For example, if input shape is [a, b, c, d] and // output shape is [e, f, g, h, i, j], then the reshaped input would have a // shape of [1, 1, a, b, c, d]. void ExpandInputDimsToOutputShape(const TensorShape& input_shape, const TensorShape& output_shape, dims* reshaped_dims) { auto ndims_input = input_shape.dims(); auto ndims_output = output_shape.dims(); auto dim_offset = ndims_output - ndims_input; DCHECK(dim_offset > 0); reshaped_dims->clear(); reshaped_dims->resize(ndims_output, 1); auto input_dims = input_shape.dim_sizes(); for (int dim_idx = 0; dim_idx < ndims_input; ++dim_idx) reshaped_dims->at(dim_idx + dim_offset) = input_dims[dim_idx]; } std::unique_ptr<MklMatMulParams> CreateMatMulParams( const TensorShape& lhs_shape, const TensorShape& rhs_shape, const TensorShape& out_shape) { const auto ndims_lhs = lhs_shape.dims(); const auto ndims_rhs = rhs_shape.dims(); const auto ndims_out = out_shape.dims(); auto lhs_dims = TFShapeToMklDnnDims(lhs_shape); auto rhs_dims = TFShapeToMklDnnDims(rhs_shape); auto out_dims = TFShapeToMklDnnDims(out_shape); // DNNL matmul_primitive requires ranks of inputs and output to be same. // Create dnnl::memory::dims for inputs and output of same rank. // It is assumed here that MatMulBCast object creates output_batch_shape as // a conforming superset of input batch shapes, i.e., ndims_out >= // ndims_lhs and ndims_out >= ndims_lhs. if (ndims_lhs < ndims_out) { ExpandInputDimsToOutputShape(lhs_shape, out_shape, &lhs_dims); } if (ndims_rhs < ndims_out) { ExpandInputDimsToOutputShape(rhs_shape, out_shape, &rhs_dims); } using dim = dnnl::memory::dim; dim m; // number of rows in x dim k; // number of columns in x dim n; // number of columns in y auto lhs_strides = CalculateTFStrides(lhs_dims); auto rhs_strides = CalculateTFStrides(rhs_dims); auto out_strides = CalculateTFStrides(out_dims); if (adj_x_) { int m_idx = ndims_out - 1; int k_idx = ndims_out - 2; m = lhs_dims[m_idx]; k = lhs_dims[k_idx]; std::swap(lhs_dims[m_idx], lhs_dims[k_idx]); lhs_strides[m_idx] = m; lhs_strides[k_idx] = 1; } if (adj_y_) { int k_idx = ndims_out - 1; int n_idx = ndims_out - 2; k = rhs_dims[k_idx]; n = rhs_dims[n_idx]; std::swap(rhs_dims[k_idx], rhs_dims[n_idx]); rhs_strides[k_idx] = k; rhs_strides[n_idx] = 1; } return std::make_unique<MklMatMulParams>( lhs_dims, rhs_dims, out_dims, lhs_strides, rhs_strides, out_strides); } }; #define REGISTER_BATCH_MATMUL_MKL(TYPE) \ REGISTER_KERNEL_BUILDER(Name("_MklBatchMatMul") \ .Device(DEVICE_CPU) \ .TypeConstraint<TYPE>("T") \ .Label(mkl_op_registry::kMklNameChangeOpLabel), \ BatchMatMulMkl<CPUDevice, TYPE, false>) #define REGISTER_BATCH_MATMUL_MKL_V2(TYPE) \ REGISTER_KERNEL_BUILDER(Name("_MklBatchMatMulV2") \ .Device(DEVICE_CPU) \ .TypeConstraint<TYPE>("T") \ .Label(mkl_op_registry::kMklNameChangeOpLabel), \ BatchMatMulMkl<CPUDevice, TYPE, true>) #ifdef ENABLE_MKL TF_CALL_float(REGISTER_BATCH_MATMUL_MKL); TF_CALL_float(REGISTER_BATCH_MATMUL_MKL_V2); TF_CALL_bfloat16(REGISTER_BATCH_MATMUL_MKL); TF_CALL_bfloat16(REGISTER_BATCH_MATMUL_MKL_V2); #endif // ENABLE_MKL } // end namespace tensorflow #endif <commit_msg>Addressed review comments.<commit_after>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ // See docs in ../ops/math_ops.cc. // This file uses oneDNN library for acceleration of Batch Matrix-Matrix // Multiplication (MatMul) operations. We currently register this kernel only // for oneDNN supported data types (float, bfloat16). The maximum number of // dimensions (rank) for output tensor is 12 in oneDNN. If output tensor rank // exceeds 12, we fall back to Eigen library based kernel. #define EIGEN_USE_THREADS #if defined(INTEL_MKL) #include "tensorflow/core/framework/op.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/register_types.h" #include "tensorflow/core/framework/tensor.h" #include "tensorflow/core/framework/tensor_shape.h" #include "tensorflow/core/framework/type_traits.h" #include "tensorflow/core/framework/types.h" #include "tensorflow/core/kernels/batch_matmul_op_impl.h" #include "tensorflow/core/kernels/fill_functor.h" #include "tensorflow/core/kernels/mkl/mkl_matmul_ops_common.h" #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/platform/types.h" #include "tensorflow/core/util/matmul_bcast.h" #include "tensorflow/core/util/mkl_util.h" #include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor" namespace tensorflow { typedef Eigen::ThreadPoolDevice CPUDevice; // The third parameter v2_bcast is set to true if we are using V2 otherwise // we set it to false. template <typename Device, typename Scalar, bool v2_bcast> class BatchMatMulMkl : public OpKernel { public: explicit BatchMatMulMkl(OpKernelConstruction* context) : OpKernel(context), eigen_batch_mm_v2_(context) { OP_REQUIRES_OK(context, context->GetAttr("adj_x", &adj_x_)); OP_REQUIRES_OK(context, context->GetAttr("adj_y", &adj_y_)); } virtual ~BatchMatMulMkl() {} void Compute(OpKernelContext* ctx) override { const Tensor& lhs = ctx->input(0); const Tensor& rhs = ctx->input(1); if (!v2_bcast) { // Using V1, so check to make sure lhs and rhs dimensions are correct and // no broadcasting is needed. OP_REQUIRES(ctx, lhs.dims() == rhs.dims(), errors::InvalidArgument("lhs and rhs has different ndims: ", lhs.shape().DebugString(), " vs. ", rhs.shape().DebugString())); const int ndims = lhs.dims(); OP_REQUIRES( ctx, ndims >= 2, errors::InvalidArgument("lhs and rhs ndims must be >= 2: ", ndims)); for (int i = 0; i < ndims - 2; ++i) { OP_REQUIRES(ctx, lhs.dim_size(i) == rhs.dim_size(i), errors::InvalidArgument( "lhs.dim(", i, ") and rhs.dim(", i, ") must be the same: ", lhs.shape().DebugString(), " vs ", rhs.shape().DebugString())); } } else { OP_REQUIRES( ctx, lhs.dims() >= 2, errors::InvalidArgument("In[0] ndims must be >= 2: ", lhs.dims())); OP_REQUIRES( ctx, rhs.dims() >= 2, errors::InvalidArgument("In[1] ndims must be >= 2: ", rhs.dims())); } // lhs and rhs can have different dimensions const auto ndims_lhs = lhs.dims(); const auto ndims_rhs = rhs.dims(); // Get broadcast info MatMulBCast bcast(lhs.shape().dim_sizes(), rhs.shape().dim_sizes()); OP_REQUIRES( ctx, bcast.IsValid(), errors::InvalidArgument( "In[0] and In[1] must have compatible batch dimensions: ", lhs.shape().DebugString(), " vs. ", rhs.shape().DebugString())); TensorShape out_shape = bcast.output_batch_shape(); auto lhs_rows = lhs.dim_size(ndims_lhs - 2); auto lhs_cols = lhs.dim_size(ndims_lhs - 1); auto rhs_rows = rhs.dim_size(ndims_rhs - 2); auto rhs_cols = rhs.dim_size(ndims_rhs - 1); if (adj_x_) std::swap(lhs_rows, lhs_cols); if (adj_y_) std::swap(rhs_rows, rhs_cols); OP_REQUIRES(ctx, lhs_cols == rhs_rows, errors::InvalidArgument( "lhs mismatch rhs shape: ", lhs_cols, " vs. ", rhs_rows, ": ", lhs.shape().DebugString(), " ", rhs.shape().DebugString(), " ", adj_x_, " ", adj_y_)); out_shape.AddDim(lhs_rows); out_shape.AddDim(rhs_cols); // The maximum number of dimensions for a tensor in DNNL is 12. OP_REQUIRES( ctx, out_shape.dims() <= 12, errors::InvalidArgument( "Rank of output tensor must be <= 12, but is ", out_shape.dims(), ". Current implementation supports upto rank 12 tensors.")); Tensor* out = nullptr; OP_REQUIRES_OK(ctx, ctx->allocate_output(0, out_shape, &out)); if (out->NumElements() == 0) { return; } if (lhs.NumElements() == 0 || rhs.NumElements() == 0) { functor::SetZeroFunctor<Device, Scalar> f; f(ctx->eigen_device<Device>(), out->flat<Scalar>()); return; } // Compute parameters for DNNL matmul primitive. auto params = CreateMatMulParams(lhs.shape(), rhs.shape(), out_shape); // Create or retrieve matmul primitive from cache. MklMatMulPrimitive<Scalar>* matmul_prim = MklMatMulPrimitiveFactory<Scalar>::Get( *params, false /* value for do_not_cache */); // Execute matmul primitive. std::shared_ptr<stream> cpu_stream; cpu_stream.reset(CreateStream(ctx, matmul_prim->GetEngine())); matmul_prim->Execute(lhs.flat<Scalar>().data(), rhs.flat<Scalar>().data(), out->flat<Scalar>().data(), cpu_stream); } private: bool adj_x_; bool adj_y_; BatchMatMulV2Op<CPUDevice, Scalar> eigen_batch_mm_v2_; using dims = dnnl::memory::dims; // This method makes the rank (ndims) of input same as the output by adding // new axes to the input. For example, if input shape is [a, b, c, d] and // output shape is [e, f, g, h, i, j], then the reshaped input would have a // shape of [1, 1, a, b, c, d]. void ExpandInputDimsToOutputShape(const TensorShape& input_shape, const TensorShape& output_shape, dims* reshaped_dims) { auto ndims_input = input_shape.dims(); auto ndims_output = output_shape.dims(); auto dim_offset = ndims_output - ndims_input; DCHECK(dim_offset > 0); reshaped_dims->clear(); reshaped_dims->resize(ndims_output, 1); auto input_dims = input_shape.dim_sizes(); for (int dim_idx = 0; dim_idx < ndims_input; ++dim_idx) reshaped_dims->at(dim_idx + dim_offset) = input_dims[dim_idx]; } std::unique_ptr<MklMatMulParams> CreateMatMulParams( const TensorShape& lhs_shape, const TensorShape& rhs_shape, const TensorShape& out_shape) { const auto ndims_lhs = lhs_shape.dims(); const auto ndims_rhs = rhs_shape.dims(); const auto ndims_out = out_shape.dims(); auto lhs_dims = TFShapeToMklDnnDims(lhs_shape); auto rhs_dims = TFShapeToMklDnnDims(rhs_shape); auto out_dims = TFShapeToMklDnnDims(out_shape); // DNNL matmul_primitive requires ranks of inputs and output to be same. // Create dnnl::memory::dims for inputs and output of same rank. // It is assumed here that MatMulBCast object creates output_batch_shape as // a conforming superset of input batch shapes, i.e., ndims_out >= // ndims_lhs and ndims_out >= ndims_rhs. if (ndims_lhs < ndims_out) { ExpandInputDimsToOutputShape(lhs_shape, out_shape, &lhs_dims); } if (ndims_rhs < ndims_out) { ExpandInputDimsToOutputShape(rhs_shape, out_shape, &rhs_dims); } using dim = dnnl::memory::dim; dim m; // number of rows in x dim k; // number of columns in x dim n; // number of columns in y auto lhs_strides = CalculateTFStrides(lhs_dims); auto rhs_strides = CalculateTFStrides(rhs_dims); auto out_strides = CalculateTFStrides(out_dims); if (adj_x_) { int m_idx = ndims_out - 1; int k_idx = ndims_out - 2; m = lhs_dims[m_idx]; k = lhs_dims[k_idx]; std::swap(lhs_dims[m_idx], lhs_dims[k_idx]); lhs_strides[m_idx] = m; lhs_strides[k_idx] = 1; } if (adj_y_) { int k_idx = ndims_out - 1; int n_idx = ndims_out - 2; k = rhs_dims[k_idx]; n = rhs_dims[n_idx]; std::swap(rhs_dims[k_idx], rhs_dims[n_idx]); rhs_strides[k_idx] = k; rhs_strides[n_idx] = 1; } return std::make_unique<MklMatMulParams>( lhs_dims, rhs_dims, out_dims, lhs_strides, rhs_strides, out_strides); } }; #define REGISTER_BATCH_MATMUL_MKL(TYPE) \ REGISTER_KERNEL_BUILDER(Name("_MklBatchMatMul") \ .Device(DEVICE_CPU) \ .TypeConstraint<TYPE>("T") \ .Label(mkl_op_registry::kMklNameChangeOpLabel), \ BatchMatMulMkl<CPUDevice, TYPE, false>) #define REGISTER_BATCH_MATMUL_MKL_V2(TYPE) \ REGISTER_KERNEL_BUILDER(Name("_MklBatchMatMulV2") \ .Device(DEVICE_CPU) \ .TypeConstraint<TYPE>("T") \ .Label(mkl_op_registry::kMklNameChangeOpLabel), \ BatchMatMulMkl<CPUDevice, TYPE, true>) #ifdef ENABLE_MKL TF_CALL_float(REGISTER_BATCH_MATMUL_MKL); TF_CALL_float(REGISTER_BATCH_MATMUL_MKL_V2); TF_CALL_bfloat16(REGISTER_BATCH_MATMUL_MKL); TF_CALL_bfloat16(REGISTER_BATCH_MATMUL_MKL_V2); #endif // ENABLE_MKL } // end namespace tensorflow #endif <|endoftext|>
<commit_before>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/lite/delegates/gpu/cl/opencl_wrapper.h" #include <dlfcn.h> #include "absl/strings/str_cat.h" #include "tensorflow/lite/delegates/gpu/common/status.h" namespace tflite { namespace gpu { namespace cl { #define LoadFunction(function) \ if (is_pixel) { \ function = reinterpret_cast<PFN_##function>(loadOpenCLPointer(#function)); \ } else { \ function = reinterpret_cast<PFN_##function>(dlsym(libopencl, #function)); \ } absl::Status LoadOpenCL() { void* libopencl = dlopen("libOpenCL.so", RTLD_NOW | RTLD_LOCAL); if (libopencl) { LoadOpenCLFunctions(libopencl, false); return absl::OkStatus(); } else { // Pixel phone? libopencl = dlopen("libOpenCL-pixel.so", RTLD_NOW | RTLD_LOCAL); if (libopencl) { typedef void (*enableOpenCL_t)(); enableOpenCL_t enableOpenCL = reinterpret_cast<enableOpenCL_t>(dlsym(libopencl, "enableOpenCL")); enableOpenCL(); LoadOpenCLFunctions(libopencl, true); return absl::OkStatus(); } else { return absl::UnknownError( absl::StrCat("OpenCL library not loaded - ", dlerror())); } } } void LoadOpenCLFunctions(void* libopencl, bool is_pixel) { typedef void* (*loadOpenCLPointer_t)(const char* name); loadOpenCLPointer_t loadOpenCLPointer; if (is_pixel) { loadOpenCLPointer = reinterpret_cast<loadOpenCLPointer_t>( dlsym(libopencl, "loadOpenCLPointer")); } LoadFunction(clGetPlatformIDs); LoadFunction(clGetPlatformInfo); LoadFunction(clGetDeviceIDs); LoadFunction(clGetDeviceInfo); LoadFunction(clCreateSubDevices); LoadFunction(clRetainDevice); LoadFunction(clReleaseDevice); LoadFunction(clCreateContext); LoadFunction(clCreateContextFromType); LoadFunction(clRetainContext); LoadFunction(clReleaseContext); LoadFunction(clGetContextInfo); LoadFunction(clCreateCommandQueueWithProperties); LoadFunction(clRetainCommandQueue); LoadFunction(clReleaseCommandQueue); LoadFunction(clGetCommandQueueInfo); LoadFunction(clCreateBuffer); LoadFunction(clCreateSubBuffer); LoadFunction(clCreateImage); LoadFunction(clCreatePipe); LoadFunction(clRetainMemObject); LoadFunction(clReleaseMemObject); LoadFunction(clGetSupportedImageFormats); LoadFunction(clGetMemObjectInfo); LoadFunction(clGetImageInfo); LoadFunction(clGetPipeInfo); LoadFunction(clSetMemObjectDestructorCallback); LoadFunction(clSVMAlloc); LoadFunction(clSVMFree); LoadFunction(clCreateSamplerWithProperties); LoadFunction(clRetainSampler); LoadFunction(clReleaseSampler); LoadFunction(clGetSamplerInfo); LoadFunction(clCreateProgramWithSource); LoadFunction(clCreateProgramWithBinary); LoadFunction(clCreateProgramWithBuiltInKernels); LoadFunction(clRetainProgram); LoadFunction(clReleaseProgram); LoadFunction(clBuildProgram); LoadFunction(clCompileProgram); LoadFunction(clLinkProgram); LoadFunction(clUnloadPlatformCompiler); LoadFunction(clGetProgramInfo); LoadFunction(clGetProgramBuildInfo); LoadFunction(clCreateKernel); LoadFunction(clCreateKernelsInProgram); LoadFunction(clRetainKernel); LoadFunction(clReleaseKernel); LoadFunction(clSetKernelArg); LoadFunction(clSetKernelArgSVMPointer); LoadFunction(clSetKernelExecInfo); LoadFunction(clGetKernelInfo); LoadFunction(clGetKernelArgInfo); LoadFunction(clGetKernelWorkGroupInfo); LoadFunction(clWaitForEvents); LoadFunction(clGetEventInfo); LoadFunction(clCreateUserEvent); LoadFunction(clRetainEvent); LoadFunction(clReleaseEvent); LoadFunction(clSetUserEventStatus); LoadFunction(clSetEventCallback); LoadFunction(clGetEventProfilingInfo); LoadFunction(clFlush); LoadFunction(clFinish); LoadFunction(clEnqueueReadBuffer); LoadFunction(clEnqueueReadBufferRect); LoadFunction(clEnqueueWriteBuffer); LoadFunction(clEnqueueWriteBufferRect); LoadFunction(clEnqueueFillBuffer); LoadFunction(clEnqueueCopyBuffer); LoadFunction(clEnqueueCopyBufferRect); LoadFunction(clEnqueueReadImage); LoadFunction(clEnqueueWriteImage); LoadFunction(clEnqueueFillImage); LoadFunction(clEnqueueCopyImage); LoadFunction(clEnqueueCopyImageToBuffer); LoadFunction(clEnqueueCopyBufferToImage); LoadFunction(clEnqueueMapBuffer); LoadFunction(clEnqueueMapImage); LoadFunction(clEnqueueUnmapMemObject); LoadFunction(clEnqueueMigrateMemObjects); LoadFunction(clEnqueueNDRangeKernel); LoadFunction(clEnqueueNativeKernel); LoadFunction(clEnqueueMarkerWithWaitList); LoadFunction(clEnqueueBarrierWithWaitList); LoadFunction(clEnqueueSVMFree); LoadFunction(clEnqueueSVMMemcpy); LoadFunction(clEnqueueSVMMemFill); LoadFunction(clEnqueueSVMMap); LoadFunction(clEnqueueSVMUnmap); LoadFunction(clGetExtensionFunctionAddressForPlatform); LoadFunction(clCreateImage2D); LoadFunction(clCreateImage3D); LoadFunction(clEnqueueMarker); LoadFunction(clEnqueueWaitForEvents); LoadFunction(clEnqueueBarrier); LoadFunction(clUnloadCompiler); LoadFunction(clGetExtensionFunctionAddress); LoadFunction(clCreateCommandQueue); LoadFunction(clCreateSampler); LoadFunction(clEnqueueTask); // OpenGL sharing LoadFunction(clCreateFromGLBuffer); LoadFunction(clCreateFromGLTexture); LoadFunction(clEnqueueAcquireGLObjects); LoadFunction(clEnqueueReleaseGLObjects); // cl_khr_egl_event extension LoadFunction(clCreateEventFromEGLSyncKHR); // EGL sharing LoadFunction(clCreateFromEGLImageKHR); LoadFunction(clEnqueueAcquireEGLObjectsKHR); LoadFunction(clEnqueueReleaseEGLObjectsKHR); } // No OpenCL support, do not set function addresses PFN_clGetPlatformIDs clGetPlatformIDs; PFN_clGetPlatformInfo clGetPlatformInfo; PFN_clGetDeviceIDs clGetDeviceIDs; PFN_clGetDeviceInfo clGetDeviceInfo; PFN_clCreateSubDevices clCreateSubDevices; PFN_clRetainDevice clRetainDevice; PFN_clReleaseDevice clReleaseDevice; PFN_clCreateContext clCreateContext; PFN_clCreateContextFromType clCreateContextFromType; PFN_clRetainContext clRetainContext; PFN_clReleaseContext clReleaseContext; PFN_clGetContextInfo clGetContextInfo; PFN_clCreateCommandQueueWithProperties clCreateCommandQueueWithProperties; PFN_clRetainCommandQueue clRetainCommandQueue; PFN_clReleaseCommandQueue clReleaseCommandQueue; PFN_clGetCommandQueueInfo clGetCommandQueueInfo; PFN_clCreateBuffer clCreateBuffer; PFN_clCreateSubBuffer clCreateSubBuffer; PFN_clCreateImage clCreateImage; PFN_clCreatePipe clCreatePipe; PFN_clRetainMemObject clRetainMemObject; PFN_clReleaseMemObject clReleaseMemObject; PFN_clGetSupportedImageFormats clGetSupportedImageFormats; PFN_clGetMemObjectInfo clGetMemObjectInfo; PFN_clGetImageInfo clGetImageInfo; PFN_clGetPipeInfo clGetPipeInfo; PFN_clSetMemObjectDestructorCallback clSetMemObjectDestructorCallback; PFN_clSVMAlloc clSVMAlloc; PFN_clSVMFree clSVMFree; PFN_clCreateSamplerWithProperties clCreateSamplerWithProperties; PFN_clRetainSampler clRetainSampler; PFN_clReleaseSampler clReleaseSampler; PFN_clGetSamplerInfo clGetSamplerInfo; PFN_clCreateProgramWithSource clCreateProgramWithSource; PFN_clCreateProgramWithBinary clCreateProgramWithBinary; PFN_clCreateProgramWithBuiltInKernels clCreateProgramWithBuiltInKernels; PFN_clRetainProgram clRetainProgram; PFN_clReleaseProgram clReleaseProgram; PFN_clBuildProgram clBuildProgram; PFN_clCompileProgram clCompileProgram; PFN_clLinkProgram clLinkProgram; PFN_clUnloadPlatformCompiler clUnloadPlatformCompiler; PFN_clGetProgramInfo clGetProgramInfo; PFN_clGetProgramBuildInfo clGetProgramBuildInfo; PFN_clCreateKernel clCreateKernel; PFN_clCreateKernelsInProgram clCreateKernelsInProgram; PFN_clRetainKernel clRetainKernel; PFN_clReleaseKernel clReleaseKernel; PFN_clSetKernelArg clSetKernelArg; PFN_clSetKernelArgSVMPointer clSetKernelArgSVMPointer; PFN_clSetKernelExecInfo clSetKernelExecInfo; PFN_clGetKernelInfo clGetKernelInfo; PFN_clGetKernelArgInfo clGetKernelArgInfo; PFN_clGetKernelWorkGroupInfo clGetKernelWorkGroupInfo; PFN_clWaitForEvents clWaitForEvents; PFN_clGetEventInfo clGetEventInfo; PFN_clCreateUserEvent clCreateUserEvent; PFN_clRetainEvent clRetainEvent; PFN_clReleaseEvent clReleaseEvent; PFN_clSetUserEventStatus clSetUserEventStatus; PFN_clSetEventCallback clSetEventCallback; PFN_clGetEventProfilingInfo clGetEventProfilingInfo; PFN_clFlush clFlush; PFN_clFinish clFinish; PFN_clEnqueueReadBuffer clEnqueueReadBuffer; PFN_clEnqueueReadBufferRect clEnqueueReadBufferRect; PFN_clEnqueueWriteBuffer clEnqueueWriteBuffer; PFN_clEnqueueWriteBufferRect clEnqueueWriteBufferRect; PFN_clEnqueueFillBuffer clEnqueueFillBuffer; PFN_clEnqueueCopyBuffer clEnqueueCopyBuffer; PFN_clEnqueueCopyBufferRect clEnqueueCopyBufferRect; PFN_clEnqueueReadImage clEnqueueReadImage; PFN_clEnqueueWriteImage clEnqueueWriteImage; PFN_clEnqueueFillImage clEnqueueFillImage; PFN_clEnqueueCopyImage clEnqueueCopyImage; PFN_clEnqueueCopyImageToBuffer clEnqueueCopyImageToBuffer; PFN_clEnqueueCopyBufferToImage clEnqueueCopyBufferToImage; PFN_clEnqueueMapBuffer clEnqueueMapBuffer; PFN_clEnqueueMapImage clEnqueueMapImage; PFN_clEnqueueUnmapMemObject clEnqueueUnmapMemObject; PFN_clEnqueueMigrateMemObjects clEnqueueMigrateMemObjects; PFN_clEnqueueNDRangeKernel clEnqueueNDRangeKernel; PFN_clEnqueueNativeKernel clEnqueueNativeKernel; PFN_clEnqueueMarkerWithWaitList clEnqueueMarkerWithWaitList; PFN_clEnqueueBarrierWithWaitList clEnqueueBarrierWithWaitList; PFN_clEnqueueSVMFree clEnqueueSVMFree; PFN_clEnqueueSVMMemcpy clEnqueueSVMMemcpy; PFN_clEnqueueSVMMemFill clEnqueueSVMMemFill; PFN_clEnqueueSVMMap clEnqueueSVMMap; PFN_clEnqueueSVMUnmap clEnqueueSVMUnmap; PFN_clGetExtensionFunctionAddressForPlatform clGetExtensionFunctionAddressForPlatform; PFN_clCreateImage2D clCreateImage2D; PFN_clCreateImage3D clCreateImage3D; PFN_clEnqueueMarker clEnqueueMarker; PFN_clEnqueueWaitForEvents clEnqueueWaitForEvents; PFN_clEnqueueBarrier clEnqueueBarrier; PFN_clUnloadCompiler clUnloadCompiler; PFN_clGetExtensionFunctionAddress clGetExtensionFunctionAddress; PFN_clCreateCommandQueue clCreateCommandQueue; PFN_clCreateSampler clCreateSampler; PFN_clEnqueueTask clEnqueueTask; // OpenGL sharing PFN_clCreateFromGLBuffer clCreateFromGLBuffer; PFN_clCreateFromGLTexture clCreateFromGLTexture; PFN_clEnqueueAcquireGLObjects clEnqueueAcquireGLObjects; PFN_clEnqueueReleaseGLObjects clEnqueueReleaseGLObjects; // cl_khr_egl_event extension PFN_clCreateEventFromEGLSyncKHR clCreateEventFromEGLSyncKHR; // EGL sharing PFN_clCreateFromEGLImageKHR clCreateFromEGLImageKHR; PFN_clEnqueueAcquireEGLObjectsKHR clEnqueueAcquireEGLObjectsKHR; PFN_clEnqueueReleaseEGLObjectsKHR clEnqueueReleaseEGLObjectsKHR; cl_mem CreateImage2DLegacy(cl_context context, cl_mem_flags flags, const cl_image_format* image_format, const cl_image_desc* image_desc, void* host_ptr, cl_int* errcode_ret) { if (clCreateImage) { // clCreateImage available since OpenCL 1.2 return clCreateImage(context, flags, image_format, image_desc, host_ptr, errcode_ret); } else { return clCreateImage2D(context, flags, image_format, image_desc->image_width, image_desc->image_height, image_desc->image_row_pitch, host_ptr, errcode_ret); } } cl_mem CreateImage3DLegacy(cl_context context, cl_mem_flags flags, const cl_image_format* image_format, const cl_image_desc* image_desc, void* host_ptr, cl_int* errcode_ret) { if (clCreateImage) { // clCreateImage available since OpenCL 1.2 return clCreateImage(context, flags, image_format, image_desc, host_ptr, errcode_ret); } else { return clCreateImage3D(context, flags, image_format, image_desc->image_width, image_desc->image_height, image_desc->image_depth, image_desc->image_row_pitch, image_desc->image_slice_pitch, host_ptr, errcode_ret); } } } // namespace cl } // namespace gpu } // namespace tflite <commit_msg>Removed mentioning of libOpenCL-pixel.so.<commit_after>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/lite/delegates/gpu/cl/opencl_wrapper.h" #include <dlfcn.h> #include <string> #include "absl/strings/str_cat.h" #include "tensorflow/lite/delegates/gpu/common/status.h" namespace tflite { namespace gpu { namespace cl { #define LoadFunction(function) \ if (is_pixel) { \ function = reinterpret_cast<PFN_##function>(loadOpenCLPointer(#function)); \ } else { \ function = reinterpret_cast<PFN_##function>(dlsym(libopencl, #function)); \ } absl::Status LoadOpenCL() { void* libopencl = dlopen("libOpenCL.so", RTLD_NOW | RTLD_LOCAL); if (libopencl) { LoadOpenCLFunctions(libopencl, false); return absl::OkStatus(); } else { // record error std::string error(dlerror()); // Pixel phone? libopencl = dlopen("libOpenCL-pixel.so", RTLD_NOW | RTLD_LOCAL); if (libopencl) { typedef void (*enableOpenCL_t)(); enableOpenCL_t enableOpenCL = reinterpret_cast<enableOpenCL_t>(dlsym(libopencl, "enableOpenCL")); enableOpenCL(); LoadOpenCLFunctions(libopencl, true); return absl::OkStatus(); } else { return absl::UnknownError( absl::StrCat("Can not open OpenCL library on this device - ", error)); } } } void LoadOpenCLFunctions(void* libopencl, bool is_pixel) { typedef void* (*loadOpenCLPointer_t)(const char* name); loadOpenCLPointer_t loadOpenCLPointer; if (is_pixel) { loadOpenCLPointer = reinterpret_cast<loadOpenCLPointer_t>( dlsym(libopencl, "loadOpenCLPointer")); } LoadFunction(clGetPlatformIDs); LoadFunction(clGetPlatformInfo); LoadFunction(clGetDeviceIDs); LoadFunction(clGetDeviceInfo); LoadFunction(clCreateSubDevices); LoadFunction(clRetainDevice); LoadFunction(clReleaseDevice); LoadFunction(clCreateContext); LoadFunction(clCreateContextFromType); LoadFunction(clRetainContext); LoadFunction(clReleaseContext); LoadFunction(clGetContextInfo); LoadFunction(clCreateCommandQueueWithProperties); LoadFunction(clRetainCommandQueue); LoadFunction(clReleaseCommandQueue); LoadFunction(clGetCommandQueueInfo); LoadFunction(clCreateBuffer); LoadFunction(clCreateSubBuffer); LoadFunction(clCreateImage); LoadFunction(clCreatePipe); LoadFunction(clRetainMemObject); LoadFunction(clReleaseMemObject); LoadFunction(clGetSupportedImageFormats); LoadFunction(clGetMemObjectInfo); LoadFunction(clGetImageInfo); LoadFunction(clGetPipeInfo); LoadFunction(clSetMemObjectDestructorCallback); LoadFunction(clSVMAlloc); LoadFunction(clSVMFree); LoadFunction(clCreateSamplerWithProperties); LoadFunction(clRetainSampler); LoadFunction(clReleaseSampler); LoadFunction(clGetSamplerInfo); LoadFunction(clCreateProgramWithSource); LoadFunction(clCreateProgramWithBinary); LoadFunction(clCreateProgramWithBuiltInKernels); LoadFunction(clRetainProgram); LoadFunction(clReleaseProgram); LoadFunction(clBuildProgram); LoadFunction(clCompileProgram); LoadFunction(clLinkProgram); LoadFunction(clUnloadPlatformCompiler); LoadFunction(clGetProgramInfo); LoadFunction(clGetProgramBuildInfo); LoadFunction(clCreateKernel); LoadFunction(clCreateKernelsInProgram); LoadFunction(clRetainKernel); LoadFunction(clReleaseKernel); LoadFunction(clSetKernelArg); LoadFunction(clSetKernelArgSVMPointer); LoadFunction(clSetKernelExecInfo); LoadFunction(clGetKernelInfo); LoadFunction(clGetKernelArgInfo); LoadFunction(clGetKernelWorkGroupInfo); LoadFunction(clWaitForEvents); LoadFunction(clGetEventInfo); LoadFunction(clCreateUserEvent); LoadFunction(clRetainEvent); LoadFunction(clReleaseEvent); LoadFunction(clSetUserEventStatus); LoadFunction(clSetEventCallback); LoadFunction(clGetEventProfilingInfo); LoadFunction(clFlush); LoadFunction(clFinish); LoadFunction(clEnqueueReadBuffer); LoadFunction(clEnqueueReadBufferRect); LoadFunction(clEnqueueWriteBuffer); LoadFunction(clEnqueueWriteBufferRect); LoadFunction(clEnqueueFillBuffer); LoadFunction(clEnqueueCopyBuffer); LoadFunction(clEnqueueCopyBufferRect); LoadFunction(clEnqueueReadImage); LoadFunction(clEnqueueWriteImage); LoadFunction(clEnqueueFillImage); LoadFunction(clEnqueueCopyImage); LoadFunction(clEnqueueCopyImageToBuffer); LoadFunction(clEnqueueCopyBufferToImage); LoadFunction(clEnqueueMapBuffer); LoadFunction(clEnqueueMapImage); LoadFunction(clEnqueueUnmapMemObject); LoadFunction(clEnqueueMigrateMemObjects); LoadFunction(clEnqueueNDRangeKernel); LoadFunction(clEnqueueNativeKernel); LoadFunction(clEnqueueMarkerWithWaitList); LoadFunction(clEnqueueBarrierWithWaitList); LoadFunction(clEnqueueSVMFree); LoadFunction(clEnqueueSVMMemcpy); LoadFunction(clEnqueueSVMMemFill); LoadFunction(clEnqueueSVMMap); LoadFunction(clEnqueueSVMUnmap); LoadFunction(clGetExtensionFunctionAddressForPlatform); LoadFunction(clCreateImage2D); LoadFunction(clCreateImage3D); LoadFunction(clEnqueueMarker); LoadFunction(clEnqueueWaitForEvents); LoadFunction(clEnqueueBarrier); LoadFunction(clUnloadCompiler); LoadFunction(clGetExtensionFunctionAddress); LoadFunction(clCreateCommandQueue); LoadFunction(clCreateSampler); LoadFunction(clEnqueueTask); // OpenGL sharing LoadFunction(clCreateFromGLBuffer); LoadFunction(clCreateFromGLTexture); LoadFunction(clEnqueueAcquireGLObjects); LoadFunction(clEnqueueReleaseGLObjects); // cl_khr_egl_event extension LoadFunction(clCreateEventFromEGLSyncKHR); // EGL sharing LoadFunction(clCreateFromEGLImageKHR); LoadFunction(clEnqueueAcquireEGLObjectsKHR); LoadFunction(clEnqueueReleaseEGLObjectsKHR); } // No OpenCL support, do not set function addresses PFN_clGetPlatformIDs clGetPlatformIDs; PFN_clGetPlatformInfo clGetPlatformInfo; PFN_clGetDeviceIDs clGetDeviceIDs; PFN_clGetDeviceInfo clGetDeviceInfo; PFN_clCreateSubDevices clCreateSubDevices; PFN_clRetainDevice clRetainDevice; PFN_clReleaseDevice clReleaseDevice; PFN_clCreateContext clCreateContext; PFN_clCreateContextFromType clCreateContextFromType; PFN_clRetainContext clRetainContext; PFN_clReleaseContext clReleaseContext; PFN_clGetContextInfo clGetContextInfo; PFN_clCreateCommandQueueWithProperties clCreateCommandQueueWithProperties; PFN_clRetainCommandQueue clRetainCommandQueue; PFN_clReleaseCommandQueue clReleaseCommandQueue; PFN_clGetCommandQueueInfo clGetCommandQueueInfo; PFN_clCreateBuffer clCreateBuffer; PFN_clCreateSubBuffer clCreateSubBuffer; PFN_clCreateImage clCreateImage; PFN_clCreatePipe clCreatePipe; PFN_clRetainMemObject clRetainMemObject; PFN_clReleaseMemObject clReleaseMemObject; PFN_clGetSupportedImageFormats clGetSupportedImageFormats; PFN_clGetMemObjectInfo clGetMemObjectInfo; PFN_clGetImageInfo clGetImageInfo; PFN_clGetPipeInfo clGetPipeInfo; PFN_clSetMemObjectDestructorCallback clSetMemObjectDestructorCallback; PFN_clSVMAlloc clSVMAlloc; PFN_clSVMFree clSVMFree; PFN_clCreateSamplerWithProperties clCreateSamplerWithProperties; PFN_clRetainSampler clRetainSampler; PFN_clReleaseSampler clReleaseSampler; PFN_clGetSamplerInfo clGetSamplerInfo; PFN_clCreateProgramWithSource clCreateProgramWithSource; PFN_clCreateProgramWithBinary clCreateProgramWithBinary; PFN_clCreateProgramWithBuiltInKernels clCreateProgramWithBuiltInKernels; PFN_clRetainProgram clRetainProgram; PFN_clReleaseProgram clReleaseProgram; PFN_clBuildProgram clBuildProgram; PFN_clCompileProgram clCompileProgram; PFN_clLinkProgram clLinkProgram; PFN_clUnloadPlatformCompiler clUnloadPlatformCompiler; PFN_clGetProgramInfo clGetProgramInfo; PFN_clGetProgramBuildInfo clGetProgramBuildInfo; PFN_clCreateKernel clCreateKernel; PFN_clCreateKernelsInProgram clCreateKernelsInProgram; PFN_clRetainKernel clRetainKernel; PFN_clReleaseKernel clReleaseKernel; PFN_clSetKernelArg clSetKernelArg; PFN_clSetKernelArgSVMPointer clSetKernelArgSVMPointer; PFN_clSetKernelExecInfo clSetKernelExecInfo; PFN_clGetKernelInfo clGetKernelInfo; PFN_clGetKernelArgInfo clGetKernelArgInfo; PFN_clGetKernelWorkGroupInfo clGetKernelWorkGroupInfo; PFN_clWaitForEvents clWaitForEvents; PFN_clGetEventInfo clGetEventInfo; PFN_clCreateUserEvent clCreateUserEvent; PFN_clRetainEvent clRetainEvent; PFN_clReleaseEvent clReleaseEvent; PFN_clSetUserEventStatus clSetUserEventStatus; PFN_clSetEventCallback clSetEventCallback; PFN_clGetEventProfilingInfo clGetEventProfilingInfo; PFN_clFlush clFlush; PFN_clFinish clFinish; PFN_clEnqueueReadBuffer clEnqueueReadBuffer; PFN_clEnqueueReadBufferRect clEnqueueReadBufferRect; PFN_clEnqueueWriteBuffer clEnqueueWriteBuffer; PFN_clEnqueueWriteBufferRect clEnqueueWriteBufferRect; PFN_clEnqueueFillBuffer clEnqueueFillBuffer; PFN_clEnqueueCopyBuffer clEnqueueCopyBuffer; PFN_clEnqueueCopyBufferRect clEnqueueCopyBufferRect; PFN_clEnqueueReadImage clEnqueueReadImage; PFN_clEnqueueWriteImage clEnqueueWriteImage; PFN_clEnqueueFillImage clEnqueueFillImage; PFN_clEnqueueCopyImage clEnqueueCopyImage; PFN_clEnqueueCopyImageToBuffer clEnqueueCopyImageToBuffer; PFN_clEnqueueCopyBufferToImage clEnqueueCopyBufferToImage; PFN_clEnqueueMapBuffer clEnqueueMapBuffer; PFN_clEnqueueMapImage clEnqueueMapImage; PFN_clEnqueueUnmapMemObject clEnqueueUnmapMemObject; PFN_clEnqueueMigrateMemObjects clEnqueueMigrateMemObjects; PFN_clEnqueueNDRangeKernel clEnqueueNDRangeKernel; PFN_clEnqueueNativeKernel clEnqueueNativeKernel; PFN_clEnqueueMarkerWithWaitList clEnqueueMarkerWithWaitList; PFN_clEnqueueBarrierWithWaitList clEnqueueBarrierWithWaitList; PFN_clEnqueueSVMFree clEnqueueSVMFree; PFN_clEnqueueSVMMemcpy clEnqueueSVMMemcpy; PFN_clEnqueueSVMMemFill clEnqueueSVMMemFill; PFN_clEnqueueSVMMap clEnqueueSVMMap; PFN_clEnqueueSVMUnmap clEnqueueSVMUnmap; PFN_clGetExtensionFunctionAddressForPlatform clGetExtensionFunctionAddressForPlatform; PFN_clCreateImage2D clCreateImage2D; PFN_clCreateImage3D clCreateImage3D; PFN_clEnqueueMarker clEnqueueMarker; PFN_clEnqueueWaitForEvents clEnqueueWaitForEvents; PFN_clEnqueueBarrier clEnqueueBarrier; PFN_clUnloadCompiler clUnloadCompiler; PFN_clGetExtensionFunctionAddress clGetExtensionFunctionAddress; PFN_clCreateCommandQueue clCreateCommandQueue; PFN_clCreateSampler clCreateSampler; PFN_clEnqueueTask clEnqueueTask; // OpenGL sharing PFN_clCreateFromGLBuffer clCreateFromGLBuffer; PFN_clCreateFromGLTexture clCreateFromGLTexture; PFN_clEnqueueAcquireGLObjects clEnqueueAcquireGLObjects; PFN_clEnqueueReleaseGLObjects clEnqueueReleaseGLObjects; // cl_khr_egl_event extension PFN_clCreateEventFromEGLSyncKHR clCreateEventFromEGLSyncKHR; // EGL sharing PFN_clCreateFromEGLImageKHR clCreateFromEGLImageKHR; PFN_clEnqueueAcquireEGLObjectsKHR clEnqueueAcquireEGLObjectsKHR; PFN_clEnqueueReleaseEGLObjectsKHR clEnqueueReleaseEGLObjectsKHR; cl_mem CreateImage2DLegacy(cl_context context, cl_mem_flags flags, const cl_image_format* image_format, const cl_image_desc* image_desc, void* host_ptr, cl_int* errcode_ret) { if (clCreateImage) { // clCreateImage available since OpenCL 1.2 return clCreateImage(context, flags, image_format, image_desc, host_ptr, errcode_ret); } else { return clCreateImage2D(context, flags, image_format, image_desc->image_width, image_desc->image_height, image_desc->image_row_pitch, host_ptr, errcode_ret); } } cl_mem CreateImage3DLegacy(cl_context context, cl_mem_flags flags, const cl_image_format* image_format, const cl_image_desc* image_desc, void* host_ptr, cl_int* errcode_ret) { if (clCreateImage) { // clCreateImage available since OpenCL 1.2 return clCreateImage(context, flags, image_format, image_desc, host_ptr, errcode_ret); } else { return clCreateImage3D(context, flags, image_format, image_desc->image_width, image_desc->image_height, image_desc->image_depth, image_desc->image_row_pitch, image_desc->image_slice_pitch, host_ptr, errcode_ret); } } } // namespace cl } // namespace gpu } // namespace tflite <|endoftext|>
<commit_before>#ifndef AMGCL_AMGCL_HPP #define AMGCL_AMGCL_HPP /* The MIT License Copyright (c) 2012-2013 Denis Demidov <ddemidov@ksu.ru> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * \file amgcl.hpp * \author Denis Demidov <ddemidov@ksu.ru> * \brief Generic algebraic multigrid framework. */ #include <iostream> #include <iomanip> #include <utility> #include <list> #include <boost/static_assert.hpp> #include <boost/smart_ptr/shared_ptr.hpp> #include <boost/smart_ptr/make_shared.hpp> #include <boost/type_traits/is_signed.hpp> #include <boost/io/ios_state.hpp> #include <amgcl/spmat.hpp> #include <amgcl/tictoc.hpp> /// Primary namespace for the library. namespace amgcl { /// Interpolation-related types and functions. namespace interp { /// Galerkin operator. struct galerkin_operator { template <class spmat, class Params> static spmat apply(const spmat &R, const spmat &A, const spmat &P, const Params&) { return sparse::prod(sparse::prod(R, A), P); } }; /// Returns coarse level construction scheme for a given interpolation scheme. /** * By default, Galerkin operator is used to construct coarse level from system * matrix, restriction and prolongation operators: * \f[A^H = R A^h P.\f] Usually, \f$R = P^T.\f$ * * \param Interpolation interpolation scheme. */ template <class Interpolation> struct coarse_operator { typedef galerkin_operator type; }; } // namespace interp /// Possible relaxation (smoothing) schemes. namespace relax { /// Possible relaxation (smoothing) schemes. /** * Each backend may support only a limited subset of these. * \sa relax_vs_backend */ enum scheme { damped_jacobi, ///< Damped Jacobi. spai0, ///< SPAI-0 algorithm from \ref spai_2002 "Broeker (2002)". gauss_seidel, ///< Gauss-Seidel. ilu0 ///< Incomplete LU decomposition with zero fill-in. }; } // namespace relax. /// Algebraic multigrid method. /** * \param value_t Type for matrix entries (double/float). * \param index_t Type for matrix indices. Should be signed integral type. * \param interp_t \ref interpolation "Interpolation scheme". * \param level_t Hierarchy level \ref levels "storage backend". */ template < typename value_t, typename index_t, typename interp_t, typename level_t > class solver { private: typedef sparse::matrix<value_t, index_t> matrix; typedef typename level_t::template instance<value_t, index_t> level_type; public: typedef value_t value_type; typedef index_t index_type; /// Parameters for AMG components. struct params { /// When level is coarse enough to be solved directly? /** * If number of variables at a next level in hierarchy becomes * lower than this threshold, then the hierarchy construction is * stopped and the linear system is solved explicitly at this * level. */ unsigned coarse_enough; typename interp_t::params interp; ///< Interpolation parameters. typename level_t::params level; ///< Level/Solution parameters. params() : coarse_enough(300) { } }; /// Constructs the AMG hierarchy from the system matrix. /** * The input matrix is copied here and may be freed afterwards. * * \param A The system matrix. Should be convertible to * amgcl::sparse::matrix<>. * \param prm Parameters controlling the setup and solution phases. * * \sa amgcl::sparse::map() */ template <typename spmat> solver(const spmat &A, const params &prm = params()) : prm(prm) { BOOST_STATIC_ASSERT_MSG(boost::is_signed<index_t>::value, "Matrix index type should be signed"); matrix copy(A); build_level(copy, prm); } /// The AMG hierarchy is used as a standalone solver. /** * The vector types should be compatible with level_t: * * -# Any type with operator[] should work on a CPU. * -# vex::vector<value_t> should be used with level::vexcl. * -# viennacl::vector<value_t> should be used with level::ViennaCL. * * \param rhs Right-hand side. * \param x Solution. Contains an initial approximation on input, and * the approximated solution on output. */ template <class vector1, class vector2> std::pair< int, value_t > solve(const vector1 &rhs, vector2 &x) const { unsigned iter = 0; value_t res = 2 * prm.level.tol; for(; res > prm.level.tol && iter < prm.level.maxiter; ++iter) { apply(rhs, x); res = hier.front()->resid(rhs, x); } return std::make_pair(iter, res); } /// Performs single multigrid cycle. /** * Is intended to be used as a preconditioner with iterative methods. * * The vector types should be compatible with level_t: * * -# Any type with operator[] should work on a CPU. * -# vex::vector<value_t> should be used with level::vexcl. * -# viennacl::vector<value_t> should be used with level::ViennaCL. * * \param rhs Right-hand side. * \param x Solution. Contains an initial approximation on input, and * the approximated solution on output. */ template <class vector1, class vector2> void apply(const vector1 &rhs, vector2 &x) const { level_type::cycle(hier.begin(), hier.end(), prm.level, rhs, x); } /// Output some general information about the AMG hierarchy. std::ostream& print(std::ostream &os) const { boost::io::ios_all_saver stream_state(os); index_t sum_dof = 0; index_t sum_nnz = 0; for(typename std::list< boost::shared_ptr<level_type> >::const_iterator lvl = hier.begin(); lvl != hier.end(); ++lvl) { sum_dof += (*lvl)->size(); sum_nnz += (*lvl)->nonzeros(); } os << "Number of levels: " << hier.size() << "\nOperator complexity: " << std::fixed << std::setprecision(2) << 1.0 * sum_nnz / hier.front()->nonzeros() << "\nGrid complexity: " << std::fixed << std::setprecision(2) << 1.0 * sum_dof / hier.front()->size() << "\n\nlevel unknowns nonzeros\n" << "---------------------------------\n"; index_t depth = 0; for(typename std::list< boost::shared_ptr<level_type> >::const_iterator lvl = hier.begin(); lvl != hier.end(); ++lvl, ++depth) os << std::setw(5) << depth << std::setw(13) << (*lvl)->size() << std::setw(15) << (*lvl)->nonzeros() << " (" << std::setw(5) << std::fixed << std::setprecision(2) << 100.0 * (*lvl)->nonzeros() / sum_nnz << "%)" << std::endl; return os; } /// Number of unknowns at the finest level. index_t size() const { return hier.front()->size(); } /// Returns reference to the system matrix at the finest level. const typename level_type::matrix& top_matrix() const { return hier.front()->get_matrix(); } private: void build_level(matrix &A, const params &prm, unsigned nlevel = 0) { if (static_cast<size_t>(A.rows) <= prm.coarse_enough) { TIC("coarsest level"); matrix Ai = sparse::inverse(A); hier.push_back( boost::shared_ptr<level_type>(new level_type(A, Ai, prm.level, nlevel) ) ); TOC("coarsest level"); } else { TIC("construct level"); TIC("interp"); std::pair<sparse::matrix<value_t, index_t>, sparse::matrix<value_t, index_t> > PR = interp_t::interp(A, prm.interp); matrix &P = PR.first; matrix &R = PR.second; TOC("interp"); TIC("coarse operator"); matrix a = interp::coarse_operator<interp_t>::type::apply( R, A, P, prm.interp); TOC("coarse operator"); TOC("construct level"); TIC("transfer level data"); hier.push_back( boost::shared_ptr<level_type>(new level_type(A, P, R, prm.level, nlevel) ) ); TOC("transfer level data"); build_level(a, prm, nlevel + 1); } } params prm; std::list< boost::shared_ptr<level_type> > hier; }; } // namespace amgcl /// Output some general information about the AMG hierarchy. template < typename value_t, typename index_t, typename interp_t, typename level_t > std::ostream& operator<<(std::ostream &os, const amgcl::solver<value_t, index_t, interp_t, level_t> &amg) { return amg.print(os); } #endif <commit_msg>Removed trailing spaces<commit_after>#ifndef AMGCL_AMGCL_HPP #define AMGCL_AMGCL_HPP /* The MIT License Copyright (c) 2012-2013 Denis Demidov <ddemidov@ksu.ru> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * \file amgcl.hpp * \author Denis Demidov <ddemidov@ksu.ru> * \brief Generic algebraic multigrid framework. */ #include <iostream> #include <iomanip> #include <utility> #include <list> #include <boost/static_assert.hpp> #include <boost/smart_ptr/shared_ptr.hpp> #include <boost/smart_ptr/make_shared.hpp> #include <boost/type_traits/is_signed.hpp> #include <boost/io/ios_state.hpp> #include <amgcl/spmat.hpp> #include <amgcl/tictoc.hpp> /// Primary namespace for the library. namespace amgcl { /// Interpolation-related types and functions. namespace interp { /// Galerkin operator. struct galerkin_operator { template <class spmat, class Params> static spmat apply(const spmat &R, const spmat &A, const spmat &P, const Params&) { return sparse::prod(sparse::prod(R, A), P); } }; /// Returns coarse level construction scheme for a given interpolation scheme. /** * By default, Galerkin operator is used to construct coarse level from system * matrix, restriction and prolongation operators: * \f[A^H = R A^h P.\f] Usually, \f$R = P^T.\f$ * * \param Interpolation interpolation scheme. */ template <class Interpolation> struct coarse_operator { typedef galerkin_operator type; }; } // namespace interp /// Possible relaxation (smoothing) schemes. namespace relax { /// Possible relaxation (smoothing) schemes. /** * Each backend may support only a limited subset of these. * \sa relax_vs_backend */ enum scheme { damped_jacobi, ///< Damped Jacobi. spai0, ///< SPAI-0 algorithm from \ref spai_2002 "Broeker (2002)". gauss_seidel, ///< Gauss-Seidel. ilu0 ///< Incomplete LU decomposition with zero fill-in. }; } // namespace relax. /// Algebraic multigrid method. /** * \param value_t Type for matrix entries (double/float). * \param index_t Type for matrix indices. Should be signed integral type. * \param interp_t \ref interpolation "Interpolation scheme". * \param level_t Hierarchy level \ref levels "storage backend". */ template < typename value_t, typename index_t, typename interp_t, typename level_t > class solver { private: typedef sparse::matrix<value_t, index_t> matrix; typedef typename level_t::template instance<value_t, index_t> level_type; public: typedef value_t value_type; typedef index_t index_type; /// Parameters for AMG components. struct params { /// When level is coarse enough to be solved directly? /** * If number of variables at a next level in hierarchy becomes * lower than this threshold, then the hierarchy construction is * stopped and the linear system is solved explicitly at this * level. */ unsigned coarse_enough; typename interp_t::params interp; ///< Interpolation parameters. typename level_t::params level; ///< Level/Solution parameters. params() : coarse_enough(300) { } }; /// Constructs the AMG hierarchy from the system matrix. /** * The input matrix is copied here and may be freed afterwards. * * \param A The system matrix. Should be convertible to * amgcl::sparse::matrix<>. * \param prm Parameters controlling the setup and solution phases. * * \sa amgcl::sparse::map() */ template <typename spmat> solver(const spmat &A, const params &prm = params()) : prm(prm) { BOOST_STATIC_ASSERT_MSG(boost::is_signed<index_t>::value, "Matrix index type should be signed"); matrix copy(A); build_level(copy, prm); } /// The AMG hierarchy is used as a standalone solver. /** * The vector types should be compatible with level_t: * * -# Any type with operator[] should work on a CPU. * -# vex::vector<value_t> should be used with level::vexcl. * -# viennacl::vector<value_t> should be used with level::ViennaCL. * * \param rhs Right-hand side. * \param x Solution. Contains an initial approximation on input, and * the approximated solution on output. */ template <class vector1, class vector2> std::pair< int, value_t > solve(const vector1 &rhs, vector2 &x) const { unsigned iter = 0; value_t res = 2 * prm.level.tol; for(; res > prm.level.tol && iter < prm.level.maxiter; ++iter) { apply(rhs, x); res = hier.front()->resid(rhs, x); } return std::make_pair(iter, res); } /// Performs single multigrid cycle. /** * Is intended to be used as a preconditioner with iterative methods. * * The vector types should be compatible with level_t: * * -# Any type with operator[] should work on a CPU. * -# vex::vector<value_t> should be used with level::vexcl. * -# viennacl::vector<value_t> should be used with level::ViennaCL. * * \param rhs Right-hand side. * \param x Solution. Contains an initial approximation on input, and * the approximated solution on output. */ template <class vector1, class vector2> void apply(const vector1 &rhs, vector2 &x) const { level_type::cycle(hier.begin(), hier.end(), prm.level, rhs, x); } /// Output some general information about the AMG hierarchy. std::ostream& print(std::ostream &os) const { boost::io::ios_all_saver stream_state(os); index_t sum_dof = 0; index_t sum_nnz = 0; for(typename std::list< boost::shared_ptr<level_type> >::const_iterator lvl = hier.begin(); lvl != hier.end(); ++lvl) { sum_dof += (*lvl)->size(); sum_nnz += (*lvl)->nonzeros(); } os << "Number of levels: " << hier.size() << "\nOperator complexity: " << std::fixed << std::setprecision(2) << 1.0 * sum_nnz / hier.front()->nonzeros() << "\nGrid complexity: " << std::fixed << std::setprecision(2) << 1.0 * sum_dof / hier.front()->size() << "\n\nlevel unknowns nonzeros\n" << "---------------------------------\n"; index_t depth = 0; for(typename std::list< boost::shared_ptr<level_type> >::const_iterator lvl = hier.begin(); lvl != hier.end(); ++lvl, ++depth) os << std::setw(5) << depth << std::setw(13) << (*lvl)->size() << std::setw(15) << (*lvl)->nonzeros() << " (" << std::setw(5) << std::fixed << std::setprecision(2) << 100.0 * (*lvl)->nonzeros() / sum_nnz << "%)" << std::endl; return os; } /// Number of unknowns at the finest level. index_t size() const { return hier.front()->size(); } /// Returns reference to the system matrix at the finest level. const typename level_type::matrix& top_matrix() const { return hier.front()->get_matrix(); } private: void build_level(matrix &A, const params &prm, unsigned nlevel = 0) { if (static_cast<size_t>(A.rows) <= prm.coarse_enough) { TIC("coarsest level"); matrix Ai = sparse::inverse(A); hier.push_back( boost::shared_ptr<level_type>(new level_type(A, Ai, prm.level, nlevel) ) ); TOC("coarsest level"); } else { TIC("construct level"); TIC("interp"); std::pair<sparse::matrix<value_t, index_t>, sparse::matrix<value_t, index_t> > PR = interp_t::interp(A, prm.interp); matrix &P = PR.first; matrix &R = PR.second; TOC("interp"); TIC("coarse operator"); matrix a = interp::coarse_operator<interp_t>::type::apply( R, A, P, prm.interp); TOC("coarse operator"); TOC("construct level"); TIC("transfer level data"); hier.push_back( boost::shared_ptr<level_type>(new level_type(A, P, R, prm.level, nlevel) ) ); TOC("transfer level data"); build_level(a, prm, nlevel + 1); } } params prm; std::list< boost::shared_ptr<level_type> > hier; }; } // namespace amgcl /// Output some general information about the AMG hierarchy. template < typename value_t, typename index_t, typename interp_t, typename level_t > std::ostream& operator<<(std::ostream &os, const amgcl::solver<value_t, index_t, interp_t, level_t> &amg) { return amg.print(os); } #endif <|endoftext|>
<commit_before>#ifndef AMGCL_IO_MM_HPP #define AMGCL_IO_MM_HPP /* The MIT License Copyright (c) 2012-2017 Denis Demidov <dennis.demidov@gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * \file amgcl/io/mm.hpp * \author Denis Demidov <dennis.demidov@gmail.com> * \brief Readers for Matrix Market sparse matrices and dense vectors. */ #include <vector> #include <string> #include <fstream> #include <sstream> #include <numeric> #include <boost/type_traits.hpp> #include <boost/tuple/tuple.hpp> #include <amgcl/util.hpp> #include <amgcl/backend/interface.hpp> #include <amgcl/value_type/interface.hpp> #include <amgcl/detail/sort_row.hpp> namespace amgcl { namespace io { /// Matrix market reader. class mm_reader { public: /// Open the file by name mm_reader(const std::string &fname) : f(fname.c_str()) { precondition(f, "Failed to open file \"" + fname + "\""); // Read banner. std::string line; precondition(std::getline(f, line), format_error()); std::istringstream is(line); std::string banner, mtx, coord, dtype, storage; precondition( is >> banner >> mtx >> coord >> dtype >> storage, format_error()); precondition(banner == "%%MatrixMarket", format_error("no banner")); precondition(mtx == "matrix", format_error("not a matrix")); if (storage == "general") { _symmetric = false; } else if (storage == "symmetric") { _symmetric = true; } else { precondition(false, "unsupported storage type"); } if (coord == "coordinate") { _sparse = true; } else if (coord == "array") { _sparse = false; } else { precondition(false, format_error("unsupported coordinate type")); } if (dtype == "real") { _complex = false; _integer = false; } else if (dtype == "complex") { _complex = true; _integer = false; } else if (dtype == "integer") { _complex = false; _integer = true; } else { precondition(false, format_error("unsupported data type")); } // Skip comments. std::streampos pos; do { pos = f.tellg(); precondition(std::getline(f, line), format_error("unexpected eof")); } while (line[0] == '%'); // Get back to the first non-comment line. f.seekg(pos); } /// Matrix in the file is symmetric. bool is_symmetric() const { return _symmetric; } /// Matrix in the file is sparse. bool is_sparse() const { return _sparse; } /// Matrix in the file is complex-valued. bool is_complex() const { return _complex; } /// Matrix in the file is integer-valued. bool is_integer() const { return _integer; } /// Read sparse matrix from the file. template <typename Idx, typename Val> boost::tuple<size_t, size_t> operator()( std::vector<Idx> &ptr, std::vector<Idx> &col, std::vector<Val> &val ) { precondition(_sparse, format_error("not a sparse matrix")); precondition(boost::is_complex<Val>::value == _complex, _complex ? "attempt to read complex values into real vector" : "attempt to read real values into complex vector" ); precondition(boost::is_integral<Val>::value == _integer, _integer ? "attempt to read integer values into real vector" : "attempt to read real values into integer vector" ); // Read sizes size_t n, m, nnz; std::string line; std::istringstream is; { precondition(std::getline(f, line), format_error("unexpected eof")); is.clear(); is.str(line); precondition(is >> n >> m >> nnz, format_error()); } std::vector<Idx> _row; _row.reserve(nnz); std::vector<Idx> _col; _col.reserve(nnz); std::vector<Val> _val; _val.reserve(nnz); for(size_t k = 0; k < nnz; ++k) { precondition(std::getline(f, line), format_error("unexpected eof")); is.clear(); is.str(line); Idx i, j; Val v; precondition(is >> i >> j, format_error()); v = read_value<Val>(is); _row.push_back(i-1); _col.push_back(j-1); _val.push_back(v); } precondition(_val.size() == nnz, format_error("inconsistent data")); ptr.resize(n+1); std::fill(ptr.begin(), ptr.end(), 0); for(size_t k = 0; k < nnz; ++k) { Idx i = _row[k]; Idx j = _col[k]; ++ptr[i+1]; if (_symmetric && j != i) ++ptr[j+1]; } std::partial_sum(ptr.begin(), ptr.end(), ptr.begin()); col.resize(ptr.back()); val.resize(ptr.back()); for(size_t k = 0; k < nnz; ++k) { Idx i = _row[k]; Idx j = _col[k]; Val v = _val[k]; Idx head = ptr[i]++; col[head] = j; val[head] = v; if (_symmetric && j != i) { Idx head = ptr[j]++; col[head] = i; val[head] = v; } } std::rotate(ptr.begin(), ptr.end() - 1, ptr.end()); ptr.front() = 0; #pragma omp parallel for for(ptrdiff_t i = 0; i < static_cast<ptrdiff_t>(n); ++i) { Idx beg = ptr[i]; Idx end = ptr[i+1]; amgcl::detail::sort_row(&col[0] + beg, &val[0] + beg, end - beg); } return boost::make_tuple(n, m); } /// Read dense array from the file. template <typename Val> boost::tuple<size_t, size_t> operator()(std::vector<Val> &val) { precondition(!_sparse, format_error("not a dense array")); precondition(boost::is_complex<Val>::value == _complex, _complex ? "attempt to read complex values into real vector" : "attempt to read real values into complex vector" ); precondition(boost::is_integral<Val>::value == _integer, _integer ? "attempt to read integer values into real vector" : "attempt to read real values into integer vector" ); // Read sizes size_t n, m; std::string line; std::istringstream is; { precondition(std::getline(f, line), format_error("unexpected eof")); is.clear(); is.str(line); precondition(is >> n >> m, format_error()); } val.resize(n * m); for(size_t j = 0; j < m; ++j) { for(size_t i = 0; i < n; ++i) { precondition(std::getline(f, line), format_error("unexpected eof")); is.clear(); is.str(line); val[i * m + j] = read_value<Val>(is); } } return boost::make_tuple(n, m); } private: std::ifstream f; bool _sparse; bool _symmetric; bool _complex; bool _integer; std::string format_error(const std::string &msg = "") const { std::string err_string = "MatrixMarket format error"; if (!msg.empty()) err_string += " (" + msg + ")"; return err_string; } template <typename T> typename boost::enable_if<typename boost::is_complex<T>::type, T>::type read_value(std::istream &s) { typename math::scalar_of<T>::type x,y; precondition(s >> x >> y, format_error()); return T(x,y); } template <typename T> typename boost::disable_if<typename boost::is_complex<T>::type, T>::type read_value(std::istream &s) { T x; precondition(s >> x, format_error()); return x; } }; namespace detail { template <typename Val> typename boost::enable_if<typename boost::is_complex<Val>::type, std::ostream&>::type write_value(std::ostream &s, Val v) { return s << std::real(v) << " " << std::imag(v); } template <typename Val> typename boost::disable_if<typename boost::is_complex<Val>::type, std::ostream&>::type write_value(std::ostream &s, Val v) { return s << v; } } // namespace detail /// Write dense array in Matrix Market format. template <typename Val> void mm_write( const std::string &fname, const Val *data, size_t rows, size_t cols = 1 ) { std::ofstream f(fname.c_str()); precondition(f, "Failed to open file \"" + fname + "\" for writing"); // Banner f << "%%MatrixMarket matrix array "; if (boost::is_complex<Val>::value) { f << "complex "; } else if(boost::is_integral<Val>::value) { f << "integer "; } else { f << "real "; } f << "general\n"; // Sizes f << rows << " " << cols << "\n"; // Data for(size_t j = 0; j < cols; ++j) { for(size_t i = 0; i < rows; ++i) { detail::write_value(f, data[i * cols + j]) << "\n"; } } } /// Write sparse matrix in Matrix Market format. template <class Matrix> void mm_write(const std::string &fname, const Matrix &A) { typedef typename backend::value_type<Matrix>::type Val; typedef typename backend::row_iterator<Matrix>::type row_iterator; const size_t rows = backend::rows(A); const size_t cols = backend::cols(A); const size_t nnz = backend::nonzeros(A); std::ofstream f(fname.c_str()); precondition(f, "Failed to open file \"" + fname + "\" for writing"); // Banner f << "%%MatrixMarket matrix coordinate "; if (boost::is_complex<Val>::value) { f << "complex "; } else if(boost::is_integral<Val>::value) { f << "integer "; } else { f << "real "; } f << "general\n"; // Sizes f << rows << " " << cols << " " << nnz << "\n"; // Data for(size_t i = 0; i < rows; ++i) { for(row_iterator a = backend::row_begin(A, i); a; ++a) { f << i + 1 << " " << a.col() + 1 << " "; detail::write_value(f, a.value()) << "\n"; } } } } // namespace io } // namespace amgcl #endif <commit_msg>Fix MatrixMarket reader for 8bit integers<commit_after>#ifndef AMGCL_IO_MM_HPP #define AMGCL_IO_MM_HPP /* The MIT License Copyright (c) 2012-2017 Denis Demidov <dennis.demidov@gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * \file amgcl/io/mm.hpp * \author Denis Demidov <dennis.demidov@gmail.com> * \brief Readers for Matrix Market sparse matrices and dense vectors. */ #include <vector> #include <string> #include <fstream> #include <sstream> #include <numeric> #include <boost/type_traits.hpp> #include <boost/tuple/tuple.hpp> #include <amgcl/util.hpp> #include <amgcl/backend/interface.hpp> #include <amgcl/value_type/interface.hpp> #include <amgcl/detail/sort_row.hpp> namespace amgcl { namespace io { /// Matrix market reader. class mm_reader { public: /// Open the file by name mm_reader(const std::string &fname) : f(fname.c_str()) { precondition(f, "Failed to open file \"" + fname + "\""); // Read banner. std::string line; precondition(std::getline(f, line), format_error()); std::istringstream is(line); std::string banner, mtx, coord, dtype, storage; precondition( is >> banner >> mtx >> coord >> dtype >> storage, format_error()); precondition(banner == "%%MatrixMarket", format_error("no banner")); precondition(mtx == "matrix", format_error("not a matrix")); if (storage == "general") { _symmetric = false; } else if (storage == "symmetric") { _symmetric = true; } else { precondition(false, "unsupported storage type"); } if (coord == "coordinate") { _sparse = true; } else if (coord == "array") { _sparse = false; } else { precondition(false, format_error("unsupported coordinate type")); } if (dtype == "real") { _complex = false; _integer = false; } else if (dtype == "complex") { _complex = true; _integer = false; } else if (dtype == "integer") { _complex = false; _integer = true; } else { precondition(false, format_error("unsupported data type")); } // Skip comments. std::streampos pos; do { pos = f.tellg(); precondition(std::getline(f, line), format_error("unexpected eof")); } while (line[0] == '%'); // Get back to the first non-comment line. f.seekg(pos); } /// Matrix in the file is symmetric. bool is_symmetric() const { return _symmetric; } /// Matrix in the file is sparse. bool is_sparse() const { return _sparse; } /// Matrix in the file is complex-valued. bool is_complex() const { return _complex; } /// Matrix in the file is integer-valued. bool is_integer() const { return _integer; } /// Read sparse matrix from the file. template <typename Idx, typename Val> boost::tuple<size_t, size_t> operator()( std::vector<Idx> &ptr, std::vector<Idx> &col, std::vector<Val> &val ) { precondition(_sparse, format_error("not a sparse matrix")); precondition(boost::is_complex<Val>::value == _complex, _complex ? "attempt to read complex values into real vector" : "attempt to read real values into complex vector" ); precondition(boost::is_integral<Val>::value == _integer, _integer ? "attempt to read integer values into real vector" : "attempt to read real values into integer vector" ); // Read sizes size_t n, m, nnz; std::string line; std::istringstream is; { precondition(std::getline(f, line), format_error("unexpected eof")); is.clear(); is.str(line); precondition(is >> n >> m >> nnz, format_error()); } std::vector<Idx> _row; _row.reserve(nnz); std::vector<Idx> _col; _col.reserve(nnz); std::vector<Val> _val; _val.reserve(nnz); for(size_t k = 0; k < nnz; ++k) { precondition(std::getline(f, line), format_error("unexpected eof")); is.clear(); is.str(line); Idx i, j; Val v; precondition(is >> i >> j, format_error()); v = read_value<Val>(is); _row.push_back(i-1); _col.push_back(j-1); _val.push_back(v); } precondition(_val.size() == nnz, format_error("inconsistent data")); ptr.resize(n+1); std::fill(ptr.begin(), ptr.end(), 0); for(size_t k = 0; k < nnz; ++k) { Idx i = _row[k]; Idx j = _col[k]; ++ptr[i+1]; if (_symmetric && j != i) ++ptr[j+1]; } std::partial_sum(ptr.begin(), ptr.end(), ptr.begin()); col.resize(ptr.back()); val.resize(ptr.back()); for(size_t k = 0; k < nnz; ++k) { Idx i = _row[k]; Idx j = _col[k]; Val v = _val[k]; Idx head = ptr[i]++; col[head] = j; val[head] = v; if (_symmetric && j != i) { Idx head = ptr[j]++; col[head] = i; val[head] = v; } } std::rotate(ptr.begin(), ptr.end() - 1, ptr.end()); ptr.front() = 0; #pragma omp parallel for for(ptrdiff_t i = 0; i < static_cast<ptrdiff_t>(n); ++i) { Idx beg = ptr[i]; Idx end = ptr[i+1]; amgcl::detail::sort_row(&col[0] + beg, &val[0] + beg, end - beg); } return boost::make_tuple(n, m); } /// Read dense array from the file. template <typename Val> boost::tuple<size_t, size_t> operator()(std::vector<Val> &val) { precondition(!_sparse, format_error("not a dense array")); precondition(boost::is_complex<Val>::value == _complex, _complex ? "attempt to read complex values into real vector" : "attempt to read real values into complex vector" ); precondition(boost::is_integral<Val>::value == _integer, _integer ? "attempt to read integer values into real vector" : "attempt to read real values into integer vector" ); // Read sizes size_t n, m; std::string line; std::istringstream is; { precondition(std::getline(f, line), format_error("unexpected eof")); is.clear(); is.str(line); precondition(is >> n >> m, format_error()); } val.resize(n * m); for(size_t j = 0; j < m; ++j) { for(size_t i = 0; i < n; ++i) { precondition(std::getline(f, line), format_error("unexpected eof")); is.clear(); is.str(line); val[i * m + j] = read_value<Val>(is); } } return boost::make_tuple(n, m); } private: std::ifstream f; bool _sparse; bool _symmetric; bool _complex; bool _integer; std::string format_error(const std::string &msg = "") const { std::string err_string = "MatrixMarket format error"; if (!msg.empty()) err_string += " (" + msg + ")"; return err_string; } template <typename T> typename boost::enable_if<typename boost::is_complex<T>::type, T>::type read_value(std::istream &s) { typename math::scalar_of<T>::type x,y; precondition(s >> x >> y, format_error()); return T(x,y); } template <typename T> typename boost::disable_if<typename boost::is_complex<T>::type, T>::type read_value(std::istream &s) { T x; if (std::is_same<T, char>::value) { // Special case: // We want to read 8bit integers from MatrixMarket, not chars. int i; precondition(s >> i, format_error()); x = static_cast<char>(i); } else { precondition(s >> x, format_error()); } return x; } }; namespace detail { template <typename Val> typename boost::enable_if<typename boost::is_complex<Val>::type, std::ostream&>::type write_value(std::ostream &s, Val v) { return s << std::real(v) << " " << std::imag(v); } template <typename Val> typename boost::disable_if<typename boost::is_complex<Val>::type, std::ostream&>::type write_value(std::ostream &s, Val v) { return s << v; } } // namespace detail /// Write dense array in Matrix Market format. template <typename Val> void mm_write( const std::string &fname, const Val *data, size_t rows, size_t cols = 1 ) { std::ofstream f(fname.c_str()); precondition(f, "Failed to open file \"" + fname + "\" for writing"); // Banner f << "%%MatrixMarket matrix array "; if (boost::is_complex<Val>::value) { f << "complex "; } else if(boost::is_integral<Val>::value) { f << "integer "; } else { f << "real "; } f << "general\n"; // Sizes f << rows << " " << cols << "\n"; // Data for(size_t j = 0; j < cols; ++j) { for(size_t i = 0; i < rows; ++i) { detail::write_value(f, data[i * cols + j]) << "\n"; } } } /// Write sparse matrix in Matrix Market format. template <class Matrix> void mm_write(const std::string &fname, const Matrix &A) { typedef typename backend::value_type<Matrix>::type Val; typedef typename backend::row_iterator<Matrix>::type row_iterator; const size_t rows = backend::rows(A); const size_t cols = backend::cols(A); const size_t nnz = backend::nonzeros(A); std::ofstream f(fname.c_str()); precondition(f, "Failed to open file \"" + fname + "\" for writing"); // Banner f << "%%MatrixMarket matrix coordinate "; if (boost::is_complex<Val>::value) { f << "complex "; } else if(boost::is_integral<Val>::value) { f << "integer "; } else { f << "real "; } f << "general\n"; // Sizes f << rows << " " << cols << " " << nnz << "\n"; // Data for(size_t i = 0; i < rows; ++i) { for(row_iterator a = backend::row_begin(A, i); a; ++a) { f << i + 1 << " " << a.col() + 1 << " "; detail::write_value(f, a.value()) << "\n"; } } } } // namespace io } // namespace amgcl #endif <|endoftext|>
<commit_before>/** * \file * \brief SoftwareTimerControlBlock class header * * \author Copyright (C) 2014-2016 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef INCLUDE_DISTORTOS_INTERNAL_SCHEDULER_SOFTWARETIMERCONTROLBLOCK_HPP_ #define INCLUDE_DISTORTOS_INTERNAL_SCHEDULER_SOFTWARETIMERCONTROLBLOCK_HPP_ #include "distortos/internal/scheduler/SoftwareTimerListNode.hpp" namespace distortos { class SoftwareTimer; namespace internal { /// SoftwareTimerControlBlock class is a control block of software timer class SoftwareTimerControlBlock : public SoftwareTimerListNode { public: /// type of runner for software timer's function using FunctionRunner = void(SoftwareTimer&); /** * \brief SoftwareTimerControlBlock's constructor * * \param [in] functionRunner is a reference to runner for software timer's function * \param [in] owner is a reference to SoftwareTimer object that owns this SoftwareTimerControlBlock */ constexpr SoftwareTimerControlBlock(FunctionRunner& functionRunner, SoftwareTimer& owner) : SoftwareTimerListNode{}, functionRunner_{functionRunner}, owner_{owner} { } /** * \brief SoftwareTimerControlBlock's destructor * * If the timer is running it is stopped. */ ~SoftwareTimerControlBlock() { stop(); } /** * \return true if the timer is running, false otherwise */ bool isRunning() const { return node.isLinked(); } /** * \brief Runs software timer's function. * * \note this should only be called by SoftwareTimerSupervisor::tickInterruptHandler() */ void run() const { functionRunner_(owner_); } /** * \brief Starts the timer. * * \param [in] timePoint is the time point at which the function will be executed */ void start(TickClock::time_point timePoint); /** * \brief Stops the timer. */ void stop(); SoftwareTimerControlBlock(const SoftwareTimerControlBlock&) = delete; SoftwareTimerControlBlock(SoftwareTimerControlBlock&&) = default; const SoftwareTimerControlBlock& operator=(const SoftwareTimerControlBlock&) = delete; SoftwareTimerControlBlock& operator=(SoftwareTimerControlBlock&&) = delete; private: /** * \brief Stops the timer - internal version, with no interrupt masking. */ void stopInternal(); /// reference to runner for software timer's function FunctionRunner& functionRunner_; /// reference to SoftwareTimer object that owns this SoftwareTimerControlBlock SoftwareTimer& owner_; }; } // namespace internal } // namespace distortos #endif // INCLUDE_DISTORTOS_INTERNAL_SCHEDULER_SOFTWARETIMERCONTROLBLOCK_HPP_ <commit_msg>Add member variable with period to SoftwareTimerControlBlock<commit_after>/** * \file * \brief SoftwareTimerControlBlock class header * * \author Copyright (C) 2014-2016 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef INCLUDE_DISTORTOS_INTERNAL_SCHEDULER_SOFTWARETIMERCONTROLBLOCK_HPP_ #define INCLUDE_DISTORTOS_INTERNAL_SCHEDULER_SOFTWARETIMERCONTROLBLOCK_HPP_ #include "distortos/internal/scheduler/SoftwareTimerListNode.hpp" namespace distortos { class SoftwareTimer; namespace internal { /// SoftwareTimerControlBlock class is a control block of software timer class SoftwareTimerControlBlock : public SoftwareTimerListNode { public: /// type of runner for software timer's function using FunctionRunner = void(SoftwareTimer&); /** * \brief SoftwareTimerControlBlock's constructor * * \param [in] functionRunner is a reference to runner for software timer's function * \param [in] owner is a reference to SoftwareTimer object that owns this SoftwareTimerControlBlock */ constexpr SoftwareTimerControlBlock(FunctionRunner& functionRunner, SoftwareTimer& owner) : SoftwareTimerListNode{}, period_{}, functionRunner_{functionRunner}, owner_{owner} { } /** * \brief SoftwareTimerControlBlock's destructor * * If the timer is running it is stopped. */ ~SoftwareTimerControlBlock() { stop(); } /** * \return true if the timer is running, false otherwise */ bool isRunning() const { return node.isLinked(); } /** * \brief Runs software timer's function. * * \note this should only be called by SoftwareTimerSupervisor::tickInterruptHandler() */ void run() const { functionRunner_(owner_); } /** * \brief Starts the timer. * * \param [in] timePoint is the time point at which the function will be executed */ void start(TickClock::time_point timePoint); /** * \brief Stops the timer. */ void stop(); SoftwareTimerControlBlock(const SoftwareTimerControlBlock&) = delete; SoftwareTimerControlBlock(SoftwareTimerControlBlock&&) = default; const SoftwareTimerControlBlock& operator=(const SoftwareTimerControlBlock&) = delete; SoftwareTimerControlBlock& operator=(SoftwareTimerControlBlock&&) = delete; private: /** * \brief Stops the timer - internal version, with no interrupt masking. */ void stopInternal(); /// period used to restart repetitive software timer, 0 for one-shot software timers TickClock::duration period_; /// reference to runner for software timer's function FunctionRunner& functionRunner_; /// reference to SoftwareTimer object that owns this SoftwareTimerControlBlock SoftwareTimer& owner_; }; } // namespace internal } // namespace distortos #endif // INCLUDE_DISTORTOS_INTERNAL_SCHEDULER_SOFTWARETIMERCONTROLBLOCK_HPP_ <|endoftext|>
<commit_before>#include <memory> #include <algorithm> #include <utility> #include "main.h" using ObjClass = uint32_t; static inline ObjClass getObjClass(unsigned char ei_class, unsigned char ei_data, unsigned char ei_osabi) { return (ei_data << 16) | (ei_class << 8) | ei_osabi; } static inline ObjClass getObjClass(Elf *elf) { return getObjClass(elf->ei_class, elf->ei_data, elf->ei_osabi); } DB::~DB() { for (auto &pkg : packages) delete pkg; } PackageList::const_iterator DB::find_pkg_i(const std::string& name) const { return std::find_if(packages.begin(), packages.end(), [&name](const Package *pkg) { return pkg->name == name; }); } Package* DB::find_pkg(const std::string& name) const { auto pkg = find_pkg_i(name); return (pkg != packages.end()) ? *pkg : nullptr; } bool DB::delete_package(const std::string& name) { Package *old; { auto pkgiter = find_pkg_i(name); if (pkgiter == packages.end()) return true; old = *pkgiter; packages.erase(packages.begin() + (pkgiter - packages.begin())); } for (auto &elfsp : old->objects) { Elf *elf = elfsp.get(); required_found.erase(elf); required_missing.erase(elf); // remove the object from the list auto self = std::find(objects.begin(), objects.end(), elf); objects.erase(self); // for each object which depends on this object, search for a replacing object for (auto &found : required_found) { // does this object depend on 'elf'? auto ref = std::find(found.second.begin(), found.second.end(), elf); if (ref == found.second.end()) continue; // erase found.second.erase(ref); // search for this dependency anew Elf *seeker = found.first; Elf *other = find_for(seeker, elf->basename); if (!other) { // it's missing now required_missing[seeker].insert(elf->basename); } else { // replace it with a new object found.second.insert(other); } } } delete old; std::remove_if(objects.begin(), objects.end(), [](rptr<Elf> &obj) { return 1 == obj->refcount; }); return true; } static bool pathlist_contains(const std::string& list, const std::string& path) { size_t at = 0; size_t to = list.find_first_of(':', 0); while (to != std::string::npos) { if (list.compare(at, to-at, path) == 0) return true; at = to+1; to = list.find_first_of(':', at); } if (list.compare(at, std::string::npos, path) == 0) return true; return false; } bool DB::elf_finds(Elf *elf, const std::string& path) const { // DT_RPATH first if (elf->rpath_set && pathlist_contains(elf->rpath, path)) return true; // LD_LIBRARY_PATH - ignored // DT_RUNPATH if (elf->runpath_set && pathlist_contains(elf->runpath, path)) return true; // Trusted Paths if (path == "/lib" || path == "/usr/lib") { return true; } if (std::find(library_path.begin(), library_path.end(), path) != library_path.end()) return true; return false; } bool DB::install_package(Package* &&pkg) { if (!delete_package(pkg->name)) return false; packages.push_back(pkg); for (auto &obj : pkg->objects) objects.push_back(obj); for (auto &obj : pkg->objects) { ObjClass objclass = getObjClass(obj); // check if the object is required for (auto missing = required_missing.begin(); missing != required_missing.end();) { Elf *seeker = missing->first; if (getObjClass(seeker) != objclass || !elf_finds(seeker, obj->dirname)) { ++missing; continue; } bool needs = (0 != missing->second.erase(obj->basename)); if (needs) // the library is indeed required and found: required_found[seeker].insert(obj); if (0 == missing->second.size()) required_missing.erase(missing++); else ++missing; } // search for whatever THIS object requires #if 0 ObjectSet req_found; StringSet req_missing; for (auto &needed : obj->needed) { Elf *found = find_for(obj, needed); if (found) req_found.insert(found); else req_missing.insert(needed); } if (req_found.size()) required_found[obj] = std::move(req_found); if (req_missing.size()) required_missing[obj] = std::move(req_missing); #else link_object(obj); #endif } return true; } Elf* DB::find_for(Elf *obj, const std::string& needed) const { log(Debug, "dependency of %s/%s : %s\n", obj->dirname.c_str(), obj->basename.c_str(), needed.c_str()); ObjClass objclass = getObjClass(obj); for (auto &lib : objects) { if (getObjClass(lib) != objclass) log(Debug, " skipping %s/%s (objclass)\n", lib->dirname.c_str(), lib->basename.c_str()); else if (lib->basename != needed) log(Debug, " skipping %s/%s (wrong name)\n", lib->dirname.c_str(), lib->basename.c_str()); else if (!elf_finds(obj, lib->dirname)) log(Debug, " skipping %s/%s (not visible)\n", lib->dirname.c_str(), lib->basename.c_str()); if (getObjClass(lib) != objclass || lib->basename != needed || !elf_finds(obj, lib->dirname)) { continue; } // same class, same name, and visible... return lib; } return 0; } void DB::link_object(Elf *obj) { ObjectSet req_found; StringSet req_missing; for (auto &needed : obj->needed) { Elf *found = find_for(obj, needed); if (found) req_found.insert(found); else req_missing.insert(needed); } if (req_found.size()) required_found[obj] = std::move(req_found); if (req_missing.size()) required_missing[obj] = std::move(req_missing); } void DB::relink_all() { required_found.clear(); required_missing.clear(); for (auto &obj : objects) { link_object(obj); } } void DB::fix_paths() { for (auto &obj : objects) { fixpath(obj->rpath); fixpath(obj->runpath); } } bool DB::empty() const { return packages.size() == 0 && objects.size() == 0 && required_found.size() == 0 && required_missing.size() == 0; } bool DB::ld_clear() { if (library_path.size()) { library_path.clear(); return true; } return false; } bool DB::ld_append(const std::string& dir) { auto old = std::find(library_path.begin(), library_path.end(), dir); if (old == library_path.begin() + (library_path.size()-1)) return false; if (old != library_path.end()) library_path.erase(old); library_path.push_back(dir); return true; } bool DB::ld_prepend(const std::string& dir) { auto old = std::find(library_path.begin(), library_path.end(), dir); if (old == library_path.begin()) return false; if (old != library_path.end()) library_path.erase(old); library_path.insert(library_path.begin(), dir); return true; } bool DB::ld_delete(const std::string& dir) { auto old = std::find(library_path.begin(), library_path.end(), dir); if (old != library_path.end()) { library_path.erase(old); return true; } return false; } bool DB::ld_insert(const std::string& dir, size_t i) { if (!library_path.size()) i = 0; else if (i >= library_path.size()) i = library_path.size()-1; auto old = std::find(library_path.begin(), library_path.end(), dir); if (old == library_path.end()) { library_path.insert(library_path.begin() + i, dir); return true; } size_t oldidx = old - library_path.begin(); if (oldidx == i) return false; // exists library_path.erase(old); library_path.insert(library_path.begin() + i, dir); return true; } void DB::show_info() { printf("DB version: %u\n", (unsigned)DB::version); printf("DB name: [%s]\n", name.c_str()); printf("Additional Library Paths:\n"); unsigned id = 0; for (auto &p : library_path) printf(" %u: %s\n", id++, p.c_str()); } void DB::show_packages() { printf("Packages:\n"); for (auto &pkg : packages) { printf(" -> %s - %s\n", pkg->name.c_str(), pkg->version.c_str()); if (opt_verbosity >= 1) { for (auto &obj : pkg->objects) printf(" contains %s / %s\n", obj->dirname.c_str(), obj->basename.c_str()); } } } void DB::show_objects() { if (!objects.size()) { printf("Objects: none\n"); return; } printf("Objects:\n"); for (auto &obj : objects) { printf(" -> %s / %s\n", obj->dirname.c_str(), obj->basename.c_str()); if (opt_verbosity < 1) continue; printf(" class: %u (%s)\n", (unsigned)obj->ei_class, obj->classString()); printf(" data: %u (%s)\n", (unsigned)obj->ei_data, obj->dataString()); printf(" osabi: %u (%s)\n", (unsigned)obj->ei_osabi, obj->osabiString()); if (opt_verbosity < 2) continue; printf(" finds:\n"); { auto &set = required_found[obj]; for (auto &found : set) printf(" -> %s / %s\n", found->dirname.c_str(), found->basename.c_str()); } printf(" misses:\n"); { auto &set = required_missing[obj]; for (auto &miss : set) printf(" -> %s\n", miss.c_str()); } if (obj->rpath_set) printf(" rpath: %s\n", obj->rpath.c_str()); if (obj->runpath_set) printf(" runpath: %s\n", obj->runpath.c_str()); } printf("\n`found` entry set size: %lu\n", (unsigned long)required_found.size()); printf("`missing` entry set size: %lu\n", (unsigned long)required_missing.size()); } void DB::show_missing() { if (!required_missing.size()) { printf("Missing: nothing\n"); return; } printf("Missing:\n"); for (auto &mis : required_missing) { Elf *obj = mis.first; StringSet &set = mis.second; printf(" -> %s / %s\n", obj->dirname.c_str(), obj->basename.c_str()); for (auto &s : set) printf(" misses: %s\n", s.c_str()); } } void DB::show_found() { printf("Found:\n"); for (auto &fnd : required_found) { Elf *obj = fnd.first; ObjectSet &set = fnd.second; printf(" -> %s / %s\n", obj->dirname.c_str(), obj->basename.c_str()); for (auto &s : set) printf(" finds: %s\n", s->basename.c_str()); } } <commit_msg>remove old #if-0-ed code<commit_after>#include <memory> #include <algorithm> #include <utility> #include "main.h" using ObjClass = uint32_t; static inline ObjClass getObjClass(unsigned char ei_class, unsigned char ei_data, unsigned char ei_osabi) { return (ei_data << 16) | (ei_class << 8) | ei_osabi; } static inline ObjClass getObjClass(Elf *elf) { return getObjClass(elf->ei_class, elf->ei_data, elf->ei_osabi); } DB::~DB() { for (auto &pkg : packages) delete pkg; } PackageList::const_iterator DB::find_pkg_i(const std::string& name) const { return std::find_if(packages.begin(), packages.end(), [&name](const Package *pkg) { return pkg->name == name; }); } Package* DB::find_pkg(const std::string& name) const { auto pkg = find_pkg_i(name); return (pkg != packages.end()) ? *pkg : nullptr; } bool DB::delete_package(const std::string& name) { Package *old; { auto pkgiter = find_pkg_i(name); if (pkgiter == packages.end()) return true; old = *pkgiter; packages.erase(packages.begin() + (pkgiter - packages.begin())); } for (auto &elfsp : old->objects) { Elf *elf = elfsp.get(); required_found.erase(elf); required_missing.erase(elf); // remove the object from the list auto self = std::find(objects.begin(), objects.end(), elf); objects.erase(self); // for each object which depends on this object, search for a replacing object for (auto &found : required_found) { // does this object depend on 'elf'? auto ref = std::find(found.second.begin(), found.second.end(), elf); if (ref == found.second.end()) continue; // erase found.second.erase(ref); // search for this dependency anew Elf *seeker = found.first; Elf *other = find_for(seeker, elf->basename); if (!other) { // it's missing now required_missing[seeker].insert(elf->basename); } else { // replace it with a new object found.second.insert(other); } } } delete old; std::remove_if(objects.begin(), objects.end(), [](rptr<Elf> &obj) { return 1 == obj->refcount; }); return true; } static bool pathlist_contains(const std::string& list, const std::string& path) { size_t at = 0; size_t to = list.find_first_of(':', 0); while (to != std::string::npos) { if (list.compare(at, to-at, path) == 0) return true; at = to+1; to = list.find_first_of(':', at); } if (list.compare(at, std::string::npos, path) == 0) return true; return false; } bool DB::elf_finds(Elf *elf, const std::string& path) const { // DT_RPATH first if (elf->rpath_set && pathlist_contains(elf->rpath, path)) return true; // LD_LIBRARY_PATH - ignored // DT_RUNPATH if (elf->runpath_set && pathlist_contains(elf->runpath, path)) return true; // Trusted Paths if (path == "/lib" || path == "/usr/lib") { return true; } if (std::find(library_path.begin(), library_path.end(), path) != library_path.end()) return true; return false; } bool DB::install_package(Package* &&pkg) { if (!delete_package(pkg->name)) return false; packages.push_back(pkg); for (auto &obj : pkg->objects) objects.push_back(obj); for (auto &obj : pkg->objects) { ObjClass objclass = getObjClass(obj); // check if the object is required for (auto missing = required_missing.begin(); missing != required_missing.end();) { Elf *seeker = missing->first; if (getObjClass(seeker) != objclass || !elf_finds(seeker, obj->dirname)) { ++missing; continue; } bool needs = (0 != missing->second.erase(obj->basename)); if (needs) // the library is indeed required and found: required_found[seeker].insert(obj); if (0 == missing->second.size()) required_missing.erase(missing++); else ++missing; } // search for whatever THIS object requires link_object(obj); } return true; } Elf* DB::find_for(Elf *obj, const std::string& needed) const { log(Debug, "dependency of %s/%s : %s\n", obj->dirname.c_str(), obj->basename.c_str(), needed.c_str()); ObjClass objclass = getObjClass(obj); for (auto &lib : objects) { if (getObjClass(lib) != objclass) log(Debug, " skipping %s/%s (objclass)\n", lib->dirname.c_str(), lib->basename.c_str()); else if (lib->basename != needed) log(Debug, " skipping %s/%s (wrong name)\n", lib->dirname.c_str(), lib->basename.c_str()); else if (!elf_finds(obj, lib->dirname)) log(Debug, " skipping %s/%s (not visible)\n", lib->dirname.c_str(), lib->basename.c_str()); if (getObjClass(lib) != objclass || lib->basename != needed || !elf_finds(obj, lib->dirname)) { continue; } // same class, same name, and visible... return lib; } return 0; } void DB::link_object(Elf *obj) { ObjectSet req_found; StringSet req_missing; for (auto &needed : obj->needed) { Elf *found = find_for(obj, needed); if (found) req_found.insert(found); else req_missing.insert(needed); } if (req_found.size()) required_found[obj] = std::move(req_found); if (req_missing.size()) required_missing[obj] = std::move(req_missing); } void DB::relink_all() { required_found.clear(); required_missing.clear(); for (auto &obj : objects) { link_object(obj); } } void DB::fix_paths() { for (auto &obj : objects) { fixpath(obj->rpath); fixpath(obj->runpath); } } bool DB::empty() const { return packages.size() == 0 && objects.size() == 0 && required_found.size() == 0 && required_missing.size() == 0; } bool DB::ld_clear() { if (library_path.size()) { library_path.clear(); return true; } return false; } bool DB::ld_append(const std::string& dir) { auto old = std::find(library_path.begin(), library_path.end(), dir); if (old == library_path.begin() + (library_path.size()-1)) return false; if (old != library_path.end()) library_path.erase(old); library_path.push_back(dir); return true; } bool DB::ld_prepend(const std::string& dir) { auto old = std::find(library_path.begin(), library_path.end(), dir); if (old == library_path.begin()) return false; if (old != library_path.end()) library_path.erase(old); library_path.insert(library_path.begin(), dir); return true; } bool DB::ld_delete(const std::string& dir) { auto old = std::find(library_path.begin(), library_path.end(), dir); if (old != library_path.end()) { library_path.erase(old); return true; } return false; } bool DB::ld_insert(const std::string& dir, size_t i) { if (!library_path.size()) i = 0; else if (i >= library_path.size()) i = library_path.size()-1; auto old = std::find(library_path.begin(), library_path.end(), dir); if (old == library_path.end()) { library_path.insert(library_path.begin() + i, dir); return true; } size_t oldidx = old - library_path.begin(); if (oldidx == i) return false; // exists library_path.erase(old); library_path.insert(library_path.begin() + i, dir); return true; } void DB::show_info() { printf("DB version: %u\n", (unsigned)DB::version); printf("DB name: [%s]\n", name.c_str()); printf("Additional Library Paths:\n"); unsigned id = 0; for (auto &p : library_path) printf(" %u: %s\n", id++, p.c_str()); } void DB::show_packages() { printf("Packages:\n"); for (auto &pkg : packages) { printf(" -> %s - %s\n", pkg->name.c_str(), pkg->version.c_str()); if (opt_verbosity >= 1) { for (auto &obj : pkg->objects) printf(" contains %s / %s\n", obj->dirname.c_str(), obj->basename.c_str()); } } } void DB::show_objects() { if (!objects.size()) { printf("Objects: none\n"); return; } printf("Objects:\n"); for (auto &obj : objects) { printf(" -> %s / %s\n", obj->dirname.c_str(), obj->basename.c_str()); if (opt_verbosity < 1) continue; printf(" class: %u (%s)\n", (unsigned)obj->ei_class, obj->classString()); printf(" data: %u (%s)\n", (unsigned)obj->ei_data, obj->dataString()); printf(" osabi: %u (%s)\n", (unsigned)obj->ei_osabi, obj->osabiString()); if (opt_verbosity < 2) continue; printf(" finds:\n"); { auto &set = required_found[obj]; for (auto &found : set) printf(" -> %s / %s\n", found->dirname.c_str(), found->basename.c_str()); } printf(" misses:\n"); { auto &set = required_missing[obj]; for (auto &miss : set) printf(" -> %s\n", miss.c_str()); } if (obj->rpath_set) printf(" rpath: %s\n", obj->rpath.c_str()); if (obj->runpath_set) printf(" runpath: %s\n", obj->runpath.c_str()); } printf("\n`found` entry set size: %lu\n", (unsigned long)required_found.size()); printf("`missing` entry set size: %lu\n", (unsigned long)required_missing.size()); } void DB::show_missing() { if (!required_missing.size()) { printf("Missing: nothing\n"); return; } printf("Missing:\n"); for (auto &mis : required_missing) { Elf *obj = mis.first; StringSet &set = mis.second; printf(" -> %s / %s\n", obj->dirname.c_str(), obj->basename.c_str()); for (auto &s : set) printf(" misses: %s\n", s.c_str()); } } void DB::show_found() { printf("Found:\n"); for (auto &fnd : required_found) { Elf *obj = fnd.first; ObjectSet &set = fnd.second; printf(" -> %s / %s\n", obj->dirname.c_str(), obj->basename.c_str()); for (auto &s : set) printf(" finds: %s\n", s->basename.c_str()); } } <|endoftext|>
<commit_before>#include <vector> #include <string> #include <iostream> #include <queso/Environment.h> #include <queso/GslVector.h> #include <queso/GslMatrix.h> #include <queso/VectorSpace.h> int main(int argc, char **argv) { MPI_Init(&argc, &argv); QUESO::EnvOptionsValues options; options.m_numSubEnvironments = 1; options.m_subDisplayFileName = "debug_output"; options.m_seed = 1.0; options.m_checkingLevel = 1; options.m_displayVerbosity = 20; QUESO::FullEnvironment *env = new QUESO::FullEnvironment(MPI_COMM_WORLD, "", "", &options); std::vector<std::string> names(1); names[0] = "my_name"; QUESO::VectorSpace<QUESO::GslVector, QUESO::GslMatrix> vec_space(*env, "vec_prefix", 1, &names); // 1x1 diagonal matrix containing the value 3.0 on the diagonal QUESO::GslMatrix * diag_matrix = vec_space.newDiagMatrix(3.0); if ((*diag_matrix)(0,0) != 3.0) { std::cerr << "newDiagMatrix test failed" << std::endl; return 1; } if (vec_space.globalIdOfFirstComponent() != 0) { std::cerr << "failed globalIdOfFirstComponent test" << std::endl; return 1; } const QUESO::DistArray<std::string> *names_array = vec_space.componentsNamesArray(); std::cout << "Test print: componentsNamesArray: " << *names_array << std::endl; std::cout << "Test print: localComponentName: " << vec_space.localComponentName(0) << std::endl; std::cout << "Test print: printComponentsNames horizontally: "; vec_space.printComponentsNames(std::cout, true); std::cout << std::endl; std::cout << "Test print: printComponentsNames vertically: "; vec_space.printComponentsNames(std::cout, false); std::cout << std::endl; std::cout << "Test print: print: "; vec_space.print(std::cout); std::cout << std::endl; delete diag_matrix; delete env; MPI_Finalize(); return 0; } <commit_msg>Adding verbosity options to pump out some coverage<commit_after>#include <vector> #include <string> #include <iostream> #include <set> #include <queso/Environment.h> #include <queso/GslVector.h> #include <queso/GslMatrix.h> #include <queso/VectorSpace.h> int main(int argc, char **argv) { MPI_Init(&argc, &argv); QUESO::EnvOptionsValues options; options.m_numSubEnvironments = 1; options.m_subDisplayFileName = "outputData/debug_output"; options.m_subDisplayAllowAll = 0; options.m_subDisplayAllowedSet.insert(0); options.m_seed = 1.0; options.m_checkingLevel = 1; options.m_displayVerbosity = 20; QUESO::FullEnvironment *env = new QUESO::FullEnvironment(MPI_COMM_WORLD, "", "", &options); std::vector<std::string> names(1); names[0] = "my_name"; QUESO::VectorSpace<QUESO::GslVector, QUESO::GslMatrix> vec_space(*env, "vec_prefix", 1, &names); // 1x1 diagonal matrix containing the value 3.0 on the diagonal QUESO::GslMatrix * diag_matrix = vec_space.newDiagMatrix(3.0); if ((*diag_matrix)(0,0) != 3.0) { std::cerr << "newDiagMatrix test failed" << std::endl; return 1; } if (vec_space.globalIdOfFirstComponent() != 0) { std::cerr << "failed globalIdOfFirstComponent test" << std::endl; return 1; } const QUESO::DistArray<std::string> *names_array = vec_space.componentsNamesArray(); std::cout << "Test print: componentsNamesArray: " << *names_array << std::endl; std::cout << "Test print: localComponentName: " << vec_space.localComponentName(0) << std::endl; std::cout << "Test print: printComponentsNames horizontally: "; vec_space.printComponentsNames(std::cout, true); std::cout << std::endl; std::cout << "Test print: printComponentsNames vertically: "; vec_space.printComponentsNames(std::cout, false); std::cout << std::endl; std::cout << "Test print: print: "; vec_space.print(std::cout); std::cout << std::endl; delete diag_matrix; MPI_Finalize(); return 0; } <|endoftext|>
<commit_before>/** * Copyright (c) 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ #include "LocalDce.h" #include <iostream> #include <array> #include <unordered_set> #include <vector> #include <boost/dynamic_bitset.hpp> #include "ControlFlow.h" #include "DexClass.h" #include "IRInstruction.h" #include "DexUtil.h" #include "Transform.h" #include "Walkers.h" namespace { constexpr const char* METRIC_DEAD_INSTRUCTIONS = "num_dead_instructions"; constexpr const char* METRIC_UNREACHABLE_INSTRUCTIONS = "num_unreachable_instructions"; /* * These instructions have observable side effects so must always be considered * live, regardless of whether their output is consumed by another instruction. */ static bool has_side_effects(DexOpcode opc) { switch (opc) { case OPCODE_RETURN_VOID: case OPCODE_RETURN: case OPCODE_RETURN_WIDE: case OPCODE_RETURN_OBJECT: case OPCODE_MONITOR_ENTER: case OPCODE_MONITOR_EXIT: case OPCODE_CHECK_CAST: case OPCODE_FILL_ARRAY_DATA: case OPCODE_THROW: case OPCODE_GOTO: case OPCODE_GOTO_16: case OPCODE_GOTO_32: case OPCODE_PACKED_SWITCH: case OPCODE_SPARSE_SWITCH: case OPCODE_IF_EQ: case OPCODE_IF_NE: case OPCODE_IF_LT: case OPCODE_IF_GE: case OPCODE_IF_GT: case OPCODE_IF_LE: case OPCODE_IF_EQZ: case OPCODE_IF_NEZ: case OPCODE_IF_LTZ: case OPCODE_IF_GEZ: case OPCODE_IF_GTZ: case OPCODE_IF_LEZ: case OPCODE_APUT: case OPCODE_APUT_WIDE: case OPCODE_APUT_OBJECT: case OPCODE_APUT_BOOLEAN: case OPCODE_APUT_BYTE: case OPCODE_APUT_CHAR: case OPCODE_APUT_SHORT: case OPCODE_IPUT: case OPCODE_IPUT_WIDE: case OPCODE_IPUT_OBJECT: case OPCODE_IPUT_BOOLEAN: case OPCODE_IPUT_BYTE: case OPCODE_IPUT_CHAR: case OPCODE_IPUT_SHORT: case OPCODE_SPUT: case OPCODE_SPUT_WIDE: case OPCODE_SPUT_OBJECT: case OPCODE_SPUT_BOOLEAN: case OPCODE_SPUT_BYTE: case OPCODE_SPUT_CHAR: case OPCODE_SPUT_SHORT: case OPCODE_INVOKE_VIRTUAL: case OPCODE_INVOKE_SUPER: case OPCODE_INVOKE_DIRECT: case OPCODE_INVOKE_STATIC: case OPCODE_INVOKE_INTERFACE: case OPCODE_INVOKE_VIRTUAL_RANGE: case OPCODE_INVOKE_SUPER_RANGE: case OPCODE_INVOKE_DIRECT_RANGE: case OPCODE_INVOKE_STATIC_RANGE: case OPCODE_INVOKE_INTERFACE_RANGE: case FOPCODE_PACKED_SWITCH: case FOPCODE_SPARSE_SWITCH: case FOPCODE_FILLED_ARRAY: case IOPCODE_LOAD_PARAM: case IOPCODE_LOAD_PARAM_OBJECT: case IOPCODE_LOAD_PARAM_WIDE: return true; default: return false; } not_reached(); } template <typename... T> std::string show(const boost::dynamic_bitset<T...>& bits) { std::string ret; to_string(bits, ret); return ret; } //////////////////////////////////////////////////////////////////////////////// class LocalDce { public: struct Stats { size_t dead_instruction_count{0}; size_t unreachable_instruction_count{0}; }; /* * Eliminate dead code using a standard backward dataflow analysis for * liveness. The algorithm is as follows: * * - Maintain a bitvector for each block representing the liveness for each * register. Function call results are represented by bit #num_regs. * * - Walk the blocks in postorder. Compute each block's output state by * OR-ing the liveness of its successors * * - Walk each block's instructions in reverse to determine its input state. * An instruction's input registers are live if (a) it has side effects, or * (b) its output registers are live. * * - If the liveness of any block changes during a pass, repeat it. Since * anything live in one pass is guaranteed to be live in the next, this is * guaranteed to reach a fixed point and terminate. Visiting blocks in * postorder guarantees a minimum number of passes. * * - Catch blocks are handled slightly differently; since any instruction * inside a `try` region can jump to a catch block, we assume that any * registers that are live-in to a catch block must be kept live throughout * the `try` region. (This is actually conservative, since only * potentially-excepting instructions can jump to a catch.) */ public: LocalDce() { /* * Pure methods have no observable side effects, so they can be removed * if their outputs are not used. * * TODO: Derive this list with static analysis rather than hard-coding * it. */ m_pure_methods.emplace(DexMethod::make_method( "Ljava/lang/Class;", "getSimpleName", "Ljava/lang/String;", {})); } void dce(DexMethod* method) { auto code = method->get_code(); code->build_cfg(); auto& cfg = code->cfg(); auto blocks = postorder_sort(cfg.blocks()); auto regs = method->get_code()->get_registers_size(); std::vector<boost::dynamic_bitset<>> liveness( cfg.blocks().size(), boost::dynamic_bitset<>(regs + 1)); bool changed; std::vector<FatMethod::iterator> dead_instructions; TRACE(DCE, 5, "%s\n", SHOW(method)); TRACE(DCE, 5, "%s", SHOW(cfg)); // Iterate liveness analysis to a fixed point. do { changed = false; dead_instructions.clear(); for (auto& b : blocks) { auto prev_liveness = liveness.at(b->id()); auto& bliveness = liveness.at(b->id()); bliveness.reset(); TRACE(DCE, 5, "B%lu: %s\n", b->id(), show(bliveness).c_str()); // Compute live-out for this block from its successors. for (auto& s : b->succs()) { if(s->id() == b->id()) { bliveness |= prev_liveness; } TRACE(DCE, 5, " S%lu: %s\n", s->id(), show(liveness[s->id()]).c_str()); bliveness |= liveness[s->id()]; } // Compute live-in for this block by walking its instruction list in // reverse and applying the liveness rules. for (auto it = b->rbegin(); it != b->rend(); ++it) { if (it->type != MFLOW_OPCODE) { continue; } bool required = is_required(it->insn, bliveness); if (required) { update_liveness(it->insn, bliveness); } else { dead_instructions.push_back(std::prev(it.base())); } TRACE(CFG, 5, "%s\n%s\n", show(it->insn).c_str(), show(bliveness).c_str()); } if (bliveness != prev_liveness) { changed = true; } } } while (changed); // Remove dead instructions. TRACE(DCE, 2, "%s\n", SHOW(method)); for (auto dead : dead_instructions) { TRACE(DCE, 2, "DEAD: %s\n", SHOW(dead->insn)); code->remove_opcode(dead); } m_stats.dead_instruction_count += dead_instructions.size(); // if we deleted an instruction that may throw, we'll need to remove any // EDGE_THROW edges in the CFG... ideally we would just prune that edge, // but we can do a conservative and inefficient hack for now and just // rebuild the entire graph if (dead_instructions.size() > 0) { code->build_cfg(); } remove_unreachable_blocks(method, &*code); TRACE(DCE, 5, "=== Post-DCE CFG ===\n"); TRACE(DCE, 5, "%s", SHOW(code->cfg())); } const Stats& get_stats() const { return m_stats; } private: void remove_block(IRCode* code, Block* b) { for (auto& mei : InstructionIterable(b)) { code->remove_opcode(mei.insn); ++m_stats.unreachable_instruction_count; } } void remove_unreachable_blocks(DexMethod* method, IRCode* code) { auto& cfg = code->cfg(); auto& blocks = cfg.blocks(); // Remove edges to catch blocks that no longer exist. std::vector<std::pair<Block*, Block*>> remove_edges; for (auto& b : blocks) { if (!is_catch(b)) { continue; } for (auto& p : b->preds()) { if (!ends_with_may_throw(p)) { // We removed whatever instruction could throw to this catch. remove_edges.emplace_back(p, b); } } } for (auto& e : remove_edges) { cfg.remove_edge(e.first, e.second, EDGE_THROW); } remove_edges.clear(); // remove unreachable blocks std::unordered_set<Block*> visited; std::function<void (Block*)> visit = [&](Block* b) { if (visited.find(b) != visited.end()) { return; } visited.emplace(b); for (auto& s : b->succs()) { visit(s); } }; visit(blocks.at(0)); for (size_t i = 1; i < blocks.size(); ++i) { auto& b = blocks.at(i); if (visited.find(b) != visited.end()) { continue; } for (auto& s : b->succs()) { remove_edges.emplace_back(b, s); } for (auto& p : remove_edges) { cfg.remove_all_edges(p.first, p.second); } remove_block(code, b); } // comb the method looking for superfluous try sections that do not enclose // throwing opcodes; remove them. note that try sections should never be // nested, otherwise this won't produce the right result. bool encloses_throw {false}; MethodItemEntry* try_start {nullptr}; for (auto& mie : *code) { if (mie.type == MFLOW_TRY) { auto tentry = mie.tentry; if (tentry->type == TRY_START) { encloses_throw = false; try_start = &mie; } else if (!encloses_throw /* && tentry->type == TRY_END */) { try_start->type = MFLOW_FALLTHROUGH; try_start->throwing_mie = nullptr; try_start = nullptr; mie.type = MFLOW_FALLTHROUGH; mie.throwing_mie = nullptr; } } else if (mie.type == MFLOW_OPCODE) { auto op = mie.insn->opcode(); encloses_throw = encloses_throw || opcode::may_throw(op) || op == OPCODE_THROW; } } } /* * An instruction is required (i.e., live) if it has side effects or if its * destination register is live. */ bool is_required(IRInstruction* inst, const boost::dynamic_bitset<>& bliveness) { if (has_side_effects(inst->opcode())) { if (is_invoke(inst->opcode())) { if (!is_pure(inst->get_method())) { return true; } return bliveness.test(bliveness.size() - 1); } return true; } else if (inst->dests_size()) { bool result = bliveness.test(inst->dest()); if (inst->dest_is_wide()) { result |= bliveness.test(inst->dest() + 1); } return result; } else if (is_filled_new_array(inst->opcode())) { // filled-new-array passes its dest via the return-value slot, but isn't // inherently live like the invoke-* instructions. return bliveness.test(bliveness.size() - 1); } return false; } bool is_pure(DexMethod* method) { if (assumenosideeffects(method)) { return true; } return m_pure_methods.find(method) != m_pure_methods.end(); } /* * Update the liveness vector given that `inst` is live. */ void update_liveness(const IRInstruction* inst, boost::dynamic_bitset<>& bliveness) { // The destination register is killed, so it isn't live before this. if (inst->dests_size()) { bliveness.reset(inst->dest()); if (inst->dest_is_wide()) { bliveness.reset(inst->dest() + 1); } } // The destination of an `invoke` is its return value, which is encoded as // the max position in the bitvector. if (is_invoke(inst->opcode()) || is_filled_new_array(inst->opcode())) { bliveness.reset(bliveness.size() - 1); } // Source registers are live. for (size_t i = 0; i < inst->srcs_size(); i++) { bliveness.set(inst->src(i)); } // `invoke-range` instructions need special handling since their sources // are encoded as a range. if (opcode::has_range(inst->opcode())) { for (size_t i = 0; i < inst->range_size(); i++) { bliveness.set(inst->range_base() + i); } } // The source of a `move-result` is the return value of the prior call, // which is encoded as the max position in the bitvector. if (is_move_result(inst->opcode())) { bliveness.set(bliveness.size() - 1); } } public: void run(const Scope& scope) { walk_methods(scope, [&](DexMethod* m) { if (!m->get_code()) { return; } dce(m); }); TRACE(DCE, 1, "Dead instructions: %lu\n", m_stats.dead_instruction_count); TRACE(DCE, 1, "Unreachable instructions: %lu\n", m_stats.unreachable_instruction_count); } private: std::unordered_set<DexMethod*> m_pure_methods; Stats m_stats; }; } // namespace void LocalDcePass::run(DexMethod* m) { LocalDce().dce(m); } void LocalDcePass::run_pass(DexStoresVector& stores, ConfigFiles& cfg, PassManager& mgr) { if (mgr.no_proguard_rules()) { TRACE(DCE, 1, "LocalDcePass not run because no ProGuard configuration was provided."); return; } auto scope = build_class_scope(stores); LocalDce ldce; ldce.run(scope); const auto& stats = ldce.get_stats(); mgr.incr_metric(METRIC_DEAD_INSTRUCTIONS, stats.dead_instruction_count); mgr.incr_metric(METRIC_UNREACHABLE_INSTRUCTIONS, stats.unreachable_instruction_count); } static LocalDcePass s_pass; <commit_msg>dce: No need to prune CFG edges before removing unreachable blocks<commit_after>/** * Copyright (c) 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ #include "LocalDce.h" #include <iostream> #include <array> #include <unordered_set> #include <vector> #include <boost/dynamic_bitset.hpp> #include "ControlFlow.h" #include "DexClass.h" #include "IRInstruction.h" #include "DexUtil.h" #include "Transform.h" #include "Walkers.h" namespace { constexpr const char* METRIC_DEAD_INSTRUCTIONS = "num_dead_instructions"; constexpr const char* METRIC_UNREACHABLE_INSTRUCTIONS = "num_unreachable_instructions"; /* * These instructions have observable side effects so must always be considered * live, regardless of whether their output is consumed by another instruction. */ static bool has_side_effects(DexOpcode opc) { switch (opc) { case OPCODE_RETURN_VOID: case OPCODE_RETURN: case OPCODE_RETURN_WIDE: case OPCODE_RETURN_OBJECT: case OPCODE_MONITOR_ENTER: case OPCODE_MONITOR_EXIT: case OPCODE_CHECK_CAST: case OPCODE_FILL_ARRAY_DATA: case OPCODE_THROW: case OPCODE_GOTO: case OPCODE_GOTO_16: case OPCODE_GOTO_32: case OPCODE_PACKED_SWITCH: case OPCODE_SPARSE_SWITCH: case OPCODE_IF_EQ: case OPCODE_IF_NE: case OPCODE_IF_LT: case OPCODE_IF_GE: case OPCODE_IF_GT: case OPCODE_IF_LE: case OPCODE_IF_EQZ: case OPCODE_IF_NEZ: case OPCODE_IF_LTZ: case OPCODE_IF_GEZ: case OPCODE_IF_GTZ: case OPCODE_IF_LEZ: case OPCODE_APUT: case OPCODE_APUT_WIDE: case OPCODE_APUT_OBJECT: case OPCODE_APUT_BOOLEAN: case OPCODE_APUT_BYTE: case OPCODE_APUT_CHAR: case OPCODE_APUT_SHORT: case OPCODE_IPUT: case OPCODE_IPUT_WIDE: case OPCODE_IPUT_OBJECT: case OPCODE_IPUT_BOOLEAN: case OPCODE_IPUT_BYTE: case OPCODE_IPUT_CHAR: case OPCODE_IPUT_SHORT: case OPCODE_SPUT: case OPCODE_SPUT_WIDE: case OPCODE_SPUT_OBJECT: case OPCODE_SPUT_BOOLEAN: case OPCODE_SPUT_BYTE: case OPCODE_SPUT_CHAR: case OPCODE_SPUT_SHORT: case OPCODE_INVOKE_VIRTUAL: case OPCODE_INVOKE_SUPER: case OPCODE_INVOKE_DIRECT: case OPCODE_INVOKE_STATIC: case OPCODE_INVOKE_INTERFACE: case OPCODE_INVOKE_VIRTUAL_RANGE: case OPCODE_INVOKE_SUPER_RANGE: case OPCODE_INVOKE_DIRECT_RANGE: case OPCODE_INVOKE_STATIC_RANGE: case OPCODE_INVOKE_INTERFACE_RANGE: case FOPCODE_PACKED_SWITCH: case FOPCODE_SPARSE_SWITCH: case FOPCODE_FILLED_ARRAY: case IOPCODE_LOAD_PARAM: case IOPCODE_LOAD_PARAM_OBJECT: case IOPCODE_LOAD_PARAM_WIDE: return true; default: return false; } not_reached(); } template <typename... T> std::string show(const boost::dynamic_bitset<T...>& bits) { std::string ret; to_string(bits, ret); return ret; } //////////////////////////////////////////////////////////////////////////////// class LocalDce { public: struct Stats { size_t dead_instruction_count{0}; size_t unreachable_instruction_count{0}; }; /* * Eliminate dead code using a standard backward dataflow analysis for * liveness. The algorithm is as follows: * * - Maintain a bitvector for each block representing the liveness for each * register. Function call results are represented by bit #num_regs. * * - Walk the blocks in postorder. Compute each block's output state by * OR-ing the liveness of its successors * * - Walk each block's instructions in reverse to determine its input state. * An instruction's input registers are live if (a) it has side effects, or * (b) its output registers are live. * * - If the liveness of any block changes during a pass, repeat it. Since * anything live in one pass is guaranteed to be live in the next, this is * guaranteed to reach a fixed point and terminate. Visiting blocks in * postorder guarantees a minimum number of passes. * * - Catch blocks are handled slightly differently; since any instruction * inside a `try` region can jump to a catch block, we assume that any * registers that are live-in to a catch block must be kept live throughout * the `try` region. (This is actually conservative, since only * potentially-excepting instructions can jump to a catch.) */ public: LocalDce() { /* * Pure methods have no observable side effects, so they can be removed * if their outputs are not used. * * TODO: Derive this list with static analysis rather than hard-coding * it. */ m_pure_methods.emplace(DexMethod::make_method( "Ljava/lang/Class;", "getSimpleName", "Ljava/lang/String;", {})); } void dce(DexMethod* method) { auto code = method->get_code(); code->build_cfg(); auto& cfg = code->cfg(); auto blocks = postorder_sort(cfg.blocks()); auto regs = method->get_code()->get_registers_size(); std::vector<boost::dynamic_bitset<>> liveness( cfg.blocks().size(), boost::dynamic_bitset<>(regs + 1)); bool changed; std::vector<FatMethod::iterator> dead_instructions; TRACE(DCE, 5, "%s\n", SHOW(method)); TRACE(DCE, 5, "%s", SHOW(cfg)); // Iterate liveness analysis to a fixed point. do { changed = false; dead_instructions.clear(); for (auto& b : blocks) { auto prev_liveness = liveness.at(b->id()); auto& bliveness = liveness.at(b->id()); bliveness.reset(); TRACE(DCE, 5, "B%lu: %s\n", b->id(), show(bliveness).c_str()); // Compute live-out for this block from its successors. for (auto& s : b->succs()) { if(s->id() == b->id()) { bliveness |= prev_liveness; } TRACE(DCE, 5, " S%lu: %s\n", s->id(), show(liveness[s->id()]).c_str()); bliveness |= liveness[s->id()]; } // Compute live-in for this block by walking its instruction list in // reverse and applying the liveness rules. for (auto it = b->rbegin(); it != b->rend(); ++it) { if (it->type != MFLOW_OPCODE) { continue; } bool required = is_required(it->insn, bliveness); if (required) { update_liveness(it->insn, bliveness); } else { dead_instructions.push_back(std::prev(it.base())); } TRACE(CFG, 5, "%s\n%s\n", show(it->insn).c_str(), show(bliveness).c_str()); } if (bliveness != prev_liveness) { changed = true; } } } while (changed); // Remove dead instructions. TRACE(DCE, 2, "%s\n", SHOW(method)); for (auto dead : dead_instructions) { TRACE(DCE, 2, "DEAD: %s\n", SHOW(dead->insn)); code->remove_opcode(dead); } m_stats.dead_instruction_count += dead_instructions.size(); // if we deleted an instruction that may throw, we'll need to remove any // EDGE_THROW edges in the CFG... ideally we would just prune that edge, // but we can do a conservative and inefficient hack for now and just // rebuild the entire graph if (dead_instructions.size() > 0) { code->build_cfg(); } remove_unreachable_blocks(method, &*code); TRACE(DCE, 5, "=== Post-DCE CFG ===\n"); TRACE(DCE, 5, "%s", SHOW(code->cfg())); } const Stats& get_stats() const { return m_stats; } private: void remove_block(IRCode* code, Block* b) { for (auto& mei : InstructionIterable(b)) { code->remove_opcode(mei.insn); ++m_stats.unreachable_instruction_count; } } void remove_unreachable_blocks(DexMethod* method, IRCode* code) { auto& cfg = code->cfg(); auto& blocks = cfg.blocks(); // remove unreachable blocks std::unordered_set<Block*> visited; std::function<void (Block*)> visit = [&](Block* b) { if (visited.find(b) != visited.end()) { return; } visited.emplace(b); for (auto& s : b->succs()) { visit(s); } }; visit(blocks.at(0)); for (size_t i = 1; i < blocks.size(); ++i) { auto& b = blocks.at(i); if (visited.find(b) != visited.end()) { continue; } std::vector<std::pair<Block*, Block*>> remove_edges; for (auto& s : b->succs()) { remove_edges.emplace_back(b, s); } for (auto& p : remove_edges) { cfg.remove_all_edges(p.first, p.second); } remove_block(code, b); } // comb the method looking for superfluous try sections that do not enclose // throwing opcodes; remove them. note that try sections should never be // nested, otherwise this won't produce the right result. bool encloses_throw {false}; MethodItemEntry* try_start {nullptr}; for (auto& mie : *code) { if (mie.type == MFLOW_TRY) { auto tentry = mie.tentry; if (tentry->type == TRY_START) { encloses_throw = false; try_start = &mie; } else if (!encloses_throw /* && tentry->type == TRY_END */) { try_start->type = MFLOW_FALLTHROUGH; try_start->throwing_mie = nullptr; try_start = nullptr; mie.type = MFLOW_FALLTHROUGH; mie.throwing_mie = nullptr; } } else if (mie.type == MFLOW_OPCODE) { auto op = mie.insn->opcode(); encloses_throw = encloses_throw || opcode::may_throw(op) || op == OPCODE_THROW; } } } /* * An instruction is required (i.e., live) if it has side effects or if its * destination register is live. */ bool is_required(IRInstruction* inst, const boost::dynamic_bitset<>& bliveness) { if (has_side_effects(inst->opcode())) { if (is_invoke(inst->opcode())) { if (!is_pure(inst->get_method())) { return true; } return bliveness.test(bliveness.size() - 1); } return true; } else if (inst->dests_size()) { bool result = bliveness.test(inst->dest()); if (inst->dest_is_wide()) { result |= bliveness.test(inst->dest() + 1); } return result; } else if (is_filled_new_array(inst->opcode())) { // filled-new-array passes its dest via the return-value slot, but isn't // inherently live like the invoke-* instructions. return bliveness.test(bliveness.size() - 1); } return false; } bool is_pure(DexMethod* method) { if (assumenosideeffects(method)) { return true; } return m_pure_methods.find(method) != m_pure_methods.end(); } /* * Update the liveness vector given that `inst` is live. */ void update_liveness(const IRInstruction* inst, boost::dynamic_bitset<>& bliveness) { // The destination register is killed, so it isn't live before this. if (inst->dests_size()) { bliveness.reset(inst->dest()); if (inst->dest_is_wide()) { bliveness.reset(inst->dest() + 1); } } // The destination of an `invoke` is its return value, which is encoded as // the max position in the bitvector. if (is_invoke(inst->opcode()) || is_filled_new_array(inst->opcode())) { bliveness.reset(bliveness.size() - 1); } // Source registers are live. for (size_t i = 0; i < inst->srcs_size(); i++) { bliveness.set(inst->src(i)); } // `invoke-range` instructions need special handling since their sources // are encoded as a range. if (opcode::has_range(inst->opcode())) { for (size_t i = 0; i < inst->range_size(); i++) { bliveness.set(inst->range_base() + i); } } // The source of a `move-result` is the return value of the prior call, // which is encoded as the max position in the bitvector. if (is_move_result(inst->opcode())) { bliveness.set(bliveness.size() - 1); } } public: void run(const Scope& scope) { walk_methods(scope, [&](DexMethod* m) { if (!m->get_code()) { return; } dce(m); }); TRACE(DCE, 1, "Dead instructions: %lu\n", m_stats.dead_instruction_count); TRACE(DCE, 1, "Unreachable instructions: %lu\n", m_stats.unreachable_instruction_count); } private: std::unordered_set<DexMethod*> m_pure_methods; Stats m_stats; }; } // namespace void LocalDcePass::run(DexMethod* m) { LocalDce().dce(m); } void LocalDcePass::run_pass(DexStoresVector& stores, ConfigFiles& cfg, PassManager& mgr) { if (mgr.no_proguard_rules()) { TRACE(DCE, 1, "LocalDcePass not run because no ProGuard configuration was provided."); return; } auto scope = build_class_scope(stores); LocalDce ldce; ldce.run(scope); const auto& stats = ldce.get_stats(); mgr.incr_metric(METRIC_DEAD_INSTRUCTIONS, stats.dead_instruction_count); mgr.incr_metric(METRIC_UNREACHABLE_INSTRUCTIONS, stats.unreachable_instruction_count); } static LocalDcePass s_pass; <|endoftext|>
<commit_before><commit_msg>add test for calculate CRC-7/ROHC<commit_after><|endoftext|>
<commit_before>// // Copyright 2013 Jeff Bush // // 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 "Debug.h" #include "Spinlock.h" #include "utils.h" extern "C" { unsigned int __udivsi3(unsigned int, unsigned int); int __divsi3(int, int); unsigned int __umodsi3(unsigned int, unsigned int); int __modsi3(int, int); } void *__dso_handle; static volatile unsigned int gNextAlloc = 0x240000; void memcpy(void *dest, const void *src, unsigned int length) { for (unsigned int i = 0; i < length; i++) ((char*) dest)[i] = ((const char *) src)[i]; } void memset(void *_dest, int value, unsigned int length) { char *dest = (char*) _dest; value &= 0xff; if ((((unsigned int) dest) & 63) == 0) { // Write 64 bytes at a time. veci16 reallyWideValue = splati(value | (value << 8) | (value << 16) | (value << 24)); while (length > 64) { *((veci16*) dest) = reallyWideValue; length -= 64; dest += 64; } } if ((((unsigned int) dest) & 3) == 0) { // Write 4 bytes at a time. unsigned wideVal = value | (value << 8) | (value << 16) | (value << 24); while (length > 4) { *((unsigned int*) dest) = wideVal; dest += 4; length -= 4; } } // Write one byte at a time while (length > 0) { *dest++ = value; length--; } } void *allocMem(unsigned int size) { return (void*) __sync_fetch_and_add(&gNextAlloc, (size + 63) & ~63); } void operator delete(void *) throw() { // Unimplemented } extern "C" void __cxa_atexit(void (*)(void *), void *, void *) { } extern "C" void __cxa_pure_virtual() { Debug::debug << "pure virtual\n"; __halt(); } // // We don't support integer division in hardware, so emulate those functions // here. // unsigned int __udivsi3(unsigned int dividend, unsigned int divisor) { if (dividend < divisor) return 0; int quotientBits = __builtin_clz(divisor) - __builtin_clz(dividend); divisor <<= quotientBits; unsigned int quotient = 0; do { quotient <<= 1; if (dividend >= divisor) { dividend -= divisor; quotient |= 1; } divisor >>= 1; } while (--quotientBits >= 0); return quotient; } int __divsi3(int value1, int value2) { int sign1 = value1 >> 31; int sign2 = value2 >> 31; // Take absolute values unsigned int u_value1 = (value1 ^ sign1) - sign1; unsigned int u_value2 = (value2 ^ sign2) - sign2; // Compute result sign sign1 ^= sign2; // Perform division, then convert back to 2's complement return (__udivsi3(u_value1, u_value2) ^ sign1) - sign1; } unsigned int __umodsi3(unsigned int value1, unsigned int value2) { return value1 - __udivsi3(value1, value2) * value2; } int __modsi3(int value1, int value2) { return value1 - __divsi3(value1, value2) * value2; } // // Math functions // float fmod(float val1, float val2) { int whole = val1 / val2; return val1 - (whole * val2); } // // Use taylor series to approximate sine // x**3/3! + x**5/5! - x**7/7! ... // const int kNumTerms = 7; const float denominators[] = { 0.166666666666667f, // 1 / 3! 0.008333333333333f, // 1 / 5! 0.000198412698413f, // 1 / 7! 0.000002755731922f, // 1 / 9! 2.50521084e-8f, // 1 / 11! 1.6059044e-10f, // 1 / 13! 7.6471637e-13f // 1 / 15! }; float sin(float angle) { // More accurate if the angle is smaller. Constrain to 0-M_PI*2 angle = fmod(angle, M_PI * 2.0f); float angleSquared = angle * angle; float numerator = angle; float result = angle; for (int i = 0; i < kNumTerms; i++) { numerator *= angleSquared; float term = numerator * denominators[i]; if (i & 1) result += term; else result -= term; } return result; } float cos(float angle) { return sin(angle + M_PI * 0.5f); } float sqrt(float value) { float guess = value; for (int iteration = 0; iteration < 10; iteration++) guess = ((value / guess) + guess) / 2.0f; return guess; } <commit_msg>Fix missing header file.<commit_after>// // Copyright 2013 Jeff Bush // // 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 "Debug.h" #include "utils.h" extern "C" { unsigned int __udivsi3(unsigned int, unsigned int); int __divsi3(int, int); unsigned int __umodsi3(unsigned int, unsigned int); int __modsi3(int, int); } void *__dso_handle; static volatile unsigned int gNextAlloc = 0x240000; void memcpy(void *dest, const void *src, unsigned int length) { for (unsigned int i = 0; i < length; i++) ((char*) dest)[i] = ((const char *) src)[i]; } void memset(void *_dest, int value, unsigned int length) { char *dest = (char*) _dest; value &= 0xff; if ((((unsigned int) dest) & 63) == 0) { // Write 64 bytes at a time. veci16 reallyWideValue = splati(value | (value << 8) | (value << 16) | (value << 24)); while (length > 64) { *((veci16*) dest) = reallyWideValue; length -= 64; dest += 64; } } if ((((unsigned int) dest) & 3) == 0) { // Write 4 bytes at a time. unsigned wideVal = value | (value << 8) | (value << 16) | (value << 24); while (length > 4) { *((unsigned int*) dest) = wideVal; dest += 4; length -= 4; } } // Write one byte at a time while (length > 0) { *dest++ = value; length--; } } void *allocMem(unsigned int size) { return (void*) __sync_fetch_and_add(&gNextAlloc, (size + 63) & ~63); } void operator delete(void *) throw() { // Unimplemented } extern "C" void __cxa_atexit(void (*)(void *), void *, void *) { } extern "C" void __cxa_pure_virtual() { Debug::debug << "pure virtual\n"; __halt(); } // // We don't support integer division in hardware, so emulate those functions // here. // unsigned int __udivsi3(unsigned int dividend, unsigned int divisor) { if (dividend < divisor) return 0; int quotientBits = __builtin_clz(divisor) - __builtin_clz(dividend); divisor <<= quotientBits; unsigned int quotient = 0; do { quotient <<= 1; if (dividend >= divisor) { dividend -= divisor; quotient |= 1; } divisor >>= 1; } while (--quotientBits >= 0); return quotient; } int __divsi3(int value1, int value2) { int sign1 = value1 >> 31; int sign2 = value2 >> 31; // Take absolute values unsigned int u_value1 = (value1 ^ sign1) - sign1; unsigned int u_value2 = (value2 ^ sign2) - sign2; // Compute result sign sign1 ^= sign2; // Perform division, then convert back to 2's complement return (__udivsi3(u_value1, u_value2) ^ sign1) - sign1; } unsigned int __umodsi3(unsigned int value1, unsigned int value2) { return value1 - __udivsi3(value1, value2) * value2; } int __modsi3(int value1, int value2) { return value1 - __divsi3(value1, value2) * value2; } // // Math functions // float fmod(float val1, float val2) { int whole = val1 / val2; return val1 - (whole * val2); } // // Use taylor series to approximate sine // x**3/3! + x**5/5! - x**7/7! ... // const int kNumTerms = 7; const float denominators[] = { 0.166666666666667f, // 1 / 3! 0.008333333333333f, // 1 / 5! 0.000198412698413f, // 1 / 7! 0.000002755731922f, // 1 / 9! 2.50521084e-8f, // 1 / 11! 1.6059044e-10f, // 1 / 13! 7.6471637e-13f // 1 / 15! }; float sin(float angle) { // More accurate if the angle is smaller. Constrain to 0-M_PI*2 angle = fmod(angle, M_PI * 2.0f); float angleSquared = angle * angle; float numerator = angle; float result = angle; for (int i = 0; i < kNumTerms; i++) { numerator *= angleSquared; float term = numerator * denominators[i]; if (i & 1) result += term; else result -= term; } return result; } float cos(float angle) { return sin(angle + M_PI * 0.5f); } float sqrt(float value) { float guess = value; for (int iteration = 0; iteration < 10; iteration++) guess = ((value / guess) + guess) / 2.0f; return guess; } <|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 "mitkPALinearSpectralUnmixingFilter.h" // Includes for AddEnmemberMatrix #include "mitkPAPropertyCalculator.h" #include <eigen3/Eigen/Dense> // Testing algorithms #include <eigen3\Eigen\src\SVD\JacobiSVD.h> // ImageAccessor #include <mitkImageReadAccessor.h> #include <mitkImageWriteAccessor.h> mitk::pa::LinearSpectralUnmixingFilter::LinearSpectralUnmixingFilter() { } mitk::pa::LinearSpectralUnmixingFilter::~LinearSpectralUnmixingFilter() { } void mitk::pa::LinearSpectralUnmixingFilter::SetAlgorithm(int SetAlgorithmIndex) { algorithmIndex = static_cast<mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType>(SetAlgorithmIndex); } Eigen::VectorXf mitk::pa::LinearSpectralUnmixingFilter::SpectralUnmixingAlgorithm( Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> EndmemberMatrix, Eigen::VectorXf inputVector) { //test other solvers https://eigen.tuxfamily.org/dox/group__TutorialLinearAlgebra.html Eigen::Vector2f resultVector; if (mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType::colPivHouseholderQr == algorithmIndex) { resultVector = EndmemberMatrix.colPivHouseholderQr().solve(inputVector); //works :) } if (mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType::llt == algorithmIndex) { resultVector = EndmemberMatrix.llt().solve(inputVector); //works with negativ values (no correct unmixing) } if (mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType::householderQr == algorithmIndex) { resultVector = EndmemberMatrix.householderQr().solve(inputVector); //works :) } if (mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType::ldlt == algorithmIndex) { mitkThrow() << "not working"; resultVector = EndmemberMatrix.ldlt().solve(inputVector); //not working because matrix not quadratic(?) } if (mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType::jacobiSvd == algorithmIndex) { mitkThrow() << "not working"; resultVector = EndmemberMatrix.jacobiSvd().solve(inputVector); //not working } if (mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType::fullPivLu == algorithmIndex) { resultVector = EndmemberMatrix.fullPivLu().solve(inputVector); //works :) } if (mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType::householderQr == algorithmIndex) { resultVector = EndmemberMatrix.householderQr().solve(inputVector); //works :) } if (mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType::fullPivHouseholderQr == algorithmIndex) { resultVector = EndmemberMatrix.fullPivHouseholderQr().solve(inputVector);//works :) } //testing new algorithms: if (mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType::test == algorithmIndex) { mitkThrow() << "nothing implemented"; } double relativeError = (EndmemberMatrix*resultVector - inputVector).norm() / inputVector.norm(); // norm() is L2 norm //MITK_INFO << "relativ error: " << relativeError; float accuracyLevel = .1; bool resultIsApprox = inputVector.isApprox(EndmemberMatrix*resultVector, accuracyLevel); //MITK_INFO << "IS APPROX RESULT: " << resultIsApprox; return resultVector; } <commit_msg>EIGEN jacobiSvd solver works now.<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 "mitkPALinearSpectralUnmixingFilter.h" // Includes for AddEnmemberMatrix #include "mitkPAPropertyCalculator.h" #include <eigen3/Eigen/Dense> // Testing algorithms #include <eigen3\Eigen\src\SVD\JacobiSVD.h> // ImageAccessor #include <mitkImageReadAccessor.h> #include <mitkImageWriteAccessor.h> mitk::pa::LinearSpectralUnmixingFilter::LinearSpectralUnmixingFilter() { } mitk::pa::LinearSpectralUnmixingFilter::~LinearSpectralUnmixingFilter() { } void mitk::pa::LinearSpectralUnmixingFilter::SetAlgorithm(int SetAlgorithmIndex) { algorithmIndex = static_cast<mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType>(SetAlgorithmIndex); } Eigen::VectorXf mitk::pa::LinearSpectralUnmixingFilter::SpectralUnmixingAlgorithm( Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> EndmemberMatrix, Eigen::VectorXf inputVector) { //test other solvers https://eigen.tuxfamily.org/dox/group__TutorialLinearAlgebra.html Eigen::Vector2f resultVector; if (mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType::colPivHouseholderQr == algorithmIndex) { resultVector = EndmemberMatrix.colPivHouseholderQr().solve(inputVector); //works :) } if (mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType::llt == algorithmIndex) { resultVector = EndmemberMatrix.llt().solve(inputVector); //works with negativ values (no correct unmixing) } if (mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType::householderQr == algorithmIndex) { resultVector = EndmemberMatrix.householderQr().solve(inputVector); //works :) } if (mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType::ldlt == algorithmIndex) { mitkThrow() << "not working"; resultVector = EndmemberMatrix.ldlt().solve(inputVector); //not working because matrix not quadratic(?) } if (mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType::jacobiSvd == algorithmIndex) { resultVector = EndmemberMatrix.jacobiSvd(Eigen::ComputeFullU | Eigen::ComputeFullV).solve(inputVector); //not working } if (mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType::fullPivLu == algorithmIndex) { resultVector = EndmemberMatrix.fullPivLu().solve(inputVector); //works :) } if (mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType::householderQr == algorithmIndex) { resultVector = EndmemberMatrix.householderQr().solve(inputVector); //works :) } if (mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType::fullPivHouseholderQr == algorithmIndex) { resultVector = EndmemberMatrix.fullPivHouseholderQr().solve(inputVector);//works :) } //testing new algorithms: if (mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType::test == algorithmIndex) { mitkThrow() << "nothing implemented"; } double relativeError = (EndmemberMatrix*resultVector - inputVector).norm() / inputVector.norm(); // norm() is L2 norm MITK_INFO << "relativ error: " << relativeError; float accuracyLevel = .1; bool resultIsApprox = inputVector.isApprox(EndmemberMatrix*resultVector, accuracyLevel); MITK_INFO << "IS APPROX RESULT: " << resultIsApprox; return resultVector; } <|endoftext|>
<commit_before>/********************************************************************** * Felix Winterstein, Imperial College London * * File: main.cpp * * Revision 1.01 * Additional Comments: distributed under a BSD license, see LICENSE.txt * **********************************************************************/ #include <stdio.h> #include <stdlib.h> //#include <stdbool.h> #include <time.h> #include <time.h> #include <unistd.h> #include "my_util.h" #include "lloyds.h" #include "filter_it.h" #include "clustering.h" int main(int argc, char** argv) { uint k = 128; uint n = 16384; const double std_dev = 0.20; const uint fidx = 1; // works for linux! char path[FILENAME_MAX]; if (!getcwd(path, sizeof(path))){ printf("ERROR: getcwd failed\n"); return EXIT_SUCCESS; } printf("Working directory is: %s\n",path); // allocate input arrays data_type_short *data_points = new data_type_short[NMAX]; centre_type *initial_centres = new centre_type[KMAX]; uint *centr_idx = new uint[KMAX]; // read data points file if (read_data_points(data_points, n, k, std_dev, fidx) == false) { printf("ERROR: Could not find data points file\n"); return EXIT_SUCCESS; } // read initial centres file if (read_initial_centres(initial_centres, centr_idx, n, k, std_dev, fidx) == false) { printf("ERROR: Could not find data points file\n"); return EXIT_SUCCESS; } // allocate output arrays data_type_short *data_output= new data_type_short[NMAX]; centre_type *centre_output = new centre_type[KMAX]; kdTree_type *tree_memory = new kdTree_type[2*NMAX]; // build kd-tree and run clustering uint root; #ifdef FILTERING_ALGO buildTree(n, k, data_points, &root, tree_memory); #endif clustering(n, k, initial_centres, data_points, tree_memory, root, data_output, centre_output); #ifdef VERBOSE // Clustering result printf("New centres after clustering\n"); for (uint i=0; i<k; i++) { printf("%d: ",i); for (uint d=0; d<D-1; d++) { printf("%d ",centre_output[i].position_short.value[d]); } printf("%d\n",centre_output[i].position_short.value[D-1]); } #endif //write_data_set_info(tree_memory_lo_lo, tree_memory_lo_hi, tree_memory_hi_lo, tree_memory_hi_hi, fidx); // free allocated memory delete data_points; delete data_output; delete centre_output; delete tree_memory; delete initial_centres; delete centr_idx; return (EXIT_SUCCESS); } <commit_msg>fix dispose-bug<commit_after>/********************************************************************** * Felix Winterstein, Imperial College London * * File: main.cpp * * Revision 1.01 * Additional Comments: distributed under a BSD license, see LICENSE.txt * **********************************************************************/ #include <stdio.h> #include <stdlib.h> //#include <stdbool.h> #include <time.h> #include <time.h> #include <unistd.h> #include "my_util.h" #include "lloyds.h" #include "filter_it.h" #include "clustering.h" int main(int argc, char** argv) { uint k = 128; uint n = 16384; const double std_dev = 0.20; const uint fidx = 1; // works for linux! char path[FILENAME_MAX]; if (!getcwd(path, sizeof(path))){ printf("ERROR: getcwd failed\n"); return EXIT_SUCCESS; } printf("Working directory is: %s\n",path); // allocate input arrays data_type_short *data_points = new data_type_short[NMAX]; centre_type *initial_centres = new centre_type[KMAX]; uint *centr_idx = new uint[KMAX]; // read data points file if (read_data_points(data_points, n, k, std_dev, fidx) == false) { printf("ERROR: Could not find data points file\n"); return EXIT_SUCCESS; } // read initial centres file if (read_initial_centres(initial_centres, centr_idx, n, k, std_dev, fidx) == false) { printf("ERROR: Could not find data points file\n"); return EXIT_SUCCESS; } // allocate output arrays data_type_short *data_output= new data_type_short[NMAX]; centre_type *centre_output = new centre_type[KMAX]; kdTree_type *tree_memory = new kdTree_type[2*NMAX]; // build kd-tree and run clustering uint root; #ifdef FILTERING_ALGO buildTree(n, k, data_points, &root, tree_memory); #endif clustering(n, k, initial_centres, data_points, tree_memory, root, data_output, centre_output); #ifdef VERBOSE // Clustering result printf("New centres after clustering\n"); for (uint i=0; i<k; i++) { printf("%d: ",i); for (uint d=0; d<D-1; d++) { printf("%d ",centre_output[i].position_short.value[d]); } printf("%d\n",centre_output[i].position_short.value[D-1]); } #endif //write_data_set_info(tree_memory_lo_lo, tree_memory_lo_hi, tree_memory_hi_lo, tree_memory_hi_hi, fidx); // free allocated memory delete[] data_points; delete[] data_output; delete[] centre_output; delete[] tree_memory; delete[] initial_centres; delete[] centr_idx; return (EXIT_SUCCESS); } <|endoftext|>
<commit_before>#ifdef NMC_HAVE_MPI #include "../gtest.h" #include <cstring> #include <vector> #include <communication/mpi_global_policy.hpp> #include <communication/mpi.hpp> #include <util/rangeutil.hpp> using namespace nest::mc; using namespace nest::mc::communication; struct big_thing { big_thing() {} big_thing(int i): value_(i) {} bool operator==(const big_thing& other) const { return value_==other.value_ && !std::memcmp(salt_, other.salt_, sizeof(salt_)); } bool operator!=(const big_thing& other) const { return !(*this==other); } private: int value_; char salt_[32] = "it's a lovely day for a picnic"; }; TEST(mpi, gather_all) { using policy = mpi_global_policy; int id = policy::id(); std::vector<big_thing> data; // odd ranks: three items; even ranks: one item. if (id%2) { data = { id, id+7, id+8 }; } else { data = { id }; } std::vector<big_thing> expected; for (int i = 0; i<policy::size(); ++i) { if (i%2) { int rank_data[] = { i, i+7, i+8 }; util::append(expected, rank_data); } else { int rank_data[] = { i }; util::append(expected, rank_data); } } auto gathered = mpi::gather_all(data); EXPECT_EQ(expected, gathered); } TEST(mpi, gather_all_with_partition) { using policy = mpi_global_policy; int id = policy::id(); std::vector<big_thing> data; // odd ranks: three items; even ranks: one item. if (id%2) { data = { id, id+7, id+8 }; } else { data = { id }; } std::vector<big_thing> expected_values; std::vector<unsigned> expected_divisions; expected_divisions.push_back(0); for (int i = 0; i<policy::size(); ++i) { if (i%2) { int rank_data[] = { i, i+7, i+8 }; util::append(expected_values, rank_data); expected_divisions.push_back(expected_divisions.back()+util::size(rank_data)); } else { int rank_data[] = { i }; util::append(expected_values, rank_data); expected_divisions.push_back(expected_divisions.back()+util::size(rank_data)); } } auto gathered = mpi::gather_all_with_partition(data); EXPECT_EQ(expected_values, gathered.values()); EXPECT_EQ(expected_divisions, gathered.partition()); } #endif // NMC_HAVE_MPI <commit_msg>fix bug introduced when global policy was refactored<commit_after>#ifdef NMC_HAVE_MPI #include "../gtest.h" #include <cstring> #include <vector> #include <communication/global_policy.hpp> #include <communication/mpi.hpp> #include <util/rangeutil.hpp> using namespace nest::mc; using namespace nest::mc::communication; struct big_thing { big_thing() {} big_thing(int i): value_(i) {} bool operator==(const big_thing& other) const { return value_==other.value_ && !std::memcmp(salt_, other.salt_, sizeof(salt_)); } bool operator!=(const big_thing& other) const { return !(*this==other); } private: int value_; char salt_[32] = "it's a lovely day for a picnic"; }; TEST(mpi, gather_all) { using policy = mpi_global_policy; int id = policy::id(); std::vector<big_thing> data; // odd ranks: three items; even ranks: one item. if (id%2) { data = { id, id+7, id+8 }; } else { data = { id }; } std::vector<big_thing> expected; for (int i = 0; i<policy::size(); ++i) { if (i%2) { int rank_data[] = { i, i+7, i+8 }; util::append(expected, rank_data); } else { int rank_data[] = { i }; util::append(expected, rank_data); } } auto gathered = mpi::gather_all(data); EXPECT_EQ(expected, gathered); } TEST(mpi, gather_all_with_partition) { using policy = mpi_global_policy; int id = policy::id(); std::vector<big_thing> data; // odd ranks: three items; even ranks: one item. if (id%2) { data = { id, id+7, id+8 }; } else { data = { id }; } std::vector<big_thing> expected_values; std::vector<unsigned> expected_divisions; expected_divisions.push_back(0); for (int i = 0; i<policy::size(); ++i) { if (i%2) { int rank_data[] = { i, i+7, i+8 }; util::append(expected_values, rank_data); expected_divisions.push_back(expected_divisions.back()+util::size(rank_data)); } else { int rank_data[] = { i }; util::append(expected_values, rank_data); expected_divisions.push_back(expected_divisions.back()+util::size(rank_data)); } } auto gathered = mpi::gather_all_with_partition(data); EXPECT_EQ(expected_values, gathered.values()); EXPECT_EQ(expected_divisions, gathered.partition()); } #endif // NMC_HAVE_MPI <|endoftext|>
<commit_before>#ifndef __PROCESS_COLLECT_HPP__ #define __PROCESS_COLLECT_HPP__ #include <assert.h> #include <set> #include <process/defer.hpp> #include <process/future.hpp> #include <process/process.hpp> namespace process { // Transforms a set of futures of type T into a set of T's. template <typename T> Future<std::set<T> > collect(std::set<Future<T> >& futures); namespace internal { template <typename T> class CollectProcess : public Process<CollectProcess<T> > { public: CollectProcess( const std::set<Future<T> >& _futures, Promise<std::set<T> >* _promise) : futures(_futures), promise(_promise) {} virtual ~CollectProcess() { delete promise; } virtual void initialize() { // Stop this nonsense if nobody cares. promise->future().onDiscarded(defer(this, &CollectProcess::discarded)); typename std::set<Future<T> >::iterator iterator; for (iterator = futures.begin(); iterator != futures.end(); ++iterator) { const Future<T>& future = *iterator; future.onAny(defer(this, &CollectProcess::waited, future)); } } private: void discarded() { terminate(this); } void waited(const Future<T>& future) { if (future.isFailed()) { promise->fail(future.failure()); } else if (future.isDiscarded()) { promise->future().discard(); } else { assert(future.isReady()); values.insert(future.get()); if (futures.size() == values.size()) { promise->set(values); terminate(this); } } } std::set<Future<T> > futures; Promise<std::set<T> >* promise; std::set<T> values; }; } // namespace internal { template <typename T> inline Future<std::set<T> > collect(std::set<Future<T> >& futures) { Promise<std::set<T> >* promise = new Promise<std::set<T> >(); spawn(new internal::CollectProcess<T>(futures, promise), true); return promise->future(); } } // namespace process { #endif // __PROCESS_COLLECT_HPP__ <commit_msg>Updated semantics of collect (on futures) and updated documentation appropriately.<commit_after>#ifndef __PROCESS_COLLECT_HPP__ #define __PROCESS_COLLECT_HPP__ #include <assert.h> #include <set> #include <process/defer.hpp> #include <process/future.hpp> #include <process/process.hpp> namespace process { // Waits on each future in the specified set and returns the set of // resulting values. If any future is discarded then the result will // be a failure. Likewise, if any future fails than the result future // will be a failure. template <typename T> Future<std::set<T> > collect(std::set<Future<T> >& futures); namespace internal { template <typename T> class CollectProcess : public Process<CollectProcess<T> > { public: CollectProcess( const std::set<Future<T> >& _futures, Promise<std::set<T> >* _promise) : futures(_futures), promise(_promise) {} virtual ~CollectProcess() { delete promise; } virtual void initialize() { // Stop this nonsense if nobody cares. promise->future().onDiscarded(defer(this, &CollectProcess::discarded)); typename std::set<Future<T> >::iterator iterator; for (iterator = futures.begin(); iterator != futures.end(); ++iterator) { const Future<T>& future = *iterator; future.onAny(defer(this, &CollectProcess::waited, future)); } } private: void discarded() { terminate(this); } void waited(const Future<T>& future) { if (future.isFailed()) { promise->fail("Collect failed: " + future.failure()); } else if (future.isDiscarded()) { promise->fail("Collect failed: future discarded"); } else { assert(future.isReady()); values.insert(future.get()); if (futures.size() == values.size()) { promise->set(values); terminate(this); } } } std::set<Future<T> > futures; Promise<std::set<T> >* promise; std::set<T> values; }; } // namespace internal { template <typename T> inline Future<std::set<T> > collect(std::set<Future<T> >& futures) { Promise<std::set<T> >* promise = new Promise<std::set<T> >(); spawn(new internal::CollectProcess<T>(futures, promise), true); return promise->future(); } } // namespace process { #endif // __PROCESS_COLLECT_HPP__ <|endoftext|>
<commit_before>#ifndef BFC_AST_SEQ_HPP #define BFC_AST_SEQ_HPP #include "ast/base.hpp" #include "ast/visitor.hpp" #include <deque> namespace bfc { namespace ast { class seq : public base { using container = std::deque<node>; public: using size_type = typename container::size_type; using iterator = typename container::iterator; using const_iterator = typename container::const_iterator; seq(void); template <class InputIt> seq(InputIt begin, InputIt end); void swap(seq &other) noexcept; iterator begin(void) noexcept; const_iterator begin(void) const noexcept; const_iterator cbegin(void) const noexcept; iterator end(void) noexcept; const_iterator end(void) const noexcept; const_iterator cend(void) const noexcept; node &front(void) noexcept; const node &front(void) const noexcept; node &back(void) noexcept; const node &back(void) const noexcept; bool empty(void) const noexcept; size_type size(void) const noexcept; void clear(void) noexcept; iterator insert(const_iterator it, node elem); template <class InputIt> iterator insert(const_iterator it, InputIt first, InputIt last); template <class ...Args> iterator emplace(const_iterator it, Args &&...args); iterator remove(const_iterator it) noexcept; iterator remove(const_iterator first, const_iterator last) noexcept; void push_front(node node); void push_back(node node); void pop_front(void) noexcept; void pop_back(void) noexcept; template <class ...Args> void emplace_front(Args &&...args); template <class ...Args> void emplace_back(Args &&...args); visitor::status accept(visitor &visitor) override; visitor::status accept(visitor &visitor) const override; base *clone(void) const override; private: container elems; }; template <class InputIt> seq::seq(InputIt first, InputIt last) : elems(first, last) {} template <class InputIt> seq::iterator seq::insert(const_iterator it, InputIt first, InputIt last) { return elems.insert(first, last); } template <class ...Args> seq::iterator seq::emplace(const_iterator it, Args &&...args) { return elems.emplace(it, std::forward<Args>(args)...); } template <class ...Args> void seq::emplace_front(Args &&...args) { elems.emplace_front(std::forward<Args>(args)...); } template <class ...Args> void seq::emplace_back(Args &&...args) { elems.emplace_back(std::forward<Args>(args)...); } } } #endif /* !BFC_AST_SEQ_HPP */ <commit_msg>Fix bug in seq::insert definition.<commit_after>#ifndef BFC_AST_SEQ_HPP #define BFC_AST_SEQ_HPP #include "ast/base.hpp" #include "ast/visitor.hpp" #include <deque> namespace bfc { namespace ast { class seq : public base { using container = std::deque<node>; public: using size_type = typename container::size_type; using iterator = typename container::iterator; using const_iterator = typename container::const_iterator; seq(void); template <class InputIt> seq(InputIt begin, InputIt end); void swap(seq &other) noexcept; iterator begin(void) noexcept; const_iterator begin(void) const noexcept; const_iterator cbegin(void) const noexcept; iterator end(void) noexcept; const_iterator end(void) const noexcept; const_iterator cend(void) const noexcept; node &front(void) noexcept; const node &front(void) const noexcept; node &back(void) noexcept; const node &back(void) const noexcept; bool empty(void) const noexcept; size_type size(void) const noexcept; void clear(void) noexcept; iterator insert(const_iterator it, node elem); template <class InputIt> iterator insert(const_iterator it, InputIt first, InputIt last); template <class ...Args> iterator emplace(const_iterator it, Args &&...args); iterator remove(const_iterator it) noexcept; iterator remove(const_iterator first, const_iterator last) noexcept; void push_front(node node); void push_back(node node); void pop_front(void) noexcept; void pop_back(void) noexcept; template <class ...Args> void emplace_front(Args &&...args); template <class ...Args> void emplace_back(Args &&...args); visitor::status accept(visitor &visitor) override; visitor::status accept(visitor &visitor) const override; private: base *clone(void) const override; container elems; }; template <class InputIt> seq::seq(InputIt first, InputIt last) : elems(first, last) {} template <class InputIt> seq::iterator seq::insert(const_iterator it, InputIt first, InputIt last) { return elems.insert(it, first, last); } template <class ...Args> seq::iterator seq::emplace(const_iterator it, Args &&...args) { return elems.emplace(it, std::forward<Args>(args)...); } template <class ...Args> void seq::emplace_front(Args &&...args) { elems.emplace_front(std::forward<Args>(args)...); } template <class ...Args> void seq::emplace_back(Args &&...args) { elems.emplace_back(std::forward<Args>(args)...); } } } #endif /* !BFC_AST_SEQ_HPP */ <|endoftext|>
<commit_before>/* * Author: Dino Wernli */ #include "scene_parser.h" #include <glog/logging.h> #include "parser/mesh_parser.h" #include "proto/scene/scene_data.pb.h" #include "proto/util/color_data.pb.h" #include "scene/camera.h" #include "scene/element.h" #include "scene/geometry/circle_plane.h" #include "scene/geometry/plane.h" #include "scene/geometry/sphere.h" #include "scene/geometry/triangle.h" #include "scene/material.h" #include "scene/mesh.h" #include "scene/point_light.h" #include "scene/scene.h" #include "util/color3.h" #include "util/point3.h" #include "util/vector3.h" SceneParser::SceneParser() { } SceneParser::~SceneParser() { } static Color3 Parse(const raytracer::ColorData& data) { return Color3(data.r(), data.g(), data.b()); } static Vector3 Parse(const raytracer::VectorData& data) { return Vector3(data.x(), data.y(), data.z()); } static Point3 Parse(const raytracer::PointData& data) { return Point3(data.x(), data.y(), data.z()); } // Fetches the material pointer from the map, returns none if it is not found. Material* SceneParser::GetMaterial(const std::string& id) const { auto it = material_map_.find(id); return ((it == material_map_.end()) ? NULL : it->second); } Material* SceneParser::ParseMaterial(const raytracer::MaterialData& data) { if (!(data.has_emission() && data.has_ambient() && data.has_diffuse() && data.has_specular())) { return NULL; } return new Material(Parse(data.emission()), Parse(data.ambient()), Parse(data.diffuse()), Parse(data.specular()), data.shininess(), data.reflection_percentage(), data.refraction_percentage(), data.refraction_index()); } // static void SceneParser::ParseScene(const raytracer::SceneData& data, Scene* scene) { material_map_.clear(); if (data.has_background()) { scene->set_background(Parse(data.background())); } if (data.has_ambient()) { scene->set_ambient(Parse(data.ambient())); } Material* material = NULL; for (int i = 0; i < data.materials_size(); ++i) { if (!data.materials(i).has_identifier()) { LOG(WARNING) << "Skipping material without identifier"; continue; } if (!(material = ParseMaterial(data.materials(i)))) { LOG(WARNING) << "Skipping incomplete material"; continue; } // Ownership taken by scene. scene->AddMaterial(material); material_map_[data.materials(i).identifier()] = material; } if (data.has_camera()) { const auto& camera = data.camera(); if (!(camera.has_position() && camera.has_view() && camera.has_up() && camera.has_opening_angle() && camera.resolution_x() && camera.resolution_y())) { LOG(WARNING) << "Skipping incomplete camera"; } else { scene->set_camera(new Camera(Parse(data.camera().position()), Parse(data.camera().view()), Parse(data.camera().up()), data.camera().opening_angle(), data.camera().resolution_x(), data.camera().resolution_y())); } } for (int i = 0; i < data.lights_size(); ++i) { if (!(data.lights(i).has_position() && data.lights(i).has_color())) { LOG(WARNING) << "Skipping incomplete light"; continue; } scene->AddLight(new PointLight(Parse(data.lights(i).position()), Parse(data.lights(i).color()))); } // Parse triangles if any. for (int i = 0; i < data.triangles_size(); ++i) { const auto& triangle = data.triangles(i); std::unique_ptr<Vector3> n1(triangle.has_n1() ? new Vector3(Parse(triangle.n1())) : NULL); std::unique_ptr<Vector3> n2(triangle.has_n2() ? new Vector3(Parse(triangle.n2())) : NULL); std::unique_ptr<Vector3> n3(triangle.has_n3() ? new Vector3(Parse(triangle.n3())) : NULL); if (triangle.has_p1() && triangle.has_p2() && triangle.has_p3()) { if (!(material = GetMaterial(triangle.material_id()))) { LOG(WARNING) << "Failed to get material, skipping triangle"; continue; } scene->AddElement( new Triangle(Parse(triangle.p1()), Parse(triangle.p2()), Parse(triangle.p3()), *material, n1.get(), n2.get(), n3.get())); } else { LOG(WARNING) << "Skipping incomplete triangle"; } } // Parse planes if any. for (int i = 0; i < data.planes_size(); ++i) { const auto& plane = data.planes(i); if (plane.has_point() && plane.has_normal()) { if (!(material = GetMaterial(plane.material_id()))) { LOG(WARNING) << "Failed to get material, skipping plane"; continue; } scene->AddElement( new Plane(Parse(plane.point()), Parse(plane.normal()), *material)); } else { LOG(WARNING) << "Skipping incomplete plane"; } } // Parse circle planes if any. for (int i = 0; i < data.circle_planes_size(); ++i) { const auto& cplane = data.circle_planes(i); if (!(cplane.has_plane_data() && cplane.plane_data().has_point() && cplane.plane_data().has_normal())) { LOG(WARNING) << "Skipping incomplete circle plane"; continue; } const Material* main_material; if (!(main_material = GetMaterial(cplane.plane_data().material_id()))) { LOG(WARNING) << "Failed to get main material, skipping circle plane"; continue; } const Material* ring_material; if (!(ring_material = GetMaterial(cplane.ring_material_id()))) { LOG(WARNING) << "Failed to get ring material, skipping circle plane"; continue; } scene->AddElement(new CirclePlane( Parse(cplane.plane_data().point()), Parse(cplane.plane_data().normal()), cplane.radius(), *main_material, *ring_material)); } // Parse spheres if any. for (int i = 0; i < data.spheres_size(); ++i) { const auto& sphere = data.spheres(i); if (!(material = GetMaterial(sphere.material_id()))) { LOG(WARNING) << "Failed to get material, skipping sphere"; continue; } if (sphere.has_center() && sphere.has_radius()) { scene->AddElement(new Sphere(Parse(sphere.center()), sphere.radius(), *material)); } else { LOG(WARNING) << "Skipping incomplete sphere"; } } // Load meshes if any. MeshParser parser; for (int i = 0; i < data.meshes_size(); ++i) { const auto& mesh_data = data.meshes(i); if (mesh_data.has_obj_file()) { const std::string& path = mesh_data.obj_file(); Mesh* mesh = parser.LoadFile(path); if (mesh != NULL) { if (!(material = GetMaterial(mesh_data.material_id()))) { LOG(WARNING) << "Failed to get main material, skipping mesh"; continue; } mesh->set_material(material); if (mesh_data.has_translation() || mesh_data.has_radius()) { Vector3 translation; if (mesh_data.has_translation()) { translation = Parse(mesh_data.translation()); } mesh->Transform(mesh_data.has_radius() ? mesh_data.radius() : 1, translation); } mesh->InferNormals(); scene->AddMesh(mesh); } else { LOG(WARNING) << "Unable to load mesh from: " << path; } } else { LOG(WARNING) << "Skipping incomplete mesh"; } } } <commit_msg>Remove misleading comment.<commit_after>/* * Author: Dino Wernli */ #include "scene_parser.h" #include <glog/logging.h> #include "parser/mesh_parser.h" #include "proto/scene/scene_data.pb.h" #include "proto/util/color_data.pb.h" #include "scene/camera.h" #include "scene/element.h" #include "scene/geometry/circle_plane.h" #include "scene/geometry/plane.h" #include "scene/geometry/sphere.h" #include "scene/geometry/triangle.h" #include "scene/material.h" #include "scene/mesh.h" #include "scene/point_light.h" #include "scene/scene.h" #include "util/color3.h" #include "util/point3.h" #include "util/vector3.h" SceneParser::SceneParser() { } SceneParser::~SceneParser() { } static Color3 Parse(const raytracer::ColorData& data) { return Color3(data.r(), data.g(), data.b()); } static Vector3 Parse(const raytracer::VectorData& data) { return Vector3(data.x(), data.y(), data.z()); } static Point3 Parse(const raytracer::PointData& data) { return Point3(data.x(), data.y(), data.z()); } // Fetches the material pointer from the map, returns none if it is not found. Material* SceneParser::GetMaterial(const std::string& id) const { auto it = material_map_.find(id); return ((it == material_map_.end()) ? NULL : it->second); } Material* SceneParser::ParseMaterial(const raytracer::MaterialData& data) { if (!(data.has_emission() && data.has_ambient() && data.has_diffuse() && data.has_specular())) { return NULL; } return new Material(Parse(data.emission()), Parse(data.ambient()), Parse(data.diffuse()), Parse(data.specular()), data.shininess(), data.reflection_percentage(), data.refraction_percentage(), data.refraction_index()); } void SceneParser::ParseScene(const raytracer::SceneData& data, Scene* scene) { material_map_.clear(); if (data.has_background()) { scene->set_background(Parse(data.background())); } if (data.has_ambient()) { scene->set_ambient(Parse(data.ambient())); } Material* material = NULL; for (int i = 0; i < data.materials_size(); ++i) { if (!data.materials(i).has_identifier()) { LOG(WARNING) << "Skipping material without identifier"; continue; } if (!(material = ParseMaterial(data.materials(i)))) { LOG(WARNING) << "Skipping incomplete material"; continue; } // Ownership taken by scene. scene->AddMaterial(material); material_map_[data.materials(i).identifier()] = material; } if (data.has_camera()) { const auto& camera = data.camera(); if (!(camera.has_position() && camera.has_view() && camera.has_up() && camera.has_opening_angle() && camera.resolution_x() && camera.resolution_y())) { LOG(WARNING) << "Skipping incomplete camera"; } else { scene->set_camera(new Camera(Parse(data.camera().position()), Parse(data.camera().view()), Parse(data.camera().up()), data.camera().opening_angle(), data.camera().resolution_x(), data.camera().resolution_y())); } } for (int i = 0; i < data.lights_size(); ++i) { if (!(data.lights(i).has_position() && data.lights(i).has_color())) { LOG(WARNING) << "Skipping incomplete light"; continue; } scene->AddLight(new PointLight(Parse(data.lights(i).position()), Parse(data.lights(i).color()))); } // Parse triangles if any. for (int i = 0; i < data.triangles_size(); ++i) { const auto& triangle = data.triangles(i); std::unique_ptr<Vector3> n1(triangle.has_n1() ? new Vector3(Parse(triangle.n1())) : NULL); std::unique_ptr<Vector3> n2(triangle.has_n2() ? new Vector3(Parse(triangle.n2())) : NULL); std::unique_ptr<Vector3> n3(triangle.has_n3() ? new Vector3(Parse(triangle.n3())) : NULL); if (triangle.has_p1() && triangle.has_p2() && triangle.has_p3()) { if (!(material = GetMaterial(triangle.material_id()))) { LOG(WARNING) << "Failed to get material, skipping triangle"; continue; } scene->AddElement( new Triangle(Parse(triangle.p1()), Parse(triangle.p2()), Parse(triangle.p3()), *material, n1.get(), n2.get(), n3.get())); } else { LOG(WARNING) << "Skipping incomplete triangle"; } } // Parse planes if any. for (int i = 0; i < data.planes_size(); ++i) { const auto& plane = data.planes(i); if (plane.has_point() && plane.has_normal()) { if (!(material = GetMaterial(plane.material_id()))) { LOG(WARNING) << "Failed to get material, skipping plane"; continue; } scene->AddElement( new Plane(Parse(plane.point()), Parse(plane.normal()), *material)); } else { LOG(WARNING) << "Skipping incomplete plane"; } } // Parse circle planes if any. for (int i = 0; i < data.circle_planes_size(); ++i) { const auto& cplane = data.circle_planes(i); if (!(cplane.has_plane_data() && cplane.plane_data().has_point() && cplane.plane_data().has_normal())) { LOG(WARNING) << "Skipping incomplete circle plane"; continue; } const Material* main_material; if (!(main_material = GetMaterial(cplane.plane_data().material_id()))) { LOG(WARNING) << "Failed to get main material, skipping circle plane"; continue; } const Material* ring_material; if (!(ring_material = GetMaterial(cplane.ring_material_id()))) { LOG(WARNING) << "Failed to get ring material, skipping circle plane"; continue; } scene->AddElement(new CirclePlane( Parse(cplane.plane_data().point()), Parse(cplane.plane_data().normal()), cplane.radius(), *main_material, *ring_material)); } // Parse spheres if any. for (int i = 0; i < data.spheres_size(); ++i) { const auto& sphere = data.spheres(i); if (!(material = GetMaterial(sphere.material_id()))) { LOG(WARNING) << "Failed to get material, skipping sphere"; continue; } if (sphere.has_center() && sphere.has_radius()) { scene->AddElement(new Sphere(Parse(sphere.center()), sphere.radius(), *material)); } else { LOG(WARNING) << "Skipping incomplete sphere"; } } // Load meshes if any. MeshParser parser; for (int i = 0; i < data.meshes_size(); ++i) { const auto& mesh_data = data.meshes(i); if (mesh_data.has_obj_file()) { const std::string& path = mesh_data.obj_file(); Mesh* mesh = parser.LoadFile(path); if (mesh != NULL) { if (!(material = GetMaterial(mesh_data.material_id()))) { LOG(WARNING) << "Failed to get main material, skipping mesh"; continue; } mesh->set_material(material); if (mesh_data.has_translation() || mesh_data.has_radius()) { Vector3 translation; if (mesh_data.has_translation()) { translation = Parse(mesh_data.translation()); } mesh->Transform(mesh_data.has_radius() ? mesh_data.radius() : 1, translation); } mesh->InferNormals(); scene->AddMesh(mesh); } else { LOG(WARNING) << "Unable to load mesh from: " << path; } } else { LOG(WARNING) << "Skipping incomplete mesh"; } } } <|endoftext|>
<commit_before>/* * Copyright (C) 2004-2013 ZNC, see the NOTICE file for details. * * 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 <znc/FileUtils.h> #include <znc/Client.h> #include <znc/Chan.h> #include <znc/Modules.h> using std::vector; class CBacklogMod : public CModule { public: MODCONSTRUCTOR(CBacklogMod) {} virtual bool OnLoad(const CString& sArgs, CString& sMessage) { PutModule("I'm being loaded with the arguments: [" + sArgs + "]"); //AddTimer(new CSampleTimer(this, 300, 0, "Sample", "Sample timer for sample things.")); //AddTimer(new CSampleTimer(this, 5, 20, "Another", "Another sample timer.")); //AddTimer(new CSampleTimer(this, 25000, 5, "Third", "A third sample timer.")); return true; } virtual ~CBacklogMod() { PutModule("I'm being unloaded!"); } virtual bool OnBoot() { // This is called when the app starts up (only modules that are loaded in the config will get this event) return true; } virtual void OnModCommand(const CString& sCommand) { /* if (sCommand.Equals("TIMERS")) { ListTimers(); } */ // TODO: sanity check on file path, see log.cpp CFile LogFile(sCommand); CString Line; if (LogFile.Open()) { while (LogFile.ReadLine(Line)) { PutModule(Line); } } else { PutModule("Could not open log file [" + sCommand + "]: " + strerror(errno)); } LogFile.Close(); } }; template<> void TModInfo<CBacklogMod>(CModInfo& Info) { Info.SetWikiPage("sample"); Info.SetHasArgs(true); Info.SetArgsHelpText("Takes %Channelname% and %number of lines% as arguments"); } NETWORKMODULEDEFS(CBacklogMod, "Module for getting the last X lines of a channels log.") <commit_msg>cleanup<commit_after>/* * Copyright (C) 2004-2013 ZNC, see the NOTICE file for details. * * 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 <znc/FileUtils.h> #include <znc/Client.h> #include <znc/Chan.h> #include <znc/Modules.h> class CBacklogMod : public CModule { public: MODCONSTRUCTOR(CBacklogMod) {} virtual bool OnLoad(const CString& sArgs, CString& sMessage); virtual ~CBacklogMod(); virtual void OnModCommand(const CString& sCommand); private: CString LogPath; }; bool CBacklogMod::OnLoad(const CString& sArgs, CString& sMessage) { PutModule("I'm being loaded with the arguments: [" + sArgs + "]"); return true; } CBacklogMod::~CBacklogMod() { PutModule("I'm being unloaded!"); } void CBacklogMod::OnModCommand(const CString& sCommand) { CFile LogFile(sCommand); CString Line; if (LogFile.Open()) { while (LogFile.ReadLine(Line)) { PutModule(Line); } } else { PutModule("Could not open log file [" + sCommand + "]: " + strerror(errno)); } LogFile.Close(); } template<> void TModInfo<CBacklogMod>(CModInfo& Info) { Info.AddType(CModInfo::NetworkModule); Info.AddType(CModInfo::GlobalModule); Info.SetWikiPage("backlog"); Info.SetArgsHelpText("Takes path to logs as argument, use keywords: $USER, $NETWORK and $WINDOW"); Info.SetHasArgs(true); } NETWORKMODULEDEFS(CBacklogMod, "Module for getting the last X lines of a channels log.") <|endoftext|>
<commit_before>/* * <one line to give the program's name and a brief idea of what it does.> * Copyright (C) 2014 Salvo Tomaselli <tiposchi@tiscali.it> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include <unordered_set> #include "boardai.h" bool BoardAI::place(int col, player_t player) { bool r = Board::place(col,player); if (!r) return false; if (player != this->aiplayer) { //Play AI round airound(); } return true; } void BoardAI::airound() { player_t other_player = (player_t)~aiplayer; //Do nothing if the game is already over if (this->completed) { return; } //Win in 1 move { for (int c=0; c<this->cols; c++) { int r = free_slot(c); if (r != -1 && winning_move(r,c,aiplayer)) { printf("Win in 1 move\n"); place(c,aiplayer); return; } } } //Prevent win in 1 move { for (int c=0; c<this->cols; c++) { int r = free_slot(c); if (r != -1 && winning_move(r,c,other_player)) { printf("Prevent win in 1 move\n"); place(c,aiplayer); return; } } } //Block lineup of 3 central pieces //Horizontal { for (int row = 0; row< this->rows; row ++) { for (int col = 1; col < this->cols-2; col++) { if ( ( get_content(row,col-1) == CELL_EMPTY && get_content(row,col) == (cell_t)other_player && get_content(row,col+1) == (cell_t)other_player && get_content(row,col+2) == CELL_EMPTY ) || ( get_content(row,col-1) == CELL_EMPTY && get_content(row,col) == (cell_t)other_player && get_content(row,col+1) == CELL_EMPTY && get_content(row,col+2) == (cell_t)other_player )) { int r1 = free_slot(col-1); int r2= free_slot(col+2); int r3 = free_slot(col+1); if (r1== row) { printf("Prevent horizontal lineup of 3 pieces %d\n",__LINE__); place(col-1, aiplayer); return; } else if (r2== row){ printf("Prevent horizontal lineup of 3 pieces %d\n",__LINE__); place(col+2,aiplayer); return; } else if (r3== row) { printf("Prevent horizontal lineup of 3 pieces %d\n",__LINE__); place(col+1,aiplayer); return; } } } } } //Diagonal { for (int row = 1; row< this->rows-1; row ++) { for (int col = 2; col < this->cols-2; col++) { if ( ( get_content(row-1,col-1) == CELL_EMPTY && get_content(row,col) == (cell_t)other_player && get_content(row+1,col+1) == (cell_t)other_player && get_content(row+2,col+2) == CELL_EMPTY ) || ( get_content(row-1,col-1) == CELL_EMPTY && get_content(row,col) == (cell_t)other_player && get_content(row+1,col+1) == CELL_EMPTY && get_content(row+2,col+2) == (cell_t)other_player )) { int r1 = free_slot(col-1); int r2= free_slot(col+2); int r3 = free_slot(col+1); if (r1== row-1) { place(col-1, aiplayer); printf("Prevent diagonal lineup of 3 pieces %d\n",__LINE__); return; } else if (r2== row+2){ place(col+2,aiplayer); printf("Prevent diagonal lineup of 3 pieces %d\n",__LINE__); return; } else if (r3== row+1) { place(col+1,aiplayer); printf("Prevent diagonal lineup of 3 pieces %d\n",__LINE__); return; } } } } } { for (int row = 1; row< this->rows-1; row ++) { for (int col = 2; col < this->cols-2; col++) { if ( ( get_content(row+1,col-1) == CELL_EMPTY && get_content(row,col) == (cell_t)other_player && get_content(row-1,col+1) == (cell_t)other_player && get_content(row-2,col+2) == CELL_EMPTY ) || ( get_content(row+1,col-1) == CELL_EMPTY && get_content(row,col) == (cell_t)other_player && get_content(row-1,col+1) == CELL_EMPTY && get_content(row-2,col+2) == (cell_t)other_player )) { int r1 = free_slot(col-1); int r2= free_slot(col+2); int r3 = free_slot(col+1); if (r1== row+1) { place(col-1, aiplayer); printf("Prevent diagonal lineup of 3 pieces %d\n",__LINE__); return; } else if (r2== row-2){ place(col+2,aiplayer); printf("Prevent diagonal lineup of 3 pieces %d\n",__LINE__); return; } else if (r3== row-1) { place(col+1,aiplayer); printf("Prevent diagonal lineup of 3 pieces %d\n",__LINE__); return; } } } } } //play randomly but blacklist some columns { printf("Randomly… %d\n",__LINE__); std::unordered_set<int> allowed_columns; for (int c=0; c< this->cols;c++) allowed_columns.insert(c); for (int c=0; c< this->cols;c++) { int r = free_slot(c)-1; if (r>=0 && winning_move(r,c,other_player)) { allowed_columns.erase(c); } } int c; do { c = rand() % this->cols; if ((!allowed_columns.empty()) && (allowed_columns.find(c) != allowed_columns.end())) continue; } while(!this->place(c,this->aiplayer)); } } <commit_msg>Fixed column blacklisting<commit_after>/* * <one line to give the program's name and a brief idea of what it does.> * Copyright (C) 2014 Salvo Tomaselli <tiposchi@tiscali.it> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include <unordered_set> #include "boardai.h" bool BoardAI::place(int col, player_t player) { bool r = Board::place(col,player); if (!r) return false; if (player != this->aiplayer) { //Play AI round airound(); } return true; } void BoardAI::airound() { player_t other_player = (player_t)~aiplayer; //Do nothing if the game is already over if (this->completed) { return; } //Win in 1 move { for (int c=0; c<this->cols; c++) { int r = free_slot(c); if (r != -1 && winning_move(r,c,aiplayer)) { printf("Win in 1 move\n"); place(c,aiplayer); return; } } } //Prevent win in 1 move { for (int c=0; c<this->cols; c++) { int r = free_slot(c); if (r != -1 && winning_move(r,c,other_player)) { printf("Prevent win in 1 move\n"); place(c,aiplayer); return; } } } //Block lineup of 3 central pieces //Horizontal { for (int row = 0; row< this->rows; row ++) { for (int col = 1; col < this->cols-2; col++) { if ( ( get_content(row,col-1) == CELL_EMPTY && get_content(row,col) == (cell_t)other_player && get_content(row,col+1) == (cell_t)other_player && get_content(row,col+2) == CELL_EMPTY ) || ( get_content(row,col-1) == CELL_EMPTY && get_content(row,col) == (cell_t)other_player && get_content(row,col+1) == CELL_EMPTY && get_content(row,col+2) == (cell_t)other_player )) { int r1 = free_slot(col-1); int r2= free_slot(col+2); int r3 = free_slot(col+1); if (r1== row) { printf("Prevent horizontal lineup of 3 pieces %d\n",__LINE__); place(col-1, aiplayer); return; } else if (r2== row){ printf("Prevent horizontal lineup of 3 pieces %d\n",__LINE__); place(col+2,aiplayer); return; } else if (r3== row) { printf("Prevent horizontal lineup of 3 pieces %d\n",__LINE__); place(col+1,aiplayer); return; } } } } } //Diagonal { for (int row = 1; row< this->rows-1; row ++) { for (int col = 2; col < this->cols-2; col++) { if ( ( get_content(row-1,col-1) == CELL_EMPTY && get_content(row,col) == (cell_t)other_player && get_content(row+1,col+1) == (cell_t)other_player && get_content(row+2,col+2) == CELL_EMPTY ) || ( get_content(row-1,col-1) == CELL_EMPTY && get_content(row,col) == (cell_t)other_player && get_content(row+1,col+1) == CELL_EMPTY && get_content(row+2,col+2) == (cell_t)other_player )) { int r1 = free_slot(col-1); int r2= free_slot(col+2); int r3 = free_slot(col+1); if (r1== row-1) { place(col-1, aiplayer); printf("Prevent diagonal lineup of 3 pieces %d\n",__LINE__); return; } else if (r2== row+2){ place(col+2,aiplayer); printf("Prevent diagonal lineup of 3 pieces %d\n",__LINE__); return; } else if (r3== row+1) { place(col+1,aiplayer); printf("Prevent diagonal lineup of 3 pieces %d\n",__LINE__); return; } } } } } { for (int row = 1; row< this->rows-1; row ++) { for (int col = 2; col < this->cols-2; col++) { if ( ( get_content(row+1,col-1) == CELL_EMPTY && get_content(row,col) == (cell_t)other_player && get_content(row-1,col+1) == (cell_t)other_player && get_content(row-2,col+2) == CELL_EMPTY ) || ( get_content(row+1,col-1) == CELL_EMPTY && get_content(row,col) == (cell_t)other_player && get_content(row-1,col+1) == CELL_EMPTY && get_content(row-2,col+2) == (cell_t)other_player )) { int r1 = free_slot(col-1); int r2= free_slot(col+2); int r3 = free_slot(col+1); if (r1== row+1) { place(col-1, aiplayer); printf("Prevent diagonal lineup of 3 pieces %d\n",__LINE__); return; } else if (r2== row-2){ place(col+2,aiplayer); printf("Prevent diagonal lineup of 3 pieces %d\n",__LINE__); return; } else if (r3== row-1) { place(col+1,aiplayer); printf("Prevent diagonal lineup of 3 pieces %d\n",__LINE__); return; } } } } } //play randomly but blacklist some columns { printf("Randomly… %d: ",__LINE__); std::unordered_set<int> allowed_columns; for (int c=0; c< this->cols;c++) { allowed_columns.insert(c); } for (int c=0; c< this->cols;c++) { int r = free_slot(c)-1; if (r>=0 && winning_move(r,c,other_player)) { allowed_columns.erase(c); printf("%d ",c); } } printf("\n"); int c; while (true) { c = rand() % this->cols; printf("Selecting column %d\n",c); if ((!allowed_columns.empty()) && (allowed_columns.find(c) == allowed_columns.end())) continue; if (this->place(c,this->aiplayer)) break; } } } <|endoftext|>
<commit_before>#include "Table.h" // int insertInstruction(int state, int symbol, int newState, int newSymbol, // char instruction); // void removeInstruction(int id); // machineAction_t getAction(int state, int symbol); // TODO: implement Table methods int Table::insertInstruction(int state, int symbol, int newState, int newSymbol, char instruction) { machineState_t mStat; mStat.state = state; mStat.symbol = symbol; machineAction_t mAct; mAct.newState = newState; mAct.newSymbol = newSymbol; mAct.instruction = instruction; machineInstruction_t mInst; mInst.state = mStat; mInst.action = mAct; mInst.id = 0; // TODO: figure out something to do with ID's or remove them this.table.push_back(mInst); } <commit_msg>Make insert instruction return something<commit_after>#include "Table.h" // int insertInstruction(int state, int symbol, int newState, int newSymbol, // char instruction); // void removeInstruction(int id); // machineAction_t getAction(int state, int symbol); // TODO: implement Table methods int Table::insertInstruction(int state, int symbol, int newState, int newSymbol, char instruction) { machineState_t mStat; mStat.state = state; mStat.symbol = symbol; machineAction_t mAct; mAct.newState = newState; mAct.newSymbol = newSymbol; mAct.instruction = instruction; machineInstruction_t mInst; mInst.state = mStat; mInst.action = mAct; mInst.id = 0; // TODO: figure out something to do with ID's or remove them this.table.push_back(mInst); return 0; //TODO: Figure out something to do with id's } <|endoftext|>
<commit_before>/* Copyright (c) 2014 D. Niklaus. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ /* * Timer.cpp * * Created on: 13.08.2013 * Author: niklausd */ #include <limits.h> #include "UptimeInfo.h" #include "Timer.h" #include "TimerContext.h" void scheduleTimers() { TimerContext::instance()->handleTick(); } void yield() { TimerContext::instance()->handleTick(); } void delayAndSchedule(unsigned int delayMillis) { // create a one-shot timer on the fly Timer delayTimer(0, Timer::IS_NON_RECURRING, (delayMillis)); // wait until the timer expires while (!delayTimer.isTimerExpired()) { // schedule the timer above and all the other timers, so they will still run in 'parallel' scheduleTimers(); } } const bool Timer::IS_NON_RECURRING = false; const bool Timer::IS_RECURRING = true; Timer::Timer(TimerAdapter* adapter, bool isRecurring, unsigned long timeMillis) : m_isRecurring(isRecurring) , m_isExpiredFlag(false) , m_currentTimeMillis(0) , m_triggerTimeMillis(0) , m_triggerTimeMillisUpperLimit(ULONG_MAX) , m_delayMillis(0) , m_adapter(adapter) , m_next(0) { TimerContext::instance()->attach(this); if (0 < timeMillis) { startTimer(timeMillis); } } Timer::~Timer() { TimerContext::instance()->detach(this); } void Timer::attachAdapter(TimerAdapter* adapter) { m_adapter = adapter; } TimerAdapter* Timer::adapter() { return m_adapter; } Timer* Timer::next() { return m_next; } void Timer::setNext(Timer* timer) { m_next = timer; } bool Timer::isTimerExpired() { internalTick(); bool isExpired = m_isExpiredFlag; m_isExpiredFlag = false; return isExpired; } bool Timer::isRunning() { return (0 != m_delayMillis); } void Timer::tick() { internalTick(); } void Timer::cancelTimer() { m_delayMillis = 0; m_isExpiredFlag = false; } void Timer::startTimer(unsigned long timeMillis) { m_delayMillis = timeMillis; if (m_delayMillis > 0) { m_currentTimeMillis = UptimeInfo::tMillis(); startInterval(); } else { cancelTimer(); } } void Timer::startTimer() { if (m_delayMillis > 0) { m_currentTimeMillis = UptimeInfo::tMillis(); startInterval(); } } void Timer::startInterval() { unsigned long deltaTime = ULONG_MAX - m_currentTimeMillis; if (deltaTime < m_delayMillis) { // overflow will occur m_triggerTimeMillis = m_delayMillis - deltaTime - 1; m_triggerTimeMillisUpperLimit = m_currentTimeMillis; } else { m_triggerTimeMillis = m_currentTimeMillis + m_delayMillis - 1; m_triggerTimeMillisUpperLimit = ULONG_MAX; } } void Timer::internalTick() { m_currentTimeMillis = UptimeInfo::tMillis(); // check if interval is over, as long as (m_delayMillis > 0) if ((m_delayMillis > 0) && (m_triggerTimeMillis < m_currentTimeMillis) && (m_currentTimeMillis < m_triggerTimeMillisUpperLimit)) { if (m_isRecurring) { startInterval(); } else { m_delayMillis = 0; } m_isExpiredFlag = true; if (0 != m_adapter) { m_adapter->timeExpired(); } } } <commit_msg>Remove LGPL license header<commit_after>/* * Timer.cpp * * Created on: 13.08.2013 * Author: niklausd */ #include <limits.h> #include "UptimeInfo.h" #include "Timer.h" #include "TimerContext.h" void scheduleTimers() { TimerContext::instance()->handleTick(); } void yield() { TimerContext::instance()->handleTick(); } void delayAndSchedule(unsigned int delayMillis) { // create a one-shot timer on the fly Timer delayTimer(0, Timer::IS_NON_RECURRING, (delayMillis)); // wait until the timer expires while (!delayTimer.isTimerExpired()) { // schedule the timer above and all the other timers, so they will still run in 'parallel' scheduleTimers(); } } const bool Timer::IS_NON_RECURRING = false; const bool Timer::IS_RECURRING = true; Timer::Timer(TimerAdapter* adapter, bool isRecurring, unsigned long timeMillis) : m_isRecurring(isRecurring) , m_isExpiredFlag(false) , m_currentTimeMillis(0) , m_triggerTimeMillis(0) , m_triggerTimeMillisUpperLimit(ULONG_MAX) , m_delayMillis(0) , m_adapter(adapter) , m_next(0) { TimerContext::instance()->attach(this); if (0 < timeMillis) { startTimer(timeMillis); } } Timer::~Timer() { TimerContext::instance()->detach(this); } void Timer::attachAdapter(TimerAdapter* adapter) { m_adapter = adapter; } TimerAdapter* Timer::adapter() { return m_adapter; } Timer* Timer::next() { return m_next; } void Timer::setNext(Timer* timer) { m_next = timer; } bool Timer::isTimerExpired() { internalTick(); bool isExpired = m_isExpiredFlag; m_isExpiredFlag = false; return isExpired; } bool Timer::isRunning() { return (0 != m_delayMillis); } void Timer::tick() { internalTick(); } void Timer::cancelTimer() { m_delayMillis = 0; m_isExpiredFlag = false; } void Timer::startTimer(unsigned long timeMillis) { m_delayMillis = timeMillis; if (m_delayMillis > 0) { m_currentTimeMillis = UptimeInfo::tMillis(); startInterval(); } else { cancelTimer(); } } void Timer::startTimer() { if (m_delayMillis > 0) { m_currentTimeMillis = UptimeInfo::tMillis(); startInterval(); } } void Timer::startInterval() { unsigned long deltaTime = ULONG_MAX - m_currentTimeMillis; if (deltaTime < m_delayMillis) { // overflow will occur m_triggerTimeMillis = m_delayMillis - deltaTime - 1; m_triggerTimeMillisUpperLimit = m_currentTimeMillis; } else { m_triggerTimeMillis = m_currentTimeMillis + m_delayMillis - 1; m_triggerTimeMillisUpperLimit = ULONG_MAX; } } void Timer::internalTick() { m_currentTimeMillis = UptimeInfo::tMillis(); // check if interval is over, as long as (m_delayMillis > 0) if ((m_delayMillis > 0) && (m_triggerTimeMillis < m_currentTimeMillis) && (m_currentTimeMillis < m_triggerTimeMillisUpperLimit)) { if (m_isRecurring) { startInterval(); } else { m_delayMillis = 0; } m_isExpiredFlag = true; if (0 != m_adapter) { m_adapter->timeExpired(); } } } <|endoftext|>
<commit_before>#include <cfloat> #include <cstdlib> #include <cmath> #include <cstdio> #include <cstring> #include <sys/time.h> #include <string> #include <algorithm> #include "Utils.hpp" using namespace std; namespace SpMP { static const double DEFAULT_CPU_FREQ = 3.33e9; double get_cpu_freq() { static double freq = DBL_MAX; if (DBL_MAX == freq) { volatile double a = rand()%1024, b = rand()%1024; struct timeval tv1, tv2; gettimeofday(&tv1, NULL); unsigned long long t1 = __rdtsc(); for (size_t i = 0; i < 1024L*1024; i++) { a += a*b + b/a; } unsigned long long dt = __rdtsc() - t1; gettimeofday(&tv2, NULL); freq = dt/((tv2.tv_sec - tv1.tv_sec) + (tv2.tv_usec - tv1.tv_usec)/1.e6); } return freq; } void getInversePerm(int *inversePerm, const int *perm, int n) { #pragma omp parallel for #pragma simd for (int i = 0; i < n; ++i) { inversePerm[perm[i]] = i; } } bool isPerm(const int *perm, int n) { int *temp = new int[n]; memcpy(temp, perm, sizeof(int)*n); sort(temp, temp + n); int *last = unique(temp, temp + n); if (last != temp + n) { memcpy(temp, perm, sizeof(int)*n); sort(temp, temp + n); for (int i = 0; i < n; ++i) { if (temp[i] == i - 1) { printf("%d duplicated\n", i - 1); assert(false); return false; } else if (temp[i] != i) { printf("%d missed\n", i); assert(false); return false; } } } delete[] temp; return true; } template<class T> void CopyVector(T *dst, const T *src, int len) { #pragma omp parallel for for (int i = 0; i < len; ++i) { dst[i] = src[i]; } } void reorderVectorOutOfPlace(double *dst, const double *src, const int *perm, int len) { if (perm) { #pragma omp parallel for for (int i = 0; i < len; ++i) { assert(perm[i] >= 0 && perm[i] < len); dst[perm[i]] = src[i]; } } else { CopyVector(dst, src, len); } } void reorderVectorOutOfPlaceWithInversePerm(double *dst, const double *src, const int *inversePerm, int len) { if (inversePerm) { #pragma omp parallel for for (int i = 0; i < len; ++i) { assert(inversePerm[i] >= 0 && inversePerm[i] < len); dst[i] = src[inversePerm[i]]; } } else { CopyVector(dst, src, len); } } double *getReorderVector(const double *v, const int *perm, int len) { double *ret = MALLOC(double, len); reorderVectorOutOfPlace(ret, v, perm, len); return ret; } double *getReorderVectorWithInversePerm(const double *v, const int *perm, int len) { double *ret = MALLOC(double, len); reorderVectorOutOfPlaceWithInversePerm(ret, v, perm, len); return ret; } void reorderVector(double *v, double *tmp, const int *perm, int len) { if (!perm) return; reorderVectorOutOfPlace(tmp, v, perm, len); CopyVector(v, tmp, len); } void reorderVectorWithInversePerm(double *v, double *tmp, const int *inversePerm, int len) { if (!inversePerm) return; reorderVectorOutOfPlaceWithInversePerm(tmp, v, inversePerm, len); CopyVector(v, tmp, len); } void reorderVector(double *v, const int *perm, int len) { double *tmp = MALLOC(double, len); reorderVector(v, tmp, perm, len); FREE(tmp); } void reorderVectorWithInversePerm(double *v, const int *perm, int len) { double *tmp = MALLOC(double, len); reorderVectorWithInversePerm(v, tmp, perm, len); FREE(tmp); } } // namespace SpMP <commit_msg>reorder int vector<commit_after>#include <cfloat> #include <cstdlib> #include <cmath> #include <cstdio> #include <cstring> #include <sys/time.h> #include <string> #include <algorithm> #include "Utils.hpp" using namespace std; namespace SpMP { static const double DEFAULT_CPU_FREQ = 3.33e9; double get_cpu_freq() { static double freq = DBL_MAX; if (DBL_MAX == freq) { volatile double a = rand()%1024, b = rand()%1024; struct timeval tv1, tv2; gettimeofday(&tv1, NULL); unsigned long long t1 = __rdtsc(); for (size_t i = 0; i < 1024L*1024; i++) { a += a*b + b/a; } unsigned long long dt = __rdtsc() - t1; gettimeofday(&tv2, NULL); freq = dt/((tv2.tv_sec - tv1.tv_sec) + (tv2.tv_usec - tv1.tv_usec)/1.e6); } return freq; } void getInversePerm(int *inversePerm, const int *perm, int n) { #pragma omp parallel for #pragma simd for (int i = 0; i < n; ++i) { inversePerm[perm[i]] = i; } } bool isPerm(const int *perm, int n) { int *temp = new int[n]; memcpy(temp, perm, sizeof(int)*n); sort(temp, temp + n); int *last = unique(temp, temp + n); if (last != temp + n) { memcpy(temp, perm, sizeof(int)*n); sort(temp, temp + n); for (int i = 0; i < n; ++i) { if (temp[i] == i - 1) { printf("%d duplicated\n", i - 1); assert(false); return false; } else if (temp[i] != i) { printf("%d missed\n", i); assert(false); return false; } } } delete[] temp; return true; } bool isInversePerm(const int *perm, const int *inversePerm, int len) { for (int i = 0; i < len; ++i) { if (inversePerm[perm[i]] != i) return false; } return true; } template<class T> void CopyVector(T *dst, const T *src, int len) { #pragma omp parallel for for (int i = 0; i < len; ++i) { dst[i] = src[i]; } } template<class T> void reorderVectorOutOfPlace_(T *dst, const T *src, const int *perm, int len) { if (perm) { #pragma omp parallel for for (int i = 0; i < len; ++i) { assert(perm[i] >= 0 && perm[i] < len); dst[perm[i]] = src[i]; } } else { CopyVector(dst, src, len); } } void reorderVectorOutOfPlace(double *dst, const double *src, const int *perm, int len) { return reorderVectorOutOfPlace_(dst, src, perm, len); } void reorderVectorOutOfPlace(int *dst, const int *src, const int *perm, int len) { return reorderVectorOutOfPlace_(dst, src, perm, len); } template<class T> void reorderVectorOutOfPlaceWithInversePerm_(T *dst, const T *src, const int *inversePerm, int len) { if (inversePerm) { #pragma omp parallel for for (int i = 0; i < len; ++i) { assert(inversePerm[i] >= 0 && inversePerm[i] < len); dst[i] = src[inversePerm[i]]; } } else { CopyVector(dst, src, len); } } void reorderVectorOutOfPlaceWithInversePerm(double *dst, const double *src, const int *inversePerm, int len) { return reorderVectorOutOfPlaceWithInversePerm_(dst, src, inversePerm, len); } void reorderVectorOutOfPlaceWithInversePerm(int *dst, const int *src, const int *inversePerm, int len) { return reorderVectorOutOfPlaceWithInversePerm_(dst, src, inversePerm, len); } double *getReorderVector(const double *v, const int *perm, int len) { double *ret = MALLOC(double, len); reorderVectorOutOfPlace(ret, v, perm, len); return ret; } double *getReorderVectorWithInversePerm(const double *v, const int *perm, int len) { double *ret = MALLOC(double, len); reorderVectorOutOfPlaceWithInversePerm(ret, v, perm, len); return ret; } void reorderVector(double *v, double *tmp, const int *perm, int len) { if (!perm) return; reorderVectorOutOfPlace(tmp, v, perm, len); CopyVector(v, tmp, len); } void reorderVectorWithInversePerm(double *v, double *tmp, const int *inversePerm, int len) { if (!inversePerm) return; reorderVectorOutOfPlaceWithInversePerm(tmp, v, inversePerm, len); CopyVector(v, tmp, len); } void reorderVector(double *v, const int *perm, int len) { double *tmp = MALLOC(double, len); reorderVector(v, tmp, perm, len); FREE(tmp); } void reorderVectorWithInversePerm(double *v, const int *perm, int len) { double *tmp = MALLOC(double, len); reorderVectorWithInversePerm(v, tmp, perm, len); FREE(tmp); } } // namespace SpMP <|endoftext|>
<commit_before>#ifndef __PK_HPP__ #define __PK_HPP__ #include <utility> #include <vector> #include <queue> #include <iostream> #include <fstream> #include <unordered_set> #include "model.hpp" class Evaluator { Evaluator(); virtual void evaluate(const Model&); }; class EvaluatorBinary : public Evaluator { // please add your structure to store the datasets public: void load_files(); } class EvaluatorRating : public Evaluator { RatingMatrix test; public: void load_files(); } void EvaluateRating::evaluate(const Model& model) { } struct pkcomp { bool operator() (std::pair<int, double> i, std::pair<int, double> j) { return i.second > j.second; } }; void EvaluateBinary::load_files (char* train_repo, char* test_repo, std::vector<int>& k) { } void EvaluateBinary::evaluate (const Model& model) { std::vector<std::unordered_set<int> > train, test; train.resize(model.n_users); test.resize(model.n_users); std::ifstream tr(train_repo); if (tr) { int uid, iid; while (tr >> uid >> iid) { train[uid - 1].insert(iid - 1); } } else { printf ("Error in opening the training repository!\n"); exit(EXIT_FAILURE); } tr.close(); std::ifstream te(test_repo); if (te) { int uid, iid; while (te >> uid >> iid) { test[uid - 1].insert(iid - 1); } } else { printf ("Error in opening the testing repository!\n"); exit(EXIT_FAILURE); } te.close(); int maxK = k[k.size() - 1]; std::vector<double> ret(k.size(), 0); std::priority_queue<std::pair<int, double>, std::vector<std::pair<int, double> >, pkcomp> pq; for (int i = 0; i < model.n_users; ++i) { for (int j = 0; j < model.n_items; ++j) { if (train[i].find(j) == train[i].end() ) { continue; } double score = 0; double *user_vec = &model.U[i * model.rank]; double *item_vec = &model.V[j * model.rank]; for (int l = 0; l < model.rank; ++l) { score += user_vec[l] * item_vec[l]; } if (pq.size() < maxK) { pq.push(std::pair<int, double>(j, score) ); } else if (pq.top().second < score) { pq.push(std::pair<int, double>(j, score) ); pq.pop(); } } int ps = pq.size(); while (ps) { int item = pq.top().first; for (int j = k.size() - 1; j >= 0; --j) { if (ps > k[j]) break; if (test[i].find(item) != test[i].end() ) ++ret[j]; } pq.pop(); --ps; } } for (int i = 0; i < k.size(); ++i) { ret[i] = ret[i] / model.n_users / k[i]; } return ret; } #endif <commit_msg>revised compute precision<commit_after>#ifndef __PK_HPP__ #define __PK_HPP__ #include <utility> #include <vector> #include <queue> #include <iostream> #include <fstream> #include <unordered_set> #include "model.hpp" class Evaluator { Evaluator(); virtual void evaluate(const Model&); }; class EvaluatorBinary : public Evaluator { std::vector<std::unordered_set<int> > train, test; std::vector<int> k; // please add your structure to store the datasets public: void load_files(char*, char*, std::vector<int>&); } class EvaluatorRating : public Evaluator { RatingMatrix test; public: void load_files(); } void EvaluateRating::evaluate(const Model& model) { } struct pkcomp { bool operator() (std::pair<int, double> i, std::pair<int, double> j) { return i.second > j.second; } }; void EvaluateBinary::load_files (char* train_repo, char* test_repo, std::vector<int>& ik) { std::ifstream tr(train_repo); if (tr) { int uid, iid; while (tr >> uid >> iid) { train[uid - 1].insert(iid - 1); } } else { printf ("Error in opening the training repository!\n"); exit(EXIT_FAILURE); } tr.close(); std::ifstream te(test_repo); if (te) { int uid, iid; while (te >> uid >> iid) { test[uid - 1].insert(iid - 1); } } else { printf ("Error in opening the testing repository!\n"); exit(EXIT_FAILURE); } te.close(); k = ik; } void EvaluateBinary::evaluate (const Model& model) { train.resize(model.n_users); test.resize(model.n_users); int maxK = k[k.size() - 1]; std::vector<double> ret(k.size(), 0); std::priority_queue<std::pair<int, double>, std::vector<std::pair<int, double> >, pkcomp> pq; for (int i = 0; i < model.n_users; ++i) { for (int j = 0; j < model.n_items; ++j) { if (train[i].find(j) == train[i].end() ) { continue; } double score = 0; double *user_vec = &model.U[i * model.rank]; double *item_vec = &model.V[j * model.rank]; for (int l = 0; l < model.rank; ++l) { score += user_vec[l] * item_vec[l]; } if (pq.size() < maxK) { pq.push(std::pair<int, double>(j, score) ); } else if (pq.top().second < score) { pq.push(std::pair<int, double>(j, score) ); pq.pop(); } } int ps = pq.size(); while (ps) { int item = pq.top().first; for (int j = k.size() - 1; j >= 0; --j) { if (ps > k[j]) break; if (test[i].find(item) != test[i].end() ) ++ret[j]; } pq.pop(); --ps; } } for (int i = 0; i < k.size(); ++i) { ret[i] = ret[i] / model.n_users / k[i]; } printf("compute precision at k\n"); for (int i = 0; i < k.size(); ++i) { printf("k %d, precision %f\n", k[i], ret[i]); } } #endif <|endoftext|>
<commit_before>#include <random> #include <celero/Celero.h> /// /// This demo was created to understand the cost with various falvors of "setters" where /// a function in a class or struct is provided solely to set the value of an internal member. /// There was some guidance being provided on the internet that if you intend to simply copy /// the value passed into the function, to incur the cost of the copy when passing the argument. /// Other guidance suggested to always pass non-pod types in by const ref. When in doubt, measure! /// /// http://stackoverflow.com/questions/18673658/should-i-always-move-on-sink-constructor-or-setter-arguments /// /// /// This is the main(int argc, char** argv) for the entire celero program. /// You can write your own, or use this macro to insert the standard one into the project. /// CELERO_MAIN; struct Foo { Foo() : nonPodType() { } void setNonPODTypeByValue(std::string x) { this->nonPodType = x; } void setNonPODTypeByValueWithMove(std::string x) { this->nonPodType = std::move(x); } void setNonPODTypeByConstRef(const std::string& x) { this->nonPodType = x; } void setNonPODTypeByConstRRef(const std::string&& x) { this->nonPodType = x; } void setNonPODTypeByConstRRefWithMove(const std::string&& x) { this->nonPodType = std::move(x); } void setPODTypeByValue(uint64_t x) { this->podType = x; } void setPODTypeByValueWithMove(uint64_t x) { this->podType = std::move(x); } void setPODTypeByConstRef(const uint64_t& x) { this->podType = x; } void setPODTypeByConstRRef(const uint64_t&& x) { this->podType = x; } void setPODTypeByConstRRefWithMove(const uint64_t&& x) { this->podType = std::move(x); } std::string nonPodType; uint64_t podType; }; #define MY_NUMBER_OF_CALLS_PER_MEASUREMENT 3000000 #define MY_NUMBER_OF_SAMPLES 100 BASELINE(NonPODParamPassing, Baseline, MY_NUMBER_OF_SAMPLES, MY_NUMBER_OF_CALLS_PER_MEASUREMENT) { // While we are not measuring the time to construct a "Foo" or create "bar", since // we do this in each of the tests, the time is exactly the same and does not // change the baseline measurement. (The only difference in each of these cases // is the part we wish to measure.) Foo f; auto bar = std::string("bar"); f.nonPodType = bar; } BENCHMARK(NonPODParamPassing, TypeMoveCopy, MY_NUMBER_OF_SAMPLES, MY_NUMBER_OF_CALLS_PER_MEASUREMENT) { Foo f; auto bar = std::string("bar"); f.nonPodType = std::move(bar); } BENCHMARK(NonPODParamPassing, TypeByValue, MY_NUMBER_OF_SAMPLES, MY_NUMBER_OF_CALLS_PER_MEASUREMENT) { Foo f; auto bar = std::string("bar"); f.setNonPODTypeByValue(bar); } BENCHMARK(NonPODParamPassing, TypeByMovedValue, MY_NUMBER_OF_SAMPLES, MY_NUMBER_OF_CALLS_PER_MEASUREMENT) { Foo f; auto bar = std::string("bar"); f.setNonPODTypeByValue(std::move(bar)); } BENCHMARK(NonPODParamPassing, TypeByValueWithMove, MY_NUMBER_OF_SAMPLES, MY_NUMBER_OF_CALLS_PER_MEASUREMENT) { Foo f; auto bar = std::string("bar"); f.setNonPODTypeByValue(bar); } BENCHMARK(NonPODParamPassing, TypeByMoveValueWithMove, MY_NUMBER_OF_SAMPLES, MY_NUMBER_OF_CALLS_PER_MEASUREMENT) { Foo f; auto bar = std::string("bar"); f.setNonPODTypeByValue(std::move(bar)); } BENCHMARK(NonPODParamPassing, TypeByConstRef, MY_NUMBER_OF_SAMPLES, MY_NUMBER_OF_CALLS_PER_MEASUREMENT) { Foo f; auto bar = std::string("bar"); f.setNonPODTypeByConstRef(bar); } BENCHMARK(NonPODParamPassing, TypeByConstRRef, MY_NUMBER_OF_SAMPLES, MY_NUMBER_OF_CALLS_PER_MEASUREMENT) { Foo f; auto bar = std::string("bar"); f.setNonPODTypeByConstRef(bar); } BENCHMARK(NonPODParamPassing, TypeByConstRRefWithMove, MY_NUMBER_OF_SAMPLES, MY_NUMBER_OF_CALLS_PER_MEASUREMENT) { Foo f; auto bar = std::string("bar"); f.setNonPODTypeByConstRef(bar); } BENCHMARK(NonPODParamPassing, TypeByMoveConstRRefWithMove, MY_NUMBER_OF_SAMPLES, MY_NUMBER_OF_CALLS_PER_MEASUREMENT) { Foo f; auto bar = std::string("bar"); f.setNonPODTypeByConstRef(std::move(bar)); } // --------------------------------------------------------------------------------------- // Repeat some of the tests above, but use the varible after the use in the "set" function // --------------------------------------------------------------------------------------- BASELINE(NonPODParamPassingUseAfter, Baseline, MY_NUMBER_OF_SAMPLES, MY_NUMBER_OF_CALLS_PER_MEASUREMENT) { // While we are not measuring the time to construct a "Foo" or create "bar", since // we do this in each of the tests, the time is exactly the same and does not // change the baseline measurement. (The only difference in each of these cases // is the part we wish to measure.) Foo f; auto bar = std::string("bar"); f.nonPodType = bar; bar += "food"; celero::DoNotOptimizeAway(&bar); } BENCHMARK(NonPODParamPassingUseAfter, TypeByValue, MY_NUMBER_OF_SAMPLES, MY_NUMBER_OF_CALLS_PER_MEASUREMENT) { Foo f; auto bar = std::string("bar"); f.setNonPODTypeByValue(bar); bar += "food"; celero::DoNotOptimizeAway(&bar); } BENCHMARK(NonPODParamPassingUseAfter, TypeByValueWithMove, MY_NUMBER_OF_SAMPLES, MY_NUMBER_OF_CALLS_PER_MEASUREMENT) { Foo f; auto bar = std::string("bar"); f.setNonPODTypeByValue(bar); bar += "food"; celero::DoNotOptimizeAway(&bar); } BENCHMARK(NonPODParamPassingUseAfter, TypeByConstRef, MY_NUMBER_OF_SAMPLES, MY_NUMBER_OF_CALLS_PER_MEASUREMENT) { Foo f; auto bar = std::string("bar"); f.setNonPODTypeByConstRef(bar); bar += "food"; celero::DoNotOptimizeAway(&bar); } BENCHMARK(NonPODParamPassingUseAfter, TypeByConstRRef, MY_NUMBER_OF_SAMPLES, MY_NUMBER_OF_CALLS_PER_MEASUREMENT) { Foo f; auto bar = std::string("bar"); f.setNonPODTypeByConstRef(bar); bar += "food"; celero::DoNotOptimizeAway(&bar); } BENCHMARK(NonPODParamPassingUseAfter, TypeByConstRRefWithMove, MY_NUMBER_OF_SAMPLES, MY_NUMBER_OF_CALLS_PER_MEASUREMENT) { Foo f; auto bar = std::string("bar"); f.setNonPODTypeByConstRef(bar); bar += "food"; celero::DoNotOptimizeAway(&bar); } // -------------------------------------------------- // Now repeat all of the tests above with a POD type. // -------------------------------------------------- BASELINE(PODParamPassing, Baseline, MY_NUMBER_OF_SAMPLES, MY_NUMBER_OF_CALLS_PER_MEASUREMENT) { // While we are not measuring the time to construct a "Foo" or create "bar", since // we do this in each of the tests, the time is exactly the same and does not // change the baseline measurement. (The only difference in each of these cases // is the part we wish to measure.) Foo f; auto bar = uint64_t(2716057); f.podType = bar; } BENCHMARK(PODParamPassing, TypeMoveCopy, MY_NUMBER_OF_SAMPLES, MY_NUMBER_OF_CALLS_PER_MEASUREMENT) { Foo f; auto bar = uint64_t(2716057); f.podType = std::move(bar); } BENCHMARK(PODParamPassing, TypeByValue, MY_NUMBER_OF_SAMPLES, MY_NUMBER_OF_CALLS_PER_MEASUREMENT) { Foo f; auto bar = uint64_t(2716057); f.setPODTypeByValue(bar); } BENCHMARK(PODParamPassing, TypeByMovedValue, MY_NUMBER_OF_SAMPLES, MY_NUMBER_OF_CALLS_PER_MEASUREMENT) { Foo f; auto bar = uint64_t(2716057); f.setPODTypeByValue(std::move(bar)); } BENCHMARK(PODParamPassing, TypeByValueWithMove, MY_NUMBER_OF_SAMPLES, MY_NUMBER_OF_CALLS_PER_MEASUREMENT) { Foo f; auto bar = uint64_t(2716057); f.setPODTypeByValue(bar); } BENCHMARK(PODParamPassing, TypeByMoveValueWithMove, MY_NUMBER_OF_SAMPLES, MY_NUMBER_OF_CALLS_PER_MEASUREMENT) { Foo f; auto bar = uint64_t(2716057); f.setPODTypeByValue(std::move(bar)); } BENCHMARK(PODParamPassing, TypeByConstRef, MY_NUMBER_OF_SAMPLES, MY_NUMBER_OF_CALLS_PER_MEASUREMENT) { Foo f; auto bar = uint64_t(2716057); f.setPODTypeByConstRef(bar); } BENCHMARK(PODParamPassing, TypeByConstRRef, MY_NUMBER_OF_SAMPLES, MY_NUMBER_OF_CALLS_PER_MEASUREMENT) { Foo f; auto bar = uint64_t(2716057); f.setPODTypeByConstRef(bar); } BENCHMARK(PODParamPassing, TypeByConstRRefWithMove, MY_NUMBER_OF_SAMPLES, MY_NUMBER_OF_CALLS_PER_MEASUREMENT) { Foo f; auto bar = uint64_t(2716057); f.setPODTypeByConstRef(bar); } BENCHMARK(PODParamPassing, TypeByMoveConstRRefWithMove, MY_NUMBER_OF_SAMPLES, MY_NUMBER_OF_CALLS_PER_MEASUREMENT) { Foo f; auto bar = uint64_t(2716057); f.setPODTypeByConstRef(std::move(bar)); } // --------------------------------------------------------------------------------------- // Repeat some of the tests above, but use the varible after the use in the "set" function // --------------------------------------------------------------------------------------- BASELINE(PODParamPassingUseAfter, Baseline, MY_NUMBER_OF_SAMPLES, MY_NUMBER_OF_CALLS_PER_MEASUREMENT) { // While we are not measuring the time to construct a "Foo" or create "bar", since // we do this in each of the tests, the time is exactly the same and does not // change the baseline measurement. (The only difference in each of these cases // is the part we wish to measure.) Foo f; auto bar = uint64_t(2716057); f.podType = bar; bar += uint64_t(3370318); celero::DoNotOptimizeAway(&bar); } BENCHMARK(PODParamPassingUseAfter, TypeByValue, MY_NUMBER_OF_SAMPLES, MY_NUMBER_OF_CALLS_PER_MEASUREMENT) { Foo f; auto bar = uint64_t(2716057); f.setPODTypeByValue(bar); bar += uint64_t(3370318); celero::DoNotOptimizeAway(&bar); } BENCHMARK(PODParamPassingUseAfter, TypeByValueWithMove, MY_NUMBER_OF_SAMPLES, MY_NUMBER_OF_CALLS_PER_MEASUREMENT) { Foo f; auto bar = uint64_t(2716057); f.setPODTypeByValue(bar); bar += uint64_t(3370318); celero::DoNotOptimizeAway(&bar); } BENCHMARK(PODParamPassingUseAfter, TypeByConstRef, MY_NUMBER_OF_SAMPLES, MY_NUMBER_OF_CALLS_PER_MEASUREMENT) { Foo f; auto bar = uint64_t(2716057); f.setPODTypeByConstRef(bar); bar += uint64_t(3370318); celero::DoNotOptimizeAway(&bar); } BENCHMARK(PODParamPassingUseAfter, TypeByConstRRef, MY_NUMBER_OF_SAMPLES, MY_NUMBER_OF_CALLS_PER_MEASUREMENT) { Foo f; auto bar = uint64_t(2716057); f.setPODTypeByConstRef(bar); bar += uint64_t(3370318); celero::DoNotOptimizeAway(&bar); } BENCHMARK(PODParamPassingUseAfter, TypeByConstRRefWithMove, MY_NUMBER_OF_SAMPLES, MY_NUMBER_OF_CALLS_PER_MEASUREMENT) { Foo f; auto bar = uint64_t(2716057); f.setPODTypeByConstRef(bar); bar += uint64_t(3370318); celero::DoNotOptimizeAway(&bar); } <commit_msg>Fixed typos in parameter passing test case.<commit_after>#include <random> #include <celero/Celero.h> /// /// This demo was created to understand the cost with various falvors of "setters" where /// a function in a class or struct is provided solely to set the value of an internal member. /// There was some guidance being provided on the internet that if you intend to simply copy /// the value passed into the function, to incur the cost of the copy when passing the argument. /// Other guidance suggested to always pass non-pod types in by const ref. When in doubt, measure! /// /// http://stackoverflow.com/questions/18673658/should-i-always-move-on-sink-constructor-or-setter-arguments /// /// /// This is the main(int argc, char** argv) for the entire celero program. /// You can write your own, or use this macro to insert the standard one into the project. /// CELERO_MAIN; struct Foo { Foo() : nonPodType() { } void setNonPODTypeByValue(std::string x) { this->nonPodType = x; } void setNonPODTypeByValueWithMove(std::string x) { this->nonPodType = std::move(x); } void setNonPODTypeByConstRef(const std::string& x) { this->nonPodType = x; } void setNonPODTypeByConstRefWithMove(const std::string& x) { this->nonPodType = std::move(x); } void setNonPODTypeByConstRRef(const std::string&& x) { this->nonPodType = x; } void setNonPODTypeByConstRRefWithMove(const std::string&& x) { this->nonPodType = std::move(x); } void setPODTypeByValue(uint64_t x) { this->podType = x; } void setPODTypeByValueWithMove(uint64_t x) { this->podType = std::move(x); } void setPODTypeByConstRef(const uint64_t& x) { this->podType = x; } void setPODTypeByConstRefWithMove(const uint64_t& x) { this->podType = std::move(x); } void setPODTypeByConstRRef(const uint64_t&& x) { this->podType = x; } void setPODTypeByConstRRefWithMove(const uint64_t&& x) { this->podType = std::move(x); } std::string nonPodType; uint64_t podType; }; #define MY_NUMBER_OF_CALLS_PER_MEASUREMENT 3000000 #define MY_NUMBER_OF_SAMPLES 100 BASELINE(NonPODParamPassing, Baseline, MY_NUMBER_OF_SAMPLES, MY_NUMBER_OF_CALLS_PER_MEASUREMENT) { // While we are not measuring the time to construct a "Foo" or create "bar", since // we do this in each of the tests, the time is exactly the same and does not // change the baseline measurement. (The only difference in each of these cases // is the part we wish to measure.) Foo f; auto bar = std::string("bar"); f.nonPodType = bar; } BENCHMARK(NonPODParamPassing, TypeMoveCopy, MY_NUMBER_OF_SAMPLES, MY_NUMBER_OF_CALLS_PER_MEASUREMENT) { Foo f; auto bar = std::string("bar"); f.nonPodType = std::move(bar); } BENCHMARK(NonPODParamPassing, TypeByValue, MY_NUMBER_OF_SAMPLES, MY_NUMBER_OF_CALLS_PER_MEASUREMENT) { Foo f; auto bar = std::string("bar"); f.setNonPODTypeByValue(bar); } BENCHMARK(NonPODParamPassing, TypeByMovedValue, MY_NUMBER_OF_SAMPLES, MY_NUMBER_OF_CALLS_PER_MEASUREMENT) { Foo f; auto bar = std::string("bar"); f.setNonPODTypeByValue(std::move(bar)); } BENCHMARK(NonPODParamPassing, TypeByValueWithMove, MY_NUMBER_OF_SAMPLES, MY_NUMBER_OF_CALLS_PER_MEASUREMENT) { Foo f; auto bar = std::string("bar"); f.setNonPODTypeByValueWithMove(bar); } BENCHMARK(NonPODParamPassing, TypeByMoveValueWithMove, MY_NUMBER_OF_SAMPLES, MY_NUMBER_OF_CALLS_PER_MEASUREMENT) { Foo f; auto bar = std::string("bar"); f.setNonPODTypeByValueWithMove(std::move(bar)); } BENCHMARK(NonPODParamPassing, TypeByConstRef, MY_NUMBER_OF_SAMPLES, MY_NUMBER_OF_CALLS_PER_MEASUREMENT) { Foo f; auto bar = std::string("bar"); f.setNonPODTypeByConstRef(bar); } BENCHMARK(NonPODParamPassing, TypeByConstRRef, MY_NUMBER_OF_SAMPLES, MY_NUMBER_OF_CALLS_PER_MEASUREMENT) { Foo f; f.setNonPODTypeByConstRRef(std::string("bar")); } BENCHMARK(NonPODParamPassing, TypeByConstRRefWithMove, MY_NUMBER_OF_SAMPLES, MY_NUMBER_OF_CALLS_PER_MEASUREMENT) { Foo f; f.setNonPODTypeByConstRRefWithMove(std::string("bar")); } BENCHMARK(NonPODParamPassing, TypeByMoveConstRRefWithMove, MY_NUMBER_OF_SAMPLES, MY_NUMBER_OF_CALLS_PER_MEASUREMENT) { Foo f; f.setNonPODTypeByConstRRefWithMove(std::move(std::string("bar"))); } // --------------------------------------------------------------------------------------- // Repeat some of the tests above, but use the varible after the use in the "set" function // --------------------------------------------------------------------------------------- BASELINE(NonPODParamPassingUseAfter, Baseline, MY_NUMBER_OF_SAMPLES, MY_NUMBER_OF_CALLS_PER_MEASUREMENT) { // While we are not measuring the time to construct a "Foo" or create "bar", since // we do this in each of the tests, the time is exactly the same and does not // change the baseline measurement. (The only difference in each of these cases // is the part we wish to measure.) Foo f; auto bar = std::string("bar"); f.nonPodType = bar; bar += "food"; celero::DoNotOptimizeAway(&bar); } BENCHMARK(NonPODParamPassingUseAfter, TypeByValue, MY_NUMBER_OF_SAMPLES, MY_NUMBER_OF_CALLS_PER_MEASUREMENT) { Foo f; auto bar = std::string("bar"); f.setNonPODTypeByValue(bar); bar += "food"; celero::DoNotOptimizeAway(&bar); } BENCHMARK(NonPODParamPassingUseAfter, TypeByValueWithMove, MY_NUMBER_OF_SAMPLES, MY_NUMBER_OF_CALLS_PER_MEASUREMENT) { Foo f; auto bar = std::string("bar"); f.setNonPODTypeByValueWithMove(bar); bar += "food"; celero::DoNotOptimizeAway(&bar); } BENCHMARK(NonPODParamPassingUseAfter, TypeByConstRef, MY_NUMBER_OF_SAMPLES, MY_NUMBER_OF_CALLS_PER_MEASUREMENT) { Foo f; auto bar = std::string("bar"); f.setNonPODTypeByConstRef(bar); bar += "food"; celero::DoNotOptimizeAway(&bar); } BENCHMARK(NonPODParamPassingUseAfter, TypeByConstRefWithMove, MY_NUMBER_OF_SAMPLES, MY_NUMBER_OF_CALLS_PER_MEASUREMENT) { Foo f; auto bar = std::string("bar"); f.setNonPODTypeByConstRefWithMove(bar); bar += "food"; celero::DoNotOptimizeAway(&bar); } // -------------------------------------------------- // Now repeat all of the tests above with a POD type. // -------------------------------------------------- BASELINE(PODParamPassing, Baseline, MY_NUMBER_OF_SAMPLES, MY_NUMBER_OF_CALLS_PER_MEASUREMENT) { // While we are not measuring the time to construct a "Foo" or create "bar", since // we do this in each of the tests, the time is exactly the same and does not // change the baseline measurement. (The only difference in each of these cases // is the part we wish to measure.) Foo f; auto bar = uint64_t(2716057); f.podType = bar; } BENCHMARK(PODParamPassing, TypeMoveCopy, MY_NUMBER_OF_SAMPLES, MY_NUMBER_OF_CALLS_PER_MEASUREMENT) { Foo f; auto bar = uint64_t(2716057); f.podType = std::move(bar); } BENCHMARK(PODParamPassing, TypeByValue, MY_NUMBER_OF_SAMPLES, MY_NUMBER_OF_CALLS_PER_MEASUREMENT) { Foo f; auto bar = uint64_t(2716057); f.setPODTypeByValue(bar); } BENCHMARK(PODParamPassing, TypeByMovedValue, MY_NUMBER_OF_SAMPLES, MY_NUMBER_OF_CALLS_PER_MEASUREMENT) { Foo f; auto bar = uint64_t(2716057); f.setPODTypeByValue(std::move(bar)); } BENCHMARK(PODParamPassing, TypeByValueWithMove, MY_NUMBER_OF_SAMPLES, MY_NUMBER_OF_CALLS_PER_MEASUREMENT) { Foo f; auto bar = uint64_t(2716057); f.setPODTypeByValueWithMove(bar); } BENCHMARK(PODParamPassing, TypeByMoveValueWithMove, MY_NUMBER_OF_SAMPLES, MY_NUMBER_OF_CALLS_PER_MEASUREMENT) { Foo f; auto bar = uint64_t(2716057); f.setPODTypeByValueWithMove(std::move(bar)); } BENCHMARK(PODParamPassing, TypeByConstRef, MY_NUMBER_OF_SAMPLES, MY_NUMBER_OF_CALLS_PER_MEASUREMENT) { Foo f; auto bar = uint64_t(2716057); f.setPODTypeByConstRef(bar); } BENCHMARK(PODParamPassing, TypeByConstRRef, MY_NUMBER_OF_SAMPLES, MY_NUMBER_OF_CALLS_PER_MEASUREMENT) { Foo f; f.setPODTypeByConstRRef(uint64_t(2716057)); } BENCHMARK(PODParamPassing, TypeByMoveConstRRef, MY_NUMBER_OF_SAMPLES, MY_NUMBER_OF_CALLS_PER_MEASUREMENT) { Foo f; f.setPODTypeByConstRRef(std::move(uint64_t(2716057))); } BENCHMARK(PODParamPassing, TypeByConstRRefWithMove, MY_NUMBER_OF_SAMPLES, MY_NUMBER_OF_CALLS_PER_MEASUREMENT) { Foo f; f.setPODTypeByConstRRefWithMove(uint64_t(2716057)); } BENCHMARK(PODParamPassing, TypeByMoveConstRRefWithMove, MY_NUMBER_OF_SAMPLES, MY_NUMBER_OF_CALLS_PER_MEASUREMENT) { Foo f; f.setPODTypeByConstRRefWithMove(std::move(uint64_t(2716057))); } // --------------------------------------------------------------------------------------- // Repeat some of the tests above, but use the varible after the use in the "set" function // --------------------------------------------------------------------------------------- BASELINE(PODParamPassingUseAfter, Baseline, MY_NUMBER_OF_SAMPLES, MY_NUMBER_OF_CALLS_PER_MEASUREMENT) { // While we are not measuring the time to construct a "Foo" or create "bar", since // we do this in each of the tests, the time is exactly the same and does not // change the baseline measurement. (The only difference in each of these cases // is the part we wish to measure.) Foo f; auto bar = uint64_t(2716057); f.podType = bar; bar += uint64_t(3370318); celero::DoNotOptimizeAway(&bar); } BENCHMARK(PODParamPassingUseAfter, TypeByValue, MY_NUMBER_OF_SAMPLES, MY_NUMBER_OF_CALLS_PER_MEASUREMENT) { Foo f; auto bar = uint64_t(2716057); f.setPODTypeByValue(bar); bar += uint64_t(3370318); celero::DoNotOptimizeAway(&bar); } BENCHMARK(PODParamPassingUseAfter, TypeByValueWithMove, MY_NUMBER_OF_SAMPLES, MY_NUMBER_OF_CALLS_PER_MEASUREMENT) { Foo f; auto bar = uint64_t(2716057); f.setPODTypeByValueWithMove(bar); bar += uint64_t(3370318); celero::DoNotOptimizeAway(&bar); } BENCHMARK(PODParamPassingUseAfter, TypeByMoveValueWithMove, MY_NUMBER_OF_SAMPLES, MY_NUMBER_OF_CALLS_PER_MEASUREMENT) { Foo f; auto bar = uint64_t(2716057); f.setPODTypeByValueWithMove(std::move(bar)); bar += uint64_t(3370318); celero::DoNotOptimizeAway(&bar); } BENCHMARK(PODParamPassingUseAfter, TypeByConstRef, MY_NUMBER_OF_SAMPLES, MY_NUMBER_OF_CALLS_PER_MEASUREMENT) { Foo f; auto bar = uint64_t(2716057); f.setPODTypeByConstRef(bar); bar += uint64_t(3370318); celero::DoNotOptimizeAway(&bar); } BENCHMARK(PODParamPassingUseAfter, TypeByMoveConstRef, MY_NUMBER_OF_SAMPLES, MY_NUMBER_OF_CALLS_PER_MEASUREMENT) { Foo f; auto bar = uint64_t(2716057); f.setPODTypeByConstRef(std::move(bar)); bar += uint64_t(3370318); celero::DoNotOptimizeAway(&bar); } BENCHMARK(PODParamPassingUseAfter, TypeByConstRefWithMove, MY_NUMBER_OF_SAMPLES, MY_NUMBER_OF_CALLS_PER_MEASUREMENT) { Foo f; auto bar = uint64_t(2716057); f.setPODTypeByConstRefWithMove(bar); bar += uint64_t(3370318); celero::DoNotOptimizeAway(&bar); } BENCHMARK(PODParamPassingUseAfter, TypeByMoveConstRefWithMove, MY_NUMBER_OF_SAMPLES, MY_NUMBER_OF_CALLS_PER_MEASUREMENT) { Foo f; auto bar = uint64_t(2716057); f.setPODTypeByConstRefWithMove(std::move(bar)); bar += uint64_t(3370318); celero::DoNotOptimizeAway(&bar); } <|endoftext|>
<commit_before>/*------------------------------------------------------------------------------ Copyright (c) 2004 Media Development Loan Fund This file is part of the LiveSupport project. http://livesupport.campware.org/ To report bugs, send an e-mail to bugs@campware.org LiveSupport 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. LiveSupport 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 LiveSupport; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Author : $Author: maroy $ Version : $Revision: 1.1 $ Location : $Source: /home/paul/cvs2svn-livesupport/newcvsrepo/livesupport/modules/schedulerClient/src/SchedulerClientFactory.cxx,v $ ------------------------------------------------------------------------------*/ /* ============================================================ include files */ #ifdef HAVE_CONFIG_H #include "configure.h" #endif #include "LiveSupport/SchedulerClient/SchedulerClientFactory.h" #include "SchedulerDaemonXmlRpcClient.h" using namespace LiveSupport::Core; using namespace LiveSupport::SchedulerClient; /* =================================================== local data structures */ /* ================================================ local constants & macros */ /*------------------------------------------------------------------------------ * The name of the config element for this class *----------------------------------------------------------------------------*/ const std::string SchedulerClientFactory::configElementNameStr = "schedulerClientFactory"; /*------------------------------------------------------------------------------ * The singleton instance of SchedulerClientFactory *----------------------------------------------------------------------------*/ Ptr<SchedulerClientFactory>::Ref SchedulerClientFactory::singleton; /* =============================================== local function prototypes */ /* ============================================================= module code */ /*------------------------------------------------------------------------------ * Return the singleton instance to SchedulerClientFactory *----------------------------------------------------------------------------*/ Ptr<SchedulerClientFactory>::Ref SchedulerClientFactory :: getInstance(void) throw () { if (!singleton.get()) { singleton.reset(new SchedulerClientFactory()); } return singleton; } /*------------------------------------------------------------------------------ * Configure the test authentication client. *----------------------------------------------------------------------------*/ void SchedulerClientFactory :: configure(const xmlpp::Element & element) throw (std::invalid_argument, std::logic_error) { if (element.get_name() != configElementNameStr) { std::string eMsg = "Bad configuration element "; eMsg += element.get_name(); throw std::invalid_argument(eMsg); } schedulerClient.reset(); // try to look for a SchedulerDaemonXmlRpcClient configuration element xmlpp::Node::NodeList nodes = element.get_children( SchedulerDaemonXmlRpcClient::getConfigElementName()); if (nodes.size() >= 1) { const xmlpp::Element * configElement = dynamic_cast<const xmlpp::Element*> (*(nodes.begin())); Ptr<SchedulerDaemonXmlRpcClient>::Ref client; client.reset(new SchedulerDaemonXmlRpcClient()); client->configure(*configElement); schedulerClient = client; return; } throw std::invalid_argument("no authentication client configuration found"); } <commit_msg>fixed small typo<commit_after>/*------------------------------------------------------------------------------ Copyright (c) 2004 Media Development Loan Fund This file is part of the LiveSupport project. http://livesupport.campware.org/ To report bugs, send an e-mail to bugs@campware.org LiveSupport 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. LiveSupport 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 LiveSupport; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Author : $Author: maroy $ Version : $Revision: 1.2 $ Location : $Source: /home/paul/cvs2svn-livesupport/newcvsrepo/livesupport/modules/schedulerClient/src/SchedulerClientFactory.cxx,v $ ------------------------------------------------------------------------------*/ /* ============================================================ include files */ #ifdef HAVE_CONFIG_H #include "configure.h" #endif #include "LiveSupport/SchedulerClient/SchedulerClientFactory.h" #include "SchedulerDaemonXmlRpcClient.h" using namespace LiveSupport::Core; using namespace LiveSupport::SchedulerClient; /* =================================================== local data structures */ /* ================================================ local constants & macros */ /*------------------------------------------------------------------------------ * The name of the config element for this class *----------------------------------------------------------------------------*/ const std::string SchedulerClientFactory::configElementNameStr = "schedulerClientFactory"; /*------------------------------------------------------------------------------ * The singleton instance of SchedulerClientFactory *----------------------------------------------------------------------------*/ Ptr<SchedulerClientFactory>::Ref SchedulerClientFactory::singleton; /* =============================================== local function prototypes */ /* ============================================================= module code */ /*------------------------------------------------------------------------------ * Return the singleton instance to SchedulerClientFactory *----------------------------------------------------------------------------*/ Ptr<SchedulerClientFactory>::Ref SchedulerClientFactory :: getInstance(void) throw () { if (!singleton.get()) { singleton.reset(new SchedulerClientFactory()); } return singleton; } /*------------------------------------------------------------------------------ * Configure the test authentication client. *----------------------------------------------------------------------------*/ void SchedulerClientFactory :: configure(const xmlpp::Element & element) throw (std::invalid_argument, std::logic_error) { if (element.get_name() != configElementNameStr) { std::string eMsg = "Bad configuration element "; eMsg += element.get_name(); throw std::invalid_argument(eMsg); } schedulerClient.reset(); // try to look for a SchedulerDaemonXmlRpcClient configuration element xmlpp::Node::NodeList nodes = element.get_children( SchedulerDaemonXmlRpcClient::getConfigElementName()); if (nodes.size() >= 1) { const xmlpp::Element * configElement = dynamic_cast<const xmlpp::Element*> (*(nodes.begin())); Ptr<SchedulerDaemonXmlRpcClient>::Ref client; client.reset(new SchedulerDaemonXmlRpcClient()); client->configure(*configElement); schedulerClient = client; return; } throw std::invalid_argument("no scheduler client configuration found"); } <|endoftext|>
<commit_before>// ========================================================================== // // This file is part of Sara, a basic set of libraries in C++ for computer // vision. // // Copyright (C) 2019 David Ok <david.ok8@gmail.com> // // This Source Code Form is subject to the terms of the Mozilla Public // License v. 2.0. If a copy of the MPL was not distributed with this file, // you can obtain one at http://mozilla.org/MPL/2.0/. // ========================================================================== // #pragma once #include <DO/Sara/Core/Tensor.hpp> #include <DO/Sara/MultiViewGeometry/FeatureGraph.hpp> #include <vector> namespace DO::Sara { /*! * @ingroup MultiViewGeometry * @{ */ //! @brief Camera model view class. template <typename T> struct CameraModelView { auto angle_axis() const -> const T* { return parameters; } auto t() const -> const T* { return parameters + 3; } auto fx() const -> const T& { return parameters[6]; } auto fy() const -> const T& { return parameters[7]; } auto x0() const -> const T& { return parameters[8]; } auto y0() const -> const T& { return parameters[9]; } auto l1() const -> const T& { return parameters[10]; } auto l2() const -> const T& { return parameters[11]; } static auto dof() { return 12; }; const T* parameters; }; //! @brief Observation reference class. struct ObservationRef { FeatureGID gid; int camera_id; int point_id; }; //! @brief Bundle adjustment class. struct BundleAdjustmentProblem { //! @brief observation = 2D points in images. Tensor_<double, 2> observations; //! @brief the corresponding 3D point index for observation 'o' std::vector<int> point_indices; //! @brief the corresponding 3D camera index for observation 'o' std::vector<int> camera_indices; //! @{ //! @brief camera parameters + 3D point coordinates. int num_cameras; int num_points; int camera_dof; std::vector<double> parameters; TensorView_<double, 2> points_abs_coords_3d; TensorView_<double, 2> camera_parameters; //! @} auto resize(int num_observations, // int num_points_, int num_cameras_, int camera_dof_) { SARA_DEBUG << "Resizing data..." << std::endl; observations = Tensor_<double, 2>{{num_observations, 2}}; point_indices = std::vector<int>(num_observations); camera_indices = std::vector<int>(num_observations); num_points = num_points_; num_cameras = num_cameras_; camera_dof = camera_dof_; const auto num_parameters = num_cameras * camera_dof + num_points * 3; parameters = std::vector<double>(num_parameters); auto points_abs_coords_3d_new = TensorView_<double, 2>{ parameters.data() + camera_dof * num_cameras, {num_points, 3}}; auto camera_parameters_new = TensorView_<double, 2>{parameters.data(), {num_cameras, camera_dof}}; points_abs_coords_3d.swap(points_abs_coords_3d_new); camera_parameters.swap(camera_parameters_new); } auto populate_observations( const std::vector<ObservationRef>& obs_refs, const std::vector<KeypointList<OERegion, float>>& keypoints) -> void { SARA_DEBUG << "Populating observations..." << std::endl; const auto num_observations = observations.size(0); for (int i = 0; i < num_observations; ++i) { const auto& ref = obs_refs[i]; // Easy things first. point_indices[i] = ref.point_id; camera_indices[i] = ref.camera_id; // Initialize the 2D observations. const auto& image_id = ref.gid.image_id; const auto& local_id = ref.gid.local_id; const double x = features(keypoints[image_id])[local_id].x(); const double y = features(keypoints[image_id])[local_id].y(); observations(i, 0) = x; observations(i, 1) = y; } } auto populate_3d_points_from_two_view_geometry( const std::set<std::set<FeatureGID>>& feature_tracks, const std::multimap<FeatureGID, MatchGID>& match_index, const TwoViewGeometry& two_view_geometry) -> void { SARA_DEBUG << "Populating 3D points..." << std::endl; auto points_view = points_abs_coords_3d.colmajor_view().matrix(); for (auto [t, track] = std::make_pair(0, feature_tracks.begin()); track != feature_tracks.end(); ++t, ++track) { const auto p = match_index.find(*track->begin())->second.m; const auto point_p = two_view_geometry.X.col(p); points_view.col(t) = point_p.hnormalized(); #if DEBUG SARA_DEBUG << "Point[" << t << "] = " // << points_view.col(t).transpose() << std::endl; #endif } } auto populate_camera_parameters(const TwoViewGeometry& two_view_geometry) -> void { SARA_DEBUG << "Populating camera parameters..." << std::endl; auto cam_matrix = camera_parameters.matrix(); // Angle axis vector. auto cam_0 = cam_matrix.row(0); auto angle_axis_0 = Eigen::AngleAxisd{two_view_geometry.C1.R}; auto aaxis0 = angle_axis_0.angle() * angle_axis_0.axis(); cam_0.segment(0, 3) = aaxis0.transpose(); // translation. const auto& t0 = two_view_geometry.C1.t; cam_0.segment(3, 3) = t0; // Internal parameters. SARA_DEBUG << "K1 =\n" << two_view_geometry.C1.K << std::endl; cam_0(6) = two_view_geometry.C1.K(0, 0); // fx cam_0(7) = two_view_geometry.C1.K(1, 1); // fy cam_0(8) = two_view_geometry.C1.K(0, 2); // x0 cam_0(9) = two_view_geometry.C1.K(1, 2); // y0 cam_0(10) = 1.0; // l1 cam_0(11) = 1.0; // l2 // Angle axis vector. auto cam_1 = cam_matrix.row(1); auto angle_axis_1 = Eigen::AngleAxisd{two_view_geometry.C2.R}; auto aaxis1 = angle_axis_1.angle() * angle_axis_1.axis(); cam_1.segment(0, 3) = aaxis1.transpose(); // translation. const auto& t1 = two_view_geometry.C2.t; cam_1.segment(3, 3) = t1; // Internal parameters. SARA_DEBUG << "K2 =\n" << two_view_geometry.C2.K << std::endl; cam_1(6) = two_view_geometry.C2.K(0, 0); // fx cam_1(7) = two_view_geometry.C2.K(1, 1); // fy cam_1(8) = two_view_geometry.C2.K(0, 2); // x0 cam_1(9) = two_view_geometry.C2.K(1, 2); // y0 cam_1(10) = 1.0; // l1 cam_1(11) = 1.0; // l2 SARA_DEBUG << "cam_matrix =\n" << cam_matrix << std::endl; } auto populate_data_from_two_view_geometry( const std::set<std::set<FeatureGID>>& feature_tracks, const std::vector<KeypointList<OERegion, float>>& keypoints, const std::multimap<FeatureGID, MatchGID>& match_index, const TwoViewGeometry& two_view_geometry) -> void { const auto num_points = static_cast<int>(feature_tracks.size()); SARA_CHECK(num_points); auto num_observations_per_points = std::vector<int>(num_points); std::transform( std::begin(feature_tracks), std::end(feature_tracks), std::begin(num_observations_per_points), [](const auto& track) { return static_cast<int>(track.size()); }); const auto num_observations = std::accumulate(std::begin(num_observations_per_points), std::end(num_observations_per_points), 0); SARA_CHECK(num_observations); // 3. Count the number of cameras, which should be equal to the number of // images. auto image_ids = std::set<int>{}; for (const auto& track : feature_tracks) for (const auto& f : track) image_ids.insert(f.image_id); const auto num_cameras = static_cast<int>(image_ids.size()); SARA_CHECK(num_cameras); const auto camera_dof_ = CameraModelView<double>::dof(); const auto num_parameters = camera_dof_ * num_cameras + 3 * num_points; SARA_CHECK(num_parameters); // 4. Transform the data for convenience. auto obs_refs = std::vector<ObservationRef>{}; { obs_refs.reserve(num_observations); for (auto [point_id, track] = std::make_pair(0, feature_tracks.begin()); track != feature_tracks.end(); ++point_id, ++track) { for (const auto& f : *track) obs_refs.push_back({f, f.image_id, point_id}); } } resize(num_observations, num_points, num_cameras, camera_dof_); populate_observations(obs_refs, keypoints); populate_3d_points_from_two_view_geometry(feature_tracks, match_index, two_view_geometry); populate_camera_parameters(two_view_geometry); } }; //! @} } /* namespace DO::Sara */ <commit_msg>MAINT: fix documentation.<commit_after>// ========================================================================== // // This file is part of Sara, a basic set of libraries in C++ for computer // vision. // // Copyright (C) 2019 David Ok <david.ok8@gmail.com> // // This Source Code Form is subject to the terms of the Mozilla Public // License v. 2.0. If a copy of the MPL was not distributed with this file, // you can obtain one at http://mozilla.org/MPL/2.0/. // ========================================================================== // #pragma once #include <DO/Sara/Core/Tensor.hpp> #include <DO/Sara/MultiViewGeometry/FeatureGraph.hpp> #include <vector> namespace DO::Sara { /*! * @addtogroup MultiViewGeometry * @{ */ //! @brief Camera model view class. template <typename T> struct CameraModelView { auto angle_axis() const -> const T* { return parameters; } auto t() const -> const T* { return parameters + 3; } auto fx() const -> const T& { return parameters[6]; } auto fy() const -> const T& { return parameters[7]; } auto x0() const -> const T& { return parameters[8]; } auto y0() const -> const T& { return parameters[9]; } auto l1() const -> const T& { return parameters[10]; } auto l2() const -> const T& { return parameters[11]; } static auto dof() { return 12; }; const T* parameters; }; //! @brief Observation reference class. struct ObservationRef { FeatureGID gid; int camera_id; int point_id; }; //! @brief Bundle adjustment class. struct BundleAdjustmentProblem { //! @brief observation = 2D points in images. Tensor_<double, 2> observations; //! @brief the corresponding 3D point index for observation 'o' std::vector<int> point_indices; //! @brief the corresponding 3D camera index for observation 'o' std::vector<int> camera_indices; //! @{ //! @brief camera parameters + 3D point coordinates. int num_cameras; int num_points; int camera_dof; std::vector<double> parameters; TensorView_<double, 2> points_abs_coords_3d; TensorView_<double, 2> camera_parameters; //! @} auto resize(int num_observations, // int num_points_, int num_cameras_, int camera_dof_) { SARA_DEBUG << "Resizing data..." << std::endl; observations = Tensor_<double, 2>{{num_observations, 2}}; point_indices = std::vector<int>(num_observations); camera_indices = std::vector<int>(num_observations); num_points = num_points_; num_cameras = num_cameras_; camera_dof = camera_dof_; const auto num_parameters = num_cameras * camera_dof + num_points * 3; parameters = std::vector<double>(num_parameters); auto points_abs_coords_3d_new = TensorView_<double, 2>{ parameters.data() + camera_dof * num_cameras, {num_points, 3}}; auto camera_parameters_new = TensorView_<double, 2>{parameters.data(), {num_cameras, camera_dof}}; points_abs_coords_3d.swap(points_abs_coords_3d_new); camera_parameters.swap(camera_parameters_new); } auto populate_observations( const std::vector<ObservationRef>& obs_refs, const std::vector<KeypointList<OERegion, float>>& keypoints) -> void { SARA_DEBUG << "Populating observations..." << std::endl; const auto num_observations = observations.size(0); for (int i = 0; i < num_observations; ++i) { const auto& ref = obs_refs[i]; // Easy things first. point_indices[i] = ref.point_id; camera_indices[i] = ref.camera_id; // Initialize the 2D observations. const auto& image_id = ref.gid.image_id; const auto& local_id = ref.gid.local_id; const double x = features(keypoints[image_id])[local_id].x(); const double y = features(keypoints[image_id])[local_id].y(); observations(i, 0) = x; observations(i, 1) = y; } } auto populate_3d_points_from_two_view_geometry( const std::set<std::set<FeatureGID>>& feature_tracks, const std::multimap<FeatureGID, MatchGID>& match_index, const TwoViewGeometry& two_view_geometry) -> void { SARA_DEBUG << "Populating 3D points..." << std::endl; auto points_view = points_abs_coords_3d.colmajor_view().matrix(); for (auto [t, track] = std::make_pair(0, feature_tracks.begin()); track != feature_tracks.end(); ++t, ++track) { const auto p = match_index.find(*track->begin())->second.m; const auto point_p = two_view_geometry.X.col(p); points_view.col(t) = point_p.hnormalized(); #if DEBUG SARA_DEBUG << "Point[" << t << "] = " // << points_view.col(t).transpose() << std::endl; #endif } } auto populate_camera_parameters(const TwoViewGeometry& two_view_geometry) -> void { SARA_DEBUG << "Populating camera parameters..." << std::endl; auto cam_matrix = camera_parameters.matrix(); // Angle axis vector. auto cam_0 = cam_matrix.row(0); auto angle_axis_0 = Eigen::AngleAxisd{two_view_geometry.C1.R}; auto aaxis0 = angle_axis_0.angle() * angle_axis_0.axis(); cam_0.segment(0, 3) = aaxis0.transpose(); // translation. const auto& t0 = two_view_geometry.C1.t; cam_0.segment(3, 3) = t0; // Internal parameters. SARA_DEBUG << "K1 =\n" << two_view_geometry.C1.K << std::endl; cam_0(6) = two_view_geometry.C1.K(0, 0); // fx cam_0(7) = two_view_geometry.C1.K(1, 1); // fy cam_0(8) = two_view_geometry.C1.K(0, 2); // x0 cam_0(9) = two_view_geometry.C1.K(1, 2); // y0 cam_0(10) = 1.0; // l1 cam_0(11) = 1.0; // l2 // Angle axis vector. auto cam_1 = cam_matrix.row(1); auto angle_axis_1 = Eigen::AngleAxisd{two_view_geometry.C2.R}; auto aaxis1 = angle_axis_1.angle() * angle_axis_1.axis(); cam_1.segment(0, 3) = aaxis1.transpose(); // translation. const auto& t1 = two_view_geometry.C2.t; cam_1.segment(3, 3) = t1; // Internal parameters. SARA_DEBUG << "K2 =\n" << two_view_geometry.C2.K << std::endl; cam_1(6) = two_view_geometry.C2.K(0, 0); // fx cam_1(7) = two_view_geometry.C2.K(1, 1); // fy cam_1(8) = two_view_geometry.C2.K(0, 2); // x0 cam_1(9) = two_view_geometry.C2.K(1, 2); // y0 cam_1(10) = 1.0; // l1 cam_1(11) = 1.0; // l2 SARA_DEBUG << "cam_matrix =\n" << cam_matrix << std::endl; } auto populate_data_from_two_view_geometry( const std::set<std::set<FeatureGID>>& feature_tracks, const std::vector<KeypointList<OERegion, float>>& keypoints, const std::multimap<FeatureGID, MatchGID>& match_index, const TwoViewGeometry& two_view_geometry) -> void { const auto num_points = static_cast<int>(feature_tracks.size()); SARA_CHECK(num_points); auto num_observations_per_points = std::vector<int>(num_points); std::transform( std::begin(feature_tracks), std::end(feature_tracks), std::begin(num_observations_per_points), [](const auto& track) { return static_cast<int>(track.size()); }); const auto num_observations = std::accumulate(std::begin(num_observations_per_points), std::end(num_observations_per_points), 0); SARA_CHECK(num_observations); // 3. Count the number of cameras, which should be equal to the number of // images. auto image_ids = std::set<int>{}; for (const auto& track : feature_tracks) for (const auto& f : track) image_ids.insert(f.image_id); const auto num_cameras = static_cast<int>(image_ids.size()); SARA_CHECK(num_cameras); const auto camera_dof_ = CameraModelView<double>::dof(); const auto num_parameters = camera_dof_ * num_cameras + 3 * num_points; SARA_CHECK(num_parameters); // 4. Transform the data for convenience. auto obs_refs = std::vector<ObservationRef>{}; { obs_refs.reserve(num_observations); for (auto [point_id, track] = std::make_pair(0, feature_tracks.begin()); track != feature_tracks.end(); ++point_id, ++track) { for (const auto& f : *track) obs_refs.push_back({f, f.image_id, point_id}); } } resize(num_observations, num_points, num_cameras, camera_dof_); populate_observations(obs_refs, keypoints); populate_3d_points_from_two_view_geometry(feature_tracks, match_index, two_view_geometry); populate_camera_parameters(two_view_geometry); } }; //! @} } /* namespace DO::Sara */ <|endoftext|>
<commit_before>/* * SessionProjectSharing.hpp * * Copyright (C) 2009-15 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #ifndef SESSION_PROJECTS_SHARING_HPP #define SESSION_PROJECTS_SHARING_HPP #define kProjectSharingSessionOption "enable-project-sharing" #define kProjectEntryExt ".proj" #define kProjectSharedDir "shared-projects" #define kProjectEntryDir "project_dir" #define kProjectEntryOwner "project_owner" #define kProjectEntrySharedWith "shared_with" namespace rstudio { namespace session { namespace projects { } // namespace projects } // namesapce session } // namespace rstudio #endif // SESSION_PROJECTS_SHARING_HPP <commit_msg>add project file constant to shared project header<commit_after>/* * SessionProjectSharing.hpp * * Copyright (C) 2009-15 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #ifndef SESSION_PROJECTS_SHARING_HPP #define SESSION_PROJECTS_SHARING_HPP #define kProjectSharingSessionOption "enable-project-sharing" #define kProjectEntryExt ".proj" #define kProjectSharedDir "shared-projects" #define kProjectEntryDir "project_dir" #define kProjectEntryFile "project_file" #define kProjectEntryOwner "project_owner" #define kProjectEntrySharedWith "shared_with" namespace rstudio { namespace session { namespace projects { } // namespace projects } // namesapce session } // namespace rstudio #endif // SESSION_PROJECTS_SHARING_HPP <|endoftext|>
<commit_before>#include "Parse.hpp" #include <iostream> #include <stdexcept> #include <cctype> namespace parse { namespace tree { void Abstraction::applyVisitor(TermVisitor& termVisitor) const { termVisitor.acceptTerm(*this); } void Application::applyVisitor(TermVisitor& termVisitor) const { termVisitor.acceptTerm(*this); } void Variable::applyVisitor(TermVisitor& termVisitor) const { termVisitor.acceptTerm(*this); } } // tree namespace { void skipWhitespace(std::istream& input) { char c = input.peek(); while (std::isspace(c)) { input.get(); c = input.peek(); } } std::string parseIdentifier(std::istream& input) { std::string ident; skipWhitespace(input); while (std::isalnum(input.peek())) { ident += input.get(); } return ident; } std::unique_ptr<tree::Abstraction> parseAbstraction(std::istream& input) { std::unique_ptr<tree::Abstraction> node(new tree::Abstraction); if (input.peek() != '^') { throw std::runtime_error("Parse error"); } input.get(); std::string argument; while ((argument = parseIdentifier(input)).size() > 0) { node->arguments.push_back(std::move(argument)); } if (node->arguments.size() == 0) { throw std::runtime_error("Parse error"); } skipWhitespace(input); if (input.peek() != '.') { throw std::runtime_error("Parse error"); } input.get(); node->body = parseTerm(input); return node; } } // anonymous std::unique_ptr<tree::Term> parseTerm(std::istream& input) { std::unique_ptr<tree::Term> node; skipWhitespace(input); if (input.peek() == '^') { node = parseAbstraction(input); } else if (input.peek() == '(') { node = parseTerm(input); skipWhitespace(input); if (input.peek() != ')') { throw std::runtime_error("Parse error"); } input.get(); } skipWhitespace(input); if (input.peek() != EOF) { std::unique_ptr<tree::Term> tempNode = std::move(node); std::unique_ptr<tree::Application> appNode = std::unique_ptr<tree::Application>(new tree::Application); appNode->terms.push_back(std::move(tempNode)); do { appNode->terms.push_back(parseTerm(input)); } while (input.peek () != EOF); node = std::move(appNode); } return node; } } // parse <commit_msg>Fix infinite recursion<commit_after>#include "Parse.hpp" #include <iostream> #include <stdexcept> #include <cctype> namespace parse { namespace tree { void Abstraction::applyVisitor(TermVisitor& termVisitor) const { termVisitor.acceptTerm(*this); } void Application::applyVisitor(TermVisitor& termVisitor) const { termVisitor.acceptTerm(*this); } void Variable::applyVisitor(TermVisitor& termVisitor) const { termVisitor.acceptTerm(*this); } } // tree namespace { void skipWhitespace(std::istream& input) { char c = input.peek(); while (std::isspace(c)) { input.get(); c = input.peek(); } } std::string parseIdentifier(std::istream& input) { std::string ident; skipWhitespace(input); while (std::isalnum(input.peek())) { ident += input.get(); } return ident; } std::unique_ptr<tree::Abstraction> parseAbstraction(std::istream& input) { std::unique_ptr<tree::Abstraction> node(new tree::Abstraction); if (input.peek() != '^') { throw std::runtime_error("Parse error"); } input.get(); std::string argument; while ((argument = parseIdentifier(input)).size() > 0) { node->arguments.push_back(std::move(argument)); } if (node->arguments.size() == 0) { throw std::runtime_error("Parse error"); } skipWhitespace(input); if (input.peek() != '.') { throw std::runtime_error("Parse error"); } input.get(); node->body = parseTerm(input); return node; } } // anonymous std::unique_ptr<tree::Term> parseTerm(std::istream& input) { std::unique_ptr<tree::Term> node; skipWhitespace(input); if (input.peek() == '^') { node = parseAbstraction(input); } else if (input.peek() == '(') { node = parseTerm(input); skipWhitespace(input); if (input.peek() != ')') { throw std::runtime_error("Parse error"); } input.get(); } else { std::string name = parseIdentifier(input); if (name.size() == 0) { throw std::runtime_error("Parse error"); } std::unique_ptr<tree::Variable> var(new tree::Variable); var->name = std::move(name); node = std::move(var); } skipWhitespace(input); if (input.peek() != EOF) { std::unique_ptr<tree::Term> tempNode = std::move(node); std::unique_ptr<tree::Application> appNode = std::unique_ptr<tree::Application>(new tree::Application); appNode->terms.push_back(std::move(tempNode)); do { appNode->terms.push_back(parseTerm(input)); } while (input.peek () != EOF); node = std::move(appNode); } return node; } } // parse <|endoftext|>
<commit_before>// // Originally written by BjÃrn Fahller (bjorn@fahller.se) // Modified by Jeff Bush // // No rights claimed. The sources are released to the public domain // // For license information, please refer to <http://unlicense.org> // #include <setjmp.h> #include <stdlib.h> #include <iostream> #include <ostream> #include <forward_list> #include <vector> #include <algorithm> namespace basic { struct stack_frame { jmp_buf buf; }; std::forward_list<stack_frame> stack; #define GOSUB \ if (!(setjmp((basic::stack.emplace_front(),basic::stack.front().buf)) \ && (basic::stack.pop_front(),true))) \ goto #define RETURN if (basic::stack.empty()) return 0; longjmp(basic::stack.front().buf, 1) template <typename T, typename U> struct separator { static char const *str() { return ""; } }; template <typename T> struct separator<T,T> { static char const *str() { return ","; } }; inline void type_mismatch() { std::cout << "Type mismatch error\n"; exit(1); } inline void array_out_of_bounds() { std::cout << "Array out of bounds error\n"; exit(1); } inline void dimension_error() { std::cout << "Array Dimension error\n"; exit(1); } inline void illegal_quantity_error() { std::cout << "Illegal quantity error\n"; exit(1); } class variant { public: variant() : isnum(true), numval(0) {} variant(double _numval) : isnum(true), numval(_numval) {} variant(int _numval) : isnum(true), numval(_numval) {} variant(const std::string _strval) : isnum(false), strval(_strval) {} variant(const char *_strval) : isnum(false), strval(_strval) {} double numeric() const { if (!isnum) type_mismatch(); return numval; } std::string string() const { if (isnum) type_mismatch(); return strval; } variant toString() const { if (isnum) return variant(std::to_string(numval)); else return *this; } variant toNum() const { if (!isnum) return variant(stod(strval)); else return *this; } variant &operator=(const variant &copyfrom) { isnum = copyfrom.isnum; numval = copyfrom.numval; strval = copyfrom.strval; return *this; } // Note that strings in BASIC are 1 based, so subtract 1 from the left // index variant midStr(const variant &left, const variant &right) const { if (isnum || !left.isnum || !right.isnum) type_mismatch(); return variant(strval.substr(int(left.numval) - 1, (int(right.numval) - int(left.numval) + 1))); } variant leftStr(const variant &count) const { if (isnum) type_mismatch(); return variant(strval.substr(0, int(count.numval))); } variant rightStr(const variant &count) const { if (isnum) type_mismatch(); return variant(strval.substr(strval.length() - int(count.numval) - 1, int(count.numval))); } variant strlen() const { if (isnum) type_mismatch(); return variant((int)strval.length()); } variant operator+(const variant op) const { if (isnum != op.isnum) type_mismatch(); if (isnum) return variant(numval + op.numval); else return variant(strval + op.strval); } variant operator-(const variant op) const { if (!isnum || !op.isnum) type_mismatch(); return variant(numval - op.numval); } variant operator*(const variant op) const { if (!isnum || !op.isnum) type_mismatch(); return variant(numval * op.numval); } variant operator/(const variant op) const { if (!isnum || !op.isnum) type_mismatch(); return variant(numval / op.numval); } bool operator>(const variant op) const { if (isnum != op.isnum) type_mismatch(); if (isnum) return numval > op.numval; else return strval > op.strval; } bool operator>=(const variant op) const { if (isnum != op.isnum) type_mismatch(); if (isnum) return numval >= op.numval; else return strval >= op.strval; } bool operator<(const variant op) const { if (isnum != op.isnum) type_mismatch(); if (isnum) return numval < op.numval; else return strval < op.strval; } bool operator<=(const variant op) const { if (isnum != op.isnum) type_mismatch(); if (isnum) return numval <= op.numval; else return strval <= op.strval; } bool operator!=(const variant op) const { if (isnum != op.isnum) type_mismatch(); if (isnum) return numval != op.numval; else return strval != op.strval; } bool operator==(const variant op) const { if (isnum != op.isnum) type_mismatch(); if (isnum) return numval == op.numval; else return strval == op.strval; } bool isnum; double numval; std::string strval; }; template <typename T> typename std::enable_if<std::is_constructible<variant, T>::value && !std::is_same<typename std::decay<T>::type, variant>::value, variant>::type operator+(T&& t, variant const& p) { return variant(std::forward<T>(t)) + p; } template <typename T> typename std::enable_if<std::is_constructible<variant, T>::value && !std::is_same<typename std::decay<T>::type, variant>::value, variant>::type operator-(T&& t, variant const& p) { return variant(std::forward<T>(t)) - p; } template <typename T> typename std::enable_if<std::is_constructible<variant, T>::value && !std::is_same<typename std::decay<T>::type, variant>::value, variant>::type operator*(T&& t, variant const& p) { return variant(std::forward<T>(t)) * p; } template <typename T> typename std::enable_if<std::is_constructible<variant, T>::value && !std::is_same<typename std::decay<T>::type, variant>::value, variant>::type operator/(T&& t, variant const& p) { return variant(std::forward<T>(t)) / p; } template <typename T> typename std::enable_if<std::is_constructible<variant, T>::value && !std::is_same<typename std::decay<T>::type, variant>::value, bool>::type operator==(T&& t, variant const& p) { return variant(std::forward<T>(t)) == p; } template <typename T> struct is_dimmable { using DT = typename std::decay<T>::type; static constexpr bool value = std::is_integral<DT>::value || std::is_same<DT, variant>::value; }; template <template <typename> class pred, typename ... T> struct all_are { static constexpr bool value = true; }; template <template <typename> class pred, typename H, typename ... T> struct all_are<pred, H, T...> { static constexpr bool value = pred<H>::value && all_are<pred, T...>::value; }; template <typename T> T numeric_value(T t) { return t; } inline long numeric_value(const variant& v) { return long(v.numeric()); } class array { public: template <typename ... T, typename = typename std::enable_if<all_are<is_dimmable, T...>::value>::type> array(T const & ... t) : dimensions{1LU+numeric_value(t)..., 1LU}, elements(std::accumulate(std::begin(dimensions), std::end(dimensions), 1U, [](std::size_t i, std::size_t j){ return i*j;})) {} template <typename ... T> typename std::enable_if<all_are<is_dimmable, T...>::value, variant&>::type operator()(T const& ... t) { if (sizeof...(t) != dimensions.size() - 1) dimension_error(); long indexes[] { long(numeric_value(t))... }; auto i = sizeof...(t); size_t mul = 1U; size_t idx = 0U; while (i--) { if (indexes[i] < 0 || indexes[i] >= dimensions[i]) array_out_of_bounds(); idx += indexes[i]*mul; mul = dimensions[i]; } return elements[idx]; } private: std::vector<std::size_t> dimensions; std::vector<variant> elements; }; class printer { public: printer &operator,(const char *s) { std::cout << s; return *this; } printer &operator,(const variant &v) { if (v.isnum) std::cout << v.numval; else std::cout << v.strval; return *this; } ~printer() { std::cout << std::endl; } }; class input { public: input& operator,(char const *s) { std::cout << s << std::flush; return *this; } input& operator,(variant& v) { if (v.isnum) std::cin >> v.numval; else std::cin >> v.strval; return *this; } }; template <typename T> variant to_char_str(T const& t) { auto n = numeric_value(t); char a[] = { char(n), '\0' }; return variant{a}; } template <std::size_t N> inline variant to_asc_val(char const (&a)[N]) { if (N < 2) illegal_quantity_error(); return variant(double(a[0])); } inline variant to_asc_val(variant const& v) { auto s = v.string(); if (s.empty()) illegal_quantity_error(); return variant(double(s[0])); } #define INPUT basic::input(), #define PRINT basic::printer(), #define IF if ( #define THEN ) #define LET basic::variant #define GOTO goto #define FOR { basic::variant& for_loop_variable = #define TO ; \ { \ jmp_buf for_loop_top; \ bool for_loop_exit = false; \ while (!for_loop_exit) \ { \ if (setjmp(for_loop_top) == 0) \ { \ basic::variant for_loop_step=1; \ basic::variant const for_loop_endval= #define STEP ; \ for_loop_step= #define NEXT for_loop_variable=for_loop_variable+for_loop_step; \ for_loop_exit=( ( for_loop_step > 0 \ && for_loop_variable > for_loop_endval) \ ||( for_loop_step < 0 \ && for_loop_variable < for_loop_endval)); \ longjmp(for_loop_top, 1); \ } \ } \ } \ } #define END exit(0) #define VAL(x) x.toNum() #define STR(x) x.toString() #define MID$(str, left, right) str.midStr(left, right) #define LEFT$(str, count) str.leftStr(count) #define RIGHT$(str, count) str.rightStr(count) #define LEN(str) str.strlen() #define DIM basic::array #define RND(x) (double) (rand() & 0xffff) #define CHR$(num) basic::to_char_str(num) #define ASC(str) basic::to_asc_val(str) } // namespace basic <commit_msg>Fixed RND()<commit_after>// // Originally written by BjÃrn Fahller (bjorn@fahller.se) // Modified by Jeff Bush // // No rights claimed. The sources are released to the public domain // // For license information, please refer to <http://unlicense.org> // #include <setjmp.h> #include <stdlib.h> #include <iostream> #include <ostream> #include <forward_list> #include <vector> #include <algorithm> namespace basic { struct stack_frame { jmp_buf buf; }; std::forward_list<stack_frame> stack; #define GOSUB \ if (!(setjmp((basic::stack.emplace_front(),basic::stack.front().buf)) \ && (basic::stack.pop_front(),true))) \ goto #define RETURN if (basic::stack.empty()) return 0; longjmp(basic::stack.front().buf, 1) template <typename T, typename U> struct separator { static char const *str() { return ""; } }; template <typename T> struct separator<T,T> { static char const *str() { return ","; } }; inline void type_mismatch() { std::cout << "Type mismatch error\n"; exit(1); } inline void array_out_of_bounds() { std::cout << "Array out of bounds error\n"; exit(1); } inline void dimension_error() { std::cout << "Array Dimension error\n"; exit(1); } inline void illegal_quantity_error() { std::cout << "Illegal quantity error\n"; exit(1); } class variant { public: variant() : isnum(true), numval(0) {} variant(double _numval) : isnum(true), numval(_numval) {} variant(int _numval) : isnum(true), numval(_numval) {} variant(const std::string _strval) : isnum(false), strval(_strval) {} variant(const char *_strval) : isnum(false), strval(_strval) {} double numeric() const { if (!isnum) type_mismatch(); return numval; } std::string string() const { if (isnum) type_mismatch(); return strval; } variant toString() const { if (isnum) return variant(std::to_string(numval)); else return *this; } variant toNum() const { if (!isnum) return variant(stod(strval)); else return *this; } variant &operator=(const variant &copyfrom) { isnum = copyfrom.isnum; numval = copyfrom.numval; strval = copyfrom.strval; return *this; } // Note that strings in BASIC are 1 based, so subtract 1 from the left // index variant midStr(const variant &left, const variant &right) const { if (isnum || !left.isnum || !right.isnum) type_mismatch(); return variant(strval.substr(int(left.numval) - 1, (int(right.numval) - int(left.numval) + 1))); } variant leftStr(const variant &count) const { if (isnum) type_mismatch(); return variant(strval.substr(0, int(count.numval))); } variant rightStr(const variant &count) const { if (isnum) type_mismatch(); return variant(strval.substr(strval.length() - int(count.numval) - 1, int(count.numval))); } variant strlen() const { if (isnum) type_mismatch(); return variant((int)strval.length()); } variant operator+(const variant op) const { if (isnum != op.isnum) type_mismatch(); if (isnum) return variant(numval + op.numval); else return variant(strval + op.strval); } variant operator-(const variant op) const { if (!isnum || !op.isnum) type_mismatch(); return variant(numval - op.numval); } variant operator*(const variant op) const { if (!isnum || !op.isnum) type_mismatch(); return variant(numval * op.numval); } variant operator/(const variant op) const { if (!isnum || !op.isnum) type_mismatch(); return variant(numval / op.numval); } bool operator>(const variant op) const { if (isnum != op.isnum) type_mismatch(); if (isnum) return numval > op.numval; else return strval > op.strval; } bool operator>=(const variant op) const { if (isnum != op.isnum) type_mismatch(); if (isnum) return numval >= op.numval; else return strval >= op.strval; } bool operator<(const variant op) const { if (isnum != op.isnum) type_mismatch(); if (isnum) return numval < op.numval; else return strval < op.strval; } bool operator<=(const variant op) const { if (isnum != op.isnum) type_mismatch(); if (isnum) return numval <= op.numval; else return strval <= op.strval; } bool operator!=(const variant op) const { if (isnum != op.isnum) type_mismatch(); if (isnum) return numval != op.numval; else return strval != op.strval; } bool operator==(const variant op) const { if (isnum != op.isnum) type_mismatch(); if (isnum) return numval == op.numval; else return strval == op.strval; } bool isnum; double numval; std::string strval; }; template <typename T> typename std::enable_if<std::is_constructible<variant, T>::value && !std::is_same<typename std::decay<T>::type, variant>::value, variant>::type operator+(T&& t, variant const& p) { return variant(std::forward<T>(t)) + p; } template <typename T> typename std::enable_if<std::is_constructible<variant, T>::value && !std::is_same<typename std::decay<T>::type, variant>::value, variant>::type operator-(T&& t, variant const& p) { return variant(std::forward<T>(t)) - p; } template <typename T> typename std::enable_if<std::is_constructible<variant, T>::value && !std::is_same<typename std::decay<T>::type, variant>::value, variant>::type operator*(T&& t, variant const& p) { return variant(std::forward<T>(t)) * p; } template <typename T> typename std::enable_if<std::is_constructible<variant, T>::value && !std::is_same<typename std::decay<T>::type, variant>::value, variant>::type operator/(T&& t, variant const& p) { return variant(std::forward<T>(t)) / p; } template <typename T> typename std::enable_if<std::is_constructible<variant, T>::value && !std::is_same<typename std::decay<T>::type, variant>::value, bool>::type operator==(T&& t, variant const& p) { return variant(std::forward<T>(t)) == p; } template <typename T> struct is_dimmable { using DT = typename std::decay<T>::type; static constexpr bool value = std::is_integral<DT>::value || std::is_same<DT, variant>::value; }; template <template <typename> class pred, typename ... T> struct all_are { static constexpr bool value = true; }; template <template <typename> class pred, typename H, typename ... T> struct all_are<pred, H, T...> { static constexpr bool value = pred<H>::value && all_are<pred, T...>::value; }; template <typename T> T numeric_value(T t) { return t; } inline long numeric_value(const variant& v) { return long(v.numeric()); } class array { public: template <typename ... T, typename = typename std::enable_if<all_are<is_dimmable, T...>::value>::type> array(T const & ... t) : dimensions{1LU+numeric_value(t)..., 1LU}, elements(std::accumulate(std::begin(dimensions), std::end(dimensions), 1U, [](std::size_t i, std::size_t j){ return i*j;})) {} template <typename ... T> typename std::enable_if<all_are<is_dimmable, T...>::value, variant&>::type operator()(T const& ... t) { if (sizeof...(t) != dimensions.size() - 1) dimension_error(); long indexes[] { long(numeric_value(t))... }; auto i = sizeof...(t); size_t mul = 1U; size_t idx = 0U; while (i--) { if (indexes[i] < 0 || indexes[i] >= dimensions[i]) array_out_of_bounds(); idx += indexes[i]*mul; mul = dimensions[i]; } return elements[idx]; } private: std::vector<std::size_t> dimensions; std::vector<variant> elements; }; class printer { public: printer &operator,(const char *s) { std::cout << s; return *this; } printer &operator,(const variant &v) { if (v.isnum) std::cout << v.numval; else std::cout << v.strval; return *this; } ~printer() { std::cout << std::endl; } }; class input { public: input& operator,(char const *s) { std::cout << s << std::flush; return *this; } input& operator,(variant& v) { if (v.isnum) std::cin >> v.numval; else std::cin >> v.strval; return *this; } }; template <typename T> variant to_char_str(T const& t) { auto n = numeric_value(t); char a[] = { char(n), '\0' }; return variant{a}; } template <std::size_t N> inline variant to_asc_val(char const (&a)[N]) { if (N < 2) illegal_quantity_error(); return variant(double(a[0])); } inline variant to_asc_val(variant const& v) { auto s = v.string(); if (s.empty()) illegal_quantity_error(); return variant(double(s[0])); } #define INPUT basic::input(), #define PRINT basic::printer(), #define IF if ( #define THEN ) #define LET basic::variant #define GOTO goto #define FOR { basic::variant& for_loop_variable = #define TO ; \ { \ jmp_buf for_loop_top; \ bool for_loop_exit = false; \ while (!for_loop_exit) \ { \ if (setjmp(for_loop_top) == 0) \ { \ basic::variant for_loop_step=1; \ basic::variant const for_loop_endval= #define STEP ; \ for_loop_step= #define NEXT for_loop_variable=for_loop_variable+for_loop_step; \ for_loop_exit=( ( for_loop_step > 0 \ && for_loop_variable > for_loop_endval) \ ||( for_loop_step < 0 \ && for_loop_variable < for_loop_endval)); \ longjmp(for_loop_top, 1); \ } \ } \ } \ } #define END exit(0) #define VAL(x) x.toNum() #define STR(x) x.toString() #define MID$(str, left, right) str.midStr(left, right) #define LEFT$(str, count) str.leftStr(count) #define RIGHT$(str, count) str.rightStr(count) #define LEN(str) str.strlen() #define DIM basic::array #define RND(x) ((rand() & 0xffff)/65535.0) #define CHR$(num) basic::to_char_str(num) #define ASC(str) basic::to_asc_val(str) } // namespace basic <|endoftext|>
<commit_before>#include <avr/pgmspace.h> #include <stdlib.h> char *to_print; char *pgmStrToRAM(PROGMEM char *theString) { free(to_print); to_print=(char *) malloc(strlen_P(theString) + 1); strcpy_P(to_print, theString); return (to_print); }<commit_msg>Add include to support SAMD core<commit_after>#include <avr/pgmspace.h> #include <stdlib.h> #include <string.h> char *to_print; char *pgmStrToRAM(PROGMEM char *theString) { free(to_print); to_print=(char *) malloc(strlen_P(theString) + 1); strcpy_P(to_print, theString); return (to_print); }<|endoftext|>
<commit_before>#pragma once //#define DEFAULT_LOGGER "blockchain" #include <bts/blockchain/chain_database.hpp> #include <bts/blockchain/checkpoints.hpp> #include <bts/blockchain/config.hpp> #include <bts/blockchain/genesis_config.hpp> #include <bts/blockchain/genesis_json.hpp> #include <bts/blockchain/market_records.hpp> #include <bts/blockchain/operation_factory.hpp> #include <bts/blockchain/time.hpp> #include <bts/db/cached_level_map.hpp> #include <bts/db/level_map.hpp> #include <fc/io/fstream.hpp> #include <fc/io/json.hpp> #include <fc/io/raw_variant.hpp> #include <fc/thread/mutex.hpp> #include <fc/thread/non_preemptable_scope_check.hpp> #include <fc/thread/unique_lock.hpp> #include <algorithm> #include <deque> #include <fstream> #include <iomanip> #include <iostream> namespace bts { namespace blockchain { struct vote_del { vote_del( int64_t v = 0, account_id_type del = 0 ) :votes(v),delegate_id(del){} int64_t votes = 0; account_id_type delegate_id; friend bool operator == ( const vote_del& a, const vote_del& b ) { return a.votes == b.votes && a.delegate_id == b.delegate_id; } friend bool operator < ( const vote_del& a, const vote_del& b ) { if( a.votes != b.votes ) return a.votes > b.votes; /* Reverse so maps sort in descending order */ return a.delegate_id < b.delegate_id; /* Lowest id wins in ties */ } }; struct fee_index { fee_index( share_type fees = 0, transaction_id_type trx = transaction_id_type() ) :_fees(fees),_trx(trx){} share_type _fees; transaction_id_type _trx; friend bool operator == ( const fee_index& a, const fee_index& b ) { return a._fees == b._fees && a._trx == b._trx; } friend bool operator < ( const fee_index& a, const fee_index& b ) { if( a._fees == b._fees ) return a._trx < b._trx; /* Lowest id wins in ties */ return a._fees > b._fees; /* Reverse so that highest fee is placed first in sorted maps */ } }; namespace detail { class chain_database_impl { public: void open_database(const fc::path& data_dir ); digest_type initialize_genesis( const optional<path>& genesis_file, bool chain_id_only = false ); std::pair<block_id_type, block_fork_data> store_and_index( const block_id_type& id, const full_block& blk ); void clear_pending( const full_block& blk ); void switch_to_fork( const block_id_type& block_id ); void extend_chain( const full_block& blk ); vector<block_id_type> get_fork_history( const block_id_type& id ); void pop_block(); void mark_invalid( const block_id_type& id, const fc::exception& reason ); void mark_included( const block_id_type& id, bool state ); void verify_header( const full_block&, const public_key_type& block_signee ); void apply_transactions( const full_block& block, const pending_chain_state_ptr& ); void pay_delegate( const pending_chain_state_ptr& pending_state, const public_key_type& block_signee )const; void save_undo_state( const block_id_type& id, const pending_chain_state_ptr& ); void update_head_block( const full_block& blk ); std::vector<block_id_type> fetch_blocks_at_number( uint32_t block_num ); std::pair<block_id_type, block_fork_data> recursive_mark_as_linked( const std::unordered_set<block_id_type>& ids ); void recursive_mark_as_invalid( const std::unordered_set<block_id_type>& ids, const fc::exception& reason ); void execute_markets(const fc::time_point_sec& timestamp, const pending_chain_state_ptr& pending_state ); void update_random_seed( const secret_hash_type& new_secret, const pending_chain_state_ptr& pending_state ); void update_active_delegate_list(const full_block& block_data, const pending_chain_state_ptr& pending_state ); void update_delegate_production_info( const full_block& block_data, const pending_chain_state_ptr& pending_state, const public_key_type& block_signee ); void revalidate_pending(); fc::future<void> _revalidate_pending; fc::mutex _push_block_mutex; /** * Used to track the cumulative effect of all pending transactions that are known, * new incomming transactions are evaluated relative to this state. * * After a new block is pushed this state is recalculated based upon what ever * pending transactions remain. */ pending_chain_state_ptr _pending_trx_state; chain_database* self = nullptr; unordered_set<chain_observer*> _observers; digest_type _chain_id; bool _skip_signature_verification; share_type _relay_fee; bts::db::cached_level_map<uint32_t, std::vector<market_transaction>> _market_transactions_db; bts::db::level_map<slate_id_type, delegate_slate> _slate_db; bts::db::level_map<uint32_t, std::vector<block_id_type>> _fork_number_db; bts::db::level_map<block_id_type,block_fork_data> _fork_db; bts::db::cached_level_map<uint32_t, fc::variant> _property_db; #if 0 bts::db::level_map<proposal_id_type, proposal_record> _proposal_db; bts::db::level_map<proposal_vote_id_type, proposal_vote> _proposal_vote_db; #endif /** the data required to 'undo' the changes a block made to the database */ bts::db::level_map<block_id_type,pending_chain_state> _undo_state_db; // blocks in the current 'official' chain. bts::db::level_map<uint32_t,block_id_type> _block_num_to_id_db; // all blocks from any fork.. bts::db::level_map<block_id_type,block_record> _block_id_to_block_record_db; bts::db::level_map<block_id_type,full_block> _block_id_to_block_data_db; std::unordered_set<transaction_id_type> _known_transactions; bts::db::level_map<transaction_id_type,transaction_record> _id_to_transaction_record_db; signed_block_header _head_block_header; block_id_type _head_block_id; bts::db::level_map<transaction_id_type, signed_transaction> _pending_transaction_db; std::map<fee_index, transaction_evaluation_state_ptr> _pending_fee_index; bts::db::level_map<asset_id_type, asset_record> _asset_db; bts::db::level_map<string, asset_id_type> _symbol_index_db; bts::db::level_map<balance_id_type, balance_record> _balance_db; bts::db::cached_level_map<account_id_type, account_record> _account_db; bts::db::cached_level_map<string, account_id_type> _account_index_db; bts::db::cached_level_map<address, account_id_type> _address_to_account_db; bts::db::cached_level_map<vote_del, int> _delegate_vote_index_db; bts::db::level_map<time_point_sec, slot_record> _slot_record_db; bts::db::level_map<burn_record_key, burn_record_value> _burn_db; bts::db::cached_level_map<market_index_key, order_record> _ask_db; bts::db::cached_level_map<market_index_key, order_record> _bid_db; bts::db::cached_level_map<market_index_key, order_record> _relative_ask_db; bts::db::cached_level_map<market_index_key, order_record> _relative_bid_db; bts::db::cached_level_map<market_index_key, order_record> _short_db; bts::db::cached_level_map<market_index_key, collateral_record> _collateral_db; bts::db::cached_level_map<feed_index, feed_record> _feed_db; bts::db::level_map<std::pair<asset_id_type,asset_id_type>, market_status> _market_status_db; bts::db::level_map<market_history_key, market_history_record> _market_history_db; std::map<operation_type_enum, std::deque<operation>> _recent_operations; }; } // end namespace bts::blockchain::detail } } // end namespace bts::blockchain FC_REFLECT_TYPENAME( std::vector<bts::blockchain::block_id_type> ) FC_REFLECT( bts::blockchain::vote_del, (votes)(delegate_id) ) FC_REFLECT( bts::blockchain::fee_index, (_fees)(_trx) ) <commit_msg>Convert more level_maps to cached_level_maps<commit_after>#pragma once //#define DEFAULT_LOGGER "blockchain" #include <bts/blockchain/chain_database.hpp> #include <bts/blockchain/checkpoints.hpp> #include <bts/blockchain/config.hpp> #include <bts/blockchain/genesis_config.hpp> #include <bts/blockchain/genesis_json.hpp> #include <bts/blockchain/market_records.hpp> #include <bts/blockchain/operation_factory.hpp> #include <bts/blockchain/time.hpp> #include <bts/db/cached_level_map.hpp> #include <bts/db/level_map.hpp> #include <fc/io/fstream.hpp> #include <fc/io/json.hpp> #include <fc/io/raw_variant.hpp> #include <fc/thread/mutex.hpp> #include <fc/thread/non_preemptable_scope_check.hpp> #include <fc/thread/unique_lock.hpp> #include <algorithm> #include <deque> #include <fstream> #include <iomanip> #include <iostream> namespace bts { namespace blockchain { struct vote_del { vote_del( int64_t v = 0, account_id_type del = 0 ) :votes(v),delegate_id(del){} int64_t votes = 0; account_id_type delegate_id; friend bool operator == ( const vote_del& a, const vote_del& b ) { return a.votes == b.votes && a.delegate_id == b.delegate_id; } friend bool operator < ( const vote_del& a, const vote_del& b ) { if( a.votes != b.votes ) return a.votes > b.votes; /* Reverse so maps sort in descending order */ return a.delegate_id < b.delegate_id; /* Lowest id wins in ties */ } }; struct fee_index { fee_index( share_type fees = 0, transaction_id_type trx = transaction_id_type() ) :_fees(fees),_trx(trx){} share_type _fees; transaction_id_type _trx; friend bool operator == ( const fee_index& a, const fee_index& b ) { return a._fees == b._fees && a._trx == b._trx; } friend bool operator < ( const fee_index& a, const fee_index& b ) { if( a._fees == b._fees ) return a._trx < b._trx; /* Lowest id wins in ties */ return a._fees > b._fees; /* Reverse so that highest fee is placed first in sorted maps */ } }; namespace detail { class chain_database_impl { public: void open_database(const fc::path& data_dir ); digest_type initialize_genesis( const optional<path>& genesis_file, bool chain_id_only = false ); std::pair<block_id_type, block_fork_data> store_and_index( const block_id_type& id, const full_block& blk ); void clear_pending( const full_block& blk ); void switch_to_fork( const block_id_type& block_id ); void extend_chain( const full_block& blk ); vector<block_id_type> get_fork_history( const block_id_type& id ); void pop_block(); void mark_invalid( const block_id_type& id, const fc::exception& reason ); void mark_included( const block_id_type& id, bool state ); void verify_header( const full_block&, const public_key_type& block_signee ); void apply_transactions( const full_block& block, const pending_chain_state_ptr& ); void pay_delegate( const pending_chain_state_ptr& pending_state, const public_key_type& block_signee )const; void save_undo_state( const block_id_type& id, const pending_chain_state_ptr& ); void update_head_block( const full_block& blk ); std::vector<block_id_type> fetch_blocks_at_number( uint32_t block_num ); std::pair<block_id_type, block_fork_data> recursive_mark_as_linked( const std::unordered_set<block_id_type>& ids ); void recursive_mark_as_invalid( const std::unordered_set<block_id_type>& ids, const fc::exception& reason ); void execute_markets(const fc::time_point_sec& timestamp, const pending_chain_state_ptr& pending_state ); void update_random_seed( const secret_hash_type& new_secret, const pending_chain_state_ptr& pending_state ); void update_active_delegate_list(const full_block& block_data, const pending_chain_state_ptr& pending_state ); void update_delegate_production_info( const full_block& block_data, const pending_chain_state_ptr& pending_state, const public_key_type& block_signee ); void revalidate_pending(); fc::future<void> _revalidate_pending; fc::mutex _push_block_mutex; /** * Used to track the cumulative effect of all pending transactions that are known, * new incomming transactions are evaluated relative to this state. * * After a new block is pushed this state is recalculated based upon what ever * pending transactions remain. */ pending_chain_state_ptr _pending_trx_state; chain_database* self = nullptr; unordered_set<chain_observer*> _observers; digest_type _chain_id; bool _skip_signature_verification; share_type _relay_fee; bts::db::cached_level_map<uint32_t, std::vector<market_transaction>> _market_transactions_db; bts::db::cached_level_map<slate_id_type, delegate_slate> _slate_db; bts::db::level_map<uint32_t, std::vector<block_id_type>> _fork_number_db; bts::db::level_map<block_id_type,block_fork_data> _fork_db; bts::db::cached_level_map<uint32_t, fc::variant> _property_db; #if 0 bts::db::level_map<proposal_id_type, proposal_record> _proposal_db; bts::db::level_map<proposal_vote_id_type, proposal_vote> _proposal_vote_db; #endif /** the data required to 'undo' the changes a block made to the database */ bts::db::level_map<block_id_type,pending_chain_state> _undo_state_db; // blocks in the current 'official' chain. bts::db::level_map<uint32_t,block_id_type> _block_num_to_id_db; // all blocks from any fork.. bts::db::level_map<block_id_type,block_record> _block_id_to_block_record_db; bts::db::level_map<block_id_type,full_block> _block_id_to_block_data_db; std::unordered_set<transaction_id_type> _known_transactions; bts::db::level_map<transaction_id_type,transaction_record> _id_to_transaction_record_db; signed_block_header _head_block_header; block_id_type _head_block_id; bts::db::level_map<transaction_id_type, signed_transaction> _pending_transaction_db; std::map<fee_index, transaction_evaluation_state_ptr> _pending_fee_index; bts::db::cached_level_map<asset_id_type, asset_record> _asset_db; bts::db::cached_level_map<string, asset_id_type> _symbol_index_db; bts::db::level_map<balance_id_type, balance_record> _balance_db; bts::db::cached_level_map<account_id_type, account_record> _account_db; bts::db::cached_level_map<string, account_id_type> _account_index_db; bts::db::cached_level_map<address, account_id_type> _address_to_account_db; bts::db::cached_level_map<vote_del, int> _delegate_vote_index_db; bts::db::level_map<time_point_sec, slot_record> _slot_record_db; bts::db::level_map<burn_record_key, burn_record_value> _burn_db; bts::db::cached_level_map<market_index_key, order_record> _ask_db; bts::db::cached_level_map<market_index_key, order_record> _bid_db; bts::db::cached_level_map<market_index_key, order_record> _relative_ask_db; bts::db::cached_level_map<market_index_key, order_record> _relative_bid_db; bts::db::cached_level_map<market_index_key, order_record> _short_db; bts::db::cached_level_map<market_index_key, collateral_record> _collateral_db; bts::db::cached_level_map<feed_index, feed_record> _feed_db; bts::db::cached_level_map<std::pair<asset_id_type,asset_id_type>, market_status> _market_status_db; bts::db::level_map<market_history_key, market_history_record> _market_history_db; std::map<operation_type_enum, std::deque<operation>> _recent_operations; }; } // end namespace bts::blockchain::detail } } // end namespace bts::blockchain FC_REFLECT_TYPENAME( std::vector<bts::blockchain::block_id_type> ) FC_REFLECT( bts::blockchain::vote_del, (votes)(delegate_id) ) FC_REFLECT( bts::blockchain::fee_index, (_fees)(_trx) ) <|endoftext|>
<commit_before>// Copyright (c) 2012-2013, Zeex // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #include <cstring> #ifdef _WIN32 #include <windows.h> #else #include <stdint.h> #include <unistd.h> #include <sys/mman.h> #endif #include "hook.h" Hook::Hook() : src_(nullptr) , dst_(nullptr) , installed_(false) {} Hook::Hook(void *src, void *dst) : src_(nullptr) , dst_(nullptr) , installed_(false) { Install(src, dst); } Hook::~Hook() { Remove(); } bool Hook::Install() { if (installed_) { return false; } // Set write permission Unprotect(src_, kJmpInstrSize); // Store the code we are going to overwrite (probably to copy it back later) memcpy(code_, src_, kJmpInstrSize); // E9 - jump near, relative unsigned char JMP = 0xE9; memcpy(src_, &JMP, 1); // Jump address is relative to the next instruction's address size_t offset = (int)dst_ - ((int)src_ + kJmpInstrSize); memcpy((void*)((int)src_ + 1), &offset, kJmpInstrSize - 1); installed_ = true; return true; } bool Hook::Install(void *src, void *dst) { if (installed_) { return false; } src_ = src; dst_ = dst; return Install(); } bool Hook::Remove() { if (!installed_) { return false; } std::memcpy(src_, code_, kJmpInstrSize); installed_ = false; return true; } bool Hook::IsInstalled() const { return installed_; } // static void *Hook::GetTargetAddress(void *jmp) { if (*reinterpret_cast<unsigned char*>(jmp) == 0xE9) { int next_instr = reinterpret_cast<int>(reinterpret_cast<char*>(jmp) + kJmpInstrSize); int rel_addr = *reinterpret_cast<int*>(reinterpret_cast<char*>(jmp) + 1); int abs_addr = rel_addr + next_instr; return reinterpret_cast<void*>(abs_addr); } return nullptr; } // static void Hook::Unprotect(void *address, int size) { #ifdef _WIN32 DWORD oldProtect; VirtualProtect(address, size, PAGE_EXECUTE_READWRITE, &oldProtect); #else size_t pagesize = getpagesize(); size_t where = ((reinterpret_cast<uint32_t>(address) / pagesize) * pagesize); size_t count = (size / pagesize) * pagesize + pagesize * 2; mprotect(reinterpret_cast<void*>(where), count, PROT_READ | PROT_WRITE | PROT_EXEC); #endif } <commit_msg>Replace size_t and int with std:intptr_t in pointer arithmetic<commit_after>// Copyright (c) 2012-2013, Zeex // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #include <cstdint> #include <cstring> #ifdef _WIN32 #include <windows.h> #else #include <stdint.h> #include <unistd.h> #include <sys/mman.h> #endif #include "hook.h" Hook::Hook() : src_(nullptr) , dst_(nullptr) , installed_(false) {} Hook::Hook(void *src, void *dst) : src_(nullptr) , dst_(nullptr) , installed_(false) { Install(src, dst); } Hook::~Hook() { Remove(); } bool Hook::Install() { if (installed_) { return false; } // Set write permission Unprotect(src_, kJmpInstrSize); // Store the code we are going to overwrite (probably to copy it back later) memcpy(code_, src_, kJmpInstrSize); // E9 - jump near, relative std::uint8_t JMP = 0xE9; memcpy(src_, &JMP, 1); // Jump address is relative to the next instruction's address std::intptr_t offset = (std::intptr_t)dst_ - ((std::intptr_t)src_ + kJmpInstrSize); memcpy((void*)((std::intptr_t)src_ + 1), &offset, kJmpInstrSize - 1); installed_ = true; return true; } bool Hook::Install(void *src, void *dst) { if (installed_) { return false; } src_ = src; dst_ = dst; return Install(); } bool Hook::Remove() { if (!installed_) { return false; } std::memcpy(src_, code_, kJmpInstrSize); installed_ = false; return true; } bool Hook::IsInstalled() const { return installed_; } // static void *Hook::GetTargetAddress(void *jmp) { if (*reinterpret_cast<unsigned char*>(jmp) == 0xE9) { std::intptr_t next_instr = reinterpret_cast<std::intptr_t>(reinterpret_cast<char*>(jmp) + kJmpInstrSize); std::intptr_t rel_addr = *reinterpret_cast<std::intptr_t*>(reinterpret_cast<char*>(jmp) + 1); std::intptr_t abs_addr = rel_addr + next_instr; return reinterpret_cast<void*>(abs_addr); } return nullptr; } // static void Hook::Unprotect(void *address, int size) { #ifdef _WIN32 DWORD oldProtect; VirtualProtect(address, size, PAGE_EXECUTE_READWRITE, &oldProtect); #else int pagesize = getpagesize(); std::intptr_t where = ((reinterpret_cast<std::intptr_t>(address) / pagesize) * pagesize); std::intptr_t count = (size / pagesize) * pagesize + pagesize * 2; mprotect(reinterpret_cast<void*>(where), count, PROT_READ | PROT_WRITE | PROT_EXEC); #endif } <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "crypto/signature_verifier_win.h" #include "crypto/rsa_private_key.h" #include "omaha/base/debug.h" #include "omaha/base/logging.h" namespace { // Wrappers of malloc and free for CRYPT_DECODE_PARA, which requires the // WINAPI calling convention. void* WINAPI MyCryptAlloc(size_t size) { return malloc(size); } void WINAPI MyCryptFree(void* p) { free(p); } } // namespace namespace crypto { SignatureVerifierWin::SignatureVerifierWin() : hash_object_(0), public_key_(0) { if (FAILED(CryptAcquireContextWithFallback(PROV_RSA_AES, provider_.receive()))) { provider_.reset(); } } SignatureVerifierWin::~SignatureVerifierWin() { } bool SignatureVerifierWin::VerifyInit(ALG_ID algorithm_id, const uint8_t* signature, size_t signature_len, const uint8_t* public_key_info, size_t public_key_info_len) { if (algorithm_id != CALG_SHA_256 && algorithm_id != CALG_SHA1) { REPORT_LOG(LE, (_T("[VerifyInit][Invalid signature algorithm][%d]"), algorithm_id)); return false; } signature_.reserve(signature_len); // CryptoAPI uses big integers in the little-endian byte order, so we need // to first swap the order of signature bytes. for (int i = signature_len - 1; i >= 0; --i) signature_.push_back(signature[i]); CRYPT_DECODE_PARA decode_para; decode_para.cbSize = sizeof(decode_para); decode_para.pfnAlloc = MyCryptAlloc; decode_para.pfnFree = MyCryptFree; CERT_PUBLIC_KEY_INFO* cert_public_key_info = NULL; DWORD struct_len = 0; BOOL ok; ok = CryptDecodeObjectEx(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, X509_PUBLIC_KEY_INFO, public_key_info, public_key_info_len, CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, &decode_para, &cert_public_key_info, &struct_len); if (!ok) return false; ok = CryptImportPublicKeyInfo(provider_, X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, cert_public_key_info, public_key_.receive()); free(cert_public_key_info); if (!ok) return false; ok = CryptCreateHash(provider_, algorithm_id, 0, 0, hash_object_.receive()); if (!ok) return false; return true; } void SignatureVerifierWin::VerifyUpdate(const uint8_t* data_part, size_t data_part_len) { CryptHashData(hash_object_, data_part, data_part_len, 0); } bool SignatureVerifierWin::VerifyFinal() { BOOL ok = CryptVerifySignature(hash_object_, &signature_[0], static_cast<DWORD>(signature_.size()), public_key_, NULL, 0); Reset(); if (!ok) return false; return true; } void SignatureVerifierWin::Reset() { hash_object_.reset(); public_key_.reset(); signature_.clear(); } } // namespace crypto <commit_msg>Add logging to diagnose DmClientRequestTest.FetchPolicies unit test failures.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "crypto/signature_verifier_win.h" #include "crypto/rsa_private_key.h" #include "omaha/base/debug.h" #include "omaha/base/error.h" #include "omaha/base/logging.h" namespace { // Wrappers of malloc and free for CRYPT_DECODE_PARA, which requires the // WINAPI calling convention. void* WINAPI MyCryptAlloc(size_t size) { return malloc(size); } void WINAPI MyCryptFree(void* p) { free(p); } } // namespace namespace crypto { SignatureVerifierWin::SignatureVerifierWin() : hash_object_(0), public_key_(0) { if (FAILED(CryptAcquireContextWithFallback(PROV_RSA_AES, provider_.receive()))) { provider_.reset(); } } SignatureVerifierWin::~SignatureVerifierWin() { } bool SignatureVerifierWin::VerifyInit(ALG_ID algorithm_id, const uint8_t* signature, size_t signature_len, const uint8_t* public_key_info, size_t public_key_info_len) { if (algorithm_id != CALG_SHA_256 && algorithm_id != CALG_SHA1) { REPORT_LOG(LE, (_T("[VerifyInit][Invalid signature algorithm][%d]"), algorithm_id)); return false; } signature_.reserve(signature_len); // CryptoAPI uses big integers in the little-endian byte order, so we need // to first swap the order of signature bytes. for (int i = signature_len - 1; i >= 0; --i) signature_.push_back(signature[i]); CRYPT_DECODE_PARA decode_para; decode_para.cbSize = sizeof(decode_para); decode_para.pfnAlloc = MyCryptAlloc; decode_para.pfnFree = MyCryptFree; CERT_PUBLIC_KEY_INFO* cert_public_key_info = NULL; DWORD struct_len = 0; BOOL ok; ok = CryptDecodeObjectEx(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, X509_PUBLIC_KEY_INFO, public_key_info, public_key_info_len, CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, &decode_para, &cert_public_key_info, &struct_len); if (!ok) { HRESULT hr = omaha::HRESULTFromLastError(); REPORT_LOG(LE, (_T("[VerifyInit][CryptDecodeObjectEx failed][%#x]"), hr)); return false; } ok = CryptImportPublicKeyInfo(provider_, X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, cert_public_key_info, public_key_.receive()); free(cert_public_key_info); if (!ok) { HRESULT hr = omaha::HRESULTFromLastError(); REPORT_LOG(LE, (_T("[VerifyInit][CryptImportPublicKeyInfo failed][%#x]"), hr)); return false; } ok = CryptCreateHash(provider_, algorithm_id, 0, 0, hash_object_.receive()); if (!ok) { HRESULT hr = omaha::HRESULTFromLastError(); REPORT_LOG(LE, (_T("[VerifyFinal][CryptVerifySignature failed][%#x]"), hr)); return false; } return true; } void SignatureVerifierWin::VerifyUpdate(const uint8_t* data_part, size_t data_part_len) { BOOL ok = CryptHashData(hash_object_, data_part, data_part_len, 0); if (!ok) { HRESULT hr = omaha::HRESULTFromLastError(); REPORT_LOG(LE, (_T("[VerifyUpdate][CryptHashData failed][%#x]"), hr)); } } bool SignatureVerifierWin::VerifyFinal() { BOOL ok = CryptVerifySignature(hash_object_, &signature_[0], static_cast<DWORD>(signature_.size()), public_key_, NULL, 0); Reset(); if (!ok) { HRESULT hr = omaha::HRESULTFromLastError(); REPORT_LOG(LE, (_T("[VerifyFinal][CryptVerifySignature failed][%#x]"), hr)); return false; } return true; } void SignatureVerifierWin::Reset() { hash_object_.reset(); public_key_.reset(); signature_.clear(); } } // namespace crypto <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit (ITK) Module: Language: C++ Date: Version: Copyright (c) 2000 National Library of Medicine All rights reserved. See COPYRIGHT.txt for copyright details. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include <iostream> // This file has been generated by BuildHeaderTest.tcl // Test to include each header file for Insight #include "itkBlobSpatialObject.txx" #include "itkEllipseSpatialObject.txx" #include "itkGaussianSpatialObject.txx" #include "itkGroupSpatialObject.txx" #include "itkImageSpatialObject.txx" #include "itkLandmarkSpatialObject.txx" #include "itkLineSpatialObject.txx" #include "itkLineSpatialObjectPoint.txx" #include "itkMeshSpatialObject.txx" #include "itkMetaBlobConverter.txx" #include "itkMetaEllipseConverter.txx" #include "itkMetaEvent.h" #include "itkMetaGaussianConverter.txx" #include "itkMetaGroupConverter.txx" #include "itkMetaImageConverter.txx" #include "itkMetaLandmarkConverter.txx" #include "itkMetaLineConverter.txx" #include "itkMetaSceneConverter.txx" #include "itkMetaSurfaceConverter.txx" #include "itkMetaTubeConverter.txx" #include "itkPlaneSpatialObject.txx" #include "itkPointBasedSpatialObject.txx" #include "itkPolygonGroupOrientation.h" #include "itkPolygonGroupSpatialObject.txx" #include "itkPolygonSpatialObject.txx" #include "itkSceneSpatialObject.txx" #include "itkSpatialObject.txx" #include "itkSpatialObjectPoint.txx" #include "itkSpatialObjectProperty.txx" #include "itkSurfaceSpatialObject.txx" #include "itkSurfaceSpatialObjectPoint.txx" #include "itkTubeSpatialObject.txx" #include "itkTubeSpatialObjectPoint.txx" #include "itkAffineGeometryFrame.h" #include "itkAffineGeometryFrame.txx" #include "itkSpatialObjectTreeContainer.h" #include "itkSpatialObjectTreeContainer.txx" #include "itkSpatialObjectTreeNode.h" #include "itkAffineGeometryFrame.h" #include "itkAffineGeometryFrame.txx" int main ( int , char* ) { return 0; } <commit_msg>ENH: added somne recent classes.<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit (ITK) Module: Language: C++ Date: Version: Copyright (c) 2000 National Library of Medicine All rights reserved. See COPYRIGHT.txt for copyright details. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include <iostream> // This file has been generated by BuildHeaderTest.tcl // Test to include each header file for Insight #include "itkAffineGeometryFrame.txx" #include "itkBlobSpatialObject.txx" #include "itkEllipseSpatialObject.txx" #include "itkGaussianSpatialObject.txx" #include "itkGroupSpatialObject.txx" #include "itkImageMaskSpatialObject.txx" #include "itkImageSpatialObject.txx" #include "itkLandmarkSpatialObject.txx" #include "itkLineSpatialObject.txx" #include "itkLineSpatialObjectPoint.txx" #include "itkMeshSpatialObject.txx" #include "itkMetaBlobConverter.txx" #include "itkMetaEllipseConverter.txx" #include "itkMetaEvent.h" #include "itkMetaGaussianConverter.txx" #include "itkMetaGroupConverter.txx" #include "itkMetaImageConverter.txx" #include "itkMetaLandmarkConverter.txx" #include "itkMetaLineConverter.txx" #include "itkMetaMeshConverter.txx" #include "itkMetaSceneConverter.txx" #include "itkMetaSurfaceConverter.txx" #include "itkMetaTubeConverter.txx" #include "itkPlaneSpatialObject.txx" #include "itkPointBasedSpatialObject.txx" #include "itkPolygonGroupOrientation.h" #include "itkPolygonGroupSpatialObject.txx" #include "itkPolygonSpatialObject.txx" #include "itkSceneSpatialObject.txx" #include "itkSpatialObject.txx" #include "itkSpatialObjectPoint.txx" #include "itkSpatialObjectProperty.txx" #include "itkSpatialObjectTreeContainer.txx" #include "itkSpatialObjectTreeNode.h" #include "itkSurfaceSpatialObject.txx" #include "itkSurfaceSpatialObjectPoint.txx" #include "itkTubeSpatialObject.txx" #include "itkTubeSpatialObjectPoint.txx" int main ( int , char* ) { return 0; } <|endoftext|>
<commit_before>// @(#)root/mathmore:$Id$ // Author: L. Moneta Wed Dec 20 14:36:31 2006 /********************************************************************** * * * Copyright (c) 2006 LCG ROOT Math Team, CERN/PH-SFT * * * * This library 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 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 * * General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this library (see file COPYING); if not, write * * to the Free Software Foundation, Inc., 59 Temple Place, Suite * * 330, Boston, MA 02111-1307 USA, or contact the author. * * * **********************************************************************/ // implementation file for class MultiNumGradFunction #include "Math/MultiNumGradFunction.h" #include <limits> #include <cmath> #ifndef ROOT_Math_Derivator #include "Math/Derivator.h" #endif namespace ROOT { namespace Math { double MultiNumGradFunction::fgEps = 0.001; double MultiNumGradFunction::DoDerivative (const double * x, unsigned int icoord ) const { // calculate derivative using mathcore derivator class // step size can be changes using SetDerivPrecision() static double kPrecision = std::sqrt ( std::numeric_limits<double>::epsilon() ); double x0 = x[icoord]; double step = std::max( fgEps* std::abs(x0), 8.0*kPrecision*(std::abs(x0) + kPrecision) ); return ROOT::Math::Derivator::Eval(*fFunc, x, icoord, step); } void MultiNumGradFunction::SetDerivPrecision(double eps) { fgEps = eps; } double MultiNumGradFunction::GetDerivPrecision( ) { return fgEps; } } // end namespace Math } // end namespace ROOT <commit_msg>fix problem on Solaris<commit_after>// @(#)root/mathmore:$Id$ // Author: L. Moneta Wed Dec 20 14:36:31 2006 /********************************************************************** * * * Copyright (c) 2006 LCG ROOT Math Team, CERN/PH-SFT * * * * This library 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 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 * * General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this library (see file COPYING); if not, write * * to the Free Software Foundation, Inc., 59 Temple Place, Suite * * 330, Boston, MA 02111-1307 USA, or contact the author. * * * **********************************************************************/ // implementation file for class MultiNumGradFunction #include "Math/MultiNumGradFunction.h" #include <limits> #include <cmath> #include <algorithm> // needed for std::max on Solaris #ifndef ROOT_Math_Derivator #include "Math/Derivator.h" #endif namespace ROOT { namespace Math { double MultiNumGradFunction::fgEps = 0.001; double MultiNumGradFunction::DoDerivative (const double * x, unsigned int icoord ) const { // calculate derivative using mathcore derivator class // step size can be changes using SetDerivPrecision() static double kPrecision = std::sqrt ( std::numeric_limits<double>::epsilon() ); double x0 = x[icoord]; double step = std::max( fgEps* std::abs(x0), 8.0*kPrecision*(std::abs(x0) + kPrecision) ); return ROOT::Math::Derivator::Eval(*fFunc, x, icoord, step); } void MultiNumGradFunction::SetDerivPrecision(double eps) { fgEps = eps; } double MultiNumGradFunction::GetDerivPrecision( ) { return fgEps; } } // end namespace Math } // end namespace ROOT <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "jingle/glue/thread_wrapper.h" #include "base/bind.h" #include "base/bind_helpers.h" #include "base/lazy_instance.h" #include "base/threading/thread_local.h" namespace jingle_glue { struct JingleThreadWrapper::PendingSend { PendingSend(const talk_base::Message& message_value) : sending_thread(JingleThreadWrapper::current()), message(message_value), done_event(true, false) { DCHECK(sending_thread); } JingleThreadWrapper* sending_thread; talk_base::Message message; base::WaitableEvent done_event; }; base::LazyInstance<base::ThreadLocalPointer<JingleThreadWrapper> > g_jingle_thread_wrapper = LAZY_INSTANCE_INITIALIZER; // static void JingleThreadWrapper::EnsureForCurrentThread() { if (JingleThreadWrapper::current() == NULL) { g_jingle_thread_wrapper.Get().Set( new JingleThreadWrapper(MessageLoop::current())); } DCHECK_EQ(talk_base::Thread::Current(), current()); } // static JingleThreadWrapper* JingleThreadWrapper::current() { return g_jingle_thread_wrapper.Get().Get(); } JingleThreadWrapper::JingleThreadWrapper(MessageLoop* message_loop) : talk_base::Thread(NULL), message_loop_(message_loop), send_allowed_(false), last_task_id_(0), pending_send_event_(true, false) { DCHECK_EQ(message_loop_, MessageLoop::current()); talk_base::ThreadManager::Instance()->UnwrapCurrentThread(); talk_base::ThreadManager::Instance()->SetCurrentThread(this); talk_base::MessageQueueManager::Instance()->Add(this); message_loop_->AddDestructionObserver(this); WrapCurrent(); } JingleThreadWrapper::~JingleThreadWrapper() { } void JingleThreadWrapper::WillDestroyCurrentMessageLoop() { DCHECK_EQ(talk_base::Thread::Current(), current()); UnwrapCurrent(); g_jingle_thread_wrapper.Get().Set(NULL); talk_base::ThreadManager::Instance()->SetCurrentThread(NULL); talk_base::MessageQueueManager::Instance()->Remove(this); message_loop_->RemoveDestructionObserver(this); delete this; } void JingleThreadWrapper::Post( talk_base::MessageHandler* handler, uint32 message_id, talk_base::MessageData* data, bool time_sensitive) { PostTaskInternal(0, handler, message_id, data); } void JingleThreadWrapper::PostDelayed( int delay_ms, talk_base::MessageHandler* handler, uint32 message_id, talk_base::MessageData* data) { PostTaskInternal(delay_ms, handler, message_id, data); } void JingleThreadWrapper::Clear(talk_base::MessageHandler* handler, uint32 id, talk_base::MessageList* removed) { base::AutoLock auto_lock(lock_); for (MessagesQueue::iterator it = messages_.begin(); it != messages_.end();) { MessagesQueue::iterator next = it; ++next; if (it->second.Match(handler, id)) { if (removed) { removed->push_back(it->second); } else { delete it->second.pdata; } messages_.erase(it); } it = next; } for (std::list<PendingSend*>::iterator it = pending_send_messages_.begin(); it != pending_send_messages_.end();) { std::list<PendingSend*>::iterator next = it; ++next; if ((*it)->message.Match(handler, id)) { if (removed) { removed ->push_back((*it)->message); } else { delete (*it)->message.pdata; } (*it)->done_event.Signal(); pending_send_messages_.erase(it); } it = next; } } void JingleThreadWrapper::Send(talk_base::MessageHandler *handler, uint32 id, talk_base::MessageData *data) { if (fStop_) return; JingleThreadWrapper* current_thread = JingleThreadWrapper::current(); DCHECK(current_thread != NULL) << "Send() can be called only from a " "thread that has JingleThreadWrapper."; talk_base::Message message; message.phandler = handler; message.message_id = id; message.pdata = data; if (current_thread == this) { handler->OnMessage(&message); return; } // Send message from a thread different than |this|. // Allow inter-thread send only from threads that have // |send_allowed_| flag set. DCHECK(current_thread->send_allowed_) << "Send()'ing synchronous " "messages is not allowed from the current thread."; PendingSend pending_send(message); { base::AutoLock auto_lock(lock_); pending_send_messages_.push_back(&pending_send); } // Need to signal |pending_send_event_| here in case the thread is // sending message to another thread. pending_send_event_.Signal(); message_loop_->PostTask(FROM_HERE, base::Bind(&JingleThreadWrapper::ProcessPendingSends, base::Unretained(this))); while (!pending_send.done_event.IsSignaled()) { base::WaitableEvent* events[] = {&pending_send.done_event, &current_thread->pending_send_event_}; size_t event = base::WaitableEvent::WaitMany(events, arraysize(events)); DCHECK(event == 0 || event == 1); if (event == 1) current_thread->ProcessPendingSends(); } } void JingleThreadWrapper::ProcessPendingSends() { while (true) { PendingSend* pending_send = NULL; { base::AutoLock auto_lock(lock_); if (!pending_send_messages_.empty()) { pending_send = pending_send_messages_.front(); pending_send_messages_.pop_front(); } else { // Reset the event while |lock_| is still locked. pending_send_event_.Reset(); break; } } if (pending_send) { pending_send->message.phandler->OnMessage(&pending_send->message); pending_send->done_event.Signal(); } } } void JingleThreadWrapper::PostTaskInternal( int delay_ms, talk_base::MessageHandler* handler, uint32 message_id, talk_base::MessageData* data) { int task_id; talk_base::Message message; message.phandler = handler; message.message_id = message_id; message.pdata = data; { base::AutoLock auto_lock(lock_); task_id = ++last_task_id_; messages_.insert(std::pair<int, talk_base::Message>(task_id, message)); } if (delay_ms <= 0) { message_loop_->PostTask(FROM_HERE, base::Bind(&JingleThreadWrapper::RunTask, base::Unretained(this), task_id)); } else { message_loop_->PostDelayedTask(FROM_HERE, base::Bind(&JingleThreadWrapper::RunTask, base::Unretained(this), task_id), base::TimeDelta::FromMilliseconds(delay_ms)); } } void JingleThreadWrapper::RunTask(int task_id) { bool have_message = false; talk_base::Message message; { base::AutoLock auto_lock(lock_); MessagesQueue::iterator it = messages_.find(task_id); if (it != messages_.end()) { have_message = true; message = it->second; messages_.erase(it); } } if (have_message) { if (message.message_id == talk_base::MQID_DISPOSE) { DCHECK(message.phandler == NULL); delete message.pdata; } else { message.phandler->OnMessage(&message); } } } // All methods below are marked as not reached. See comments in the // header for more details. void JingleThreadWrapper::Quit() { NOTREACHED(); } bool JingleThreadWrapper::IsQuitting() { NOTREACHED(); return false; } void JingleThreadWrapper::Restart() { NOTREACHED(); } bool JingleThreadWrapper::Get(talk_base::Message*, int, bool) { NOTREACHED(); return false; } bool JingleThreadWrapper::Peek(talk_base::Message*, int) { NOTREACHED(); return false; } void JingleThreadWrapper::PostAt(uint32, talk_base::MessageHandler*, uint32, talk_base::MessageData*) { NOTREACHED(); } void JingleThreadWrapper::Dispatch(talk_base::Message* message) { NOTREACHED(); } void JingleThreadWrapper::ReceiveSends() { NOTREACHED(); } int JingleThreadWrapper::GetDelay() { NOTREACHED(); return 0; } void JingleThreadWrapper::Stop() { NOTREACHED(); } void JingleThreadWrapper::Run() { NOTREACHED(); } } // namespace jingle_glue <commit_msg>Currently when talk_base::Thread exists, Clear(NULL) is called from its destructor. But JingleThreadWrapper never gets a chance to remove pending messages from its queue. <commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "jingle/glue/thread_wrapper.h" #include "base/bind.h" #include "base/bind_helpers.h" #include "base/lazy_instance.h" #include "base/threading/thread_local.h" namespace jingle_glue { struct JingleThreadWrapper::PendingSend { PendingSend(const talk_base::Message& message_value) : sending_thread(JingleThreadWrapper::current()), message(message_value), done_event(true, false) { DCHECK(sending_thread); } JingleThreadWrapper* sending_thread; talk_base::Message message; base::WaitableEvent done_event; }; base::LazyInstance<base::ThreadLocalPointer<JingleThreadWrapper> > g_jingle_thread_wrapper = LAZY_INSTANCE_INITIALIZER; // static void JingleThreadWrapper::EnsureForCurrentThread() { if (JingleThreadWrapper::current() == NULL) { g_jingle_thread_wrapper.Get().Set( new JingleThreadWrapper(MessageLoop::current())); } DCHECK_EQ(talk_base::Thread::Current(), current()); } // static JingleThreadWrapper* JingleThreadWrapper::current() { return g_jingle_thread_wrapper.Get().Get(); } JingleThreadWrapper::JingleThreadWrapper(MessageLoop* message_loop) : talk_base::Thread(NULL), message_loop_(message_loop), send_allowed_(false), last_task_id_(0), pending_send_event_(true, false) { DCHECK_EQ(message_loop_, MessageLoop::current()); talk_base::ThreadManager::Instance()->UnwrapCurrentThread(); talk_base::ThreadManager::Instance()->SetCurrentThread(this); talk_base::MessageQueueManager::Instance()->Add(this); message_loop_->AddDestructionObserver(this); WrapCurrent(); } JingleThreadWrapper::~JingleThreadWrapper() { Clear(NULL, talk_base::MQID_ANY, NULL); } void JingleThreadWrapper::WillDestroyCurrentMessageLoop() { DCHECK_EQ(talk_base::Thread::Current(), current()); UnwrapCurrent(); g_jingle_thread_wrapper.Get().Set(NULL); talk_base::ThreadManager::Instance()->SetCurrentThread(NULL); talk_base::MessageQueueManager::Instance()->Remove(this); message_loop_->RemoveDestructionObserver(this); delete this; } void JingleThreadWrapper::Post( talk_base::MessageHandler* handler, uint32 message_id, talk_base::MessageData* data, bool time_sensitive) { PostTaskInternal(0, handler, message_id, data); } void JingleThreadWrapper::PostDelayed( int delay_ms, talk_base::MessageHandler* handler, uint32 message_id, talk_base::MessageData* data) { PostTaskInternal(delay_ms, handler, message_id, data); } void JingleThreadWrapper::Clear(talk_base::MessageHandler* handler, uint32 id, talk_base::MessageList* removed) { base::AutoLock auto_lock(lock_); for (MessagesQueue::iterator it = messages_.begin(); it != messages_.end();) { MessagesQueue::iterator next = it; ++next; if (it->second.Match(handler, id)) { if (removed) { removed->push_back(it->second); } else { delete it->second.pdata; } messages_.erase(it); } it = next; } for (std::list<PendingSend*>::iterator it = pending_send_messages_.begin(); it != pending_send_messages_.end();) { std::list<PendingSend*>::iterator next = it; ++next; if ((*it)->message.Match(handler, id)) { if (removed) { removed ->push_back((*it)->message); } else { delete (*it)->message.pdata; } (*it)->done_event.Signal(); pending_send_messages_.erase(it); } it = next; } } void JingleThreadWrapper::Send(talk_base::MessageHandler *handler, uint32 id, talk_base::MessageData *data) { if (fStop_) return; JingleThreadWrapper* current_thread = JingleThreadWrapper::current(); DCHECK(current_thread != NULL) << "Send() can be called only from a " "thread that has JingleThreadWrapper."; talk_base::Message message; message.phandler = handler; message.message_id = id; message.pdata = data; if (current_thread == this) { handler->OnMessage(&message); return; } // Send message from a thread different than |this|. // Allow inter-thread send only from threads that have // |send_allowed_| flag set. DCHECK(current_thread->send_allowed_) << "Send()'ing synchronous " "messages is not allowed from the current thread."; PendingSend pending_send(message); { base::AutoLock auto_lock(lock_); pending_send_messages_.push_back(&pending_send); } // Need to signal |pending_send_event_| here in case the thread is // sending message to another thread. pending_send_event_.Signal(); message_loop_->PostTask(FROM_HERE, base::Bind(&JingleThreadWrapper::ProcessPendingSends, base::Unretained(this))); while (!pending_send.done_event.IsSignaled()) { base::WaitableEvent* events[] = {&pending_send.done_event, &current_thread->pending_send_event_}; size_t event = base::WaitableEvent::WaitMany(events, arraysize(events)); DCHECK(event == 0 || event == 1); if (event == 1) current_thread->ProcessPendingSends(); } } void JingleThreadWrapper::ProcessPendingSends() { while (true) { PendingSend* pending_send = NULL; { base::AutoLock auto_lock(lock_); if (!pending_send_messages_.empty()) { pending_send = pending_send_messages_.front(); pending_send_messages_.pop_front(); } else { // Reset the event while |lock_| is still locked. pending_send_event_.Reset(); break; } } if (pending_send) { pending_send->message.phandler->OnMessage(&pending_send->message); pending_send->done_event.Signal(); } } } void JingleThreadWrapper::PostTaskInternal( int delay_ms, talk_base::MessageHandler* handler, uint32 message_id, talk_base::MessageData* data) { int task_id; talk_base::Message message; message.phandler = handler; message.message_id = message_id; message.pdata = data; { base::AutoLock auto_lock(lock_); task_id = ++last_task_id_; messages_.insert(std::pair<int, talk_base::Message>(task_id, message)); } if (delay_ms <= 0) { message_loop_->PostTask(FROM_HERE, base::Bind(&JingleThreadWrapper::RunTask, base::Unretained(this), task_id)); } else { message_loop_->PostDelayedTask(FROM_HERE, base::Bind(&JingleThreadWrapper::RunTask, base::Unretained(this), task_id), base::TimeDelta::FromMilliseconds(delay_ms)); } } void JingleThreadWrapper::RunTask(int task_id) { bool have_message = false; talk_base::Message message; { base::AutoLock auto_lock(lock_); MessagesQueue::iterator it = messages_.find(task_id); if (it != messages_.end()) { have_message = true; message = it->second; messages_.erase(it); } } if (have_message) { if (message.message_id == talk_base::MQID_DISPOSE) { DCHECK(message.phandler == NULL); delete message.pdata; } else { message.phandler->OnMessage(&message); } } } // All methods below are marked as not reached. See comments in the // header for more details. void JingleThreadWrapper::Quit() { NOTREACHED(); } bool JingleThreadWrapper::IsQuitting() { NOTREACHED(); return false; } void JingleThreadWrapper::Restart() { NOTREACHED(); } bool JingleThreadWrapper::Get(talk_base::Message*, int, bool) { NOTREACHED(); return false; } bool JingleThreadWrapper::Peek(talk_base::Message*, int) { NOTREACHED(); return false; } void JingleThreadWrapper::PostAt(uint32, talk_base::MessageHandler*, uint32, talk_base::MessageData*) { NOTREACHED(); } void JingleThreadWrapper::Dispatch(talk_base::Message* message) { NOTREACHED(); } void JingleThreadWrapper::ReceiveSends() { NOTREACHED(); } int JingleThreadWrapper::GetDelay() { NOTREACHED(); return 0; } void JingleThreadWrapper::Stop() { NOTREACHED(); } void JingleThreadWrapper::Run() { NOTREACHED(); } } // namespace jingle_glue <|endoftext|>
<commit_before>#include "stdafx.h" #include "directory_description.h" #include "directory_comparer.h" #include "list_directory.h" #include "directory_mismatch.h" void test() { list_directory lister; directory_description* a(lister.read("C:\\Projects\\kitschensync - Kopie")); directory_description* b(lister.read("T:\\kitschensync")); directory_comparer dc; directory_mismatch* diffs = dc.compare_directories(a, b); if (diffs) { const directory_description* newer; const directory_description* older; diffs->dump(); relationship_order ro = diffs->determine_relationship(&newer, &older); if (ro != relationship_order::undefined) { printf("--------------------------------------------\r\n"); printf("%s is newer than %s\r\n", newer->get_path(), older->get_path()); printf("--------------------------------------------\r\n"); DWORD t0 = GetTickCount(); diffs->apply_changes(ro, directory_sync_mode::copy_missing_objects_and_delete_obsolete_ones); printf("Time to sync directories: %ld ms.\r\n", GetTickCount() - t0); } else { printf("*** WARNING: was unable to determine relationship between these two directories...\r\n"); diffs->dump(); } delete diffs; } else { printf("Great: directories are identical!\r\n"); } delete diffs; delete a; delete b; } int _tmain(int, _TCHAR* []) { test(); #ifdef _DEBUG _CrtDumpMemoryLeaks(); #endif return 0; } <commit_msg>Fixed access-denied issues<commit_after>#include "stdafx.h" #include "directory_description.h" #include "directory_comparer.h" #include "list_directory.h" #include "directory_mismatch.h" void test() { list_directory lister; directory_description* a(lister.read("C:\\Projects\\kitschensync - Kopie")); directory_description* b(lister.read("T:\\kitschensync")); directory_comparer dc; directory_mismatch* diffs = dc.compare_directories(a, b); if (diffs) { const directory_description* newer; const directory_description* older; diffs->dump(); relationship_order ro = diffs->determine_relationship(&newer, &older); if (ro != relationship_order::undefined) { printf("--------------------------------------------\r\n"); printf("%s is newer than %s\r\n", newer->get_path(), older->get_path()); printf("--------------------------------------------\r\n"); DWORD t0 = GetTickCount(); diffs->apply_changes(ro, directory_sync_mode::copy_missing_objects_and_delete_obsolete_ones); printf("Time to sync directories: %ld ms.\r\n", GetTickCount() - t0); } else { printf("*** WARNING: was unable to determine relationship between these two directories...\r\n"); diffs->dump(); } delete diffs; diffs = nullptr; } else { printf("Great: directories are identical!\r\n"); } delete a; delete b; } int _tmain(int, _TCHAR* []) { test(); #ifdef _DEBUG _CrtDumpMemoryLeaks(); #endif getchar(); return 0; } <|endoftext|>
<commit_before> #include <cstring> #include <stdexcept> #include <sys/mman.h> #include <xf86drm.h> #include <xf86drmMode.h> #include <fcntl.h> #include <unistd.h> #include <drm_fourcc.h> #include <drm.h> #include <drm_mode.h> #include <kms++/kms++.h> #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0])) using namespace std; namespace kms { DumbFramebuffer::DumbFramebuffer(Card &card, uint32_t width, uint32_t height, const string& fourcc) :DumbFramebuffer(card, width, height, FourCCToPixelFormat(fourcc)) { } DumbFramebuffer::DumbFramebuffer(Card& card, uint32_t width, uint32_t height, PixelFormat format) :Framebuffer(card, width, height), m_format(format) { Create(); } DumbFramebuffer::~DumbFramebuffer() { Destroy(); } void DumbFramebuffer::Create() { int r; const PixelFormatInfo& format_info = get_pixel_format_info(m_format); m_num_planes = format_info.num_planes; for (int i = 0; i < format_info.num_planes; ++i) { const PixelFormatPlaneInfo& pi = format_info.planes[i]; FramebufferPlane& plane = m_planes[i]; /* create dumb buffer */ struct drm_mode_create_dumb creq = drm_mode_create_dumb(); creq.width = width(); creq.height = height() / pi.ysub; creq.bpp = pi.bitspp; r = drmIoctl(card().fd(), DRM_IOCTL_MODE_CREATE_DUMB, &creq); if (r) throw invalid_argument(string("DRM_IOCTL_MODE_CREATE_DUMB failed") + strerror(errno)); plane.handle = creq.handle; plane.stride = creq.pitch; plane.size = creq.height * creq.pitch; plane.offset = 0; plane.map = 0; plane.prime_fd = -1; } /* create framebuffer object for the dumb-buffer */ uint32_t bo_handles[4] = { m_planes[0].handle, m_planes[1].handle }; uint32_t pitches[4] = { m_planes[0].stride, m_planes[1].stride }; uint32_t offsets[4] = { m_planes[0].offset, m_planes[1].offset }; uint32_t id; r = drmModeAddFB2(card().fd(), width(), height(), (uint32_t)format(), bo_handles, pitches, offsets, &id, 0); if (r) throw invalid_argument(string("drmModeAddFB2 failed: ") + strerror(errno)); set_id(id); } void DumbFramebuffer::Destroy() { /* delete framebuffer */ drmModeRmFB(card().fd(), id()); for (uint i = 0; i < m_num_planes; ++i) { FramebufferPlane& plane = m_planes[i]; /* unmap buffer */ if (plane.map) munmap(plane.map, plane.size); /* delete dumb buffer */ struct drm_mode_destroy_dumb dreq = drm_mode_destroy_dumb(); dreq.handle = plane.handle; drmIoctl(card().fd(), DRM_IOCTL_MODE_DESTROY_DUMB, &dreq); if (plane.prime_fd >= 0) ::close(plane.prime_fd); } } uint8_t* DumbFramebuffer::map(unsigned plane) { FramebufferPlane& p = m_planes[plane]; if (p.map) return p.map; /* prepare buffer for memory mapping */ struct drm_mode_map_dumb mreq = drm_mode_map_dumb(); mreq.handle = p.handle; int r = drmIoctl(card().fd(), DRM_IOCTL_MODE_MAP_DUMB, &mreq); if (r) throw invalid_argument(string("DRM_IOCTL_MODE_MAP_DUMB failed") + strerror(errno)); /* perform actual memory mapping */ p.map = (uint8_t *)mmap(0, p.size, PROT_READ | PROT_WRITE, MAP_SHARED, card().fd(), mreq.offset); if (p.map == MAP_FAILED) throw invalid_argument(string("mmap failed: ") + strerror(errno)); return p.map; } int DumbFramebuffer::prime_fd(unsigned int plane) { if (m_planes[plane].prime_fd >= 0) return m_planes[plane].prime_fd; int r = drmPrimeHandleToFD(card().fd(), m_planes[plane].handle, DRM_CLOEXEC, &m_planes[plane].prime_fd); if (r) throw std::runtime_error("drmPrimeHandleToFD failed"); return m_planes[plane].prime_fd; } } <commit_msg>Fix error prints<commit_after> #include <cstring> #include <stdexcept> #include <sys/mman.h> #include <xf86drm.h> #include <xf86drmMode.h> #include <fcntl.h> #include <unistd.h> #include <drm_fourcc.h> #include <drm.h> #include <drm_mode.h> #include <kms++/kms++.h> #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0])) using namespace std; namespace kms { DumbFramebuffer::DumbFramebuffer(Card &card, uint32_t width, uint32_t height, const string& fourcc) :DumbFramebuffer(card, width, height, FourCCToPixelFormat(fourcc)) { } DumbFramebuffer::DumbFramebuffer(Card& card, uint32_t width, uint32_t height, PixelFormat format) :Framebuffer(card, width, height), m_format(format) { Create(); } DumbFramebuffer::~DumbFramebuffer() { Destroy(); } void DumbFramebuffer::Create() { int r; const PixelFormatInfo& format_info = get_pixel_format_info(m_format); m_num_planes = format_info.num_planes; for (int i = 0; i < format_info.num_planes; ++i) { const PixelFormatPlaneInfo& pi = format_info.planes[i]; FramebufferPlane& plane = m_planes[i]; /* create dumb buffer */ struct drm_mode_create_dumb creq = drm_mode_create_dumb(); creq.width = width(); creq.height = height() / pi.ysub; creq.bpp = pi.bitspp; r = drmIoctl(card().fd(), DRM_IOCTL_MODE_CREATE_DUMB, &creq); if (r) throw invalid_argument(string("DRM_IOCTL_MODE_CREATE_DUMB failed: ") + strerror(errno)); plane.handle = creq.handle; plane.stride = creq.pitch; plane.size = creq.height * creq.pitch; plane.offset = 0; plane.map = 0; plane.prime_fd = -1; } /* create framebuffer object for the dumb-buffer */ uint32_t bo_handles[4] = { m_planes[0].handle, m_planes[1].handle }; uint32_t pitches[4] = { m_planes[0].stride, m_planes[1].stride }; uint32_t offsets[4] = { m_planes[0].offset, m_planes[1].offset }; uint32_t id; r = drmModeAddFB2(card().fd(), width(), height(), (uint32_t)format(), bo_handles, pitches, offsets, &id, 0); if (r) throw invalid_argument(string("drmModeAddFB2 failed: ") + strerror(errno)); set_id(id); } void DumbFramebuffer::Destroy() { /* delete framebuffer */ drmModeRmFB(card().fd(), id()); for (uint i = 0; i < m_num_planes; ++i) { FramebufferPlane& plane = m_planes[i]; /* unmap buffer */ if (plane.map) munmap(plane.map, plane.size); /* delete dumb buffer */ struct drm_mode_destroy_dumb dreq = drm_mode_destroy_dumb(); dreq.handle = plane.handle; drmIoctl(card().fd(), DRM_IOCTL_MODE_DESTROY_DUMB, &dreq); if (plane.prime_fd >= 0) ::close(plane.prime_fd); } } uint8_t* DumbFramebuffer::map(unsigned plane) { FramebufferPlane& p = m_planes[plane]; if (p.map) return p.map; /* prepare buffer for memory mapping */ struct drm_mode_map_dumb mreq = drm_mode_map_dumb(); mreq.handle = p.handle; int r = drmIoctl(card().fd(), DRM_IOCTL_MODE_MAP_DUMB, &mreq); if (r) throw invalid_argument(string("DRM_IOCTL_MODE_MAP_DUMB failed: ") + strerror(errno)); /* perform actual memory mapping */ p.map = (uint8_t *)mmap(0, p.size, PROT_READ | PROT_WRITE, MAP_SHARED, card().fd(), mreq.offset); if (p.map == MAP_FAILED) throw invalid_argument(string("mmap failed: ") + strerror(errno)); return p.map; } int DumbFramebuffer::prime_fd(unsigned int plane) { if (m_planes[plane].prime_fd >= 0) return m_planes[plane].prime_fd; int r = drmPrimeHandleToFD(card().fd(), m_planes[plane].handle, DRM_CLOEXEC, &m_planes[plane].prime_fd); if (r) throw std::runtime_error("drmPrimeHandleToFD failed"); return m_planes[plane].prime_fd; } } <|endoftext|>
<commit_before>#include "pen.h" #include "renderer.h" #include "timer.h" #include "file_system.h" #include "pen_string.h" #include "loader.h" #include "dev_ui.h" #include "camera.h" #include "debug_render.h" #include "pmfx.h" #include "pen_json.h" #include "hash.h" #include "str_utilities.h" #include "input.h" #include "ces/ces_scene.h" #include "ces/ces_resources.h" #include "ces/ces_editor.h" #include "ces/ces_utilities.h" using namespace put; using namespace ces; pen::window_creation_params pen_window { 1280, //width 720, //height 4, //MSAA samples "rigid_body_primitives" //window title / process name }; namespace physics { extern PEN_THREAD_RETURN physics_thread_main( void* params ); } void create_physics_objects( ces::entity_scene* scene ) { clear_scene( scene ); material_resource* default_material = get_material_resource( PEN_HASH( "default_material" ) ); geometry_resource* box = get_geometry_resource(PEN_HASH("cube")); geometry_resource* cylinder = get_geometry_resource( PEN_HASH( "cylinder" ) ); geometry_resource* capsule = get_geometry_resource( PEN_HASH( "capsule" ) ); geometry_resource* sphere = get_geometry_resource( PEN_HASH( "sphere" ) ); geometry_resource* cone = get_geometry_resource( PEN_HASH( "cone" ) ); //add light u32 light = get_new_node( scene ); scene->names[light] = "front_light"; scene->id_name[light] = PEN_HASH( "front_light" ); scene->lights[light].colour = vec3f::one(); scene->lights[light].direction = vec3f::one(); scene->lights[light].type = LIGHT_TYPE_DIR;f scene->transforms->translation = vec3f::zero(); scene->transforms->rotation = quat(); scene->transforms->scale = vec3f::one(); scene->entities[light] |= CMP_LIGHT; scene->entities[light] |= CMP_TRANSFORM; //ground u32 ground = get_new_node( scene ); scene->names[ground] = "ground"; scene->transforms[ground].translation = vec3f::zero(); scene->transforms[ground].rotation = quat(); scene->transforms[ground].scale = vec3f( 50.0f, 1.0f, 50.0f ); scene->entities[ground] |= CMP_TRANSFORM; scene->parents[ground] = ground; instantiate_geometry( box, scene, ground ); instantiate_material( default_material, scene, ground ); instantiate_model_cbuffer( scene, ground ); scene->physics_data[ground].rigid_body.shape = physics::BOX; scene->physics_data[ground].rigid_body.mass = 0.0f; instantiate_rigid_body( scene, ground ); vec3f start_positions[] = { vec3f( -20.0f, 10.0f, -20.0f ), vec3f( 20.0f, 10.0f, 20.0f ), vec3f( -20.0f, 10.0f, 20.0f ), vec3f( 20.0f, 10.0f, -20.0f ), vec3f( 0.0f, 10.0f, 0.0f ), }; const c8* primitive_names[] = { "box", "cylinder", "capsule", "cone", "sphere" }; u32 primitive_types[] = { physics::BOX, physics::CYLINDER, physics::CAPSULE, physics::CONE, physics::SPHERE }; geometry_resource* primitive_resources[] = { box, cylinder, capsule, cone, sphere }; s32 num_prims = 5; for (s32 p = 0; p < num_prims; ++p) { //add stack of cubes vec3f start_pos = start_positions[p]; vec3f cur_pos = start_pos; for (s32 i = 0; i < 4; ++i) { cur_pos.y = start_pos.y; for (s32 j = 0; j < 4; ++j) { cur_pos.x = start_pos.x; for (s32 k = 0; k < 4; ++k) { u32 new_prim = get_new_node( scene ); scene->names[new_prim] = primitive_names[p]; scene->names[new_prim].appendf( "%i", new_prim ); scene->transforms[new_prim].rotation = quat(); scene->transforms[new_prim].scale = vec3f::one(); scene->transforms[new_prim].translation = cur_pos; scene->entities[new_prim] |= CMP_TRANSFORM; scene->parents[new_prim] = new_prim; instantiate_geometry( primitive_resources[p], scene, new_prim ); instantiate_material( default_material, scene, new_prim ); instantiate_model_cbuffer( scene, new_prim ); scene->physics_data[new_prim].rigid_body.shape = primitive_types[p]; scene->physics_data[new_prim].rigid_body.mass = 1.0f; instantiate_rigid_body( scene, new_prim ); cur_pos.x += 2.5f; } cur_pos.y += 2.5f; } cur_pos.z += 2.5f; } } } PEN_THREAD_RETURN pen::game_entry( void* params ) { //unpack the params passed to the thread and signal to the engine it ok to proceed pen::job_thread_params* job_params = (pen::job_thread_params*)params; pen::job_thread* p_thread_info = job_params->job_thread_info; pen::threads_semaphore_signal(p_thread_info->p_sem_continue, 1); pen::threads_create_job( physics::physics_thread_main, 1024*10, nullptr, pen::THREAD_START_DETACHED ); put::dev_ui::init(); put::dbg::init(); //create main camera and controller put::camera main_camera; put::camera_create_perspective( &main_camera, 60.0f, (f32)pen_window.width / (f32)pen_window.height, 0.1f, 1000.0f ); put::camera_controller cc; cc.camera = &main_camera; cc.update_function = &ces::update_model_viewer_camera; cc.name = "model_viewer_camera"; cc.id_name = PEN_HASH(cc.name.c_str()); //create the main scene and controller put::ces::entity_scene* main_scene = put::ces::create_scene("main_scene"); put::ces::editor_init( main_scene ); put::scene_controller sc; sc.scene = main_scene; sc.update_function = &ces::update_model_viewer_scene; sc.name = "main_scene"; sc.camera = &main_camera; sc.id_name = PEN_HASH(sc.name.c_str()); //create view renderers put::scene_view_renderer svr_main; svr_main.name = "ces_render_scene"; svr_main.id_name = PEN_HASH(svr_main.name.c_str()); svr_main.render_function = &ces::render_scene_view; put::scene_view_renderer svr_editor; svr_editor.name = "ces_render_editor"; svr_editor.id_name = PEN_HASH(svr_editor.name.c_str()); svr_editor.render_function = &ces::render_scene_editor; pmfx::register_scene_view_renderer(svr_main); pmfx::register_scene_view_renderer(svr_editor); pmfx::register_scene(sc); pmfx::register_camera(cc); pmfx::init("data/configs/editor_renderer.json"); create_physics_objects( main_scene ); bool enable_dev_ui = true; f32 frame_time = 0.0f; while( 1 ) { static u32 frame_timer = pen::timer_create("frame_timer"); pen::timer_start(frame_timer); put::dev_ui::new_frame(); pmfx::update(); pmfx::render(); pmfx::show_dev_ui(); if( enable_dev_ui ) { put::dev_ui::console(); put::dev_ui::render(); } if( pen::input_is_key_held(PENK_MENU) && pen::input_is_key_pressed(PENK_D) ) enable_dev_ui = !enable_dev_ui; frame_time = pen::timer_elapsed_ms(frame_timer); pen::renderer_present(); pen::renderer_consume_cmd_buffer(); pmfx::poll_for_changes(); put::poll_hot_loader(); //msg from the engine we want to terminate if( pen::threads_semaphore_try_wait( p_thread_info->p_sem_exit ) ) break; } ces::destroy_scene(main_scene); ces::editor_shutdown(); //clean up mem here put::pmfx::shutdown(); put::dbg::shutdown(); put::dev_ui::shutdown(); pen::renderer_consume_cmd_buffer(); //signal to the engine the thread has finished pen::threads_semaphore_signal( p_thread_info->p_sem_terminated, 1); return PEN_THREAD_OK; } <commit_msg>fix texture dependencies on win32, tidy up forward lit shader to handle vertex colours and albedo texture<commit_after>#include "pen.h" #include "renderer.h" #include "timer.h" #include "file_system.h" #include "pen_string.h" #include "loader.h" #include "dev_ui.h" #include "camera.h" #include "debug_render.h" #include "pmfx.h" #include "pen_json.h" #include "hash.h" #include "str_utilities.h" #include "input.h" #include "ces/ces_scene.h" #include "ces/ces_resources.h" #include "ces/ces_editor.h" #include "ces/ces_utilities.h" using namespace put; using namespace ces; pen::window_creation_params pen_window { 1280, //width 720, //height 4, //MSAA samples "rigid_body_primitives" //window title / process name }; namespace physics { extern PEN_THREAD_RETURN physics_thread_main( void* params ); } void create_physics_objects( ces::entity_scene* scene ) { clear_scene( scene ); material_resource* default_material = get_material_resource( PEN_HASH( "default_material" ) ); geometry_resource* box = get_geometry_resource(PEN_HASH("cube")); geometry_resource* cylinder = get_geometry_resource( PEN_HASH( "cylinder" ) ); geometry_resource* capsule = get_geometry_resource( PEN_HASH( "capsule" ) ); geometry_resource* sphere = get_geometry_resource( PEN_HASH( "sphere" ) ); geometry_resource* cone = get_geometry_resource( PEN_HASH( "cone" ) ); //add light u32 light = get_new_node( scene ); scene->names[light] = "front_light"; scene->id_name[light] = PEN_HASH( "front_light" ); scene->lights[light].colour = vec3f::one(); scene->lights[light].direction = vec3f::one(); scene->lights[light].type = LIGHT_TYPE_DIR; scene->transforms->translation = vec3f::zero(); scene->transforms->rotation = quat(); scene->transforms->scale = vec3f::one(); scene->entities[light] |= CMP_LIGHT; scene->entities[light] |= CMP_TRANSFORM; //ground u32 ground = get_new_node( scene ); scene->names[ground] = "ground"; scene->transforms[ground].translation = vec3f::zero(); scene->transforms[ground].rotation = quat(); scene->transforms[ground].scale = vec3f( 50.0f, 1.0f, 50.0f ); scene->entities[ground] |= CMP_TRANSFORM; scene->parents[ground] = ground; instantiate_geometry( box, scene, ground ); instantiate_material( default_material, scene, ground ); instantiate_model_cbuffer( scene, ground ); scene->physics_data[ground].rigid_body.shape = physics::BOX; scene->physics_data[ground].rigid_body.mass = 0.0f; instantiate_rigid_body( scene, ground ); vec3f start_positions[] = { vec3f( -20.0f, 10.0f, -20.0f ), vec3f( 20.0f, 10.0f, 20.0f ), vec3f( -20.0f, 10.0f, 20.0f ), vec3f( 20.0f, 10.0f, -20.0f ), vec3f( 0.0f, 10.0f, 0.0f ), }; const c8* primitive_names[] = { "box", "cylinder", "capsule", "cone", "sphere" }; u32 primitive_types[] = { physics::BOX, physics::CYLINDER, physics::CAPSULE, physics::CONE, physics::SPHERE }; geometry_resource* primitive_resources[] = { box, cylinder, capsule, cone, sphere }; s32 num_prims = 5; for (s32 p = 0; p < num_prims; ++p) { //add stack of cubes vec3f start_pos = start_positions[p]; vec3f cur_pos = start_pos; for (s32 i = 0; i < 4; ++i) { cur_pos.y = start_pos.y; for (s32 j = 0; j < 4; ++j) { cur_pos.x = start_pos.x; for (s32 k = 0; k < 4; ++k) { u32 new_prim = get_new_node( scene ); scene->names[new_prim] = primitive_names[p]; scene->names[new_prim].appendf( "%i", new_prim ); scene->transforms[new_prim].rotation = quat(); scene->transforms[new_prim].scale = vec3f::one(); scene->transforms[new_prim].translation = cur_pos; scene->entities[new_prim] |= CMP_TRANSFORM; scene->parents[new_prim] = new_prim; instantiate_geometry( primitive_resources[p], scene, new_prim ); instantiate_material( default_material, scene, new_prim ); instantiate_model_cbuffer( scene, new_prim ); scene->physics_data[new_prim].rigid_body.shape = primitive_types[p]; scene->physics_data[new_prim].rigid_body.mass = 1.0f; instantiate_rigid_body( scene, new_prim ); cur_pos.x += 2.5f; } cur_pos.y += 2.5f; } cur_pos.z += 2.5f; } } } PEN_THREAD_RETURN pen::game_entry( void* params ) { //unpack the params passed to the thread and signal to the engine it ok to proceed pen::job_thread_params* job_params = (pen::job_thread_params*)params; pen::job_thread* p_thread_info = job_params->job_thread_info; pen::threads_semaphore_signal(p_thread_info->p_sem_continue, 1); pen::threads_create_job( physics::physics_thread_main, 1024*10, nullptr, pen::THREAD_START_DETACHED ); put::dev_ui::init(); put::dbg::init(); //create main camera and controller put::camera main_camera; put::camera_create_perspective( &main_camera, 60.0f, (f32)pen_window.width / (f32)pen_window.height, 0.1f, 1000.0f ); put::camera_controller cc; cc.camera = &main_camera; cc.update_function = &ces::update_model_viewer_camera; cc.name = "model_viewer_camera"; cc.id_name = PEN_HASH(cc.name.c_str()); //create the main scene and controller put::ces::entity_scene* main_scene = put::ces::create_scene("main_scene"); put::ces::editor_init( main_scene ); put::scene_controller sc; sc.scene = main_scene; sc.update_function = &ces::update_model_viewer_scene; sc.name = "main_scene"; sc.camera = &main_camera; sc.id_name = PEN_HASH(sc.name.c_str()); //create view renderers put::scene_view_renderer svr_main; svr_main.name = "ces_render_scene"; svr_main.id_name = PEN_HASH(svr_main.name.c_str()); svr_main.render_function = &ces::render_scene_view; put::scene_view_renderer svr_editor; svr_editor.name = "ces_render_editor"; svr_editor.id_name = PEN_HASH(svr_editor.name.c_str()); svr_editor.render_function = &ces::render_scene_editor; pmfx::register_scene_view_renderer(svr_main); pmfx::register_scene_view_renderer(svr_editor); pmfx::register_scene(sc); pmfx::register_camera(cc); pmfx::init("data/configs/editor_renderer.json"); create_physics_objects( main_scene ); bool enable_dev_ui = true; f32 frame_time = 0.0f; while( 1 ) { static u32 frame_timer = pen::timer_create("frame_timer"); pen::timer_start(frame_timer); put::dev_ui::new_frame(); pmfx::update(); pmfx::render(); pmfx::show_dev_ui(); if( enable_dev_ui ) { put::dev_ui::console(); put::dev_ui::render(); } if( pen::input_is_key_held(PENK_MENU) && pen::input_is_key_pressed(PENK_D) ) enable_dev_ui = !enable_dev_ui; frame_time = pen::timer_elapsed_ms(frame_timer); pen::renderer_present(); pen::renderer_consume_cmd_buffer(); pmfx::poll_for_changes(); put::poll_hot_loader(); //msg from the engine we want to terminate if( pen::threads_semaphore_try_wait( p_thread_info->p_sem_exit ) ) break; } ces::destroy_scene(main_scene); ces::editor_shutdown(); //clean up mem here put::pmfx::shutdown(); put::dbg::shutdown(); put::dev_ui::shutdown(); pen::renderer_consume_cmd_buffer(); //signal to the engine the thread has finished pen::threads_semaphore_signal( p_thread_info->p_sem_terminated, 1); return PEN_THREAD_OK; } <|endoftext|>
<commit_before>/* Copyright 2007-2015 QReal Research Group * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "generatorBase/semanticTree/switchNode.h" #include <qrutils/stringUtils.h> using namespace generatorBase::semantics; using namespace qReal; SwitchNode::SwitchNode(const Id &idBinded, QObject *parent) : NonZoneNode(idBinded, parent) , mDefaultBranch(nullptr) , mBranchesMerged(false) , mGenerateIfs(false) { } void SwitchNode::addBranch(const QString &value, SemanticNode * const node) { ZoneNode * const zone = new ZoneNode(this); zone->setParentNode(this); bind(value, zone); if (node) { zone->appendChild(node); } } void SwitchNode::mergeBranch(const QString &value, NonZoneNode * const node) { Q_ASSERT(node); bind(value, node->parentZone()); } bool SwitchNode::branchesMerged() const { return mBranchesMerged; } void SwitchNode::setBranchesMergedFlag() { mBranchesMerged = true; } void SwitchNode::setGenerateIfs() { mGenerateIfs = true; } QString SwitchNode::toStringImpl(GeneratorCustomizer &customizer, int indent, const QString &indentString) const { QString result; bool isHead = true; for (ZoneNode * const zone : mBranches.values().toSet()) { if (zone == mDefaultBranch) { // Branches merged with default on the diagram will be merged with it in code too continue; } result += generatePart(customizer, indent, indentString, zone, isHead ? customizer.factory()->switchHeadGenerator(mId, customizer, mBranches.keys(zone), mGenerateIfs || !customizer.supportsSwitchUnstableToBreaks()) : customizer.factory()->switchMiddleGenerator(mId, customizer, mBranches.keys(zone), mGenerateIfs || !customizer.supportsSwitchUnstableToBreaks())); isHead = false; } if (result.isEmpty()) { // Then all branches lead to one block, we may ignore switch construction. return mDefaultBranch->toString(customizer, indent, indentString); } result += generatePart(customizer, indent, indentString, mDefaultBranch , customizer.factory()->switchDefaultGenerator(mId, customizer, mGenerateIfs || !customizer.supportsSwitchUnstableToBreaks())); return result; } void SwitchNode::bind(const QString &value, ZoneNode *zone) { if (value.isEmpty()) { mDefaultBranch = zone; } else { mBranches[value] = zone; } } QString SwitchNode::generatePart(generatorBase::GeneratorCustomizer &customizer , int indent , const QString &indentString , ZoneNode * const zone , generatorBase::simple::AbstractSimpleGenerator *generator) const { return utils::StringUtils::addIndent(generator->generate() .replace("@@BODY@@", zone->toString(customizer, indent + 1, indentString)), indent, indentString); } QLinkedList<SemanticNode *> SwitchNode::children() const { QLinkedList<SemanticNode *> result; for (ZoneNode * const zone : mBranches.values().toSet()) { result << zone; } if (mDefaultBranch) { result << mDefaultBranch; } return result; } <commit_msg>Style guide fixes<commit_after>/* Copyright 2007-2015 QReal Research Group * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "generatorBase/semanticTree/switchNode.h" #include <qrutils/stringUtils.h> using namespace generatorBase::semantics; using namespace qReal; SwitchNode::SwitchNode(const Id &idBinded, QObject *parent) : NonZoneNode(idBinded, parent) , mDefaultBranch(nullptr) , mBranchesMerged(false) , mGenerateIfs(false) { } void SwitchNode::addBranch(const QString &value, SemanticNode * const node) { ZoneNode * const zone = new ZoneNode(this); zone->setParentNode(this); bind(value, zone); if (node) { zone->appendChild(node); } } void SwitchNode::mergeBranch(const QString &value, NonZoneNode * const node) { Q_ASSERT(node); bind(value, node->parentZone()); } bool SwitchNode::branchesMerged() const { return mBranchesMerged; } void SwitchNode::setBranchesMergedFlag() { mBranchesMerged = true; } void SwitchNode::setGenerateIfs() { mGenerateIfs = true; } QString SwitchNode::toStringImpl(GeneratorCustomizer &customizer, int indent, const QString &indentString) const { QString result; bool isHead = true; for (ZoneNode * const zone : mBranches.values().toSet()) { if (zone == mDefaultBranch) { // Branches merged with default on the diagram will be merged with it in code too continue; } result += generatePart(customizer, indent, indentString, zone, isHead ? customizer.factory()->switchHeadGenerator(mId, customizer, mBranches.keys(zone) , mGenerateIfs || !customizer.supportsSwitchUnstableToBreaks()) : customizer.factory()->switchMiddleGenerator(mId, customizer, mBranches.keys(zone) , mGenerateIfs || !customizer.supportsSwitchUnstableToBreaks())); isHead = false; } if (result.isEmpty()) { // Then all branches lead to one block, we may ignore switch construction. return mDefaultBranch->toString(customizer, indent, indentString); } result += generatePart(customizer, indent, indentString, mDefaultBranch , customizer.factory()->switchDefaultGenerator(mId, customizer , mGenerateIfs || !customizer.supportsSwitchUnstableToBreaks())); return result; } void SwitchNode::bind(const QString &value, ZoneNode *zone) { if (value.isEmpty()) { mDefaultBranch = zone; } else { mBranches[value] = zone; } } QString SwitchNode::generatePart(generatorBase::GeneratorCustomizer &customizer , int indent , const QString &indentString , ZoneNode * const zone , generatorBase::simple::AbstractSimpleGenerator *generator) const { return utils::StringUtils::addIndent(generator->generate() .replace("@@BODY@@", zone->toString(customizer, indent + 1, indentString)), indent, indentString); } QLinkedList<SemanticNode *> SwitchNode::children() const { QLinkedList<SemanticNode *> result; for (ZoneNode * const zone : mBranches.values().toSet()) { result << zone; } if (mDefaultBranch) { result << mDefaultBranch; } return result; } <|endoftext|>
<commit_before>/* Copyright (C) 2005 by Andrew Mann Based in part on work by Matt Reda This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "cssysdef.h" #include "csutil/event.h" #include "csutil/sysfunc.h" #include "iutil/cfgfile.h" #include "iutil/cmdline.h" #include "iutil/comp.h" #include "iutil/event.h" #include "iutil/eventh.h" #include "iutil/eventh.h" #include "iutil/eventq.h" #include "iutil/objreg.h" #include "iutil/plugin.h" #include "iutil/virtclk.h" #include "ivaria/reporter.h" #include "../../renderer.h" #include "isndsys/ss_driver.h" #include "isndsys/ss_renderer.h" #include "driver_coreaudio.h" CS_IMPLEMENT_PLUGIN CS_PLUGIN_NAMESPACE_BEGIN(SndSysCOREAUDIO) { SCF_IMPLEMENT_FACTORY (csSndSysDriverCoreAudio) SCF_IMPLEMENT_IBASE(csSndSysDriverCoreAudio) SCF_IMPLEMENTS_INTERFACE(iSndSysSoftwareDriver) SCF_IMPLEMENTS_EMBEDDED_INTERFACE(iComponent) SCF_IMPLEMENT_IBASE_END; SCF_IMPLEMENT_EMBEDDED_IBASE (csSndSysDriverCoreAudio::eiComponent) SCF_IMPLEMENTS_INTERFACE (iComponent) SCF_IMPLEMENT_EMBEDDED_IBASE_END // CoreAudio static IO procedure wrapper static OSStatus StaticAudioProc(AudioDeviceID inDevice, const AudioTimeStamp *inNow, const AudioBufferList *inInputData, const AudioTimeStamp *inInputTime, AudioBufferList *outOutputData, const AudioTimeStamp *inOutputTime, void *inClientData) { csSndSysDriverCoreAudio *p_audio=(csSndSysDriverCoreAudio *)inClientData; return p_audio->AudioProc(inDevice, inNow, inInputData, inInputTime, outOutputData, inOutputTime); } csSndSysDriverCoreAudio::csSndSysDriverCoreAudio(iBase* piBase) : object_reg(0), attached_renderer(0), running(false) { SCF_CONSTRUCT_IBASE(piBase); SCF_CONSTRUCT_EMBEDDED_IBASE(scfiComponent); convert_buffer = 0; } csSndSysDriverCoreAudio::~csSndSysDriverCoreAudio() { SCF_DESTRUCT_EMBEDDED_IBASE(scfiComponent); SCF_DESTRUCT_IBASE(); free(convert_buffer); } void csSndSysDriverCoreAudio::Report(int severity, const char* msg, ...) { va_list arg; va_start (arg, msg); csRef<iReporter> reporter = CS_QUERY_REGISTRY(object_reg, iReporter); if (reporter) { reporter->ReportV (severity, "crystalspace.sndsys.driver.software.coreaudio", msg, arg); } else { csPrintfV (msg, arg); csPrintf ("\n"); } va_end (arg); } bool csSndSysDriverCoreAudio::Initialize (iObjectRegistry* r) { object_reg = r; Report (CS_REPORTER_SEVERITY_DEBUG, "Sound System: CoreAudio driver for software sound renderer initialized."); return true; } bool csSndSysDriverCoreAudio::Open (csSndSysRendererSoftware *renderer, csSndSysSoundFormat *requested_format) { uint32 propertysize, buffersize; AudioStreamBasicDescription outStreamDesc; //description of the data that CS will be providing AudioStreamBasicDescription inStreamDesc; OSStatus status; Report(CS_REPORTER_SEVERITY_DEBUG, "Sound System: CoreAudio Driver: Open()"); attached_renderer = renderer; // Retrieve the output device ID - this is almost verbatim from the available // sample code propertysize = sizeof(outputDeviceID); status = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice, (UInt32*)&propertysize, &outputDeviceID); if (status) { Report(CS_REPORTER_SEVERITY_ERROR, "Failed to obtain default CoreAudio output device. Return of %d.", (int)status); return false; } if (outputDeviceID == kAudioDeviceUnknown) { Report(CS_REPORTER_SEVERITY_ERROR, "Failed to obtain default CoreAudio output device. " "Resulting ID is kAudioDeviceUnknown."); return false; } // Set buffer size - 1/10th of a second buffer of floats propertysize = sizeof(buffersize); buffersize = requested_format->Freq * sizeof(float) * requested_format->Channels / 10; convert_size = requested_format->Freq / 10; convert_buffer = malloc(convert_size * requested_format->Channels * requested_format->Bits/8); status = AudioDeviceSetProperty(outputDeviceID, 0, 0, false, kAudioDevicePropertyBufferSize, propertysize, &buffersize); if (status) { Report(CS_REPORTER_SEVERITY_ERROR, "Failed to set buffersize to %d bytes for CoreAudio output device. " "Return of %d.", buffersize, (int)status); free(convert_buffer); return false; } // Get stream information propertysize = sizeof(outStreamDesc); status = AudioDeviceGetProperty(outputDeviceID, 0, false, kAudioDevicePropertyStreamFormat, (UInt32*)&propertysize, &outStreamDesc); if (status != 0) { Report(CS_REPORTER_SEVERITY_ERROR, "Failed to retrieve output stream description from CoreAudio " "output device. Return of %d.", (int)status); return false; } //get another copy to create the input format spec status = AudioDeviceGetProperty(outputDeviceID, 0, false, kAudioDevicePropertyStreamFormat, (UInt32*)&propertysize, &inStreamDesc); // Set up source stream description for an AudioConverter to do its thang inStreamDesc.mSampleRate = requested_format->Freq; inStreamDesc.mFormatID = kAudioFormatLinearPCM; inStreamDesc.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked ; if ((requested_format->Flags & CSSNDSYS_SAMPLE_ENDIAN_MASK) == CSSNDSYS_SAMPLE_BIG_ENDIAN) inStreamDesc.mFormatFlags |= kAudioFormatFlagIsBigEndian; inStreamDesc.mChannelsPerFrame = requested_format->Channels; inStreamDesc.mBitsPerChannel = requested_format->Bits; inStreamDesc.mFramesPerPacket = 1; inStreamDesc.mBytesPerFrame = requested_format->Channels * requested_format->Bits / 8; // The bytes per packet is purely a product of bytes per frame and frames per // packet since we don't have any padding in a packet here inStreamDesc.mBytesPerPacket = inStreamDesc.mFramesPerPacket * inStreamDesc.mBytesPerFrame; /* inStreamDesc.mSampleRate = 44100.00; inStreamDesc.mFormatID = kAudioFormatLinearPCM; inStreamDesc.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked ; inStreamDesc.mChannelsPerFrame = 2; inStreamDesc.mBitsPerChannel = 16; inStreamDesc.mFramesPerPacket = 1; inStreamDesc.mBytesPerFrame = 4; // The bytes per packet is purely a product of bytes per frame and frames per // packet since we don't have any padding in a packet here inStreamDesc.mBytesPerPacket = 4; */ Report(CS_REPORTER_SEVERITY_WARNING,"Read in hardware properties of to Freq=%f Channels=%d Bits=%d FormatID=%s Flags=%x", outStreamDesc.mSampleRate, outStreamDesc.mChannelsPerFrame, outStreamDesc.mBitsPerChannel, &outStreamDesc.mFormatID, outStreamDesc.mFormatFlags ); // Set up destination stream parameters outStreamDesc.mSampleRate = 44100.00; outStreamDesc.mFormatID=kAudioFormatLinearPCM; outStreamDesc.mFormatFlags = kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked | kAudioFormatFlagIsBigEndian; outStreamDesc.mChannelsPerFrame= 2; outStreamDesc.mBitsPerChannel= 32; // outStreamDesc.mFramesPerPacket= 1; // At this level, Core Audio demands 32 bit floats outStreamDesc.mBytesPerFrame = requested_format->Channels * sizeof(float); // The bytes per packet is purely a product of bytes per frame and frames per // packet since we don't have any padding in a packet here outStreamDesc.mBytesPerPacket = outStreamDesc.mFramesPerPacket * outStreamDesc.mBytesPerFrame; //Make sure our HAL likes the output format? propertysize = sizeof(outStreamDesc); status = AudioDeviceSetProperty(outputDeviceID, 0, 0, false, kAudioDevicePropertyStreamFormat, propertysize, &outStreamDesc); if (status != 0) { Report(CS_REPORTER_SEVERITY_ERROR, "Failed to set output stream properties to Freq=%f Channels=%d Bits=%d FormatID=%s Flags=%x. Return of %s", outStreamDesc.mSampleRate, outStreamDesc.mChannelsPerFrame, outStreamDesc.mBitsPerChannel, &outStreamDesc.mFormatID, outStreamDesc.mFormatFlags, &status); //return false; } //Create a converter to do the translation for us status = AudioConverterNew(&inStreamDesc, &outStreamDesc, &converter); if (status != 0) { Report(CS_REPORTER_SEVERITY_ERROR, "Failed to create converter with error %s", &status); //return false; } // Copy the final format into local storage memcpy(&playback_format, requested_format, sizeof(csSndSysSoundFormat)); // Add a callback and begin playback status = AudioDeviceAddIOProc(outputDeviceID, StaticAudioProc, this); if (status != 0) { Report(CS_REPORTER_SEVERITY_ERROR, "Failed to add audio device IO proc. Return of %d.", (int)status); return false; } return true; } void csSndSysDriverCoreAudio::Close () { StopThread(); AudioDeviceRemoveIOProc(outputDeviceID, StaticAudioProc); free(convert_buffer); convert_buffer = 0; } bool csSndSysDriverCoreAudio::StartThread() { OSStatus status; // Since the Core Audio API is callback driven, we don't actually start a // thread here ourselves. Instead we start the audio device pulling from the // audio procedure. This runs in its own thread that we don't see. Report(CS_REPORTER_SEVERITY_ERROR, "Getting our thread on!"); status = AudioDeviceStart(outputDeviceID, StaticAudioProc); if (status != 0) { Report(CS_REPORTER_SEVERITY_ERROR, "Failed to start audio device IO proc. " "Return of %d.", (int)status); return false; } running = true; return true; } void csSndSysDriverCoreAudio::StopThread() { running = false; AudioDeviceStop(outputDeviceID, StaticAudioProc); csSleep(100); } OSStatus csSndSysDriverCoreAudio::AudioProc(AudioDeviceID inDevice, const AudioTimeStamp *inNow, const AudioBufferList *inInputData, const AudioTimeStamp *inInputTime, AudioBufferList *outOutputData, const AudioTimeStamp *inOutputTime) { if (!running) { outOutputData->mBuffers[0].mDataByteSize=0; return 0; } // Fill the provided buffer with as many samples as possible and return the // number of frames provided int q = 0; OSStatus stat = 0; int x = 0; //lame attempt to null-terminate OSStatus for string interpretation size_t framesFilled = attached_renderer->FillDriverBuffer( convert_buffer, convert_size, 0, 0); size_t bytesWritten = outOutputData->mBuffers[0].mDataByteSize; stat = AudioConverterConvertBuffer(converter, framesFilled * playback_format.Bits/8 * playback_format.Channels, convert_buffer, &bytesWritten, outOutputData->mBuffers[0].mData); if(stat){ //attached_renderer->RecordEvent(SSEC_DRIVER,SSEL_DEBUG, "Audio convert error %s",&stat); } //attached_renderer->RecordEvent(SSEC_DRIVER,SSEL_DEBUG, "CA requested %d bytes, we wrote %d.",outOutputData->mBuffers[0].mDataByteSize,bytesWritten); return stat; } } CS_PLUGIN_NAMESPACE_END(SndSysCOREAUDIO) <commit_msg>AndyDude changed the non-error CoreAudio messages to be not so 'loud'. The two CoreAudio messages that I changed were Report()'d at very high severity levels, when it wasn't really that severe.<commit_after>/* Copyright (C) 2005 by Andrew Mann Based in part on work by Matt Reda This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "cssysdef.h" #include "csutil/event.h" #include "csutil/sysfunc.h" #include "iutil/cfgfile.h" #include "iutil/cmdline.h" #include "iutil/comp.h" #include "iutil/event.h" #include "iutil/eventh.h" #include "iutil/eventh.h" #include "iutil/eventq.h" #include "iutil/objreg.h" #include "iutil/plugin.h" #include "iutil/virtclk.h" #include "ivaria/reporter.h" #include "../../renderer.h" #include "isndsys/ss_driver.h" #include "isndsys/ss_renderer.h" #include "driver_coreaudio.h" CS_IMPLEMENT_PLUGIN CS_PLUGIN_NAMESPACE_BEGIN(SndSysCOREAUDIO) { SCF_IMPLEMENT_FACTORY (csSndSysDriverCoreAudio) SCF_IMPLEMENT_IBASE(csSndSysDriverCoreAudio) SCF_IMPLEMENTS_INTERFACE(iSndSysSoftwareDriver) SCF_IMPLEMENTS_EMBEDDED_INTERFACE(iComponent) SCF_IMPLEMENT_IBASE_END; SCF_IMPLEMENT_EMBEDDED_IBASE (csSndSysDriverCoreAudio::eiComponent) SCF_IMPLEMENTS_INTERFACE (iComponent) SCF_IMPLEMENT_EMBEDDED_IBASE_END // CoreAudio static IO procedure wrapper static OSStatus StaticAudioProc(AudioDeviceID inDevice, const AudioTimeStamp *inNow, const AudioBufferList *inInputData, const AudioTimeStamp *inInputTime, AudioBufferList *outOutputData, const AudioTimeStamp *inOutputTime, void *inClientData) { csSndSysDriverCoreAudio *p_audio=(csSndSysDriverCoreAudio *)inClientData; return p_audio->AudioProc(inDevice, inNow, inInputData, inInputTime, outOutputData, inOutputTime); } csSndSysDriverCoreAudio::csSndSysDriverCoreAudio(iBase* piBase) : object_reg(0), attached_renderer(0), running(false) { SCF_CONSTRUCT_IBASE(piBase); SCF_CONSTRUCT_EMBEDDED_IBASE(scfiComponent); convert_buffer = 0; } csSndSysDriverCoreAudio::~csSndSysDriverCoreAudio() { SCF_DESTRUCT_EMBEDDED_IBASE(scfiComponent); SCF_DESTRUCT_IBASE(); free(convert_buffer); } void csSndSysDriverCoreAudio::Report(int severity, const char* msg, ...) { va_list arg; va_start (arg, msg); csRef<iReporter> reporter = CS_QUERY_REGISTRY(object_reg, iReporter); if (reporter) { reporter->ReportV (severity, "crystalspace.sndsys.driver.software.coreaudio", msg, arg); } else { csPrintfV (msg, arg); csPrintf ("\n"); } va_end (arg); } bool csSndSysDriverCoreAudio::Initialize (iObjectRegistry* r) { object_reg = r; Report (CS_REPORTER_SEVERITY_DEBUG, "Sound System: CoreAudio driver for software sound renderer initialized."); return true; } bool csSndSysDriverCoreAudio::Open (csSndSysRendererSoftware *renderer, csSndSysSoundFormat *requested_format) { uint32 propertysize, buffersize; AudioStreamBasicDescription outStreamDesc; //description of the data that CS will be providing AudioStreamBasicDescription inStreamDesc; OSStatus status; Report(CS_REPORTER_SEVERITY_DEBUG, "Sound System: CoreAudio Driver: Open()"); attached_renderer = renderer; // Retrieve the output device ID - this is almost verbatim from the available // sample code propertysize = sizeof(outputDeviceID); status = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice, (UInt32*)&propertysize, &outputDeviceID); if (status) { Report(CS_REPORTER_SEVERITY_ERROR, "Failed to obtain default CoreAudio output device. Return of %d.", (int)status); return false; } if (outputDeviceID == kAudioDeviceUnknown) { Report(CS_REPORTER_SEVERITY_ERROR, "Failed to obtain default CoreAudio output device. " "Resulting ID is kAudioDeviceUnknown."); return false; } // Set buffer size - 1/10th of a second buffer of floats propertysize = sizeof(buffersize); buffersize = requested_format->Freq * sizeof(float) * requested_format->Channels / 10; convert_size = requested_format->Freq / 10; convert_buffer = malloc(convert_size * requested_format->Channels * requested_format->Bits/8); status = AudioDeviceSetProperty(outputDeviceID, 0, 0, false, kAudioDevicePropertyBufferSize, propertysize, &buffersize); if (status) { Report(CS_REPORTER_SEVERITY_ERROR, "Failed to set buffersize to %d bytes for CoreAudio output device. " "Return of %d.", buffersize, (int)status); free(convert_buffer); return false; } // Get stream information propertysize = sizeof(outStreamDesc); status = AudioDeviceGetProperty(outputDeviceID, 0, false, kAudioDevicePropertyStreamFormat, (UInt32*)&propertysize, &outStreamDesc); if (status != 0) { Report(CS_REPORTER_SEVERITY_ERROR, "Failed to retrieve output stream description from CoreAudio " "output device. Return of %d.", (int)status); return false; } //get another copy to create the input format spec status = AudioDeviceGetProperty(outputDeviceID, 0, false, kAudioDevicePropertyStreamFormat, (UInt32*)&propertysize, &inStreamDesc); // Set up source stream description for an AudioConverter to do its thang inStreamDesc.mSampleRate = requested_format->Freq; inStreamDesc.mFormatID = kAudioFormatLinearPCM; inStreamDesc.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked ; if ((requested_format->Flags & CSSNDSYS_SAMPLE_ENDIAN_MASK) == CSSNDSYS_SAMPLE_BIG_ENDIAN) inStreamDesc.mFormatFlags |= kAudioFormatFlagIsBigEndian; inStreamDesc.mChannelsPerFrame = requested_format->Channels; inStreamDesc.mBitsPerChannel = requested_format->Bits; inStreamDesc.mFramesPerPacket = 1; inStreamDesc.mBytesPerFrame = requested_format->Channels * requested_format->Bits / 8; // The bytes per packet is purely a product of bytes per frame and frames per // packet since we don't have any padding in a packet here inStreamDesc.mBytesPerPacket = inStreamDesc.mFramesPerPacket * inStreamDesc.mBytesPerFrame; /* inStreamDesc.mSampleRate = 44100.00; inStreamDesc.mFormatID = kAudioFormatLinearPCM; inStreamDesc.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked ; inStreamDesc.mChannelsPerFrame = 2; inStreamDesc.mBitsPerChannel = 16; inStreamDesc.mFramesPerPacket = 1; inStreamDesc.mBytesPerFrame = 4; // The bytes per packet is purely a product of bytes per frame and frames per // packet since we don't have any padding in a packet here inStreamDesc.mBytesPerPacket = 4; */ Report(CS_REPORTER_SEVERITY_DEBUG,"Read in hardware properties of to Freq=%f Channels=%d Bits=%d FormatID=%s Flags=%x", outStreamDesc.mSampleRate, outStreamDesc.mChannelsPerFrame, outStreamDesc.mBitsPerChannel, &outStreamDesc.mFormatID, outStreamDesc.mFormatFlags ); // Set up destination stream parameters outStreamDesc.mSampleRate = 44100.00; outStreamDesc.mFormatID=kAudioFormatLinearPCM; outStreamDesc.mFormatFlags = kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked | kAudioFormatFlagIsBigEndian; outStreamDesc.mChannelsPerFrame= 2; outStreamDesc.mBitsPerChannel= 32; // outStreamDesc.mFramesPerPacket= 1; // At this level, Core Audio demands 32 bit floats outStreamDesc.mBytesPerFrame = requested_format->Channels * sizeof(float); // The bytes per packet is purely a product of bytes per frame and frames per // packet since we don't have any padding in a packet here outStreamDesc.mBytesPerPacket = outStreamDesc.mFramesPerPacket * outStreamDesc.mBytesPerFrame; //Make sure our HAL likes the output format? propertysize = sizeof(outStreamDesc); status = AudioDeviceSetProperty(outputDeviceID, 0, 0, false, kAudioDevicePropertyStreamFormat, propertysize, &outStreamDesc); if (status != 0) { Report(CS_REPORTER_SEVERITY_ERROR, "Failed to set output stream properties to Freq=%f Channels=%d Bits=%d FormatID=%s Flags=%x. Return of %s", outStreamDesc.mSampleRate, outStreamDesc.mChannelsPerFrame, outStreamDesc.mBitsPerChannel, &outStreamDesc.mFormatID, outStreamDesc.mFormatFlags, &status); //return false; } //Create a converter to do the translation for us status = AudioConverterNew(&inStreamDesc, &outStreamDesc, &converter); if (status != 0) { Report(CS_REPORTER_SEVERITY_ERROR, "Failed to create converter with error %s", &status); //return false; } // Copy the final format into local storage memcpy(&playback_format, requested_format, sizeof(csSndSysSoundFormat)); // Add a callback and begin playback status = AudioDeviceAddIOProc(outputDeviceID, StaticAudioProc, this); if (status != 0) { Report(CS_REPORTER_SEVERITY_ERROR, "Failed to add audio device IO proc. Return of %d.", (int)status); return false; } return true; } void csSndSysDriverCoreAudio::Close () { StopThread(); AudioDeviceRemoveIOProc(outputDeviceID, StaticAudioProc); free(convert_buffer); convert_buffer = 0; } bool csSndSysDriverCoreAudio::StartThread() { OSStatus status; // Since the Core Audio API is callback driven, we don't actually start a // thread here ourselves. Instead we start the audio device pulling from the // audio procedure. This runs in its own thread that we don't see. Report(CS_REPORTER_SEVERITY_DEBUG, "Getting our thread on!"); status = AudioDeviceStart(outputDeviceID, StaticAudioProc); if (status != 0) { Report(CS_REPORTER_SEVERITY_ERROR, "Failed to start audio device IO proc. " "Return of %d.", (int)status); return false; } running = true; return true; } void csSndSysDriverCoreAudio::StopThread() { running = false; AudioDeviceStop(outputDeviceID, StaticAudioProc); csSleep(100); } OSStatus csSndSysDriverCoreAudio::AudioProc(AudioDeviceID inDevice, const AudioTimeStamp *inNow, const AudioBufferList *inInputData, const AudioTimeStamp *inInputTime, AudioBufferList *outOutputData, const AudioTimeStamp *inOutputTime) { if (!running) { outOutputData->mBuffers[0].mDataByteSize=0; return 0; } // Fill the provided buffer with as many samples as possible and return the // number of frames provided int q = 0; OSStatus stat = 0; int x = 0; //lame attempt to null-terminate OSStatus for string interpretation size_t framesFilled = attached_renderer->FillDriverBuffer( convert_buffer, convert_size, 0, 0); size_t bytesWritten = outOutputData->mBuffers[0].mDataByteSize; stat = AudioConverterConvertBuffer(converter, framesFilled * playback_format.Bits/8 * playback_format.Channels, convert_buffer, &bytesWritten, outOutputData->mBuffers[0].mData); if(stat){ //attached_renderer->RecordEvent(SSEC_DRIVER,SSEL_DEBUG, "Audio convert error %s",&stat); } //attached_renderer->RecordEvent(SSEC_DRIVER,SSEL_DEBUG, "CA requested %d bytes, we wrote %d.",outOutputData->mBuffers[0].mDataByteSize,bytesWritten); return stat; } } CS_PLUGIN_NAMESPACE_END(SndSysCOREAUDIO) <|endoftext|>
<commit_before>// // Landscape.cpp // // Created by Soso Limited on 5/26/15. // // #include "Landscape.h" #include "cinder/Log.h" #include "Constants.h" #include "LandscapeGeometry.h" #include "cinder/Json.h" #include "cinder/Xml.h" #include "cinder/gl/GlslProg.h" #include "cinder/app/App.h" #include "cinder/Easing.h" using namespace soso; using namespace cinder; namespace { struct alignas(16) Vertex { /// Position vec3 position; float frame_offset; /// Color vec2 color_tex_coord; // smooth across sections (bars in a section have shared edge values) vec2 flat_tex_coord; // shared within bands float color_weight; /// Deformation vec3 normal; float deform_frame_offset; // shared across seams float deform_weight; }; const auto kVertexLayout = ([] { auto layout = geom::BufferLayout(); layout.append( geom::Attrib::POSITION, 3, sizeof(Vertex), offsetof(Vertex, position) ); layout.append( geom::Attrib::NORMAL, 3, sizeof(Vertex), offsetof(Vertex, normal) ); layout.append( geom::Attrib::TEX_COORD_0, 2, sizeof(Vertex), offsetof(Vertex, color_tex_coord) ); layout.append( geom::Attrib::TEX_COORD_1, 2, sizeof(Vertex), offsetof(Vertex, flat_tex_coord) ); layout.append( geom::Attrib::CUSTOM_0, 1, sizeof(Vertex), offsetof(Vertex, deform_weight) ); layout.append( geom::Attrib::CUSTOM_1, 1, sizeof(Vertex), offsetof(Vertex, frame_offset) ); layout.append( geom::Attrib::CUSTOM_2, 1, sizeof(Vertex), offsetof(Vertex, color_weight) ); layout.append( geom::Attrib::CUSTOM_3, 1, sizeof(Vertex), offsetof(Vertex, deform_frame_offset) ); return layout; } ()); const auto kVertexMapping = ([] { return gl::Batch::AttributeMapping{ { geom::Attrib::CUSTOM_0, "DeformScaling" }, { geom::Attrib::CUSTOM_1, "FrameOffset" }, { geom::Attrib::CUSTOM_2, "ColorWeight" }, { geom::Attrib::CUSTOM_3, "DeformFrameOffset" } }; } ()); // Load a shader and handle exceptions. Return nullptr on failure. gl::GlslProgRef loadShader( const fs::path &iVertex, const fs::path &iFragment ) { try { auto shader_format = gl::GlslProg::Format() .vertex( app::loadAsset( iVertex ) ) .fragment( app::loadAsset( iFragment ) ); return gl::GlslProg::create( shader_format ); } catch( ci::Exception &exc ) { CI_LOG_E( "Error loading shader: " << exc.what() ); } return nullptr; } /// Add a ring of geometry containing a given number of time bands (slitscanning effect) and repeats around the donut. void addRing( std::vector<Vertex> &vertices, const Bar &bar, int next_bar_time, float deform_start_time, const ci::vec2 &center_offset ) { const auto segments = 64; const auto texture_insets = vec2( 0.05f, 0.0875f ); // Generate cartesian position. const auto calc_pos = [=] (int r, int s) { auto pos = mix( bar.begin, bar.end, (float)r ) + center_offset; auto t = (float) s / segments; auto rotation = glm::rotate<float>( t * Tau, vec3(0, 1, 0) ); return vec3( rotation * vec4( pos, 0.0f, 1.0f ) ); }; const auto calc_normal = [=] (int r, int s) { auto normal = normalize( vec3(mix(bar.normal_begin, bar.normal_end, (float)r), 0.0f) ); auto t = (float) s / segments; auto rotation = glm::rotate<float>( t * Tau, vec3(0, 1, 0) ); return vec3( rotation * vec4(normal, 0.0f) ); }; // Generate texture coordinate mirrored at halfway point. const auto calc_tc = [=] (int r, int s) { auto t = (float) s / segments; if( t < 1 ) { t = glm::fract( t * bar.repeats ); } // mirror copies t = std::abs( t - 0.5f ) * 2.0f; auto tc = vec2(0); // Repeat t with mirroring // insetting the texture coordinates minimizes edge color flashing. tc.y = mix( texture_insets.y, 1.0f - texture_insets.y, t ); auto x = mix( bar.texture_begin, bar.texture_end, (float) r ); tc.x = mix( 1.0f - texture_insets.x, texture_insets.x, x ); return tc; }; // Add a vertex to texture (color_tc parameter allows us to do flat shading in ES2) const auto add_vert = [=,&vertices] (int r, int s, const ivec2 &provoking) { auto pos = calc_pos(r, s); auto color_tc = calc_tc(r, s); auto flat_tc = calc_tc( provoking.x, provoking.y ); auto normal = calc_normal(r, s); auto deform_t = lmap( glm::clamp<float>( bar.time, deform_start_time, 144.0f ), deform_start_time, 144.0f, 0.0f, 1.0f ); auto deform_scaling = easeInOutQuad( deform_t ); auto color_weight = easeInOutCubic( deform_t ); auto deform_frame = (float)mix( bar.time, next_bar_time, (float)r ); if (deform_scaling > 1.0f) { CI_LOG_W("Deform scaling out of bounds: " << deform_scaling ); } vertices.emplace_back( Vertex { pos, (float)bar.time, color_tc, flat_tc, color_weight, normal, deform_frame, deform_scaling } ); }; // Create triangles for flat shading const auto r = 0; for( auto s = 0; s < segments; s += 1 ) { auto provoking = ivec2(r, s); add_vert( r, s, provoking ); add_vert( r, s + 1, provoking ); add_vert( r + 1, s + 1, provoking ); add_vert( r, s, provoking ); add_vert( r + 1, s, provoking ); add_vert( r + 1, s + 1, provoking ); } } } // namespace void Landscape::setup() { CI_LOG_I("Loading landscape shader"); auto shader = loadShader( "landscape.vs", "landscape.fs" ); std::vector<Vertex> vertices; auto offset = vec2( 0.05f, 0.0f ); CI_LOG_I("Loading shape profile."); auto xml = XmlTree( app::loadAsset("profile.xml") ); auto deform_start_time = xml.getChild("shape").getChild("deform_start").getValue<float>(); auto &bars = xml.getChild("shape").getChild("bars").getChildren(); auto iter = bars.begin(); Bar bar(**iter); while( iter != bars.end() ) { ++iter; if( iter != bars.end() ) { Bar next(**iter); addRing( vertices, bar, next.time, deform_start_time, offset ); bar = next; } else { addRing( vertices, bar, bar.time, deform_start_time, offset ); } } auto center = vec3( 0, -4.0f, 0 ); // Flip up auto xf = glm::rotate<float>( Tau * 0.25f, vec3( 0, 0, 1 ) ) * glm::translate( center ) * glm::scale( vec3( 4.0f ) ); for( auto &v : vertices ) { v.position = vec3( xf * vec4(v.position, 1.0f) ); v.normal = vec3( xf * vec4(v.normal, 0.0f) ); } /* // Mirror (maybe just draw twice) auto copy = vertices; auto mirror = glm::mat4( glm::angleAxis<float>( Tau * 0.5f, vec3( 0, 1, 0 ) ) ); for( auto &v : copy ) { v.position = vec3( mirror * vec4(v.position, 1.0f) ); v.normal = vec3( mirror * vec4(v.normal, 0.0f) ); } vertices.insert( vertices.end(), copy.begin(), copy.end() ); // */ CI_LOG_I("Uploading shape to GPU."); auto vbo = gl::Vbo::create( GL_ARRAY_BUFFER, vertices, GL_STATIC_DRAW ); auto mesh = gl::VboMesh::create( vertices.size(), GL_TRIANGLES, {{ kVertexLayout, vbo }} ); batch = gl::Batch::create( mesh, shader, kVertexMapping ); } void Landscape::setTextureUnits( uint8_t iClearUnit, uint8_t iBlurredUnit ) { auto &shader = batch->getGlslProg(); shader->uniform( "uClearTexture", iClearUnit ); shader->uniform( "uBlurredTexture", iBlurredUnit ); } void Landscape::setGridSize( const ci::vec2 &iSize ) { auto &shader = batch->getGlslProg(); shader->uniform( "uGridSize", iSize ); } void Landscape::draw( float iFrameOffset ) { auto &shader = batch->getGlslProg(); shader->uniform( "uCurrentFrame", iFrameOffset ); batch->draw(); } <commit_msg>Mirrored, but overlapping.<commit_after>// // Landscape.cpp // // Created by Soso Limited on 5/26/15. // // #include "Landscape.h" #include "cinder/Log.h" #include "Constants.h" #include "LandscapeGeometry.h" #include "cinder/Json.h" #include "cinder/Xml.h" #include "cinder/gl/GlslProg.h" #include "cinder/app/App.h" #include "cinder/Easing.h" using namespace soso; using namespace cinder; namespace { struct alignas(16) Vertex { /// Position vec3 position; float frame_offset; /// Color vec2 color_tex_coord; // smooth across sections (bars in a section have shared edge values) vec2 flat_tex_coord; // shared within bands float color_weight; /// Deformation vec3 normal; float deform_frame_offset; // shared across seams float deform_weight; }; const auto kVertexLayout = ([] { auto layout = geom::BufferLayout(); layout.append( geom::Attrib::POSITION, 3, sizeof(Vertex), offsetof(Vertex, position) ); layout.append( geom::Attrib::NORMAL, 3, sizeof(Vertex), offsetof(Vertex, normal) ); layout.append( geom::Attrib::TEX_COORD_0, 2, sizeof(Vertex), offsetof(Vertex, color_tex_coord) ); layout.append( geom::Attrib::TEX_COORD_1, 2, sizeof(Vertex), offsetof(Vertex, flat_tex_coord) ); layout.append( geom::Attrib::CUSTOM_0, 1, sizeof(Vertex), offsetof(Vertex, deform_weight) ); layout.append( geom::Attrib::CUSTOM_1, 1, sizeof(Vertex), offsetof(Vertex, frame_offset) ); layout.append( geom::Attrib::CUSTOM_2, 1, sizeof(Vertex), offsetof(Vertex, color_weight) ); layout.append( geom::Attrib::CUSTOM_3, 1, sizeof(Vertex), offsetof(Vertex, deform_frame_offset) ); return layout; } ()); const auto kVertexMapping = ([] { return gl::Batch::AttributeMapping{ { geom::Attrib::CUSTOM_0, "DeformScaling" }, { geom::Attrib::CUSTOM_1, "FrameOffset" }, { geom::Attrib::CUSTOM_2, "ColorWeight" }, { geom::Attrib::CUSTOM_3, "DeformFrameOffset" } }; } ()); // Load a shader and handle exceptions. Return nullptr on failure. gl::GlslProgRef loadShader( const fs::path &iVertex, const fs::path &iFragment ) { try { auto shader_format = gl::GlslProg::Format() .vertex( app::loadAsset( iVertex ) ) .fragment( app::loadAsset( iFragment ) ); return gl::GlslProg::create( shader_format ); } catch( ci::Exception &exc ) { CI_LOG_E( "Error loading shader: " << exc.what() ); } return nullptr; } /// Add a ring of geometry containing a given number of time bands (slitscanning effect) and repeats around the donut. void addRing( std::vector<Vertex> &vertices, const Bar &bar, int next_bar_time, float deform_start_time, const ci::vec2 &center_offset ) { const auto segments = 64; const auto texture_insets = vec2( 0.05f, 0.0875f ); // Generate cartesian position. const auto calc_pos = [=] (int r, int s) { auto pos = mix( bar.begin, bar.end, (float)r ) + center_offset; auto t = (float) s / segments; auto rotation = glm::rotate<float>( t * Tau, vec3(0, 1, 0) ); return vec3( rotation * vec4( pos, 0.0f, 1.0f ) ); }; const auto calc_normal = [=] (int r, int s) { auto normal = normalize( vec3(mix(bar.normal_begin, bar.normal_end, (float)r), 0.0f) ); auto t = (float) s / segments; auto rotation = glm::rotate<float>( t * Tau, vec3(0, 1, 0) ); return vec3( rotation * vec4(normal, 0.0f) ); }; // Generate texture coordinate mirrored at halfway point. const auto calc_tc = [=] (int r, int s) { auto t = (float) s / segments; if( t < 1 ) { t = glm::fract( t * bar.repeats ); } // mirror copies t = std::abs( t - 0.5f ) * 2.0f; auto tc = vec2(0); // Repeat t with mirroring // insetting the texture coordinates minimizes edge color flashing. tc.y = mix( texture_insets.y, 1.0f - texture_insets.y, t ); auto x = mix( bar.texture_begin, bar.texture_end, (float) r ); tc.x = mix( 1.0f - texture_insets.x, texture_insets.x, x ); return tc; }; // Add a vertex to texture (color_tc parameter allows us to do flat shading in ES2) const auto add_vert = [=,&vertices] (int r, int s, const ivec2 &provoking) { auto pos = calc_pos(r, s); auto color_tc = calc_tc(r, s); auto flat_tc = calc_tc( provoking.x, provoking.y ); auto normal = calc_normal(r, s); auto deform_t = lmap( glm::clamp<float>( bar.time, deform_start_time, 144.0f ), deform_start_time, 144.0f, 0.0f, 1.0f ); auto deform_scaling = easeInOutQuad( deform_t ); auto color_weight = easeInOutCubic( deform_t ); auto deform_frame = (float)mix( bar.time, next_bar_time, (float)r ); if (deform_scaling > 1.0f) { CI_LOG_W("Deform scaling out of bounds: " << deform_scaling ); } vertices.emplace_back( Vertex { pos, (float)bar.time, color_tc, flat_tc, color_weight, normal, deform_frame, deform_scaling } ); }; // Create triangles for flat shading const auto r = 0; for( auto s = 0; s < segments; s += 1 ) { auto provoking = ivec2(r, s); add_vert( r, s, provoking ); add_vert( r, s + 1, provoking ); add_vert( r + 1, s + 1, provoking ); add_vert( r, s, provoking ); add_vert( r + 1, s, provoking ); add_vert( r + 1, s + 1, provoking ); } } } // namespace void Landscape::setup() { CI_LOG_I("Loading landscape shader"); auto shader = loadShader( "landscape.vs", "landscape.fs" ); std::vector<Vertex> vertices; auto offset = vec2( 0.05f, 0.0f ); CI_LOG_I("Loading shape profile."); auto xml = XmlTree( app::loadAsset("profile.xml") ); auto deform_start_time = xml.getChild("shape").getChild("deform_start").getValue<float>(); auto &bars = xml.getChild("shape").getChild("bars").getChildren(); auto iter = bars.begin(); Bar bar(**iter); while( iter != bars.end() ) { ++iter; if( iter != bars.end() ) { Bar next(**iter); addRing( vertices, bar, next.time, deform_start_time, offset ); bar = next; } else { addRing( vertices, bar, bar.time, deform_start_time, offset ); } } auto center = vec3( 0, -4.0f, 0 ); // Flip up auto xf = glm::rotate<float>( Tau * 0.25f, vec3( 0, 0, 1 ) ) * glm::translate( center ) * glm::scale( vec3( 4.0f ) ); for( auto &v : vertices ) { v.position = vec3( xf * vec4(v.position, 1.0f) ); v.normal = vec3( xf * vec4(v.normal, 0.0f) ); } // /* // Mirror (maybe just draw twice) auto copy = vertices; auto mirror = glm::translate( vec3( -8.0f, 0.0f, 0.0f ) ) * glm::mat4( glm::angleAxis<float>( Tau * 0.5f, vec3( 0, 1, 0 ) ) ); for( auto &v : copy ) { v.position = vec3( mirror * vec4(v.position, 1.0f) ); v.normal = vec3( mirror * vec4(v.normal, 0.0f) ); } vertices.insert( vertices.end(), copy.begin(), copy.end() ); // */ CI_LOG_I("Uploading shape to GPU."); auto vbo = gl::Vbo::create( GL_ARRAY_BUFFER, vertices, GL_STATIC_DRAW ); auto mesh = gl::VboMesh::create( vertices.size(), GL_TRIANGLES, {{ kVertexLayout, vbo }} ); batch = gl::Batch::create( mesh, shader, kVertexMapping ); } void Landscape::setTextureUnits( uint8_t iClearUnit, uint8_t iBlurredUnit ) { auto &shader = batch->getGlslProg(); shader->uniform( "uClearTexture", iClearUnit ); shader->uniform( "uBlurredTexture", iBlurredUnit ); } void Landscape::setGridSize( const ci::vec2 &iSize ) { auto &shader = batch->getGlslProg(); shader->uniform( "uGridSize", iSize ); } void Landscape::draw( float iFrameOffset ) { auto &shader = batch->getGlslProg(); shader->uniform( "uCurrentFrame", iFrameOffset ); batch->draw(); } <|endoftext|>
<commit_before>/* Luwra * Minimal-overhead Lua wrapper for C++ * * Copyright (C) 2015, Ole Krüger <ole@vprsm.de> */ #ifndef LUWRA_FUNCTIONS_H_ #define LUWRA_FUNCTIONS_H_ #include "common.hpp" #include "types.hpp" #include "stack.hpp" LUWRA_NS_BEGIN namespace internal { template <typename T> struct FunctionWrapper { static_assert( sizeof(T) == -1, "Parameter to FunctionWrapper is not a function signature" ); }; template <> struct FunctionWrapper<void()> { template <void(*function_pointer)()> static inline int invoke(State*) { function_pointer(); return 0; } }; template <typename R> struct FunctionWrapper<R()> { template <R(*function_pointer)()> static inline int invoke(State* state) { return push(state, function_pointer()); } }; template <typename... A> struct FunctionWrapper<void(A...)> { template <void (*function_pointer)(A...)> static inline int invoke(State* state) { apply(state, function_pointer); return 0; } }; template <typename R, typename... A> struct FunctionWrapper<R(A...)> { template <R (*function_pointer)(A...)> static inline int invoke(State* state) { return push( state, apply(state, function_pointer) ); } }; template <typename T> struct FunctionWrapperHelper { static_assert( sizeof(T) == -1, "Parameter to FunctionWrapperHelper is not a function pointer" ); }; template <typename R, typename... A> struct FunctionWrapperHelper<R(*)(A...)> { using Signature = R(A...); template <R(*function_pointer)(A...)> static constexpr CFunction wrapped = &internal::FunctionWrapper<Signature>::template invoke<function_pointer>; }; } /** * Assuming its parameters can be retrieved from the Lua stack, ordinary functions can be wrapped * using the `wrap_function` instance in order to produce a C function which can be used by the * Lua VM. * * Assuming your function has the following signature: * * R my_fun(A0, A1 ... An); * * Generate a Lua-compatible like so: * * CFunction wrapped_fun = wrap_function<R(A0, A1 ... An), my_fun>; */ template < typename S, S* function_pointer > constexpr CFunction wrap_function = &internal::FunctionWrapper<S>::template invoke<function_pointer>; /** * This macros allows you to wrap functions without providing a type signature. */ #define LUWRA_WRAP_FUNCTION(fun) \ (luwra::internal::FunctionWrapperHelper<decltype(&fun)>::wrapped<&fun>) LUWRA_NS_END #endif <commit_msg>Fix bug with Clang where wrapped function pointers are optimized out<commit_after>/* Luwra * Minimal-overhead Lua wrapper for C++ * * Copyright (C) 2015, Ole Krüger <ole@vprsm.de> */ #ifndef LUWRA_FUNCTIONS_H_ #define LUWRA_FUNCTIONS_H_ #include "common.hpp" #include "types.hpp" #include "stack.hpp" LUWRA_NS_BEGIN namespace internal { template <typename T> struct FunctionWrapper { static_assert( sizeof(T) == -1, "Parameter to FunctionWrapper is not a function signature" ); }; template <> struct FunctionWrapper<void()> { template <void(*function_pointer)()> static inline int invoke(State*) { function_pointer(); return 0; } }; template <typename R> struct FunctionWrapper<R()> { template <R(*function_pointer)()> static inline int invoke(State* state) { return push(state, function_pointer()); } }; template <typename... A> struct FunctionWrapper<void(A...)> { template <void (*function_pointer)(A...)> static inline int invoke(State* state) { apply(state, function_pointer); return 0; } }; template <typename R, typename... A> struct FunctionWrapper<R(A...)> { template <R (*function_pointer)(A...)> static inline int invoke(State* state) { return push( state, apply(state, function_pointer) ); } }; template <typename T> struct FunctionWrapperHelper { static_assert( sizeof(T) == -1, "Parameter to FunctionWrapperHelper is not a function pointer" ); }; template <typename R, typename... A> struct FunctionWrapperHelper<R(*)(A...)> { using Signature = R(A...); }; } /** * Assuming its parameters can be retrieved from the Lua stack, ordinary functions can be wrapped * using the `wrap_function` instance in order to produce a C function which can be used by the * Lua VM. * * Assuming your function has the following signature: * * R my_fun(A0, A1 ... An); * * Generate a Lua-compatible like so: * * CFunction wrapped_fun = wrap_function<R(A0, A1 ... An), my_fun>; */ template < typename S, S* function_pointer > constexpr CFunction wrap_function = &internal::FunctionWrapper<S>::template invoke<function_pointer>; /** * This macros allows you to wrap functions without providing a type signature. */ #define LUWRA_WRAP_FUNCTION(fun) \ (luwra::wrap_function< \ typename luwra::internal::FunctionWrapperHelper<decltype(&fun)>::Signature, \ &fun \ >) LUWRA_NS_END #endif <|endoftext|>
<commit_before>//===-- GameModel.cpp - Model for Game State ----------------------- c++ --===// // // UWH Timer // // This file is distributed under the BSD 3-Clause License. // See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "uwhd/model/GameModel.h" #include <ctime> #include <iomanip> #include <string> #include <sstream> using namespace uwhtimer; bool GameModel::operator==(const GameModel &Other) { return BlackScore == Other.BlackScore && WhiteScore == Other.WhiteScore && GameClockSecs == Other.GameClockSecs; } GameModel *GameModelManager::getModel() { return &Model; } std::string GameModel::dump() { std::stringstream SS; SS << "Black: " << BlackScore << "\n" << "White: " << WhiteScore << "\n" << "GameClockSecs: " << GameClockSecs << "\n"; return SS.str(); } std::string GameModel::serialize() { std::stringstream SS; SS << "S" << "B" << std::setfill('0') << std::setw(2) << BlackScore << "W" << std::setfill('0') << std::setw(2) << WhiteScore << "T" << std::setfill('0') << std::setw(5) << GameClockSecs << "E"; return SS.str(); } static bool check(std::stringstream &SS, char V) { char C; SS.get(C); return C != V; } bool GameModel::deSerialize(std::string S, GameModel &M) { GameModel NewM; std::stringstream SS; SS << S; if (check(SS, 'S')) return true; if (check(SS, 'B')) return true; SS >> NewM.BlackScore; if (check(SS, 'W')) return true; SS >> NewM.WhiteScore; if (check(SS, 'T')) return true; SS >> NewM.GameClockSecs; if (check(SS, 'E')) return true; M = NewM; return false; } <commit_msg>Always dump GameModel values as int values<commit_after>//===-- GameModel.cpp - Model for Game State ----------------------- c++ --===// // // UWH Timer // // This file is distributed under the BSD 3-Clause License. // See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "uwhd/model/GameModel.h" #include <ctime> #include <iomanip> #include <string> #include <sstream> using namespace uwhtimer; bool GameModel::operator==(const GameModel &Other) { return BlackScore == Other.BlackScore && WhiteScore == Other.WhiteScore && GameClockSecs == Other.GameClockSecs; } GameModel *GameModelManager::getModel() { return &Model; } std::string GameModel::dump() { std::stringstream SS; SS << "Black: " << int(BlackScore) << "\n" << "White: " << int(WhiteScore) << "\n" << "GameClockSecs: " << int(GameClockSecs) << "\n"; return SS.str(); } std::string GameModel::serialize() { std::stringstream SS; SS << "S" << "B" << std::setfill('0') << std::setw(2) << BlackScore << "W" << std::setfill('0') << std::setw(2) << WhiteScore << "T" << std::setfill('0') << std::setw(5) << GameClockSecs << "E"; return SS.str(); } static bool check(std::stringstream &SS, char V) { char C; SS.get(C); return C != V; } bool GameModel::deSerialize(std::string S, GameModel &M) { GameModel NewM; std::stringstream SS; SS << S; if (check(SS, 'S')) return true; if (check(SS, 'B')) return true; SS >> NewM.BlackScore; if (check(SS, 'W')) return true; SS >> NewM.WhiteScore; if (check(SS, 'T')) return true; SS >> NewM.GameClockSecs; if (check(SS, 'E')) return true; M = NewM; return false; } <|endoftext|>
<commit_before>/* * Copyright (c) 2019, Arm Limited and affiliates. * SPDX-License-Identifier: Apache-2.0 * * 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 "UBLOX_N2XX.h" using namespace mbed; using namespace events; static const intptr_t cellular_properties[AT_CellularBase::PROPERTY_MAX] = { AT_CellularNetwork::RegistrationModeLAC, // C_EREG AT_CellularNetwork::RegistrationModeDisable, // C_GREG AT_CellularNetwork::RegistrationModeDisable, // C_REG 1, // AT_CGSN_WITH_TYPE 0, // AT_CGDATA 0, // AT_CGAUTH 0, // AT_CNMI 0, // AT_CSMP 0, // AT_CMGF 0, // AT_CSDH 1, // PROPERTY_IPV4_STACK 0, // PROPERTY_IPV6_STACK 0, // PROPERTY_IPV4V6_STACK }; UBLOX_N2XX::UBLOX_N2XX(FileHandle *fh): AT_CellularDevice(fh) { AT_CellularBase::set_cellular_properties(cellular_properties); _at->set_urc_handler("+NPIN:", mbed::Callback<void()>(this, &UBLOX_N2XX::NPIN_URC)); memset(simstr, 0, sizeof(simstr)); } UBLOX_N2XX::~UBLOX_N2XX() { _at->set_urc_handler("+NPIN:", NULL); } // Callback for Sim Pin. void UBLOX_N2XX::NPIN_URC() { _at->read_string(simstr, sizeof(simstr)); } AT_CellularContext *UBLOX_N2XX::create_context_impl(ATHandler &at, const char *apn, bool cp_req, bool nonip_req) { return new UBLOX_N2XX_CellularContext(at, this, apn, cp_req, nonip_req); } AT_CellularSMS *UBLOX_N2XX::open_sms_impl(ATHandler &at) { return new UBLOX_N2XX_CellularSMS(at); } nsapi_error_t UBLOX_N2XX::init() { _at->lock(); _at->flush(); _at->cmd_start("AT"); // echo off _at->cmd_stop_read_resp(); _at->cmd_start("AT+CMEE=1"); // verbose responses _at->cmd_stop_read_resp(); #ifdef MBED_CONF_NSAPI_DEFAULT_CELLULAR_SIM_PIN set_pin(MBED_CONF_NSAPI_DEFAULT_CELLULAR_SIM_PIN); #endif return _at->unlock_return_error(); } nsapi_error_t UBLOX_N2XX::get_sim_state(SimState &state) { nsapi_error_t error = NSAPI_ERROR_DEVICE_ERROR; _at->lock(); _at->flush(); _at->cmd_start("AT+CFUN=1"); _at->cmd_stop(); _at->resp_start(); _at->read_string(simstr, sizeof(simstr)); _at->resp_stop(); error = _at->unlock_return_error(); int len = strlen(simstr); if (len > 0 || error == NSAPI_ERROR_OK) { if (error == NSAPI_ERROR_OK) { state = SimStateReady; } else if (len >= 6 && memcmp(simstr, "ENTER PIN", 9) == 0) { state = SimStatePinNeeded; } else { simstr[len] = '\0'; tr_error("Unknown SIM state %s", simstr); state = SimStateUnknown; } error = NSAPI_ERROR_OK; } else { tr_warn("SIM not readable."); state = SimStateUnknown; // SIM may not be ready yet or pin command may not be supported } #if MBED_CONF_MBED_TRACE_ENABLE switch (state) { case SimStatePinNeeded: tr_info("SIM PIN required"); break; case SimStatePukNeeded: tr_error("SIM PUK required"); break; case SimStateUnknown: tr_warn("SIM state unknown"); break; default: tr_info("SIM is ready"); break; } #endif return error; } nsapi_error_t UBLOX_N2XX::set_pin(const char *sim_pin) { // if SIM is already in ready state then settings the PIN // will return error so let's check the state before settings the pin. SimState state; if (get_sim_state(state) == NSAPI_ERROR_OK && state == SimStateReady) { return NSAPI_ERROR_OK; } if (sim_pin == NULL) { return NSAPI_ERROR_PARAMETER; } _at->lock(); _at->cmd_start("AT+NPIN=0,"); _at->write_string(sim_pin); _at->cmd_stop_read_resp(); return _at->unlock_return_error(); } <commit_msg>C030_N2XX default interface<commit_after>/* * Copyright (c) 2019, Arm Limited and affiliates. * SPDX-License-Identifier: Apache-2.0 * * 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 "UBLOX_N2XX.h" using namespace mbed; using namespace events; static const intptr_t cellular_properties[AT_CellularBase::PROPERTY_MAX] = { AT_CellularNetwork::RegistrationModeLAC, // C_EREG AT_CellularNetwork::RegistrationModeDisable, // C_GREG AT_CellularNetwork::RegistrationModeDisable, // C_REG 1, // AT_CGSN_WITH_TYPE 0, // AT_CGDATA 0, // AT_CGAUTH 0, // AT_CNMI 0, // AT_CSMP 0, // AT_CMGF 0, // AT_CSDH 1, // PROPERTY_IPV4_STACK 0, // PROPERTY_IPV6_STACK 0, // PROPERTY_IPV4V6_STACK }; UBLOX_N2XX::UBLOX_N2XX(FileHandle *fh): AT_CellularDevice(fh) { AT_CellularBase::set_cellular_properties(cellular_properties); _at->set_urc_handler("+NPIN:", mbed::Callback<void()>(this, &UBLOX_N2XX::NPIN_URC)); memset(simstr, 0, sizeof(simstr)); } UBLOX_N2XX::~UBLOX_N2XX() { _at->set_urc_handler("+NPIN:", NULL); } // Callback for Sim Pin. void UBLOX_N2XX::NPIN_URC() { _at->read_string(simstr, sizeof(simstr)); } AT_CellularContext *UBLOX_N2XX::create_context_impl(ATHandler &at, const char *apn, bool cp_req, bool nonip_req) { return new UBLOX_N2XX_CellularContext(at, this, apn, cp_req, nonip_req); } AT_CellularSMS *UBLOX_N2XX::open_sms_impl(ATHandler &at) { return new UBLOX_N2XX_CellularSMS(at); } nsapi_error_t UBLOX_N2XX::init() { _at->lock(); _at->flush(); _at->cmd_start("AT"); // echo off _at->cmd_stop_read_resp(); _at->cmd_start("AT+CMEE=1"); // verbose responses _at->cmd_stop_read_resp(); #ifdef MBED_CONF_NSAPI_DEFAULT_CELLULAR_SIM_PIN set_pin(MBED_CONF_NSAPI_DEFAULT_CELLULAR_SIM_PIN); #endif return _at->unlock_return_error(); } nsapi_error_t UBLOX_N2XX::get_sim_state(SimState &state) { nsapi_error_t error = NSAPI_ERROR_DEVICE_ERROR; _at->lock(); _at->flush(); _at->cmd_start("AT+CFUN=1"); _at->cmd_stop(); _at->resp_start(); _at->read_string(simstr, sizeof(simstr)); _at->resp_stop(); error = _at->unlock_return_error(); int len = strlen(simstr); if (len > 0 || error == NSAPI_ERROR_OK) { if (error == NSAPI_ERROR_OK) { state = SimStateReady; } else if (len >= 6 && memcmp(simstr, "ENTER PIN", 9) == 0) { state = SimStatePinNeeded; } else { simstr[len] = '\0'; tr_error("Unknown SIM state %s", simstr); state = SimStateUnknown; } error = NSAPI_ERROR_OK; } else { tr_warn("SIM not readable."); state = SimStateUnknown; // SIM may not be ready yet or pin command may not be supported } #if MBED_CONF_MBED_TRACE_ENABLE switch (state) { case SimStatePinNeeded: tr_info("SIM PIN required"); break; case SimStatePukNeeded: tr_error("SIM PUK required"); break; case SimStateUnknown: tr_warn("SIM state unknown"); break; default: tr_info("SIM is ready"); break; } #endif return error; } nsapi_error_t UBLOX_N2XX::set_pin(const char *sim_pin) { // if SIM is already in ready state then settings the PIN // will return error so let's check the state before settings the pin. SimState state; if (get_sim_state(state) == NSAPI_ERROR_OK && state == SimStateReady) { return NSAPI_ERROR_OK; } if (sim_pin == NULL) { return NSAPI_ERROR_PARAMETER; } _at->lock(); _at->cmd_start("AT+NPIN=0,"); _at->write_string(sim_pin); _at->cmd_stop_read_resp(); return _at->unlock_return_error(); } #if MBED_CONF_UBLOX_N2XX_PROVIDE_DEFAULT #include "UARTSerial.h" CellularDevice *CellularDevice::get_default_instance() { static UARTSerial serial(MBED_CONF_UBLOX_N2XX_TX, MBED_CONF_UBLOX_N2XX_RX, MBED_CONF_UBLOX_N2XX_BAUDRATE); #if defined (MBED_CONF_UBLOX_N2XX_RTS) && defined(MBED_CONF_UBLOX_N2XX_CTS) tr_debug("UBLOX_N2XX flow control: RTS %d CTS %d", MBED_CONF_UBLOX_N2XX_RTS, MBED_CONF_UBLOX_N2XX_CTS); serial.set_flow_control(SerialBase::RTSCTS, MBED_CONF_UBLOX_N2XX_RTS, MBED_CONF_UBLOX_N2XX_CTS); #endif static UBLOX_N2XX device(&serial); return &device; } #endif <|endoftext|>
<commit_before>/* * Software License Agreement (BSD License) * * Copyright (c) 2011, Alexandru-Eugen Ichim * Willow Garage, Inc * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * $Id$ */ #ifndef PCL_FEATURES_IMPL_NORMAL_BASED_SIGNATURE_H_ #define PCL_FEATURES_IMPL_NORMAL_BASED_SIGNATURE_H_ #include "pcl/features/normal_based_signature.h" template <typename PointT, typename PointNT, typename PointFeature> void pcl::NormalBasedSignatureEstimation<PointT, PointNT, PointFeature>::computeFeature (FeatureCloud &output) { // do a few checks before starting the computations if (!normals_) { PCL_ERROR ("NormalBasedSignatureEstimation: input normals not set\n"); return; } PointFeature test_feature; if (N_prime * M_prime != sizeof (test_feature.values) / sizeof (float)) { PCL_ERROR ("NormalBasedSignatureEstimation: not using the proper signature size: %u vs %u\n", N_prime * M_prime, sizeof (test_feature.values) / sizeof (float)); return; } tree_->setInputCloud (input_); output.points.clear (); //for (size_t point_i = 0; point_i < input_->points.size (); ++point_i) for (size_t index_i = 0; index_i < indices_->size (); ++index_i) { size_t point_i = indices_->at (index_i); Eigen::MatrixXf s_matrix (N, M); Eigen::Vector3f center_point = input_->points[point_i].getVector3fMap (); for (size_t k = 0; k < N; ++k) { Eigen::VectorXf s_row (M); for (size_t l = 0; l < M; ++l) { Eigen::Vector3f normal = normals_->points[point_i].getNormalVector3fMap (); Eigen::Vector3f normal_u, normal_v; if (fabs (normal.x ()) > 0.0001f) { normal_u.x () = - normal.y () / normal.x (); normal_u.y () = 1.0f; normal_u.z () = 0.0f; normal_u.normalize (); } else if (fabs (normal.y ()) > 0.0001f) { normal_u.x () = 1.0f; normal_u.y () = - normal.x () / normal.y (); normal_u.z () = 0.0f; normal_u.normalize (); } else { normal_u.x () = 0.0f; normal_u.y () = 1.0f; normal_u.z () = - normal.y () / normal.z (); } normal_v = normal.cross (normal_u); Eigen::Vector3f zeta_point = 2.0f*(l+1)*scale_h / M * (cos (2.0f*M_PI*(k+1) / N) * normal_u + sin (2.0f*M_PI*(k+1) / N) * normal_v); // compute normal by using the neighbors Eigen::Vector3f zeta_point_plus_center = zeta_point + center_point; PointT zeta_point_pcl; zeta_point_pcl.x = zeta_point_plus_center.x (); zeta_point_pcl.y = zeta_point_plus_center.y (); zeta_point_pcl.z = zeta_point_plus_center.z (); std::vector<int> k_indices; std::vector<float> k_sqr_distances; tree_->radiusSearch (zeta_point_pcl, normal_search_radius, k_indices, k_sqr_distances); // do k nearest search if there are no neighbors nearby if (k_indices.size () == 0) { k_indices.resize (5); k_sqr_distances.resize (5); tree_->nearestKSearch (zeta_point_pcl, 5, k_indices, k_sqr_distances); } Eigen::Vector3f average_normal (0.0f, 0.0f, 0.0f); float average_normalization_factor = 0.0f; // normals weighted by 1/squared_distances for (size_t nn_i = 0; nn_i < k_indices.size (); ++nn_i) { if (k_sqr_distances[nn_i] < 0.0000001f) { average_normal = normals_->points[k_indices[nn_i]].getNormalVector3fMap (); average_normalization_factor = 1.0f; break; } average_normal += normals_->points[k_indices[nn_i]].getNormalVector3fMap () / k_sqr_distances[nn_i]; average_normalization_factor += 1.0f / k_sqr_distances[nn_i]; } average_normal /= average_normalization_factor; float s = zeta_point.dot (average_normal) / zeta_point.norm (); s_row[l] = s; } // do DCT on the s_matrix row-wise Eigen::VectorXf dct_row (M); for (int m = 0; m < s_row.size (); ++m) { float Xk = 0.0f; for (int n = 0; n < s_row.size (); ++n) Xk += s_row[n] * cos (M_PI / M * (n + 0.5f) * k); dct_row[m] = Xk; } s_row = dct_row; s_matrix.row (k) = dct_row; } // do DFT on the s_matrix column-wise Eigen::MatrixXf dft_matrix (N, M); for (size_t column_i = 0; column_i < M; ++column_i) { Eigen::VectorXf dft_col (N); for (size_t k = 0; k < N; ++k) { float Xk_real = 0.0f, Xk_imag = 0.0f; for (size_t n = 0; n < N; ++n) { Xk_real += s_matrix(n, column_i) * cos (2.0f * M_PI / N * k * n); Xk_imag += s_matrix(n, column_i) * sin (2.0f * M_PI / N * k * n); } dft_col[k] = sqrt (Xk_real*Xk_real + Xk_imag*Xk_imag); } dft_matrix.col (column_i) = dft_col; } Eigen::MatrixXf final_matrix = dft_matrix.block (0, 0, N_prime, M_prime); PointFeature feature_point; for (size_t i = 0; i < N_prime; ++i) for (size_t j = 0; j < M_prime; ++j) feature_point.values[i*M_prime + j] = final_matrix (i, j); output.points.push_back (feature_point); } } #define PCL_INSTANTIATE_NormalBasedSignatureEstimation(T,NT,OutT) template class PCL_EXPORTS pcl::NormalBasedSignatureEstimation<T,NT,OutT>; #endif /* PCL_FEATURES_IMPL_NORMAL_BASED_SIGNATURE_H_ */ <commit_msg>tiny optimizations<commit_after>/* * Software License Agreement (BSD License) * * Copyright (c) 2011, Alexandru-Eugen Ichim * Willow Garage, Inc * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * $Id$ */ #ifndef PCL_FEATURES_IMPL_NORMAL_BASED_SIGNATURE_H_ #define PCL_FEATURES_IMPL_NORMAL_BASED_SIGNATURE_H_ #include "pcl/features/normal_based_signature.h" template <typename PointT, typename PointNT, typename PointFeature> void pcl::NormalBasedSignatureEstimation<PointT, PointNT, PointFeature>::computeFeature (FeatureCloud &output) { // do a few checks before starting the computations if (!normals_) { PCL_ERROR ("NormalBasedSignatureEstimation: input normals not set\n"); return; } PointFeature test_feature; if (N_prime * M_prime != sizeof (test_feature.values) / sizeof (float)) { PCL_ERROR ("NormalBasedSignatureEstimation: not using the proper signature size: %u vs %u\n", N_prime * M_prime, sizeof (test_feature.values) / sizeof (float)); return; } std::vector<int> k_indices; std::vector<float> k_sqr_distances; tree_->setInputCloud (input_); output.points.resize (indices_->size ()); //for (size_t point_i = 0; point_i < input_->points.size (); ++point_i) for (size_t index_i = 0; index_i < indices_->size (); ++index_i) { size_t point_i = (*indices_)[index_i]; Eigen::MatrixXf s_matrix (N, M); Eigen::Vector4f center_point = input_->points[point_i].getVector4fMap (); for (size_t k = 0; k < N; ++k) { Eigen::VectorXf s_row (M); for (size_t l = 0; l < M; ++l) { Eigen::Vector4f normal = normals_->points[point_i].getNormalVector4fMap (); Eigen::Vector4f normal_u = Eigen::Vector4f::Zero (); Eigen::Vector4f normal_v = Eigen::Vector4f::Zero (); if (fabs (normal.x ()) > 0.0001f) { normal_u.x () = - normal.y () / normal.x (); normal_u.y () = 1.0f; normal_u.z () = 0.0f; normal_u.normalize (); } else if (fabs (normal.y ()) > 0.0001f) { normal_u.x () = 1.0f; normal_u.y () = - normal.x () / normal.y (); normal_u.z () = 0.0f; normal_u.normalize (); } else { normal_u.x () = 0.0f; normal_u.y () = 1.0f; normal_u.z () = - normal.y () / normal.z (); } normal_v = normal.cross3 (normal_u); Eigen::Vector4f zeta_point = 2.0f * (l+1) * scale_h / M * (cos (2.0f * M_PI * (k+1) / N) * normal_u + sin (2.0f * M_PI * (k+1) / N) * normal_v); // Compute normal by using the neighbors Eigen::Vector4f zeta_point_plus_center = zeta_point + center_point; PointT zeta_point_pcl; zeta_point_pcl.x = zeta_point_plus_center.x (); zeta_point_pcl.y = zeta_point_plus_center.y (); zeta_point_pcl.z = zeta_point_plus_center.z (); tree_->radiusSearch (zeta_point_pcl, normal_search_radius, k_indices, k_sqr_distances); // Do k nearest search if there are no neighbors nearby if (k_indices.size () == 0) { k_indices.resize (5); k_sqr_distances.resize (5); tree_->nearestKSearch (zeta_point_pcl, 5, k_indices, k_sqr_distances); } Eigen::Vector4f average_normal = Eigen::Vector4f::Zero (); float average_normalization_factor = 0.0f; // Normals weighted by 1/squared_distances for (size_t nn_i = 0; nn_i < k_indices.size (); ++nn_i) { if (k_sqr_distances[nn_i] < 0.0000001f) { average_normal = normals_->points[k_indices[nn_i]].getNormalVector4fMap (); average_normalization_factor = 1.0f; break; } average_normal += normals_->points[k_indices[nn_i]].getNormalVector4fMap () / k_sqr_distances[nn_i]; average_normalization_factor += 1.0f / k_sqr_distances[nn_i]; } average_normal /= average_normalization_factor; float s = zeta_point.dot (average_normal) / zeta_point.norm (); s_row[l] = s; } // do DCT on the s_matrix row-wise Eigen::VectorXf dct_row (M); for (int m = 0; m < s_row.size (); ++m) { float Xk = 0.0f; for (int n = 0; n < s_row.size (); ++n) Xk += s_row[n] * cos (M_PI / M * (n + 0.5f) * k); dct_row[m] = Xk; } s_row = dct_row; s_matrix.row (k) = dct_row; } // do DFT on the s_matrix column-wise Eigen::MatrixXf dft_matrix (N, M); for (size_t column_i = 0; column_i < M; ++column_i) { Eigen::VectorXf dft_col (N); for (size_t k = 0; k < N; ++k) { float Xk_real = 0.0f, Xk_imag = 0.0f; for (size_t n = 0; n < N; ++n) { Xk_real += s_matrix(n, column_i) * cos (2.0f * M_PI / N * k * n); Xk_imag += s_matrix(n, column_i) * sin (2.0f * M_PI / N * k * n); } dft_col[k] = sqrt (Xk_real*Xk_real + Xk_imag*Xk_imag); } dft_matrix.col (column_i) = dft_col; } Eigen::MatrixXf final_matrix = dft_matrix.block (0, 0, N_prime, M_prime); PointFeature feature_point; for (size_t i = 0; i < N_prime; ++i) for (size_t j = 0; j < M_prime; ++j) feature_point.values[i*M_prime + j] = final_matrix (i, j); output.points[index_i] = feature_point; } } #define PCL_INSTANTIATE_NormalBasedSignatureEstimation(T,NT,OutT) template class PCL_EXPORTS pcl::NormalBasedSignatureEstimation<T,NT,OutT>; #endif /* PCL_FEATURES_IMPL_NORMAL_BASED_SIGNATURE_H_ */ <|endoftext|>
<commit_before>// Copyright (c) 2009-2018 The Regents of the University of Michigan // This file is part of the HOOMD-blue project, released under the BSD 3-Clause License. // Maintainer: joaander #include "IntegrationMethodTwoStep.h" #include "hoomd/VectorMath.h" #include "QuaternionMath.h" #include "hoomd/HOOMDMath.h" #include "hoomd/Saru.h" namespace py = pybind11; #ifdef ENABLE_MPI #include "hoomd/Communicator.h" #endif using namespace std; /*! \file IntegrationMethodTwoStep.h \brief Contains code for the IntegrationMethodTwoStep class */ /*! \param sysdef SystemDefinition this method will act on. Must not be NULL. \param group The group of particles this integration method is to work on \post The method is constructed with the given particle data and a NULL profiler. */ IntegrationMethodTwoStep::IntegrationMethodTwoStep(std::shared_ptr<SystemDefinition> sysdef, std::shared_ptr<ParticleGroup> group) : m_sysdef(sysdef), m_group(group), m_pdata(m_sysdef->getParticleData()), m_exec_conf(m_pdata->getExecConf()), m_aniso(false), m_deltaT(Scalar(0.0)), m_valid_restart(false) { // sanity check assert(m_sysdef); assert(m_pdata); assert(m_group); m_integrator_id = m_sysdef->getIntegratorData()->registerIntegrator(); } /*! It is useful for the user to know where computation time is spent, so all integration methods should profile themselves. This method sets the profiler for them to use. This method does not need to be called, as Computes will not profile themselves on a NULL profiler \param prof Pointer to a profiler for the compute to use. Set to NULL (std::shared_ptr<Profiler>()) to stop the analyzer from profiling itself. \note Derived classes MUST check if m_prof is set before calling any profiler methods. */ void IntegrationMethodTwoStep::setProfiler(std::shared_ptr<Profiler> prof) { m_prof = prof; } /*! \param deltaT New time step to set */ void IntegrationMethodTwoStep::setDeltaT(Scalar deltaT) { m_deltaT = deltaT; } /*! \param v is the restart variables for the current integrator \param type is the type of expected integrator type \param nvariables is the expected number of variables If the either the integrator type or number of variables does not match the expected values, this function throws the appropriate warning and returns "false." Otherwise, the function returns true. */ bool IntegrationMethodTwoStep::restartInfoTestValid(const IntegratorVariables& v, std::string type, unsigned int nvariables) { bool good = true; if (v.type == "") good = false; else if (v.type != type && v.type != "") { m_exec_conf->msg->warning() << "Integrator #"<< m_integrator_id <<" type "<< type <<" does not match type "; m_exec_conf->msg->warning() << v.type << " found in restart file. " << endl; m_exec_conf->msg->warning() << "Ensure that the integrator order is consistent for restarted simulations. " << endl; m_exec_conf->msg->warning() << "Continuing while ignoring restart information..." << endl; good = false; } else if (v.type == type) { if (v.variable.size() != nvariables) { m_exec_conf->msg->warning() << "Integrator #"<< m_integrator_id <<" type "<< type << endl; m_exec_conf->msg->warning() << "appears to contain bad or incomplete restart information. " << endl; m_exec_conf->msg->warning() << "Continuing while ignoring restart information..." << endl; good = false; } } return good; } /*! \param query_group Group over which to count (translational) degrees of freedom. A majority of the integration methods add D degrees of freedom per particle in \a query_group that is also in the group assigned to the method. Hence, the base class IntegrationMethodTwoStep will implement that counting. Derived classes can override if needed. */ unsigned int IntegrationMethodTwoStep::getNDOF(std::shared_ptr<ParticleGroup> query_group) { // get the size of the intersection between query_group and m_group unsigned int intersect_size = ParticleGroup::groupIntersection(query_group, m_group)->getNumMembersGlobal(); return m_sysdef->getNDimensions() * intersect_size; } unsigned int IntegrationMethodTwoStep::getRotationalNDOF(std::shared_ptr<ParticleGroup> query_group) { // get the size of the intersection between query_group and m_group std::shared_ptr<ParticleGroup> intersect = ParticleGroup::groupIntersection(query_group, m_group); unsigned int local_group_size = intersect->getNumMembers(); unsigned int query_group_dof = 0; unsigned int dimension = m_sysdef->getNDimensions(); unsigned int dof_one; ArrayHandle<Scalar3> h_moment_inertia(m_pdata->getMomentsOfInertiaArray(), access_location::host, access_mode::read); for (unsigned int group_idx = 0; group_idx < local_group_size; group_idx++) { unsigned int j = intersect->getMemberIndex(group_idx); if (dimension == 3) { dof_one = 3; if (fabs(h_moment_inertia.data[j].x) < EPSILON) dof_one--; if (fabs(h_moment_inertia.data[j].y) < EPSILON) dof_one--; if (fabs(h_moment_inertia.data[j].z) < EPSILON) dof_one--; } else { dof_one = 1; if (fabs(h_moment_inertia.data[j].z) < EPSILON) dof_one--; } query_group_dof += dof_one; } #ifdef ENABLE_MPI if (m_pdata->getDomainDecomposition()) { MPI_Allreduce(MPI_IN_PLACE, &query_group_dof, 1, MPI_UNSIGNED, MPI_SUM, m_exec_conf->getMPICommunicator()); } #endif return query_group_dof; } /*! Checks that every particle in the group is valid. This method may be called by anyone wishing to make this error check. The base class does nothing */ void IntegrationMethodTwoStep::validateGroup() { for (unsigned int gidx = 0; gidx < m_group->getNumMembersGlobal(); gidx++) { unsigned int tag = m_group->getMemberTag(gidx); if (m_pdata->isParticleLocal(tag)) { ArrayHandle<unsigned int> h_body(m_pdata->getBodies(), access_location::host, access_mode::read); ArrayHandle<unsigned int> h_rtag(m_pdata->getRTags(), access_location::host, access_mode::read); ArrayHandle<unsigned int> h_tag(m_pdata->getTags(), access_location::host, access_mode::read); unsigned int body = h_body.data[h_rtag.data[tag]]; if (body != NO_BODY && body != tag) { m_exec_conf->msg->error() << "Particle " << tag << " belongs to a rigid body, but is not its center particle. " << std::endl << "This integration method does not operate on constituent particles." << std::endl << std::endl; throw std::runtime_error("Error initializing integration method"); } } } } /*! Randomizes linear velocities and angular momenta by sampling the Maxwell-Boltzmann (MB) distribution. The user provides three arguments: - The particle group - Temperature - Seed for initializing the random number generator used for this purpose These variables are member variables of the class. */ void IntegrationMethodTwoStep::randomizeVelocities(unsigned int timestep) { if (m_shouldRandomize == false) { return; } /* Get the number of particles in the group */ unsigned int group_size = m_group->getNumMembers(); /* Grab some variables */ const unsigned int D = Scalar(m_sysdef->getNDimensions()); ArrayHandle<Scalar4> h_vel(m_pdata->getVelocities(), access_location::host, access_mode::readwrite); ArrayHandle<Scalar4> h_orientation(m_pdata->getOrientationArray(), access_location::host, access_mode::read); ArrayHandle<Scalar4> h_angmom(m_pdata->getAngularMomentumArray(), access_location::host, access_mode::readwrite); ArrayHandle<Scalar3> h_inertia(m_pdata->getMomentsOfInertiaArray(), access_location::host, access_mode::read); ArrayHandle<unsigned int> h_tag(m_pdata->getTags(), access_location::host, access_mode::read); /* Total momentum */ vec3<Scalar> tot_momentum(0, 0, 0); /* Loop over all the particles in the group */ for (unsigned int group_idx = 0; group_idx < group_size; group_idx++) { unsigned int j = m_group->getMemberIndex(group_idx); unsigned int ptag = h_tag.data[j]; /* Initialize the random number generator */ hoomd::detail::Saru saru(ptag, timestep, m_seed_randomize); /* Generate a new random linear velocity for particle j */ Scalar mass = h_vel.data[j].w; Scalar sigma = fast::sqrt(m_T_randomize / mass); h_vel.data[j].x = gaussian_rng(saru, sigma); h_vel.data[j].y = gaussian_rng(saru, sigma); if (D > 2) h_vel.data[j].z = gaussian_rng(saru, sigma); else h_vel.data[j].z = 0; // For 2D systems tot_momentum += mass * vec3<Scalar>(h_vel.data[j]); /* Generate a new random angular momentum if the particle is a rigid * body and anisotropy flag gets set. * There may be some issues for 2D systems */ if (m_aniso) { vec3<Scalar> p_vec(0,0,0); quat<Scalar> q(h_orientation.data[j]); vec3<Scalar> I(h_inertia.data[j]); /* Generate a new random angular momentum for particle j in * body frame */ if (I.x >= EPSILON) p_vec.x = gaussian_rng(saru, fast::sqrt(m_T_randomize * I.x)); if (I.y >= EPSILON) p_vec.y = gaussian_rng(saru, fast::sqrt(m_T_randomize * I.y)); if (I.z >= EPSILON) p_vec.z = gaussian_rng(saru, fast::sqrt(m_T_randomize * I.z)); /* Store the angular momentum quaternion */ quat<Scalar> p = Scalar(2.0) * q * p_vec; h_angmom.data[j] = quat_to_scalar4(p); } } /* Remove the drift i.e. remove the center of mass velocity */ #ifdef ENABLE_MPI // Reduce the total momentum from all MPI ranks if (m_comm) { MPI_Allreduce(MPI_IN_PLACE, &tot_momentum, 3, MPI_HOOMD_SCALAR, MPI_SUM, m_exec_conf->getMPICommunicator()); } #endif vec3<Scalar> com_momentum(tot_momentum / Scalar(m_group->getNumMembersGlobal())); for (unsigned int group_idx = 0; group_idx < group_size; group_idx++) { unsigned int j = m_group->getMemberIndex(group_idx); Scalar mass = h_vel.data[j].w; h_vel.data[j].x = h_vel.data[j].x - com_momentum.x / mass; h_vel.data[j].y = h_vel.data[j].y - com_momentum.y / mass; if (D > 2) h_vel.data[j].z = h_vel.data[j].z - com_momentum.z / mass; else h_vel.data[j].z = 0; // For 2D systems } /* Done randomizing velocities */ /* Reset the flag */ m_shouldRandomize = false; } void export_IntegrationMethodTwoStep(py::module& m) { py::class_<IntegrationMethodTwoStep, std::shared_ptr<IntegrationMethodTwoStep> >(m, "IntegrationMethodTwoStep") .def(py::init< std::shared_ptr<SystemDefinition>, std::shared_ptr<ParticleGroup> >()) .def("validateGroup", &IntegrationMethodTwoStep::validateGroup) #ifdef ENABLE_MPI .def("setCommunicator", &IntegrationMethodTwoStep::setCommunicator) #endif .def("setRandomizeVelocitiesParams", &IntegrationMethodTwoStep::setRandomizeVelocitiesParams) ; } <commit_msg>speed up startup<commit_after>// Copyright (c) 2009-2018 The Regents of the University of Michigan // This file is part of the HOOMD-blue project, released under the BSD 3-Clause License. // Maintainer: joaander #include "IntegrationMethodTwoStep.h" #include "hoomd/VectorMath.h" #include "QuaternionMath.h" #include "hoomd/HOOMDMath.h" #include "hoomd/Saru.h" namespace py = pybind11; #ifdef ENABLE_MPI #include "hoomd/Communicator.h" #endif using namespace std; /*! \file IntegrationMethodTwoStep.h \brief Contains code for the IntegrationMethodTwoStep class */ /*! \param sysdef SystemDefinition this method will act on. Must not be NULL. \param group The group of particles this integration method is to work on \post The method is constructed with the given particle data and a NULL profiler. */ IntegrationMethodTwoStep::IntegrationMethodTwoStep(std::shared_ptr<SystemDefinition> sysdef, std::shared_ptr<ParticleGroup> group) : m_sysdef(sysdef), m_group(group), m_pdata(m_sysdef->getParticleData()), m_exec_conf(m_pdata->getExecConf()), m_aniso(false), m_deltaT(Scalar(0.0)), m_valid_restart(false) { // sanity check assert(m_sysdef); assert(m_pdata); assert(m_group); m_integrator_id = m_sysdef->getIntegratorData()->registerIntegrator(); } /*! It is useful for the user to know where computation time is spent, so all integration methods should profile themselves. This method sets the profiler for them to use. This method does not need to be called, as Computes will not profile themselves on a NULL profiler \param prof Pointer to a profiler for the compute to use. Set to NULL (std::shared_ptr<Profiler>()) to stop the analyzer from profiling itself. \note Derived classes MUST check if m_prof is set before calling any profiler methods. */ void IntegrationMethodTwoStep::setProfiler(std::shared_ptr<Profiler> prof) { m_prof = prof; } /*! \param deltaT New time step to set */ void IntegrationMethodTwoStep::setDeltaT(Scalar deltaT) { m_deltaT = deltaT; } /*! \param v is the restart variables for the current integrator \param type is the type of expected integrator type \param nvariables is the expected number of variables If the either the integrator type or number of variables does not match the expected values, this function throws the appropriate warning and returns "false." Otherwise, the function returns true. */ bool IntegrationMethodTwoStep::restartInfoTestValid(const IntegratorVariables& v, std::string type, unsigned int nvariables) { bool good = true; if (v.type == "") good = false; else if (v.type != type && v.type != "") { m_exec_conf->msg->warning() << "Integrator #"<< m_integrator_id <<" type "<< type <<" does not match type "; m_exec_conf->msg->warning() << v.type << " found in restart file. " << endl; m_exec_conf->msg->warning() << "Ensure that the integrator order is consistent for restarted simulations. " << endl; m_exec_conf->msg->warning() << "Continuing while ignoring restart information..." << endl; good = false; } else if (v.type == type) { if (v.variable.size() != nvariables) { m_exec_conf->msg->warning() << "Integrator #"<< m_integrator_id <<" type "<< type << endl; m_exec_conf->msg->warning() << "appears to contain bad or incomplete restart information. " << endl; m_exec_conf->msg->warning() << "Continuing while ignoring restart information..." << endl; good = false; } } return good; } /*! \param query_group Group over which to count (translational) degrees of freedom. A majority of the integration methods add D degrees of freedom per particle in \a query_group that is also in the group assigned to the method. Hence, the base class IntegrationMethodTwoStep will implement that counting. Derived classes can override if needed. */ unsigned int IntegrationMethodTwoStep::getNDOF(std::shared_ptr<ParticleGroup> query_group) { // get the size of the intersection between query_group and m_group unsigned int intersect_size = ParticleGroup::groupIntersection(query_group, m_group)->getNumMembersGlobal(); return m_sysdef->getNDimensions() * intersect_size; } unsigned int IntegrationMethodTwoStep::getRotationalNDOF(std::shared_ptr<ParticleGroup> query_group) { // get the size of the intersection between query_group and m_group std::shared_ptr<ParticleGroup> intersect = ParticleGroup::groupIntersection(query_group, m_group); unsigned int local_group_size = intersect->getNumMembers(); unsigned int query_group_dof = 0; unsigned int dimension = m_sysdef->getNDimensions(); unsigned int dof_one; ArrayHandle<Scalar3> h_moment_inertia(m_pdata->getMomentsOfInertiaArray(), access_location::host, access_mode::read); for (unsigned int group_idx = 0; group_idx < local_group_size; group_idx++) { unsigned int j = intersect->getMemberIndex(group_idx); if (dimension == 3) { dof_one = 3; if (fabs(h_moment_inertia.data[j].x) < EPSILON) dof_one--; if (fabs(h_moment_inertia.data[j].y) < EPSILON) dof_one--; if (fabs(h_moment_inertia.data[j].z) < EPSILON) dof_one--; } else { dof_one = 1; if (fabs(h_moment_inertia.data[j].z) < EPSILON) dof_one--; } query_group_dof += dof_one; } #ifdef ENABLE_MPI if (m_pdata->getDomainDecomposition()) { MPI_Allreduce(MPI_IN_PLACE, &query_group_dof, 1, MPI_UNSIGNED, MPI_SUM, m_exec_conf->getMPICommunicator()); } #endif return query_group_dof; } /*! Checks that every particle in the group is valid. This method may be called by anyone wishing to make this error check. The base class does nothing */ void IntegrationMethodTwoStep::validateGroup() { ArrayHandle<unsigned int> h_body(m_pdata->getBodies(), access_location::host, access_mode::read); ArrayHandle<unsigned int> h_rtag(m_pdata->getRTags(), access_location::host, access_mode::read); ArrayHandle<unsigned int> h_tag(m_pdata->getTags(), access_location::host, access_mode::read); ArrayHandle<unsigned int> h_group_index(m_group->getIndexArray(), access_location::host, access_mode::read); for (unsigned int gidx = 0; gidx < m_group->getNumMembers(); gidx++) { unsigned int i = h_group_index.data[gidx]; unsigned int tag = h_tag.data[i]; unsigned int body = h_body.data[i]; if (body != NO_BODY && body != tag) { m_exec_conf->msg->error() << "Particle " << tag << " belongs to a rigid body, but is not its center particle. " << std::endl << "This integration method does not operate on constituent particles." << std::endl << std::endl; throw std::runtime_error("Error initializing integration method"); } } } /*! Randomizes linear velocities and angular momenta by sampling the Maxwell-Boltzmann (MB) distribution. The user provides three arguments: - The particle group - Temperature - Seed for initializing the random number generator used for this purpose These variables are member variables of the class. */ void IntegrationMethodTwoStep::randomizeVelocities(unsigned int timestep) { if (m_shouldRandomize == false) { return; } /* Get the number of particles in the group */ unsigned int group_size = m_group->getNumMembers(); /* Grab some variables */ const unsigned int D = Scalar(m_sysdef->getNDimensions()); ArrayHandle<Scalar4> h_vel(m_pdata->getVelocities(), access_location::host, access_mode::readwrite); ArrayHandle<Scalar4> h_orientation(m_pdata->getOrientationArray(), access_location::host, access_mode::read); ArrayHandle<Scalar4> h_angmom(m_pdata->getAngularMomentumArray(), access_location::host, access_mode::readwrite); ArrayHandle<Scalar3> h_inertia(m_pdata->getMomentsOfInertiaArray(), access_location::host, access_mode::read); ArrayHandle<unsigned int> h_tag(m_pdata->getTags(), access_location::host, access_mode::read); /* Total momentum */ vec3<Scalar> tot_momentum(0, 0, 0); /* Loop over all the particles in the group */ for (unsigned int group_idx = 0; group_idx < group_size; group_idx++) { unsigned int j = m_group->getMemberIndex(group_idx); unsigned int ptag = h_tag.data[j]; /* Initialize the random number generator */ hoomd::detail::Saru saru(ptag, timestep, m_seed_randomize); /* Generate a new random linear velocity for particle j */ Scalar mass = h_vel.data[j].w; Scalar sigma = fast::sqrt(m_T_randomize / mass); h_vel.data[j].x = gaussian_rng(saru, sigma); h_vel.data[j].y = gaussian_rng(saru, sigma); if (D > 2) h_vel.data[j].z = gaussian_rng(saru, sigma); else h_vel.data[j].z = 0; // For 2D systems tot_momentum += mass * vec3<Scalar>(h_vel.data[j]); /* Generate a new random angular momentum if the particle is a rigid * body and anisotropy flag gets set. * There may be some issues for 2D systems */ if (m_aniso) { vec3<Scalar> p_vec(0,0,0); quat<Scalar> q(h_orientation.data[j]); vec3<Scalar> I(h_inertia.data[j]); /* Generate a new random angular momentum for particle j in * body frame */ if (I.x >= EPSILON) p_vec.x = gaussian_rng(saru, fast::sqrt(m_T_randomize * I.x)); if (I.y >= EPSILON) p_vec.y = gaussian_rng(saru, fast::sqrt(m_T_randomize * I.y)); if (I.z >= EPSILON) p_vec.z = gaussian_rng(saru, fast::sqrt(m_T_randomize * I.z)); /* Store the angular momentum quaternion */ quat<Scalar> p = Scalar(2.0) * q * p_vec; h_angmom.data[j] = quat_to_scalar4(p); } } /* Remove the drift i.e. remove the center of mass velocity */ #ifdef ENABLE_MPI // Reduce the total momentum from all MPI ranks if (m_comm) { MPI_Allreduce(MPI_IN_PLACE, &tot_momentum, 3, MPI_HOOMD_SCALAR, MPI_SUM, m_exec_conf->getMPICommunicator()); } #endif vec3<Scalar> com_momentum(tot_momentum / Scalar(m_group->getNumMembersGlobal())); for (unsigned int group_idx = 0; group_idx < group_size; group_idx++) { unsigned int j = m_group->getMemberIndex(group_idx); Scalar mass = h_vel.data[j].w; h_vel.data[j].x = h_vel.data[j].x - com_momentum.x / mass; h_vel.data[j].y = h_vel.data[j].y - com_momentum.y / mass; if (D > 2) h_vel.data[j].z = h_vel.data[j].z - com_momentum.z / mass; else h_vel.data[j].z = 0; // For 2D systems } /* Done randomizing velocities */ /* Reset the flag */ m_shouldRandomize = false; } void export_IntegrationMethodTwoStep(py::module& m) { py::class_<IntegrationMethodTwoStep, std::shared_ptr<IntegrationMethodTwoStep> >(m, "IntegrationMethodTwoStep") .def(py::init< std::shared_ptr<SystemDefinition>, std::shared_ptr<ParticleGroup> >()) .def("validateGroup", &IntegrationMethodTwoStep::validateGroup) #ifdef ENABLE_MPI .def("setCommunicator", &IntegrationMethodTwoStep::setCommunicator) #endif .def("setRandomizeVelocitiesParams", &IntegrationMethodTwoStep::setRandomizeVelocitiesParams) ; } <|endoftext|>
<commit_before>/***************************************************************************** ****************************************************************************** bmpgrep Author: Gordon McCreight email: gordon@mccreight.com date modified: 2009-04-25 version: 0.08 License: GPL 2 Copyright: 2009 by Gordon McCreight usage: bmpgrep return_how_many_matches pattern_threshold (the line continues...) tolerance_r tolerance_g tolerance_b big.bmp small.bmp If return_how_many_matches is set to 0, then it will find as many as it can. "pattern_threshold" determines how aggressively it tries to shrink the pattern it creates for the small image. We recommend something around 30. A value of 0 skips no pixels. Over 100 tends to cause false positive matches, because there may not be enough pixels to check. tolerances are 0-255 description: Find the location of a small BMP within a big one. Prints a comma seperated list of x,y (for one match) or x,y,x,y,x,y for multiple matches. Note: Can be compiled like so: g++ -o bmpgrep bmpgrep.cpp EasyBMP.cpp After you compile, you might want to test with this (the result should be six numbers long): ./bmpgrep 0 30 0 0 0 test_images/big.bmp test_images/small.bmp The program also ships with a compile_and_test.pl perl script that pushes the tests a bit harder. You can also run that test script with the option 1 ( so, like ./compile_and_test.pl 1 ) and it will run it as a performance test. One note, we modify the stock EasyBMP library in one place where is does bounds checking on the pixel requested. We've removed the bounds checking. This speeds things up a bit. TODO: Better options verification and add help information. ****************************************************************************** *****************************************************************************/ #include "EasyBMP.h" using namespace std; // This needs to be created as a global because it potentially needs to be // really big. Arrays allocated inside a function cannot be this big. int fast_pattern[800 * 600][5]; static inline double Abs (double Nbr) { if( Nbr >= 0 ) return Nbr; else return -Nbr; } int main( int argc, char* argv[] ) { int optind = 1; int return_how_many_matches = atoi(argv[ optind ]); optind++; int pattern_threshold = atoi(argv[ optind ]); optind++; int tolerance_r = atoi(argv[ optind ]); optind++; int tolerance_g = atoi(argv[ optind ]); optind++; int tolerance_b = atoi(argv[ optind ]); optind++; int has_tolerances = false; if (tolerance_r > 0 || tolerance_g > 0 || tolerance_b > 0) { has_tolerances = true; } BMP Big; Big.ReadFromFile(argv[ optind ]); optind++; BMP Small; Small.ReadFromFile(argv[ optind ]); optind++; int big_x, big_y, small_x, small_y; int big_height = Big.TellHeight(); int big_width = Big.TellWidth(); int small_height = Small.TellHeight(); int small_width = Small.TellWidth(); if ( small_height * small_width > 800 * 600 ) { cout << "We can only handle small images that contain fewer than" << "800 x 600 pixels" << endl; return 0; } int small_pattern_array_size = 0; int last_pattern_pixel_brightness = -1; for (small_y = 0; small_y < small_height; small_y++) { for (small_x = 0; small_x < small_width; small_x++) { RGBApixel* SmallPixel = Small(small_x, small_y); int this_pixel_brightness = SmallPixel->Red + SmallPixel->Green + SmallPixel->Blue; if ( Abs( this_pixel_brightness - last_pattern_pixel_brightness ) >= pattern_threshold ) { fast_pattern[small_pattern_array_size][0] = small_x; fast_pattern[small_pattern_array_size][1] = small_y; fast_pattern[small_pattern_array_size][2] = SmallPixel->Red; fast_pattern[small_pattern_array_size][3] = SmallPixel->Green; fast_pattern[small_pattern_array_size][4] = SmallPixel->Blue; last_pattern_pixel_brightness = this_pixel_brightness; small_pattern_array_size++; } } } //#define DEBUG_THE_FAST_PATTERN #ifdef DEBUG_THE_FAST_PATTERN for ( int pattern_index = 0; pattern_index < 5; pattern_index++ ) { for ( int part = 0; part < 5; part++ ) { cout << fast_pattern[pattern_index][part] << endl; } cout << endl; } cout << small_pattern_array_size << endl; return 0; #endif /* You don't need to check the whole big image. For example, if the small image is 100 pixels wide, then you know that there's no way it could match in the 99 right-most pixels of the big image. The same idea is applicable for the height. */ int max_y_to_check = big_height - small_height; int max_x_to_check = big_width - small_width; int has_written_results = 0; int has_matched_x_times = 0; /* This is declared here instead of inside the inner "pattern" for loop because we use it after the for loop is completed to check if there was a perfect match */ int small_pattern_index = 0; for (big_y = 0; big_y < max_y_to_check; ++big_y) { for (big_x = 0; big_x < max_x_to_check; ++big_x) { for ( small_pattern_index = 0; small_pattern_index < small_pattern_array_size; small_pattern_index++ ) { RGBApixel* BigPixel = Big(big_x + fast_pattern[small_pattern_index][0], big_y + fast_pattern[small_pattern_index][1]); /* Do these as preprocessor macros for two reasons. The first is that they're used in two places, and the code looks a lot cleaner. The second is that it's better than writing them to variables, since they may not all three be used in each comparison, and variables are overkill anyhow. */ #define SMALL_RED fast_pattern[small_pattern_index][2] #define SMALL_GREEN fast_pattern[small_pattern_index][3] #define SMALL_BLUE fast_pattern[small_pattern_index][4] if ( has_tolerances == false ) { // zero tolerance, so do it faster if ( BigPixel->Red != SMALL_RED ) { break; } else if ( BigPixel->Green != SMALL_GREEN ) { break; } else if ( BigPixel->Blue != SMALL_BLUE ) { break; } } else { if ( Abs(BigPixel->Red - SMALL_RED ) > tolerance_r ) { break; } else if ( Abs(BigPixel->Green - SMALL_GREEN ) > tolerance_g ) { break; } else if ( Abs(BigPixel->Blue - SMALL_BLUE ) > tolerance_b ) { break; } } } // There was a complete match! Note that this check // is done after the for loop, not inside it. Checking // outside the loop is a bit faster. if (small_pattern_index == small_pattern_array_size) { if (has_written_results == 1) { cout << ","; } cout << big_x << "," << big_y; has_matched_x_times++; if (has_matched_x_times == return_how_many_matches) { cout << endl; return 0; } has_written_results = 1; } } } if (has_written_results == 1) { cout << endl; } return 0; } <commit_msg>committing so I can revert but keep this version<commit_after>/***************************************************************************** ****************************************************************************** bmpgrep Author: Gordon McCreight email: gordon@mccreight.com date modified: 2009-04-27 version: 0.09 License: GPL 2 Copyright: 2009 by Gordon McCreight usage: bmpgrep return_how_many_matches pattern_threshold (the line continues...) tolerance_r tolerance_g tolerance_b big.bmp small.bmp If return_how_many_matches is set to 0, then it will find as many as it can. "pattern_threshold" determines how aggressively it tries to shrink the pattern it creates for the small image. We recommend something around 30. A value of 0 skips no pixels. Over 100 tends to cause false positive matches, because there may not be enough pixels to check. tolerances are 0-255 description: Find the location of a small BMP within a big one. Prints a comma seperated list of x,y (for one match) or x,y,x,y,x,y for multiple matches. Note: Can be compiled like so: g++ -o bmpgrep bmpgrep.cpp EasyBMP.cpp After you compile, you might want to test with this (the result should be six numbers long): ./bmpgrep 0 30 0 0 0 test_images/big.bmp test_images/small.bmp The program also ships with a compile_and_test.pl perl script that pushes the tests a bit harder. You can also run that test script with the option 1 ( so, like ./compile_and_test.pl 1 ) and it will run it as a performance test. One note, we modify the stock EasyBMP library in one place where is does bounds checking on the pixel requested. We've removed the bounds checking. This speeds things up a bit. TODO: Better options verification and add help information. ****************************************************************************** *****************************************************************************/ #include "EasyBMP.h" using namespace std; // This needs to be created as a global because it potentially needs to be // really big. Arrays allocated inside a function cannot be this big. int fast_pattern[800 * 600][5]; static inline double Abs (double Nbr) { if( Nbr >= 0 ) return Nbr; else return -Nbr; } int main( int argc, char* argv[] ) { int optind = 1; int return_how_many_matches = atoi(argv[ optind ]); optind++; int pattern_threshold = atoi(argv[ optind ]); optind++; int tolerance_r = atoi(argv[ optind ]); optind++; int tolerance_g = atoi(argv[ optind ]); optind++; int tolerance_b = atoi(argv[ optind ]); optind++; int has_tolerances = false; if (tolerance_r > 0 || tolerance_g > 0 || tolerance_b > 0) { has_tolerances = true; } BMP Big; Big.ReadFromFile(argv[ optind ]); optind++; BMP Small; Small.ReadFromFile(argv[ optind ]); optind++; int big_x, big_y, small_x, small_y; int big_height = Big.TellHeight(); int big_width = Big.TellWidth(); int small_height = Small.TellHeight(); int small_width = Small.TellWidth(); if ( small_height * small_width > 800 * 600 ) { cout << "We can only handle small images that contain fewer than" << "800 x 600 pixels" << endl; return 0; } int small_pattern_array_size = 0; int last_pattern_pixel_brightness = -1; for (small_y = 0; small_y < small_height; small_y++) { for (small_x = 0; small_x < small_width; small_x++) { RGBApixel* SmallPixel = Small(small_x, small_y); int this_pixel_brightness = SmallPixel->Red + SmallPixel->Green + SmallPixel->Blue; if ( Abs( this_pixel_brightness - last_pattern_pixel_brightness ) >= pattern_threshold ) { fast_pattern[small_pattern_array_size][0] = small_x; fast_pattern[small_pattern_array_size][1] = small_y; fast_pattern[small_pattern_array_size][2] = SmallPixel->Red; fast_pattern[small_pattern_array_size][3] = SmallPixel->Green; fast_pattern[small_pattern_array_size][4] = SmallPixel->Blue; last_pattern_pixel_brightness = this_pixel_brightness; small_pattern_array_size++; } } } //#define DEBUG_THE_FAST_PATTERN #ifdef DEBUG_THE_FAST_PATTERN for ( int pattern_index = 0; pattern_index < 5; pattern_index++ ) { for ( int part = 0; part < 5; part++ ) { cout << fast_pattern[pattern_index][part] << endl; } cout << endl; } cout << small_pattern_array_size << endl; return 0; #endif /* You don't need to check the whole big image. For example, if the small image is 100 pixels wide, then you know that there's no way it could match in the 99 right-most pixels of the big image. The same idea is applicable for the height. */ int max_y_to_check = big_height - small_height; int max_x_to_check = big_width - small_width; int has_written_results = 0; int has_matched_x_times = 0; /* This is declared here instead of inside the inner "pattern" for loop because we use it after the for loop is completed to check if there was a perfect match */ int small_pattern_index = 0; /* LOOPS_START and LOOPS_END are done as preprocessor macros because of the difference between has_tolerances == true and has_tolerances == false. I used to check whether has_tolerances == false inside the inner loop, but that would be checked potentially millions of times for even a smaller "big" image. So, I decided to move the check to the outside of the loop. But that meant we had to have the exact same set of source code for the loop in two places. Ugly. So I consolidated it into these two preprocessor definitions. Still not too pretty, but DRY. In the previous version, the fastest run was 6.57 */ #define LOOPS_START \ for (big_y = 0; big_y < max_y_to_check; big_y++) { \ for (big_x = 0; big_x < max_x_to_check; big_x++) { \ for ( small_pattern_index = 0; \ small_pattern_index < small_pattern_array_size; \ small_pattern_index++ ) { \ RGBApixel* BigPixel = Big(big_x + fast_pattern[small_pattern_index][0], \ big_y + fast_pattern[small_pattern_index][1]); #define LOOPS_END \ } \ if (small_pattern_index == small_pattern_array_size) { \ if (has_written_results == 1) { \ cout << ","; \ } \ cout << big_x << "," << big_y; \ has_matched_x_times++; \ if (has_matched_x_times == return_how_many_matches) { \ cout << endl; \ return 0; \ } \ has_written_results = 1; \ } \ } \ } \ /* These three are preprocessor macros for two reasons. The first is that they're used in two places, and the code looks a lot cleaner. The second is that it's better than writing them to variables, since they may not all three be used in each comparison, and variables are overkill. */ #define SMALL_RED fast_pattern[small_pattern_index][2] #define SMALL_GREEN fast_pattern[small_pattern_index][3] #define SMALL_BLUE fast_pattern[small_pattern_index][4] if ( has_tolerances == false ) { LOOPS_START // zero tolerance, so do it faster if ( BigPixel->Red != SMALL_RED ) { break; } else if ( BigPixel->Green != SMALL_GREEN ) { break; } else if ( BigPixel->Blue != SMALL_BLUE ) { break; } LOOPS_END } else { LOOPS_START if ( Abs(BigPixel->Red - SMALL_RED ) > tolerance_r ) { break; } else if ( Abs(BigPixel->Green - SMALL_GREEN ) > tolerance_g ) { break; } else if ( Abs(BigPixel->Blue - SMALL_BLUE ) > tolerance_b ) { break; } LOOPS_END } if (has_written_results == 1) { cout << endl; } return 0; } <|endoftext|>
<commit_before>#include <sstream> #include "StorageFlattening.h" #include "IRMutator.h" #include "IROperator.h" #include "Scope.h" #include "Bounds.h" #include "Parameter.h" namespace Halide { namespace Internal { using std::ostringstream; using std::string; using std::vector; using std::map; using std::pair; using std::set; namespace { class FlattenDimensions : public IRMutator { public: FlattenDimensions(const map<string, pair<Function, int>> &e, const Target &t) : env(e), target(t) {} Scope<int> scope; private: const map<string, pair<Function, int>> &env; const Target &target; Scope<int> realizations; Expr flatten_args(const string &name, const vector<Expr> &args) { bool internal = realizations.contains(name); Expr idx = target.has_feature(Target::LargeBuffers) ? make_zero(Int(64)) : 0; vector<Expr> mins(args.size()), strides(args.size()); for (size_t i = 0; i < args.size(); i++) { string dim = std::to_string(i); string stride_name = name + ".stride." + dim; string min_name = name + ".min." + dim; string stride_name_constrained = stride_name + ".constrained"; string min_name_constrained = min_name + ".constrained"; if (scope.contains(stride_name_constrained)) { stride_name = stride_name_constrained; } if (scope.contains(min_name_constrained)) { min_name = min_name_constrained; } strides[i] = Variable::make(Int(32), stride_name); mins[i] = Variable::make(Int(32), min_name); } if (internal) { // f(x, y) -> f[(x-xmin)*xstride + (y-ymin)*ystride] This // strategy makes sense when we expect x to cancel with // something in xmin. We use this for internal allocations for (size_t i = 0; i < args.size(); i++) { if (target.has_feature(Target::LargeBuffers)) { idx += cast<int64_t>(args[i] - mins[i]) * cast<int64_t>(strides[i]); } else { idx += (args[i] - mins[i]) * strides[i]; } } } else { // f(x, y) -> f[x*stride + y*ystride - (xstride*xmin + // ystride*ymin)]. The idea here is that the last term // will be pulled outside the inner loop. We use this for // external buffers, where the mins and strides are likely // to be symbolic Expr base = target.has_feature(Target::LargeBuffers) ? make_zero(Int(64)) : 0; for (size_t i = 0; i < args.size(); i++) { if (target.has_feature(Target::LargeBuffers)) { idx += cast<int64_t>(args[i]) * cast<int64_t>(strides[i]); base += cast<int64_t>(mins[i]) * cast<int64_t>(strides[i]); } else { idx += args[i] * strides[i]; base += mins[i] * strides[i]; } } idx -= base; } return idx; } using IRMutator::visit; void visit(const Realize *op) { realizations.push(op->name, 0); Stmt body = mutate(op->body); // Compute the size std::vector<Expr> extents; for (size_t i = 0; i < op->bounds.size(); i++) { extents.push_back(op->bounds[i].extent); extents[i] = mutate(extents[i]); } Expr condition = mutate(op->condition); realizations.pop(op->name); vector<int> storage_permutation; { auto iter = env.find(op->name); Function f = iter->second.first; internal_assert(iter != env.end()) << "Realize node refers to function not in environment.\n"; const vector<StorageDim> &storage_dims = f.schedule().storage_dims(); const vector<string> &args = f.args(); for (size_t i = 0; i < storage_dims.size(); i++) { for (size_t j = 0; j < args.size(); j++) { if (args[j] == storage_dims[i].var) { storage_permutation.push_back((int)j); Expr alignment = storage_dims[i].alignment; if (alignment.defined()) { extents[j] = ((extents[j] + alignment - 1)/alignment)*alignment; } } } internal_assert(storage_permutation.size() == i+1); } } internal_assert(storage_permutation.size() == op->bounds.size()); stmt = body; internal_assert(op->types.size() == 1); // Make the names for the mins, extents, and strides int dims = op->bounds.size(); vector<string> min_name(dims), extent_name(dims), stride_name(dims); for (int i = 0; i < dims; i++) { string d = std::to_string(i); min_name[i] = op->name + ".min." + d; stride_name[i] = op->name + ".stride." + d; extent_name[i] = op->name + ".extent." + d; } vector<Expr> min_var(dims), extent_var(dims), stride_var(dims); for (int i = 0; i < dims; i++) { min_var[i] = Variable::make(Int(32), min_name[i]); extent_var[i] = Variable::make(Int(32), extent_name[i]); stride_var[i] = Variable::make(Int(32), stride_name[i]); } // Create a buffer_t object for this allocation. if (dims <= 4) { BufferBuilder builder; Expr first_elem = Load::make(op->types[0], op->name, 0, Buffer<>(), Parameter(), const_true(op->types[0].lanes())); builder.host = Call::make(Handle(), Call::address_of, {first_elem}, Call::PureIntrinsic); builder.type = op->types[0]; builder.dimensions = dims; for (int i = 0; i < dims; i++) { builder.mins.push_back(min_var[i]); builder.extents.push_back(extent_var[i]); builder.strides.push_back(stride_var[i]); } stmt = LetStmt::make(op->name + ".buffer", builder.build(), stmt); } // Make the allocation node stmt = Allocate::make(op->name, op->types[0], extents, condition, stmt); // Compute the strides for (int i = (int)op->bounds.size()-1; i > 0; i--) { int prev_j = storage_permutation[i-1]; int j = storage_permutation[i]; Expr stride = stride_var[prev_j] * extent_var[prev_j]; stmt = LetStmt::make(stride_name[j], stride, stmt); } // Innermost stride is one if (dims > 0) { int innermost = storage_permutation.empty() ? 0 : storage_permutation[0]; stmt = LetStmt::make(stride_name[innermost], 1, stmt); } // Assign the mins and extents stored for (size_t i = op->bounds.size(); i > 0; i--) { stmt = LetStmt::make(min_name[i-1], op->bounds[i-1].min, stmt); stmt = LetStmt::make(extent_name[i-1], extents[i-1], stmt); } } void visit(const Provide *op) { internal_assert(op->values.size() == 1); Expr idx = mutate(flatten_args(op->name, op->args)); Expr value = mutate(op->values[0]); stmt = Store::make(op->name, value, idx, Parameter(), const_true(value.type().lanes())); } void visit(const Call *op) { if (op->call_type == Call::Halide || op->call_type == Call::Image) { internal_assert(op->value_index == 0); Expr idx = mutate(flatten_args(op->name, op->args)); expr = Load::make(op->type, op->name, idx, op->image, op->param, const_true(op->type.lanes())); } else { IRMutator::visit(op); } } void visit(const LetStmt *let) { // Discover constrained versions of things. bool constrained_version_exists = ends_with(let->name, ".constrained"); if (constrained_version_exists) { scope.push(let->name, 0); } IRMutator::visit(let); if (constrained_version_exists) { scope.pop(let->name); } } }; // Realizations, stores, and loads must all be on types that are // multiples of 8-bits. This really only affects bools class PromoteToMemoryType : public IRMutator { using IRMutator::visit; Type upgrade(Type t) { return t.with_bits(((t.bits() + 7)/8)*8); } void visit(const Call *op) { if (op->is_intrinsic(Call::address_of)) { Expr load = mutate(op->args[0]); if (const Cast *cast = load.as<Cast>()) { load = cast->value; } expr = Call::make(op->type, op->name, {load}, op->call_type); } else { IRMutator::visit(op); } } void visit(const Load *op) { Type t = upgrade(op->type); if (t != op->type) { expr = Cast::make(op->type, Load::make(t, op->name, mutate(op->index), op->image, op->param, mutate(op->predicate))); } else { IRMutator::visit(op); } } void visit(const Store *op) { Type t = upgrade(op->value.type()); if (t != op->value.type()) { stmt = Store::make(op->name, Cast::make(t, mutate(op->value)), mutate(op->index), op->param, mutate(op->predicate)); } else { IRMutator::visit(op); } } void visit(const Allocate *op) { Type t = upgrade(op->type); if (t != op->type) { vector<Expr> extents; for (Expr e : op->extents) { extents.push_back(mutate(e)); } stmt = Allocate::make(op->name, t, extents, mutate(op->condition), mutate(op->body), mutate(op->new_expr), op->free_function); } else { IRMutator::visit(op); } } }; // Connect Store nodes to their output buffers class ConnectOutputBuffers : public IRMutator { using IRMutator::visit; void visit(const Store *op) { Parameter output_buf; auto it = env.find(op->name); if (it != env.end()) { const Function &f = it->second.first; int idx = it->second.second; // We only want to do this for actual pipeline outputs, // even though every Function has an output buffer. Any // constraints you set on the output buffer of a Func that // isn't actually an output is ignored. This is a language // wart. if (outputs.count(f.name())) { output_buf = f.output_buffers()[idx]; } } if (output_buf.defined()) { stmt = Store::make(op->name, op->value, op->index, output_buf, const_true()); } else { stmt = op; } } const map<string, pair<Function, int>> &env; set<string> outputs; public: ConnectOutputBuffers(const std::map<string, pair<Function, int>> &e, const vector<Function> &o) : env(e) { for (auto &f : o) { outputs.insert(f.name()); } } }; } // namespace Stmt storage_flattening(Stmt s, const vector<Function> &outputs, const map<string, Function> &env, const Target &target) { // Make an environment that makes it easier to figure out which // Function corresponds to a tuple component. foo.0, foo.1, foo.2, // all point to the function foo. map<string, pair<Function, int>> tuple_env; for (auto p : env) { if (p.second.outputs() > 1) { for (int i = 0; i < p.second.outputs(); i++) { tuple_env[p.first + "." + std::to_string(i)] = {p.second, i}; } } else { tuple_env[p.first] = {p.second, 0}; } } s = FlattenDimensions(tuple_env, target).mutate(s); s = PromoteToMemoryType().mutate(s); s = ConnectOutputBuffers(tuple_env, outputs).mutate(s); return s; } } } <commit_msg>Fix .min/.stride symbols not being connected to Param<commit_after>#include <sstream> #include "StorageFlattening.h" #include "IRMutator.h" #include "IROperator.h" #include "Scope.h" #include "Bounds.h" #include "Parameter.h" namespace Halide { namespace Internal { using std::ostringstream; using std::string; using std::vector; using std::map; using std::pair; using std::set; namespace { class FlattenDimensions : public IRMutator { public: FlattenDimensions(const map<string, pair<Function, int>> &e, const vector<Function> &o, const Target &t) : env(e), target(t) { for (auto &f : o) { outputs.insert(f.name()); } } Scope<int> scope; private: const map<string, pair<Function, int>> &env; set<string> outputs; const Target &target; Scope<int> realizations; Expr flatten_args(const string &name, const vector<Expr> &args, const Buffer<> &buf, const Parameter &param) { bool internal = realizations.contains(name); Expr idx = target.has_feature(Target::LargeBuffers) ? make_zero(Int(64)) : 0; vector<Expr> mins(args.size()), strides(args.size()); ReductionDomain rdom; for (size_t i = 0; i < args.size(); i++) { string dim = std::to_string(i); string stride_name = name + ".stride." + dim; string min_name = name + ".min." + dim; string stride_name_constrained = stride_name + ".constrained"; string min_name_constrained = min_name + ".constrained"; if (scope.contains(stride_name_constrained)) { stride_name = stride_name_constrained; } if (scope.contains(min_name_constrained)) { min_name = min_name_constrained; } strides[i] = Variable::make(Int(32), stride_name, buf, param, rdom); mins[i] = Variable::make(Int(32), min_name, buf, param, rdom); } if (internal) { // f(x, y) -> f[(x-xmin)*xstride + (y-ymin)*ystride] This // strategy makes sense when we expect x to cancel with // something in xmin. We use this for internal allocations for (size_t i = 0; i < args.size(); i++) { if (target.has_feature(Target::LargeBuffers)) { idx += cast<int64_t>(args[i] - mins[i]) * cast<int64_t>(strides[i]); } else { idx += (args[i] - mins[i]) * strides[i]; } } } else { // f(x, y) -> f[x*stride + y*ystride - (xstride*xmin + // ystride*ymin)]. The idea here is that the last term // will be pulled outside the inner loop. We use this for // external buffers, where the mins and strides are likely // to be symbolic Expr base = target.has_feature(Target::LargeBuffers) ? make_zero(Int(64)) : 0; for (size_t i = 0; i < args.size(); i++) { if (target.has_feature(Target::LargeBuffers)) { idx += cast<int64_t>(args[i]) * cast<int64_t>(strides[i]); base += cast<int64_t>(mins[i]) * cast<int64_t>(strides[i]); } else { idx += args[i] * strides[i]; base += mins[i] * strides[i]; } } idx -= base; } return idx; } using IRMutator::visit; void visit(const Realize *op) { realizations.push(op->name, 0); Stmt body = mutate(op->body); // Compute the size std::vector<Expr> extents; for (size_t i = 0; i < op->bounds.size(); i++) { extents.push_back(op->bounds[i].extent); extents[i] = mutate(extents[i]); } Expr condition = mutate(op->condition); realizations.pop(op->name); vector<int> storage_permutation; { auto iter = env.find(op->name); Function f = iter->second.first; internal_assert(iter != env.end()) << "Realize node refers to function not in environment.\n"; const vector<StorageDim> &storage_dims = f.schedule().storage_dims(); const vector<string> &args = f.args(); for (size_t i = 0; i < storage_dims.size(); i++) { for (size_t j = 0; j < args.size(); j++) { if (args[j] == storage_dims[i].var) { storage_permutation.push_back((int)j); Expr alignment = storage_dims[i].alignment; if (alignment.defined()) { extents[j] = ((extents[j] + alignment - 1)/alignment)*alignment; } } } internal_assert(storage_permutation.size() == i+1); } } internal_assert(storage_permutation.size() == op->bounds.size()); stmt = body; internal_assert(op->types.size() == 1); // Make the names for the mins, extents, and strides int dims = op->bounds.size(); vector<string> min_name(dims), extent_name(dims), stride_name(dims); for (int i = 0; i < dims; i++) { string d = std::to_string(i); min_name[i] = op->name + ".min." + d; stride_name[i] = op->name + ".stride." + d; extent_name[i] = op->name + ".extent." + d; } vector<Expr> min_var(dims), extent_var(dims), stride_var(dims); for (int i = 0; i < dims; i++) { min_var[i] = Variable::make(Int(32), min_name[i]); extent_var[i] = Variable::make(Int(32), extent_name[i]); stride_var[i] = Variable::make(Int(32), stride_name[i]); } // Create a buffer_t object for this allocation. if (dims <= 4) { BufferBuilder builder; Expr first_elem = Load::make(op->types[0], op->name, 0, Buffer<>(), Parameter(), const_true(op->types[0].lanes())); builder.host = Call::make(Handle(), Call::address_of, {first_elem}, Call::PureIntrinsic); builder.type = op->types[0]; builder.dimensions = dims; for (int i = 0; i < dims; i++) { builder.mins.push_back(min_var[i]); builder.extents.push_back(extent_var[i]); builder.strides.push_back(stride_var[i]); } stmt = LetStmt::make(op->name + ".buffer", builder.build(), stmt); } // Make the allocation node stmt = Allocate::make(op->name, op->types[0], extents, condition, stmt); // Compute the strides for (int i = (int)op->bounds.size()-1; i > 0; i--) { int prev_j = storage_permutation[i-1]; int j = storage_permutation[i]; Expr stride = stride_var[prev_j] * extent_var[prev_j]; stmt = LetStmt::make(stride_name[j], stride, stmt); } // Innermost stride is one if (dims > 0) { int innermost = storage_permutation.empty() ? 0 : storage_permutation[0]; stmt = LetStmt::make(stride_name[innermost], 1, stmt); } // Assign the mins and extents stored for (size_t i = op->bounds.size(); i > 0; i--) { stmt = LetStmt::make(min_name[i-1], op->bounds[i-1].min, stmt); stmt = LetStmt::make(extent_name[i-1], extents[i-1], stmt); } } void visit(const Provide *op) { internal_assert(op->values.size() == 1); Parameter output_buf; auto it = env.find(op->name); if (it != env.end()) { const Function &f = it->second.first; int idx = it->second.second; // We only want to do this for actual pipeline outputs, // even though every Function has an output buffer. Any // constraints you set on the output buffer of a Func that // isn't actually an output is ignored. This is a language // wart. if (outputs.count(f.name())) { output_buf = f.output_buffers()[idx]; } } Expr idx = mutate(flatten_args(op->name, op->args, Buffer<>(), output_buf)); Expr value = mutate(op->values[0]); stmt = Store::make(op->name, value, idx, output_buf, const_true(value.type().lanes())); } void visit(const Call *op) { if (op->call_type == Call::Halide || op->call_type == Call::Image) { internal_assert(op->value_index == 0); Expr idx = mutate(flatten_args(op->name, op->args, op->image, op->param)); expr = Load::make(op->type, op->name, idx, op->image, op->param, const_true(op->type.lanes())); } else { IRMutator::visit(op); } } void visit(const LetStmt *let) { // Discover constrained versions of things. bool constrained_version_exists = ends_with(let->name, ".constrained"); if (constrained_version_exists) { scope.push(let->name, 0); } IRMutator::visit(let); if (constrained_version_exists) { scope.pop(let->name); } } }; // Realizations, stores, and loads must all be on types that are // multiples of 8-bits. This really only affects bools class PromoteToMemoryType : public IRMutator { using IRMutator::visit; Type upgrade(Type t) { return t.with_bits(((t.bits() + 7)/8)*8); } void visit(const Call *op) { if (op->is_intrinsic(Call::address_of)) { Expr load = mutate(op->args[0]); if (const Cast *cast = load.as<Cast>()) { load = cast->value; } expr = Call::make(op->type, op->name, {load}, op->call_type); } else { IRMutator::visit(op); } } void visit(const Load *op) { Type t = upgrade(op->type); if (t != op->type) { expr = Cast::make(op->type, Load::make(t, op->name, mutate(op->index), op->image, op->param, mutate(op->predicate))); } else { IRMutator::visit(op); } } void visit(const Store *op) { Type t = upgrade(op->value.type()); if (t != op->value.type()) { stmt = Store::make(op->name, Cast::make(t, mutate(op->value)), mutate(op->index), op->param, mutate(op->predicate)); } else { IRMutator::visit(op); } } void visit(const Allocate *op) { Type t = upgrade(op->type); if (t != op->type) { vector<Expr> extents; for (Expr e : op->extents) { extents.push_back(mutate(e)); } stmt = Allocate::make(op->name, t, extents, mutate(op->condition), mutate(op->body), mutate(op->new_expr), op->free_function); } else { IRMutator::visit(op); } } }; } // namespace Stmt storage_flattening(Stmt s, const vector<Function> &outputs, const map<string, Function> &env, const Target &target) { // Make an environment that makes it easier to figure out which // Function corresponds to a tuple component. foo.0, foo.1, foo.2, // all point to the function foo. map<string, pair<Function, int>> tuple_env; for (auto p : env) { if (p.second.outputs() > 1) { for (int i = 0; i < p.second.outputs(); i++) { tuple_env[p.first + "." + std::to_string(i)] = {p.second, i}; } } else { tuple_env[p.first] = {p.second, 0}; } } s = FlattenDimensions(tuple_env, outputs, target).mutate(s); s = PromoteToMemoryType().mutate(s); return s; } } } <|endoftext|>
<commit_before>/* * Project: FullereneViewer * Version: 1.0 * Copyright: (C) 2011-14 Dr.Sc.KAWAMOTO,Takuji (Ext) * Create: 2011/12/26 18:06:18 JST */ #include <assert.h> #include "SymmetryAxisNormal.h" #include "CarbonAllotrope.h" #include "OpenGLUtil.h" SymmetryAxisNormal::SymmetryAxisNormal(CarbonAllotrope* ca, SymmetryAxis* axis) : InteractiveRegularPolygon(ca, 0, 1.0, 2), p_ca(ca), p_axis(axis) { } SymmetryAxisNormal::~SymmetryAxisNormal() { } void SymmetryAxisNormal::reset_interaction() { InteractiveRegularPolygon::reset_interaction(); } void SymmetryAxisNormal::interaction_original(OriginalForceType force_type, Interactives* interactives, double delta) { Vector3 north_location; Vector3 south_location; int north = p_axis->get_north_sequence_no(); int south = p_axis->get_south_sequence_no(); switch (p_axis->get_type()) { case AXIS_TYPE_CENTER_OF_RING: { Ring* north_ring = p_ca->get_ring_by_sequence_no(north); Ring* south_ring = p_ca->get_ring_by_sequence_no(south); north_location = north_ring->get_center_location(); south_location = south_ring->get_center_location(); } break; case AXIS_TYPE_CENTER_OF_BOND: { Bond* north_bond = p_ca->get_bond_by_sequence_no(north); Bond* south_bond = p_ca->get_bond_by_sequence_no(south); north_location = north_bond->get_center_location(); south_location = south_bond->get_center_location(); } break; case AXIS_TYPE_CENTER_OF_CARBON: { Carbon* north_carbon = p_ca->get_carbon_by_sequence_no(north); Carbon* south_carbon = p_ca->get_carbon_by_sequence_no(south); north_location = north_carbon->get_center_location(); south_location = south_carbon->get_center_location(); } break; case AXIS_TYPE_CENTER_OF_RING_AND_BOND: { Ring* north_ring = p_ca->get_ring_by_sequence_no(north); Bond* south_bond = p_ca->get_bond_by_sequence_no(south); north_location = north_ring->get_center_location(); south_location = south_bond->get_center_location(); } break; case AXIS_TYPE_CENTER_OF_RING_AND_CARBON: { Ring* north_ring = p_ca->get_ring_by_sequence_no(north); Carbon* south_carbon = p_ca->get_carbon_by_sequence_no(south); north_location = north_ring->get_center_location(); south_location = south_carbon->get_center_location(); } break; default: assert(0); } Vector3 center = (north_location + south_location) * 0.5; Vector3 normal = north_location - south_location; p_normal.clockwise = 1; fix_center_location(center); fix_radius_length(normal.abs() * 0.6); fix_posture(Matrix3(Quaternion(Vector3(0.0, 0.0, 1.0), normal))); } void SymmetryAxisNormal::draw_opaque_by_OpenGL(bool selection) const { Vector3 norm = get_normal(); norm *= p_radius.length; OpenGLUtil::set_color(0x808080); OpenGLUtil::draw_cylinder(0.1, get_center_location() - norm, get_center_location() + norm); } /* Local Variables: */ /* mode: c++ */ /* End: */ <commit_msg>対称軸はもうちょっと明るくした。with #53<commit_after>/* * Project: FullereneViewer * Version: 1.0 * Copyright: (C) 2011-14 Dr.Sc.KAWAMOTO,Takuji (Ext) * Create: 2011/12/26 18:06:18 JST */ #include <assert.h> #include "SymmetryAxisNormal.h" #include "CarbonAllotrope.h" #include "OpenGLUtil.h" SymmetryAxisNormal::SymmetryAxisNormal(CarbonAllotrope* ca, SymmetryAxis* axis) : InteractiveRegularPolygon(ca, 0, 1.0, 2), p_ca(ca), p_axis(axis) { } SymmetryAxisNormal::~SymmetryAxisNormal() { } void SymmetryAxisNormal::reset_interaction() { InteractiveRegularPolygon::reset_interaction(); } void SymmetryAxisNormal::interaction_original(OriginalForceType force_type, Interactives* interactives, double delta) { Vector3 north_location; Vector3 south_location; int north = p_axis->get_north_sequence_no(); int south = p_axis->get_south_sequence_no(); switch (p_axis->get_type()) { case AXIS_TYPE_CENTER_OF_RING: { Ring* north_ring = p_ca->get_ring_by_sequence_no(north); Ring* south_ring = p_ca->get_ring_by_sequence_no(south); north_location = north_ring->get_center_location(); south_location = south_ring->get_center_location(); } break; case AXIS_TYPE_CENTER_OF_BOND: { Bond* north_bond = p_ca->get_bond_by_sequence_no(north); Bond* south_bond = p_ca->get_bond_by_sequence_no(south); north_location = north_bond->get_center_location(); south_location = south_bond->get_center_location(); } break; case AXIS_TYPE_CENTER_OF_CARBON: { Carbon* north_carbon = p_ca->get_carbon_by_sequence_no(north); Carbon* south_carbon = p_ca->get_carbon_by_sequence_no(south); north_location = north_carbon->get_center_location(); south_location = south_carbon->get_center_location(); } break; case AXIS_TYPE_CENTER_OF_RING_AND_BOND: { Ring* north_ring = p_ca->get_ring_by_sequence_no(north); Bond* south_bond = p_ca->get_bond_by_sequence_no(south); north_location = north_ring->get_center_location(); south_location = south_bond->get_center_location(); } break; case AXIS_TYPE_CENTER_OF_RING_AND_CARBON: { Ring* north_ring = p_ca->get_ring_by_sequence_no(north); Carbon* south_carbon = p_ca->get_carbon_by_sequence_no(south); north_location = north_ring->get_center_location(); south_location = south_carbon->get_center_location(); } break; default: assert(0); } Vector3 center = (north_location + south_location) * 0.5; Vector3 normal = north_location - south_location; p_normal.clockwise = 1; fix_center_location(center); fix_radius_length(normal.abs() * 0.6); fix_posture(Matrix3(Quaternion(Vector3(0.0, 0.0, 1.0), normal))); } void SymmetryAxisNormal::draw_opaque_by_OpenGL(bool selection) const { Vector3 norm = get_normal(); norm *= p_radius.length; OpenGLUtil::set_color(0xc0c0c0); OpenGLUtil::draw_cylinder(0.1, get_center_location() - norm, get_center_location() + norm); } /* Local Variables: */ /* mode: c++ */ /* End: */ <|endoftext|>
<commit_before><commit_msg>Eliminate the 8-sockets-per-proxy field trial. Reduce the percentage of clients in the max-sockets tests from 20-25% to 1%.<commit_after><|endoftext|>
<commit_before><commit_msg>#include what you use: <Security/Security.h> for SecKeychainAddCallback and friends following r43492.<commit_after><|endoftext|>
<commit_before><commit_msg>Reset the clear browser data checkbox prefs when the user clicks "Reset to defaults".<commit_after><|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// // // File: InputFld.cpp // // For more information, please see: http://www.nektar.info/ // // The MIT License // // Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA), // Department of Aeronautics, Imperial College London (UK), and Scientific // Computing and Imaging Institute, University of Utah (USA). // // License for the specific language governing rights and limitations under // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // // Description: GMSH converter. // //////////////////////////////////////////////////////////////////////////////// #include <string> #include <iostream> using namespace std; #include "InputFld.h" static std::string npts = LibUtilities::SessionReader::RegisterCmdLineArgument( "NumberOfPoints","n","Define number of points to dump output"); namespace Nektar { namespace Utilities { ModuleKey InputFld::m_className[3] = { GetModuleFactory().RegisterCreatorFunction( ModuleKey(eInputModule, "fld"), InputFld::create, "Reads Fld file."), GetModuleFactory().RegisterCreatorFunction( ModuleKey(eInputModule, "chk"), InputFld::create, "Reads Fld file."), GetModuleFactory().RegisterCreatorFunction( ModuleKey(eInputModule, "rst"), InputFld::create, "Reads Fld file."), }; /** * @brief Set up InputFld object. * */ InputFld::InputFld(FieldSharedPtr f) : InputModule(f) { m_allowedFiles.insert("fld"); m_allowedFiles.insert("chk"); m_allowedFiles.insert("rst"); } InputFld::~InputFld() { } /** * */ void InputFld::Process(po::variables_map &vm) { if(m_f->m_verbose) { cout << "Processing input fld file" << endl; } int i,j; string fldending; //Determine appropriate field input if(m_f->m_inputfiles.count("fld") != 0) { fldending = "fld"; } else if(m_f->m_inputfiles.count("chk") != 0) { fldending = "chk"; } else if (m_f->m_inputfiles.count("rst") != 0) { fldending = "rst"; } else { ASSERTL0(false,"no input file found"); } if(!m_f->m_fld) { if(m_f->m_session) { m_f->m_fld = MemoryManager<LibUtilities::FieldIO> ::AllocateSharedPtr(m_f->m_session->GetComm()); } else // serial communicator { LibUtilities::CommSharedPtr c = LibUtilities::GetCommFactory().CreateInstance("Serial", 0, 0); m_f->m_fld = MemoryManager<LibUtilities::FieldIO> ::AllocateSharedPtr(c); } } if(m_f->m_graph) // all for restricted expansion defintion when loading field { // currently load all field (possibly could read data from expansion list // but it is re-arranged in expansion) const SpatialDomains::ExpansionMap &expansions = m_f->m_graph->GetExpansions(); // if Range has been speficied it is possible to have a // partition which is empty so ccheck this and return if // no elements present. if(!expansions.size()) { return; } m_f->m_exp.resize(1); Array<OneD,int> ElementGIDs(expansions.size()); SpatialDomains::ExpansionMap::const_iterator expIt; i = 0; for (expIt = expansions.begin(); expIt != expansions.end(); ++expIt) { ElementGIDs[i++] = expIt->second->m_geomShPtr->GetGlobalID(); } m_f->m_fielddef.clear(); m_f->m_data.clear(); m_f->m_fld->Import(m_f->m_inputfiles[fldending][0], m_f->m_fielddef, m_f->m_data, LibUtilities::NullFieldMetaDataMap, ElementGIDs); } else // load all data. { m_f->m_fld->Import(m_f->m_inputfiles[fldending][0], m_f->m_fielddef, m_f->m_data); } // if m_exp defined presume we want to load all field into expansions if(m_f->m_exp.size()) { int nfields; if(vm.count("useSessionVariables")) { nfields = m_f->m_session->GetVariables().size(); } else { nfields = m_f->m_fielddef[0]->m_fields.size(); } m_f->m_exp.resize(nfields); vector<string> vars = m_f->m_session->GetVariables(); // declare other fields; for (i = 1; i < nfields; ++i) { if(i < vars.size()) { m_f->m_exp[i] = m_f->AppendExpList(m_f->m_fielddef[0]->m_numHomogeneousDir, vars[i]); } else { if(vars.size()) { m_f->m_exp[i] = m_f->AppendExpList(m_f->m_fielddef[0]->m_numHomogeneousDir,vars[0]); } else { m_f->m_exp[i] = m_f->AppendExpList(m_f->m_fielddef[0]->m_numHomogeneousDir); } } } for (j = 0; j < nfields; ++j) { for (i = 0; i < m_f->m_data.size(); ++i) { m_f->m_exp[j]->ExtractDataToCoeffs(m_f->m_fielddef[i], m_f->m_data[i], m_f->m_fielddef[i]->m_fields[j], m_f->m_exp[j]->UpdateCoeffs()); } m_f->m_exp[j]->BwdTrans(m_f->m_exp[j]->GetCoeffs(), m_f->m_exp[j]->UpdatePhys()); } // if range is defined reset up output field in case or // reducing fld definition if(vm.count("range")) { std::vector<LibUtilities::FieldDefinitionsSharedPtr> FieldDef = m_f->m_exp[0]->GetFieldDefinitions(); std::vector<std::vector<NekDouble> > FieldData(FieldDef.size()); for (j = 0; j < nfields; ++j) { for (i = 0; i < FieldDef.size(); ++i) { FieldDef[i]->m_fields.push_back(m_f->m_fielddef[0]->m_fields[j]); m_f->m_exp[j]->AppendFieldData(FieldDef[i], FieldData[i]); } } m_f->m_fielddef = FieldDef; m_f->m_data = FieldData; } } } } } <commit_msg>Modified to be able to handle strips for Yan's work<commit_after>//////////////////////////////////////////////////////////////////////////////// // // File: InputFld.cpp // // For more information, please see: http://www.nektar.info/ // // The MIT License // // Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA), // Department of Aeronautics, Imperial College London (UK), and Scientific // Computing and Imaging Institute, University of Utah (USA). // // License for the specific language governing rights and limitations under // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // // Description: GMSH converter. // //////////////////////////////////////////////////////////////////////////////// #include <string> #include <iostream> using namespace std; #include "InputFld.h" static std::string npts = LibUtilities::SessionReader::RegisterCmdLineArgument( "NumberOfPoints","n","Define number of points to dump output"); namespace Nektar { namespace Utilities { ModuleKey InputFld::m_className[3] = { GetModuleFactory().RegisterCreatorFunction( ModuleKey(eInputModule, "fld"), InputFld::create, "Reads Fld file."), GetModuleFactory().RegisterCreatorFunction( ModuleKey(eInputModule, "chk"), InputFld::create, "Reads Fld file."), GetModuleFactory().RegisterCreatorFunction( ModuleKey(eInputModule, "rst"), InputFld::create, "Reads Fld file."), }; /** * @brief Set up InputFld object. * */ InputFld::InputFld(FieldSharedPtr f) : InputModule(f) { m_allowedFiles.insert("fld"); m_allowedFiles.insert("chk"); m_allowedFiles.insert("rst"); } InputFld::~InputFld() { } /** * */ void InputFld::Process(po::variables_map &vm) { if(m_f->m_verbose) { cout << "Processing input fld file" << endl; } int i,j; string fldending; //Determine appropriate field input if(m_f->m_inputfiles.count("fld") != 0) { fldending = "fld"; } else if(m_f->m_inputfiles.count("chk") != 0) { fldending = "chk"; } else if (m_f->m_inputfiles.count("rst") != 0) { fldending = "rst"; } else { ASSERTL0(false,"no input file found"); } if(!m_f->m_fld) { if(m_f->m_session) { m_f->m_fld = MemoryManager<LibUtilities::FieldIO> ::AllocateSharedPtr(m_f->m_session->GetComm()); } else // serial communicator { LibUtilities::CommSharedPtr c = LibUtilities::GetCommFactory().CreateInstance("Serial", 0, 0); m_f->m_fld = MemoryManager<LibUtilities::FieldIO> ::AllocateSharedPtr(c); } } if(m_f->m_graph) // all for restricted expansion defintion when loading field { // currently load all field (possibly could read data from expansion list // but it is re-arranged in expansion) const SpatialDomains::ExpansionMap &expansions = m_f->m_graph->GetExpansions(); // if Range has been speficied it is possible to have a // partition which is empty so ccheck this and return if // no elements present. if(!expansions.size()) { return; } m_f->m_exp.resize(1); Array<OneD,int> ElementGIDs(expansions.size()); SpatialDomains::ExpansionMap::const_iterator expIt; i = 0; for (expIt = expansions.begin(); expIt != expansions.end(); ++expIt) { ElementGIDs[i++] = expIt->second->m_geomShPtr->GetGlobalID(); } m_f->m_fielddef.clear(); m_f->m_data.clear(); m_f->m_fld->Import(m_f->m_inputfiles[fldending][0], m_f->m_fielddef, m_f->m_data, LibUtilities::NullFieldMetaDataMap, ElementGIDs); } else // load all data. { m_f->m_fld->Import(m_f->m_inputfiles[fldending][0], m_f->m_fielddef, m_f->m_data); } // if m_exp defined presume we want to load all field into expansions if(m_f->m_exp.size()) { int nfields,nstrips; if(vm.count("useSessionVariables")) { nfields = m_f->m_session->GetVariables().size(); } else { nfields = m_f->m_fielddef[0]->m_fields.size(); } m_f->m_exp.resize(nfields); m_f->m_session->LoadParameter("Strip_Z",nstrips,1); vector<string> vars = m_f->m_session->GetVariables(); // declare other fields; for (i = 1; i < nfields; ++i) { if(i < vars.size()) { m_f->m_exp[i] = m_f->AppendExpList(m_f->m_fielddef[0]->m_numHomogeneousDir, vars[i]); } else { if(vars.size()) { m_f->m_exp[i] = m_f->AppendExpList(m_f->m_fielddef[0]->m_numHomogeneousDir,vars[0]); } else { m_f->m_exp[i] = m_f->AppendExpList(m_f->m_fielddef[0]->m_numHomogeneousDir); } } } for(int s = 0; s < nstrips; ++s) //homogeneous strip varient { for (j = 0; j < nfields; ++j) { for (i = 0; i < m_f->m_data.size()/nstrips; ++i) { m_f->m_exp[j]-> ExtractDataToCoeffs(m_f->m_fielddef[i*nstrips+s], m_f->m_data[i*nstrips+s], m_f->m_fielddef[i*nstrips+s] ->m_fields[j], m_f->m_exp[j]->UpdateCoeffs()); } m_f->m_exp[j]->BwdTrans(m_f->m_exp[j]->GetCoeffs(), m_f->m_exp[j]->UpdatePhys()); } } // if range is defined reset up output field in case or // reducing fld definition if(vm.count("range")) { std::vector<LibUtilities::FieldDefinitionsSharedPtr> FieldDef = m_f->m_exp[0]->GetFieldDefinitions(); std::vector<std::vector<NekDouble> > FieldData(FieldDef.size()); for (j = 0; j < nfields; ++j) { for (i = 0; i < FieldDef.size(); ++i) { FieldDef[i]->m_fields.push_back(m_f->m_fielddef[0]->m_fields[j]); m_f->m_exp[j]->AppendFieldData(FieldDef[i], FieldData[i]); } } m_f->m_fielddef = FieldDef; m_f->m_data = FieldData; } } } } } <|endoftext|>
<commit_before><commit_msg>When zooming, webkit reports width and height as if the zoom wasn't there (by dividing the pixel size by the zoom factor). If we want actual pixel sizes that the content will best fit, we need to undo that.<commit_after><|endoftext|>
<commit_before>#include "qnitelinearticker.h" #include <algorithm> #include <QDebug> // defines #define DEFAULT_NUM_STEPS 10 #define DEFAULT_LOOSENESS true namespace { double nice(double x, bool round) { int exp; double f; double nicef; exp = floor(log10(x)); f = x / pow(10., exp); if (round) { if (f<1.5) nicef=1.; else if (f<3.) nicef=2.; else if (f<7.) nicef=5.; else nicef=10.; } else { if (f<=1.) nicef=1.; else if (f<=2.) nicef=2.; else if (f<=5.) nicef=5.; else nicef=10.; } return nicef*pow(10., exp); } void fill(QList<qreal>& ticks, qreal min, qreal max, int steps) { double range = nice(max-min, false); double d = nice(range/(steps-1), true); double graph_min = floor(min/d) * d; // loose version of the algo double graph_max = ceil(max/d) * d; // loose version of the algo // nFrac is the number of decimal numbers it'd be nice to show double nFrac = std::max(-floor(log10(d)), 0.); // we use it to better approximate values double precision = pow(10, nFrac); for (double x=graph_min; x<=graph_max + .5*d; x+=d) { // round to the "precision" decimal place double val = round(x*precision); ticks.append(val/precision); //ticks.append(x); } } } QniteLinearTicker::QniteLinearTicker(QObject *parent) : QniteTicker(parent), m_loose{DEFAULT_LOOSENESS} { setNumSteps(DEFAULT_NUM_STEPS); } void QniteLinearTicker::buildTicks() { if (lower() >= upper()) { qWarning() << QString("Illegal values for ticker bounds: %1,%2") .arg(lower()).arg(upper()); return; } // build major ticks QList<qreal> majors; fill(majors, lower(), upper(), numSteps()); setMajorTicks(majors); // build min ticks QList<qreal> mins; for (int i=0; i<majors.size()-1; i++) { fill(mins, majors[i], majors[i+1], ceil(numSteps()/2.)); } // remove duplicates QSet<qreal> minSet = mins.toSet(); QSet<qreal> majSet = majors.toSet(); minSet = minSet.subtract(majSet); mins = minSet.toList(); std::sort(mins.begin(), mins.end(), std::less<qreal>()); // set tick series setMinorTicks(mins); setMajorTicks(majors); } void QniteLinearTicker::setLooseNiceness(bool is_loose) { m_loose = is_loose; } bool QniteLinearTicker::looseNiceness() const { return m_loose; } void QniteLinearTicker::reset() { QniteTicker::reset(); m_loose = DEFAULT_LOOSENESS; setNumSteps(DEFAULT_NUM_STEPS); } void QniteLinearTicker::setNumSteps(int steps) { if (steps < 2) { qWarning() << "Number of steps must be at least 2"; return; } QniteTicker::setNumSteps(steps); } <commit_msg>simplified duplicates removal<commit_after>#include "qnitelinearticker.h" #include <algorithm> #include <QDebug> // defines #define DEFAULT_NUM_STEPS 10 #define DEFAULT_LOOSENESS true namespace { double nice(double x, bool round) { int exp; double f; double nicef; exp = floor(log10(x)); f = x / pow(10., exp); if (round) { if (f<1.5) nicef=1.; else if (f<3.) nicef=2.; else if (f<7.) nicef=5.; else nicef=10.; } else { if (f<=1.) nicef=1.; else if (f<=2.) nicef=2.; else if (f<=5.) nicef=5.; else nicef=10.; } return nicef*pow(10., exp); } void fill(QList<qreal>& ticks, qreal min, qreal max, int steps) { double range = nice(max-min, false); double d = nice(range/(steps-1), true); double graph_min = floor(min/d) * d; // loose version of the algo double graph_max = ceil(max/d) * d; // loose version of the algo // nFrac is the number of decimal numbers it'd be nice to show double nFrac = std::max(-floor(log10(d)), 0.); // we use it to better approximate values double precision = pow(10, nFrac); for (double x=graph_min; x<=graph_max + .5*d; x+=d) { // round to the "precision" decimal place double val = round(x*precision); ticks.append(val/precision); //ticks.append(x); } } } QniteLinearTicker::QniteLinearTicker(QObject *parent) : QniteTicker(parent), m_loose{DEFAULT_LOOSENESS} { setNumSteps(DEFAULT_NUM_STEPS); } void QniteLinearTicker::buildTicks() { if (lower() >= upper()) { qWarning() << QString("Illegal values for ticker bounds: %1,%2") .arg(lower()).arg(upper()); return; } // build major ticks QList<qreal> majors; fill(majors, lower(), upper(), numSteps()); setMajorTicks(majors); // build min ticks QList<qreal> mins; for (int i=0; i<majors.size()-1; i++) { fill(mins, majors[i], majors[i+1], ceil(numSteps()/2.)); } // remove duplicates mins = mins.toSet().subtract(majors.toSet()).toList(); std::sort(mins.begin(), mins.end(), std::less<qreal>()); // set tick series setMinorTicks(mins); setMajorTicks(majors); } void QniteLinearTicker::setLooseNiceness(bool is_loose) { m_loose = is_loose; } bool QniteLinearTicker::looseNiceness() const { return m_loose; } void QniteLinearTicker::reset() { QniteTicker::reset(); m_loose = DEFAULT_LOOSENESS; setNumSteps(DEFAULT_NUM_STEPS); } void QniteLinearTicker::setNumSteps(int steps) { if (steps < 2) { qWarning() << "Number of steps must be at least 2"; return; } QniteTicker::setNumSteps(steps); } <|endoftext|>
<commit_before>/***************************************************************************************** * * * OpenSpace * * * * Copyright (c) 2014-2018 * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * * without restriction, including without limitation the rights to use, copy, modify, * * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * * permit persons to whom the Software is furnished to do so, subject to the following * * conditions: * * * * The above copyright notice and this permission notice shall be included in all copies * * or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ #include <modules/base/rendering/renderableplane.h> #include <modules/base/basemodule.h> #include <openspace/documentation/documentation.h> #include <openspace/documentation/verifier.h> #include <openspace/engine/openspaceengine.h> #include <openspace/rendering/renderengine.h> #include <openspace/scene/scenegraphnode.h> #include <openspace/util/updatestructures.h> #include <ghoul/filesystem/filesystem.h> #include <ghoul/io/texture/texturereader.h> #include <ghoul/misc/defer.h> #include <ghoul/opengl/programobject.h> #include <ghoul/opengl/texture.h> #include <ghoul/opengl/textureunit.h> namespace { constexpr const char* ProgramName = "Plane"; enum BlendMode { BlendModeNormal = 0, BlendModeAdditive }; const openspace::properties::Property::PropertyInfo BillboardInfo = { "Billboard", "Billboard mode", "This value specifies whether the plane is a billboard, which means that it is " "always facing the camera. If this is false, it can be oriented using other " "transformations." }; const openspace::properties::Property::PropertyInfo SizeInfo = { "Size", "Size (in meters)", "This value specifies the size of the plane in meters." }; const openspace::properties::Property::PropertyInfo BlendModeInfo = { "BlendMode", "Blending Mode", "This determines the blending mode that is applied to this plane." }; } // namespace namespace openspace { documentation::Documentation RenderablePlane::Documentation() { using namespace documentation; return { "Renderable Plane", "base_renderable_plane", { { SizeInfo.identifier, new DoubleVerifier, Optional::No, SizeInfo.description }, { BillboardInfo.identifier, new BoolVerifier, Optional::Yes, BillboardInfo.description }, { BlendModeInfo.identifier, new StringInListVerifier({ "Normal", "Additive" }), Optional::Yes, BlendModeInfo.description, // + " The default value is 'Normal'.", } } }; } RenderablePlane::RenderablePlane(const ghoul::Dictionary& dictionary) : Renderable(dictionary) , _billboard(BillboardInfo, false) , _size(SizeInfo, 10.f, 0.f, 1e25f) , _blendMode(BlendModeInfo, properties::OptionProperty::DisplayType::Dropdown) { documentation::testSpecificationAndThrow( Documentation(), dictionary, "RenderablePlane" ); addProperty(_opacity); registerUpdateRenderBinFromOpacity(); _size = static_cast<float>(dictionary.value<double>(SizeInfo.identifier)); if (dictionary.hasKey(BillboardInfo.identifier)) { _billboard = dictionary.value<bool>(BillboardInfo.identifier); } _blendMode.addOptions({ { BlendModeNormal, "Normal" }, { BlendModeAdditive, "Additive"} }); _blendMode.onChange([&]() { switch (_blendMode) { case BlendModeNormal: setRenderBin(Renderable::RenderBin::Opaque); break; case BlendModeAdditive: setRenderBin(Renderable::RenderBin::Transparent); break; default: throw ghoul::MissingCaseException(); } }); if (dictionary.hasKey(BlendModeInfo.identifier)) { const std::string v = dictionary.value<std::string>(BlendModeInfo.identifier); if (v == "Normal") { _blendMode = BlendModeNormal; } else if (v == "Additive") { _blendMode = BlendModeAdditive; } } addProperty(_billboard); addProperty(_size); _size.onChange([this](){ _planeIsDirty = true; }); setBoundingSphere(_size); } bool RenderablePlane::isReady() const { return _shader != nullptr; } void RenderablePlane::initializeGL() { glGenVertexArrays(1, &_quad); // generate array glGenBuffers(1, &_vertexPositionBuffer); // generate buffer createPlane(); _shader = BaseModule::ProgramObjectManager.requestProgramObject( ProgramName, []() -> std::unique_ptr<ghoul::opengl::ProgramObject> { return OsEng.renderEngine().buildRenderProgram( ProgramName, absPath("${MODULE_BASE}/shaders/plane_vs.glsl"), absPath("${MODULE_BASE}/shaders/plane_fs.glsl") ); } ); } void RenderablePlane::deinitializeGL() { glDeleteVertexArrays(1, &_quad); _quad = 0; glDeleteBuffers(1, &_vertexPositionBuffer); _vertexPositionBuffer = 0; BaseModule::ProgramObjectManager.releaseProgramObject( ProgramName, [](ghoul::opengl::ProgramObject* p) { OsEng.renderEngine().removeRenderProgram(p); } ); _shader = nullptr; } void RenderablePlane::render(const RenderData& data, RendererTasks&) { _shader->activate(); _shader->setUniform("opacity", _opacity); // Model transform and view transform needs to be in double precision const glm::dmat4 rotationTransform = _billboard ? glm::inverse(glm::dmat4(data.camera.viewRotationMatrix())) : glm::dmat4(data.modelTransform.rotation); const glm::dmat4 modelTransform = glm::translate(glm::dmat4(1.0), data.modelTransform.translation) * rotationTransform * glm::scale(glm::dmat4(1.0), glm::dvec3(data.modelTransform.scale)) * glm::dmat4(1.0); const glm::dmat4 modelViewTransform = data.camera.combinedViewMatrix() * modelTransform; _shader->setUniform("modelViewProjectionTransform", data.camera.projectionMatrix() * glm::mat4(modelViewTransform)); _shader->setUniform("modelViewTransform", glm::mat4(data.camera.combinedViewMatrix() * glm::dmat4(modelViewTransform))); ghoul::opengl::TextureUnit unit; unit.activate(); bindTexture(); defer { unbindTexture(); }; _shader->setUniform("texture1", unit); bool usingFramebufferRenderer = OsEng.renderEngine().rendererImplementation() == RenderEngine::RendererImplementation::Framebuffer; bool usingABufferRenderer = OsEng.renderEngine().rendererImplementation() == RenderEngine::RendererImplementation::ABuffer; if (usingABufferRenderer) { _shader->setUniform("additiveBlending", _blendMode == BlendModeAdditive); } bool additiveBlending = (_blendMode == BlendModeAdditive) && usingFramebufferRenderer; if (additiveBlending) { glDepthMask(false); glBlendFunc(GL_SRC_ALPHA, GL_ONE); } glBindVertexArray(_quad); glDrawArrays(GL_TRIANGLES, 0, 6); if (additiveBlending) { glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDepthMask(true); } _shader->deactivate(); } void RenderablePlane::bindTexture() {} void RenderablePlane::unbindTexture() {} void RenderablePlane::update(const UpdateData&) { if (_shader->isDirty()) { _shader->rebuildFromFile(); } if (_planeIsDirty) { createPlane(); } } void RenderablePlane::createPlane() { const GLfloat size = _size; const GLfloat vertexData[] = { // x y z w s t -size, -size, 0.f, 0.f, 0.f, 0.f, size, size, 0.f, 0.f, 1.f, 1.f, -size, size, 0.f, 0.f, 0.f, 1.f, -size, -size, 0.f, 0.f, 0.f, 0.f, size, -size, 0.f, 0.f, 1.f, 0.f, size, size, 0.f, 0.f, 1.f, 1.f, }; glBindVertexArray(_quad); glBindBuffer(GL_ARRAY_BUFFER, _vertexPositionBuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(vertexData), vertexData, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 6, nullptr); glEnableVertexAttribArray(1); glVertexAttribPointer( 1, 2, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 6, reinterpret_cast<void*>(sizeof(GLfloat) * 4) ); } } // namespace openspace <commit_msg>Fixed RenderablePlane billboard orientation in dome. (#620)<commit_after>/***************************************************************************************** * * * OpenSpace * * * * Copyright (c) 2014-2018 * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * * without restriction, including without limitation the rights to use, copy, modify, * * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * * permit persons to whom the Software is furnished to do so, subject to the following * * conditions: * * * * The above copyright notice and this permission notice shall be included in all copies * * or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ #include <modules/base/rendering/renderableplane.h> #include <modules/base/basemodule.h> #include <openspace/documentation/documentation.h> #include <openspace/documentation/verifier.h> #include <openspace/engine/openspaceengine.h> #include <openspace/rendering/renderengine.h> #include <openspace/scene/scenegraphnode.h> #include <openspace/util/updatestructures.h> #include <ghoul/filesystem/filesystem.h> #include <ghoul/io/texture/texturereader.h> #include <ghoul/misc/defer.h> #include <ghoul/opengl/programobject.h> #include <ghoul/opengl/texture.h> #include <ghoul/opengl/textureunit.h> #include <ghoul/glm.h> #include <glm/gtx/string_cast.hpp> namespace { constexpr const char* ProgramName = "Plane"; enum BlendMode { BlendModeNormal = 0, BlendModeAdditive }; const openspace::properties::Property::PropertyInfo BillboardInfo = { "Billboard", "Billboard mode", "This value specifies whether the plane is a billboard, which means that it is " "always facing the camera. If this is false, it can be oriented using other " "transformations." }; const openspace::properties::Property::PropertyInfo SizeInfo = { "Size", "Size (in meters)", "This value specifies the size of the plane in meters." }; const openspace::properties::Property::PropertyInfo BlendModeInfo = { "BlendMode", "Blending Mode", "This determines the blending mode that is applied to this plane." }; } // namespace namespace openspace { documentation::Documentation RenderablePlane::Documentation() { using namespace documentation; return { "Renderable Plane", "base_renderable_plane", { { SizeInfo.identifier, new DoubleVerifier, Optional::No, SizeInfo.description }, { BillboardInfo.identifier, new BoolVerifier, Optional::Yes, BillboardInfo.description }, { BlendModeInfo.identifier, new StringInListVerifier({ "Normal", "Additive" }), Optional::Yes, BlendModeInfo.description, // + " The default value is 'Normal'.", } } }; } RenderablePlane::RenderablePlane(const ghoul::Dictionary& dictionary) : Renderable(dictionary) , _billboard(BillboardInfo, false) , _size(SizeInfo, 10.f, 0.f, 1e25f) , _blendMode(BlendModeInfo, properties::OptionProperty::DisplayType::Dropdown) { documentation::testSpecificationAndThrow( Documentation(), dictionary, "RenderablePlane" ); addProperty(_opacity); registerUpdateRenderBinFromOpacity(); _size = static_cast<float>(dictionary.value<double>(SizeInfo.identifier)); if (dictionary.hasKey(BillboardInfo.identifier)) { _billboard = dictionary.value<bool>(BillboardInfo.identifier); } _blendMode.addOptions({ { BlendModeNormal, "Normal" }, { BlendModeAdditive, "Additive"} }); _blendMode.onChange([&]() { switch (_blendMode) { case BlendModeNormal: setRenderBin(Renderable::RenderBin::Opaque); break; case BlendModeAdditive: setRenderBin(Renderable::RenderBin::Transparent); break; default: throw ghoul::MissingCaseException(); } }); if (dictionary.hasKey(BlendModeInfo.identifier)) { const std::string v = dictionary.value<std::string>(BlendModeInfo.identifier); if (v == "Normal") { _blendMode = BlendModeNormal; } else if (v == "Additive") { _blendMode = BlendModeAdditive; } } addProperty(_billboard); addProperty(_size); _size.onChange([this](){ _planeIsDirty = true; }); setBoundingSphere(_size); } bool RenderablePlane::isReady() const { return _shader != nullptr; } void RenderablePlane::initializeGL() { glGenVertexArrays(1, &_quad); // generate array glGenBuffers(1, &_vertexPositionBuffer); // generate buffer createPlane(); _shader = BaseModule::ProgramObjectManager.requestProgramObject( ProgramName, []() -> std::unique_ptr<ghoul::opengl::ProgramObject> { return OsEng.renderEngine().buildRenderProgram( ProgramName, absPath("${MODULE_BASE}/shaders/plane_vs.glsl"), absPath("${MODULE_BASE}/shaders/plane_fs.glsl") ); } ); } void RenderablePlane::deinitializeGL() { glDeleteVertexArrays(1, &_quad); _quad = 0; glDeleteBuffers(1, &_vertexPositionBuffer); _vertexPositionBuffer = 0; BaseModule::ProgramObjectManager.releaseProgramObject( ProgramName, [](ghoul::opengl::ProgramObject* p) { OsEng.renderEngine().removeRenderProgram(p); } ); _shader = nullptr; } void RenderablePlane::render(const RenderData& data, RendererTasks&) { _shader->activate(); _shader->setUniform("opacity", _opacity); glm::dvec3 objectPositionWorld = glm::dvec3( glm::translate( glm::dmat4(1.0), data.modelTransform.translation) * glm::dvec4(0.0, 0.0, 0.0, 1.0) ); glm::dvec3 normal = glm::normalize(data.camera.positionVec3() - objectPositionWorld); glm::dvec3 newRight = glm::normalize( glm::cross(data.camera.lookUpVectorWorldSpace(), normal) ); glm::dvec3 newUp = glm::cross(normal, newRight); glm::dmat4 cameraOrientedRotation; cameraOrientedRotation[0] = glm::dvec4(newRight, 0.0); cameraOrientedRotation[1] = glm::dvec4(newUp, 0.0); cameraOrientedRotation[2] = glm::dvec4(normal, 0.0); const glm::dmat4 rotationTransform = _billboard ? cameraOrientedRotation : glm::dmat4(data.modelTransform.rotation); const glm::dmat4 modelTransform = glm::translate(glm::dmat4(1.0), data.modelTransform.translation) * rotationTransform * glm::scale(glm::dmat4(1.0), glm::dvec3(data.modelTransform.scale)) * glm::dmat4(1.0); const glm::dmat4 modelViewTransform = data.camera.combinedViewMatrix() * modelTransform; _shader->setUniform("modelViewProjectionTransform", data.camera.projectionMatrix() * glm::mat4(modelViewTransform)); _shader->setUniform("modelViewTransform", glm::mat4(data.camera.combinedViewMatrix() * glm::dmat4(modelViewTransform))); ghoul::opengl::TextureUnit unit; unit.activate(); bindTexture(); defer { unbindTexture(); }; _shader->setUniform("texture1", unit); bool usingFramebufferRenderer = OsEng.renderEngine().rendererImplementation() == RenderEngine::RendererImplementation::Framebuffer; bool usingABufferRenderer = OsEng.renderEngine().rendererImplementation() == RenderEngine::RendererImplementation::ABuffer; if (usingABufferRenderer) { _shader->setUniform("additiveBlending", _blendMode == BlendModeAdditive); } bool additiveBlending = (_blendMode == BlendModeAdditive) && usingFramebufferRenderer; if (additiveBlending) { glDepthMask(false); glBlendFunc(GL_SRC_ALPHA, GL_ONE); } glBindVertexArray(_quad); glDrawArrays(GL_TRIANGLES, 0, 6); if (additiveBlending) { glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDepthMask(true); } _shader->deactivate(); } void RenderablePlane::bindTexture() {} void RenderablePlane::unbindTexture() {} void RenderablePlane::update(const UpdateData&) { if (_shader->isDirty()) { _shader->rebuildFromFile(); } if (_planeIsDirty) { createPlane(); } } void RenderablePlane::createPlane() { const GLfloat size = _size; const GLfloat vertexData[] = { // x y z w s t -size, -size, 0.f, 0.f, 0.f, 0.f, size, size, 0.f, 0.f, 1.f, 1.f, -size, size, 0.f, 0.f, 0.f, 1.f, -size, -size, 0.f, 0.f, 0.f, 0.f, size, -size, 0.f, 0.f, 1.f, 0.f, size, size, 0.f, 0.f, 1.f, 1.f, }; glBindVertexArray(_quad); glBindBuffer(GL_ARRAY_BUFFER, _vertexPositionBuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(vertexData), vertexData, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 6, nullptr); glEnableVertexAttribArray(1); glVertexAttribPointer( 1, 2, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 6, reinterpret_cast<void*>(sizeof(GLfloat) * 4) ); } } // namespace openspace <|endoftext|>
<commit_before>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/common/adapters/adapter_manager.h" #include "modules/common/adapters/adapter_gflags.h" #include "modules/common/util/util.h" namespace apollo { namespace common { namespace adapter { AdapterManager::AdapterManager() {} void AdapterManager::Observe() { for (const auto observe : instance()->observers_) { observe(); } } bool AdapterManager::Initialized() { return instance()->initialized_; } void AdapterManager::Reset() { instance()->initialized_ = false; instance()->observers_.clear(); } void AdapterManager::Init(const std::string &adapter_config_filename) { // Parse config file AdapterManagerConfig configs; CHECK(util::GetProtoFromFile(adapter_config_filename, &configs)) << "Unable to parse adapter config file " << adapter_config_filename; AINFO << "Init AdapterManger config:" << configs.DebugString(); Init(configs); } void AdapterManager::Init(const AdapterManagerConfig &configs) { if (Initialized()) { return; } instance()->initialized_ = true; if (configs.is_ros()) { instance()->node_handle_.reset(new ros::NodeHandle()); } for (const auto &config : configs.config()) { switch (config.type()) { case AdapterConfig::POINT_CLOUD: EnablePointCloud(FLAGS_pointcloud_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::GPS: EnableGps(FLAGS_gps_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::IMU: EnableImu(FLAGS_imu_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::CHASSIS: EnableChassis(FLAGS_chassis_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::LOCALIZATION: EnableLocalization(FLAGS_localization_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::PERCEPTION_OBSTACLES: EnablePerceptionObstacles(FLAGS_perception_obstacle_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::TRAFFIC_LIGHT_DETECTION: EnableTrafficLightDetection(FLAGS_traffic_light_detection_topic, config.mode(), config.message_history_limit()); case AdapterConfig::PAD: EnablePad(FLAGS_pad_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::CONTROL_COMMAND: EnableControlCommand(FLAGS_control_command_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::ROUTING_REQUEST: EnableRoutingRequest(FLAGS_routing_request_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::ROUTING_RESPONSE: EnableRoutingResponse(FLAGS_routing_response_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::PLANNING_TRAJECTORY: EnablePlanning(FLAGS_planning_trajectory_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::PREDICTION: EnablePrediction(FLAGS_prediction_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::MONITOR: EnableMonitor(FLAGS_monitor_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::CHASSIS_DETAIL: EnableChassisDetail(FLAGS_chassis_detail_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::RELATIVE_ODOMETRY: EnableRelativeOdometry(FLAGS_relative_odometry_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::INS_STAT: EnableInsStat(FLAGS_ins_stat_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::INS_STATUS: EnableInsStat(FLAGS_ins_status_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::GNSS_STATUS: EnableInsStat(FLAGS_gnss_status_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::HMI_COMMAND: EnableHMICommand(FLAGS_hmi_command_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::MOBILEYE: EnableMobileye(FLAGS_mobileye_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::DELPHIESR: EnableDelphiESR(FLAGS_delphi_esr_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::COMPRESSED_IMAGE: EnableCompressedImage(FLAGS_compressed_image_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::HMI_STATUS: EnableHMIStatus(FLAGS_hmi_status_topic, config.mode(), config.message_history_limit()); break; default: AERROR << "Unknown adapter config type!"; break; } } } } // namespace adapter } // namespace common } // namespace apollo <commit_msg>Common: Fix switch case fall through.<commit_after>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/common/adapters/adapter_manager.h" #include "modules/common/adapters/adapter_gflags.h" #include "modules/common/util/util.h" namespace apollo { namespace common { namespace adapter { AdapterManager::AdapterManager() {} void AdapterManager::Observe() { for (const auto observe : instance()->observers_) { observe(); } } bool AdapterManager::Initialized() { return instance()->initialized_; } void AdapterManager::Reset() { instance()->initialized_ = false; instance()->observers_.clear(); } void AdapterManager::Init(const std::string &adapter_config_filename) { // Parse config file AdapterManagerConfig configs; CHECK(util::GetProtoFromFile(adapter_config_filename, &configs)) << "Unable to parse adapter config file " << adapter_config_filename; AINFO << "Init AdapterManger config:" << configs.DebugString(); Init(configs); } void AdapterManager::Init(const AdapterManagerConfig &configs) { if (Initialized()) { return; } instance()->initialized_ = true; if (configs.is_ros()) { instance()->node_handle_.reset(new ros::NodeHandle()); } for (const auto &config : configs.config()) { switch (config.type()) { case AdapterConfig::POINT_CLOUD: EnablePointCloud(FLAGS_pointcloud_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::GPS: EnableGps(FLAGS_gps_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::IMU: EnableImu(FLAGS_imu_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::CHASSIS: EnableChassis(FLAGS_chassis_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::LOCALIZATION: EnableLocalization(FLAGS_localization_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::PERCEPTION_OBSTACLES: EnablePerceptionObstacles(FLAGS_perception_obstacle_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::TRAFFIC_LIGHT_DETECTION: EnableTrafficLightDetection(FLAGS_traffic_light_detection_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::PAD: EnablePad(FLAGS_pad_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::CONTROL_COMMAND: EnableControlCommand(FLAGS_control_command_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::ROUTING_REQUEST: EnableRoutingRequest(FLAGS_routing_request_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::ROUTING_RESPONSE: EnableRoutingResponse(FLAGS_routing_response_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::PLANNING_TRAJECTORY: EnablePlanning(FLAGS_planning_trajectory_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::PREDICTION: EnablePrediction(FLAGS_prediction_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::MONITOR: EnableMonitor(FLAGS_monitor_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::CHASSIS_DETAIL: EnableChassisDetail(FLAGS_chassis_detail_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::RELATIVE_ODOMETRY: EnableRelativeOdometry(FLAGS_relative_odometry_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::INS_STAT: EnableInsStat(FLAGS_ins_stat_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::INS_STATUS: EnableInsStat(FLAGS_ins_status_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::GNSS_STATUS: EnableInsStat(FLAGS_gnss_status_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::HMI_COMMAND: EnableHMICommand(FLAGS_hmi_command_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::MOBILEYE: EnableMobileye(FLAGS_mobileye_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::DELPHIESR: EnableDelphiESR(FLAGS_delphi_esr_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::COMPRESSED_IMAGE: EnableCompressedImage(FLAGS_compressed_image_topic, config.mode(), config.message_history_limit()); break; case AdapterConfig::HMI_STATUS: EnableHMIStatus(FLAGS_hmi_status_topic, config.mode(), config.message_history_limit()); break; default: AERROR << "Unknown adapter config type!"; break; } } } } // namespace adapter } // namespace common } // namespace apollo <|endoftext|>
<commit_before>/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) however caused // and on any theory of liability, whether in contract, strict liability, // or tort (including negligence or otherwise) arising in any way out of // the use of this software, even if advised of the possibility of such damage. // //M*/ #include "precomp.hpp" #include "fast_score.hpp" using namespace cv; Ptr<Feature2D> Feature2D::create( const string& feature2DType ) { return Algorithm::create<Feature2D>("Feature2D." + feature2DType); } /////////////////////// AlgorithmInfo for various detector & descriptors //////////////////////////// /* NOTE!!! All the AlgorithmInfo-related stuff should be in the same file as initModule_features2d(). Otherwise, linker may throw away some seemingly unused stuff. */ CV_INIT_ALGORITHM(BRISK, "Feature2D.BRISK", obj.info()->addParam(obj, "thres", obj.threshold); obj.info()->addParam(obj, "octaves", obj.octaves)); /////////////////////////////////////////////////////////////////////////////////////////////////////////// CV_INIT_ALGORITHM(BriefDescriptorExtractor, "Feature2D.BRIEF", obj.info()->addParam(obj, "bytes", obj.bytes_)); /////////////////////////////////////////////////////////////////////////////////////////////////////////// CV_INIT_ALGORITHM(FastFeatureDetector, "Feature2D.FAST", obj.info()->addParam(obj, "threshold", obj.threshold); obj.info()->addParam(obj, "nonmaxSuppression", obj.nonmaxSuppression)); CV_INIT_ALGORITHM(FastFeatureDetector2, "Feature2D.FASTX", obj.info()->addParam(obj, "threshold", obj.threshold); obj.info()->addParam(obj, "nonmaxSuppression", obj.nonmaxSuppression); obj.info()->addParam(obj, "type", obj.type)); /////////////////////////////////////////////////////////////////////////////////////////////////////////// CV_INIT_ALGORITHM(StarDetector, "Feature2D.STAR", obj.info()->addParam(obj, "maxSize", obj.maxSize); obj.info()->addParam(obj, "responseThreshold", obj.responseThreshold); obj.info()->addParam(obj, "lineThresholdProjected", obj.lineThresholdProjected); obj.info()->addParam(obj, "lineThresholdBinarized", obj.lineThresholdBinarized); obj.info()->addParam(obj, "suppressNonmaxSize", obj.suppressNonmaxSize)); /////////////////////////////////////////////////////////////////////////////////////////////////////////// CV_INIT_ALGORITHM(MSER, "Feature2D.MSER", obj.info()->addParam(obj, "delta", obj.delta); obj.info()->addParam(obj, "minArea", obj.minArea); obj.info()->addParam(obj, "maxArea", obj.maxArea); obj.info()->addParam(obj, "maxVariation", obj.maxVariation); obj.info()->addParam(obj, "minDiversity", obj.minDiversity); obj.info()->addParam(obj, "maxEvolution", obj.maxEvolution); obj.info()->addParam(obj, "areaThreshold", obj.areaThreshold); obj.info()->addParam(obj, "minMargin", obj.minMargin); obj.info()->addParam(obj, "edgeBlurSize", obj.edgeBlurSize)); /////////////////////////////////////////////////////////////////////////////////////////////////////////// CV_INIT_ALGORITHM(ORB, "Feature2D.ORB", obj.info()->addParam(obj, "nFeatures", obj.nfeatures); obj.info()->addParam(obj, "scaleFactor", obj.scaleFactor); obj.info()->addParam(obj, "nLevels", obj.nlevels); obj.info()->addParam(obj, "firstLevel", obj.firstLevel); obj.info()->addParam(obj, "edgeThreshold", obj.edgeThreshold); obj.info()->addParam(obj, "patchSize", obj.patchSize); obj.info()->addParam(obj, "WTA_K", obj.WTA_K); obj.info()->addParam(obj, "scoreType", obj.scoreType)); /////////////////////////////////////////////////////////////////////////////////////////////////////////// CV_INIT_ALGORITHM(FREAK, "Feature2D.FREAK", obj.info()->addParam(obj, "orientationNormalized", obj.orientationNormalized); obj.info()->addParam(obj, "scaleNormalized", obj.scaleNormalized); obj.info()->addParam(obj, "patternScale", obj.patternScale); obj.info()->addParam(obj, "nbOctave", obj.nOctaves)); /////////////////////////////////////////////////////////////////////////////////////////////////////////// CV_INIT_ALGORITHM(GFTTDetector, "Feature2D.GFTT", obj.info()->addParam(obj, "nfeatures", obj.nfeatures); obj.info()->addParam(obj, "qualityLevel", obj.qualityLevel); obj.info()->addParam(obj, "minDistance", obj.minDistance); obj.info()->addParam(obj, "useHarrisDetector", obj.useHarrisDetector); obj.info()->addParam(obj, "k", obj.k)); /////////////////////////////////////////////////////////////////////////////////////////////////////////// CV_INIT_ALGORITHM(SimpleBlobDetector, "Feature2D.SimpleBlob", obj.info()->addParam(obj, "thresholdStep", obj.params.thresholdStep); obj.info()->addParam(obj, "minThreshold", obj.params.minThreshold); obj.info()->addParam(obj, "maxThreshold", obj.params.maxThreshold); obj.info()->addParam_(obj, "minRepeatability", ParamType<size_t>::type, &obj.params.minRepeatability, false, 0, 0); obj.info()->addParam(obj, "minDistBetweenBlobs", obj.params.minDistBetweenBlobs); obj.info()->addParam(obj, "filterByColor", obj.params.filterByColor); obj.info()->addParam(obj, "blobColor", obj.params.blobColor); obj.info()->addParam(obj, "filterByArea", obj.params.filterByArea); obj.info()->addParam(obj, "maxArea", obj.params.maxArea); obj.info()->addParam(obj, "filterByCircularity", obj.params.filterByCircularity); obj.info()->addParam(obj, "maxCircularity", obj.params.maxCircularity); obj.info()->addParam(obj, "filterByInertia", obj.params.filterByInertia); obj.info()->addParam(obj, "maxInertiaRatio", obj.params.maxInertiaRatio); obj.info()->addParam(obj, "filterByConvexity", obj.params.filterByConvexity); obj.info()->addParam(obj, "maxConvexity", obj.params.maxConvexity); ); /////////////////////////////////////////////////////////////////////////////////////////////////////////// class CV_EXPORTS HarrisDetector : public GFTTDetector { public: HarrisDetector( int maxCorners=1000, double qualityLevel=0.01, double minDistance=1, int blockSize=3, bool useHarrisDetector=true, double k=0.04 ); AlgorithmInfo* info() const; }; inline HarrisDetector::HarrisDetector( int _maxCorners, double _qualityLevel, double _minDistance, int _blockSize, bool _useHarrisDetector, double _k ) : GFTTDetector( _maxCorners, _qualityLevel, _minDistance, _blockSize, _useHarrisDetector, _k ) {} CV_INIT_ALGORITHM(HarrisDetector, "Feature2D.HARRIS", obj.info()->addParam(obj, "nfeatures", obj.nfeatures); obj.info()->addParam(obj, "qualityLevel", obj.qualityLevel); obj.info()->addParam(obj, "minDistance", obj.minDistance); obj.info()->addParam(obj, "useHarrisDetector", obj.useHarrisDetector); obj.info()->addParam(obj, "k", obj.k)); //////////////////////////////////////////////////////////////////////////////////////////////////////////// CV_INIT_ALGORITHM(DenseFeatureDetector, "Feature2D.Dense", obj.info()->addParam(obj, "initFeatureScale", obj.initFeatureScale); obj.info()->addParam(obj, "featureScaleLevels", obj.featureScaleLevels); obj.info()->addParam(obj, "featureScaleMul", obj.featureScaleMul); obj.info()->addParam(obj, "initXyStep", obj.initXyStep); obj.info()->addParam(obj, "initImgBound", obj.initImgBound); obj.info()->addParam(obj, "varyXyStepWithScale", obj.varyXyStepWithScale); obj.info()->addParam(obj, "varyImgBoundWithScale", obj.varyImgBoundWithScale)); CV_INIT_ALGORITHM(GridAdaptedFeatureDetector, "Feature2D.Grid", obj.info()->addParam(obj, "detector", obj.detector); obj.info()->addParam(obj, "maxTotalKeypoints", obj.maxTotalKeypoints); obj.info()->addParam(obj, "gridRows", obj.gridRows); obj.info()->addParam(obj, "gridCols", obj.gridCols)); //////////////////////////////////////////////////////////////////////////////////////////////////////////// CV_INIT_ALGORITHM(BFMatcher, "DescriptorMatcher.BFMatcher", obj.info()->addParam(obj, "normType", obj.normType); obj.info()->addParam(obj, "crossCheck", obj.crossCheck)); CV_INIT_ALGORITHM(FlannBasedMatcher, "DescriptorMatcher.FlannBasedMatcher",); /////////////////////////////////////////////////////////////////////////////////////////////////////////// bool cv::initModule_features2d(void) { bool all = true; all &= !BriefDescriptorExtractor_info_auto.name().empty(); all &= !BRISK_info_auto.name().empty(); all &= !FastFeatureDetector_info_auto.name().empty(); all &= !FastFeatureDetector2_info_auto.name().empty(); all &= !StarDetector_info_auto.name().empty(); all &= !MSER_info_auto.name().empty(); all &= !FREAK_info_auto.name().empty(); all &= !ORB_info_auto.name().empty(); all &= !GFTTDetector_info_auto.name().empty(); all &= !HarrisDetector_info_auto.name().empty(); all &= !DenseFeatureDetector_info_auto.name().empty(); all &= !GridAdaptedFeatureDetector_info_auto.name().empty(); all &= !BFMatcher_info_auto.name().empty(); all &= !FlannBasedMatcher_info_auto.name().empty(); return all; } <commit_msg>The next attempt to fix a build error on Mac.<commit_after>/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) however caused // and on any theory of liability, whether in contract, strict liability, // or tort (including negligence or otherwise) arising in any way out of // the use of this software, even if advised of the possibility of such damage. // //M*/ #include "precomp.hpp" #include "fast_score.hpp" using namespace cv; Ptr<Feature2D> Feature2D::create( const string& feature2DType ) { return Algorithm::create<Feature2D>("Feature2D." + feature2DType); } /////////////////////// AlgorithmInfo for various detector & descriptors //////////////////////////// /* NOTE!!! All the AlgorithmInfo-related stuff should be in the same file as initModule_features2d(). Otherwise, linker may throw away some seemingly unused stuff. */ CV_INIT_ALGORITHM(BRISK, "Feature2D.BRISK", obj.info()->addParam(obj, "thres", obj.threshold); obj.info()->addParam(obj, "octaves", obj.octaves)); /////////////////////////////////////////////////////////////////////////////////////////////////////////// CV_INIT_ALGORITHM(BriefDescriptorExtractor, "Feature2D.BRIEF", obj.info()->addParam(obj, "bytes", obj.bytes_)); /////////////////////////////////////////////////////////////////////////////////////////////////////////// CV_INIT_ALGORITHM(FastFeatureDetector, "Feature2D.FAST", obj.info()->addParam(obj, "threshold", obj.threshold); obj.info()->addParam(obj, "nonmaxSuppression", obj.nonmaxSuppression)); CV_INIT_ALGORITHM(FastFeatureDetector2, "Feature2D.FASTX", obj.info()->addParam(obj, "threshold", obj.threshold); obj.info()->addParam(obj, "nonmaxSuppression", obj.nonmaxSuppression); obj.info()->addParam(obj, "type", obj.type)); /////////////////////////////////////////////////////////////////////////////////////////////////////////// CV_INIT_ALGORITHM(StarDetector, "Feature2D.STAR", obj.info()->addParam(obj, "maxSize", obj.maxSize); obj.info()->addParam(obj, "responseThreshold", obj.responseThreshold); obj.info()->addParam(obj, "lineThresholdProjected", obj.lineThresholdProjected); obj.info()->addParam(obj, "lineThresholdBinarized", obj.lineThresholdBinarized); obj.info()->addParam(obj, "suppressNonmaxSize", obj.suppressNonmaxSize)); /////////////////////////////////////////////////////////////////////////////////////////////////////////// CV_INIT_ALGORITHM(MSER, "Feature2D.MSER", obj.info()->addParam(obj, "delta", obj.delta); obj.info()->addParam(obj, "minArea", obj.minArea); obj.info()->addParam(obj, "maxArea", obj.maxArea); obj.info()->addParam(obj, "maxVariation", obj.maxVariation); obj.info()->addParam(obj, "minDiversity", obj.minDiversity); obj.info()->addParam(obj, "maxEvolution", obj.maxEvolution); obj.info()->addParam(obj, "areaThreshold", obj.areaThreshold); obj.info()->addParam(obj, "minMargin", obj.minMargin); obj.info()->addParam(obj, "edgeBlurSize", obj.edgeBlurSize)); /////////////////////////////////////////////////////////////////////////////////////////////////////////// CV_INIT_ALGORITHM(ORB, "Feature2D.ORB", obj.info()->addParam(obj, "nFeatures", obj.nfeatures); obj.info()->addParam(obj, "scaleFactor", obj.scaleFactor); obj.info()->addParam(obj, "nLevels", obj.nlevels); obj.info()->addParam(obj, "firstLevel", obj.firstLevel); obj.info()->addParam(obj, "edgeThreshold", obj.edgeThreshold); obj.info()->addParam(obj, "patchSize", obj.patchSize); obj.info()->addParam(obj, "WTA_K", obj.WTA_K); obj.info()->addParam(obj, "scoreType", obj.scoreType)); /////////////////////////////////////////////////////////////////////////////////////////////////////////// CV_INIT_ALGORITHM(FREAK, "Feature2D.FREAK", obj.info()->addParam(obj, "orientationNormalized", obj.orientationNormalized); obj.info()->addParam(obj, "scaleNormalized", obj.scaleNormalized); obj.info()->addParam(obj, "patternScale", obj.patternScale); obj.info()->addParam(obj, "nbOctave", obj.nOctaves)); /////////////////////////////////////////////////////////////////////////////////////////////////////////// CV_INIT_ALGORITHM(GFTTDetector, "Feature2D.GFTT", obj.info()->addParam(obj, "nfeatures", obj.nfeatures); obj.info()->addParam(obj, "qualityLevel", obj.qualityLevel); obj.info()->addParam(obj, "minDistance", obj.minDistance); obj.info()->addParam(obj, "useHarrisDetector", obj.useHarrisDetector); obj.info()->addParam(obj, "k", obj.k)); /////////////////////////////////////////////////////////////////////////////////////////////////////////// CV_INIT_ALGORITHM(SimpleBlobDetector, "Feature2D.SimpleBlob", obj.info()->addParam(obj, "thresholdStep", obj.params.thresholdStep); obj.info()->addParam(obj, "minThreshold", obj.params.minThreshold); obj.info()->addParam(obj, "maxThreshold", obj.params.maxThreshold); obj.info()->addParam_(obj, "minRepeatability", (sizeof(size_t) == sizeof(uint64))?Param::UINT64 : Param::UNSIGNED_INT, &obj.params.minRepeatability, false, 0, 0); obj.info()->addParam(obj, "minDistBetweenBlobs", obj.params.minDistBetweenBlobs); obj.info()->addParam(obj, "filterByColor", obj.params.filterByColor); obj.info()->addParam(obj, "blobColor", obj.params.blobColor); obj.info()->addParam(obj, "filterByArea", obj.params.filterByArea); obj.info()->addParam(obj, "maxArea", obj.params.maxArea); obj.info()->addParam(obj, "filterByCircularity", obj.params.filterByCircularity); obj.info()->addParam(obj, "maxCircularity", obj.params.maxCircularity); obj.info()->addParam(obj, "filterByInertia", obj.params.filterByInertia); obj.info()->addParam(obj, "maxInertiaRatio", obj.params.maxInertiaRatio); obj.info()->addParam(obj, "filterByConvexity", obj.params.filterByConvexity); obj.info()->addParam(obj, "maxConvexity", obj.params.maxConvexity); ); /////////////////////////////////////////////////////////////////////////////////////////////////////////// class CV_EXPORTS HarrisDetector : public GFTTDetector { public: HarrisDetector( int maxCorners=1000, double qualityLevel=0.01, double minDistance=1, int blockSize=3, bool useHarrisDetector=true, double k=0.04 ); AlgorithmInfo* info() const; }; inline HarrisDetector::HarrisDetector( int _maxCorners, double _qualityLevel, double _minDistance, int _blockSize, bool _useHarrisDetector, double _k ) : GFTTDetector( _maxCorners, _qualityLevel, _minDistance, _blockSize, _useHarrisDetector, _k ) {} CV_INIT_ALGORITHM(HarrisDetector, "Feature2D.HARRIS", obj.info()->addParam(obj, "nfeatures", obj.nfeatures); obj.info()->addParam(obj, "qualityLevel", obj.qualityLevel); obj.info()->addParam(obj, "minDistance", obj.minDistance); obj.info()->addParam(obj, "useHarrisDetector", obj.useHarrisDetector); obj.info()->addParam(obj, "k", obj.k)); //////////////////////////////////////////////////////////////////////////////////////////////////////////// CV_INIT_ALGORITHM(DenseFeatureDetector, "Feature2D.Dense", obj.info()->addParam(obj, "initFeatureScale", obj.initFeatureScale); obj.info()->addParam(obj, "featureScaleLevels", obj.featureScaleLevels); obj.info()->addParam(obj, "featureScaleMul", obj.featureScaleMul); obj.info()->addParam(obj, "initXyStep", obj.initXyStep); obj.info()->addParam(obj, "initImgBound", obj.initImgBound); obj.info()->addParam(obj, "varyXyStepWithScale", obj.varyXyStepWithScale); obj.info()->addParam(obj, "varyImgBoundWithScale", obj.varyImgBoundWithScale)); CV_INIT_ALGORITHM(GridAdaptedFeatureDetector, "Feature2D.Grid", obj.info()->addParam(obj, "detector", obj.detector); obj.info()->addParam(obj, "maxTotalKeypoints", obj.maxTotalKeypoints); obj.info()->addParam(obj, "gridRows", obj.gridRows); obj.info()->addParam(obj, "gridCols", obj.gridCols)); //////////////////////////////////////////////////////////////////////////////////////////////////////////// CV_INIT_ALGORITHM(BFMatcher, "DescriptorMatcher.BFMatcher", obj.info()->addParam(obj, "normType", obj.normType); obj.info()->addParam(obj, "crossCheck", obj.crossCheck)); CV_INIT_ALGORITHM(FlannBasedMatcher, "DescriptorMatcher.FlannBasedMatcher",); /////////////////////////////////////////////////////////////////////////////////////////////////////////// bool cv::initModule_features2d(void) { bool all = true; all &= !BriefDescriptorExtractor_info_auto.name().empty(); all &= !BRISK_info_auto.name().empty(); all &= !FastFeatureDetector_info_auto.name().empty(); all &= !FastFeatureDetector2_info_auto.name().empty(); all &= !StarDetector_info_auto.name().empty(); all &= !MSER_info_auto.name().empty(); all &= !FREAK_info_auto.name().empty(); all &= !ORB_info_auto.name().empty(); all &= !GFTTDetector_info_auto.name().empty(); all &= !HarrisDetector_info_auto.name().empty(); all &= !DenseFeatureDetector_info_auto.name().empty(); all &= !GridAdaptedFeatureDetector_info_auto.name().empty(); all &= !BFMatcher_info_auto.name().empty(); all &= !FlannBasedMatcher_info_auto.name().empty(); return all; } <|endoftext|>
<commit_before>/* * Copyright 2007-2017 Content Management AG * All rights reserved. * * author: Max Kellermann <mk@cm4all.com> * * 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 * 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 "Launch.hxx" #include "spawn/UidGid.hxx" #include "system/Error.hxx" #include "util/PrintException.hxx" #include "util/Compiler.h" #include <sys/socket.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <errno.h> gcc_noreturn static void RunLogger(const char *command, UniqueSocketDescriptor &&fd) { fd.CheckDuplicate(FileDescriptor(STDIN_FILENO)); execl("/bin/sh", "sh", "-c", command, nullptr); fprintf(stderr, "failed to execute %s: %s\n", command, strerror(errno)); _exit(EXIT_FAILURE); } LogProcess LaunchLogger(const char *command, const UidGid *user) { LogProcess p; UniqueSocketDescriptor server_fd; if (!UniqueSocketDescriptor::CreateSocketPair(AF_LOCAL, SOCK_SEQPACKET, 0, server_fd, p.fd)) throw MakeErrno("socketpair() failed"); /* we need an unidirectional socket only */ p.fd.ShutdownRead(); server_fd.ShutdownWrite(); p.pid = fork(); if (p.pid < 0) throw MakeErrno("fork() failed"); if (p.pid == 0) { try { if (user != nullptr) user->Apply(); RunLogger(command, std::move(server_fd)); } catch (...) { PrintException(std::current_exception()); _exit(EXIT_FAILURE); } } return p; } <commit_msg>access_log/Launch: pass SocketDescriptor to RunLogger()<commit_after>/* * Copyright 2007-2017 Content Management AG * All rights reserved. * * author: Max Kellermann <mk@cm4all.com> * * 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 * 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 "Launch.hxx" #include "spawn/UidGid.hxx" #include "system/Error.hxx" #include "util/PrintException.hxx" #include "util/Compiler.h" #include <sys/socket.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <errno.h> gcc_noreturn static void RunLogger(const char *command, SocketDescriptor fd) { fd.CheckDuplicate(FileDescriptor(STDIN_FILENO)); execl("/bin/sh", "sh", "-c", command, nullptr); fprintf(stderr, "failed to execute %s: %s\n", command, strerror(errno)); _exit(EXIT_FAILURE); } LogProcess LaunchLogger(const char *command, const UidGid *user) { LogProcess p; UniqueSocketDescriptor server_fd; if (!UniqueSocketDescriptor::CreateSocketPair(AF_LOCAL, SOCK_SEQPACKET, 0, server_fd, p.fd)) throw MakeErrno("socketpair() failed"); /* we need an unidirectional socket only */ p.fd.ShutdownRead(); server_fd.ShutdownWrite(); p.pid = fork(); if (p.pid < 0) throw MakeErrno("fork() failed"); if (p.pid == 0) { try { if (user != nullptr) user->Apply(); RunLogger(command, server_fd); } catch (...) { PrintException(std::current_exception()); _exit(EXIT_FAILURE); } } return p; } <|endoftext|>
<commit_before>///////////////////////////////////////////////////////////////////////// // $Id: memory.cc,v 1.40 2005/04/10 19:42:48 sshwarts Exp $ ///////////////////////////////////////////////////////////////////////// // // Copyright (C) 2001 MandrakeSoft S.A. // // MandrakeSoft S.A. // 43, rue d'Aboukir // 75002 Paris - France // http://www.linux-mandrake.com/ // http://www.mandrakesoft.com/ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include "iodev/iodev.h" #define LOG_THIS BX_MEM_THIS #if BX_PROVIDE_CPU_MEMORY void BX_CPP_AttrRegparmN(3) BX_MEM_C::writePhysicalPage(BX_CPU_C *cpu, Bit32u addr, unsigned len, void *data) { Bit8u *data_ptr; Bit32u a20addr; // Note: accesses should always be contained within a single page now. #if BX_SUPPORT_IODEBUG bx_iodebug_c::mem_write(cpu, addr, len, data); #endif a20addr = A20ADDR(addr); struct memory_handler_struct *memory_handler = memory_handlers[a20addr >> 20]; while (memory_handler) { if (memory_handler->begin <= a20addr && memory_handler->end >= a20addr && memory_handler->write_handler(a20addr, len, data, memory_handler->write_param)) return; memory_handler = memory_handler->next; } BX_INSTR_PHY_WRITE(cpu->which_cpu(), a20addr, len); #if BX_DEBUGGER // (mch) Check for physical write break points, TODO // (bbd) Each breakpoint should have an associated CPU#, TODO for (int i = 0; i < num_write_watchpoints; i++) if (write_watchpoint[i] == a20addr) { BX_CPU(0)->watchpoint = a20addr; BX_CPU(0)->break_point = BREAK_POINT_WRITE; break; } #endif #if BX_SUPPORT_ICACHE if (a20addr < BX_MEM_THIS len) pageWriteStampTable.decWriteStamp(a20addr); #endif #if BX_SUPPORT_APIC bx_generic_apic_c *local_apic = &cpu->local_apic; bx_generic_apic_c *ioapic = bx_devices.ioapic; if (local_apic->is_selected (a20addr, len)) { local_apic->write (a20addr, (Bit32u *)data, len); return; } if (ioapic->is_selected (a20addr, len)) { ioapic->write (a20addr, (Bit32u *)data, len); return; } #endif if ( (a20addr + len) <= BX_MEM_THIS len ) { // all of data is within limits of physical memory if ( (a20addr & 0xfff80000) != 0x00080000 ) { if (len == 4) { WriteHostDWordToLittleEndian(&vector[a20addr], *(Bit32u*)data); BX_DBG_DIRTY_PAGE(a20addr >> 12); return; } if (len == 2) { WriteHostWordToLittleEndian(&vector[a20addr], *(Bit16u*)data); BX_DBG_DIRTY_PAGE(a20addr >> 12); return; } if (len == 1) { * ((Bit8u *) (&vector[a20addr])) = * (Bit8u *) data; BX_DBG_DIRTY_PAGE(a20addr >> 12); return; } // len == other, just fall thru to special cases handling } #ifdef BX_LITTLE_ENDIAN data_ptr = (Bit8u *) data; #else // BX_BIG_ENDIAN data_ptr = (Bit8u *) data + (len - 1); #endif write_one: if ( (a20addr & 0xfff80000) != 0x00080000 ) { // addr *not* in range 00080000 .. 000FFFFF vector[a20addr] = *data_ptr; BX_DBG_DIRTY_PAGE(a20addr >> 12); inc_one: if (len == 1) return; len--; a20addr++; #ifdef BX_LITTLE_ENDIAN data_ptr++; #else // BX_BIG_ENDIAN data_ptr--; #endif goto write_one; } // addr in range 00080000 .. 000FFFFF if (a20addr <= 0x0009ffff) { // regular memory 80000 .. 9FFFF vector[a20addr] = *data_ptr; BX_DBG_DIRTY_PAGE(a20addr >> 12); goto inc_one; } // adapter ROM C0000 .. DFFFF // ROM BIOS memory E0000 .. FFFFF #if BX_SUPPORT_PCI == 0 // ignore write to ROM #else // Write Based on 440fx Programming if ( bx_options.Oi440FXSupport->get () && ((a20addr & 0xfffc0000) == 0x000c0000) ) { switch (DEV_pci_wr_memtype(a20addr & 0xFC000)) { case 0x1: // Writes to ShadowRAM BX_DEBUG(("Writing to ShadowRAM: address %08x, data %02x", (unsigned) a20addr, *data_ptr)); vector[a20addr] = *data_ptr; BX_DBG_DIRTY_PAGE(a20addr >> 12); goto inc_one; case 0x0: // Writes to ROM, Inhibit BX_DEBUG(("Write to ROM ignored: address %08x, data %02x", (unsigned) a20addr, *data_ptr)); goto inc_one; default: BX_PANIC(("writePhysicalPage: default case")); goto inc_one; } } #endif goto inc_one; } else { // some or all of data is outside limits of physical memory #ifdef BX_LITTLE_ENDIAN data_ptr = (Bit8u *) data; #else // BX_BIG_ENDIAN data_ptr = (Bit8u *) data + (len - 1); #endif for (unsigned i = 0; i < len; i++) { if (a20addr < BX_MEM_THIS len) { vector[a20addr] = *data_ptr; BX_DBG_DIRTY_PAGE(a20addr >> 12); } // otherwise ignore byte, since it overruns memory addr++; a20addr = (addr); #ifdef BX_LITTLE_ENDIAN data_ptr++; #else // BX_BIG_ENDIAN data_ptr--; #endif } return; } } void BX_CPP_AttrRegparmN(3) BX_MEM_C::readPhysicalPage(BX_CPU_C *cpu, Bit32u addr, unsigned len, void *data) { Bit8u *data_ptr; Bit32u a20addr; #if BX_SUPPORT_IODEBUG bx_iodebug_c::mem_read(cpu, addr, len, data); #endif a20addr = A20ADDR(addr); struct memory_handler_struct *memory_handler = memory_handlers[a20addr >> 20]; while (memory_handler) { if (memory_handler->begin <= a20addr && memory_handler->end >= a20addr && memory_handler->read_handler(a20addr, len, data, memory_handler->read_param)) return; memory_handler = memory_handler->next; } BX_INSTR_PHY_READ(cpu->which_cpu(), a20addr, len); #if BX_DEBUGGER // (mch) Check for physical read break points, TODO // (bbd) Each breakpoint should have an associated CPU#, TODO for (int i = 0; i < num_read_watchpoints; i++) if (read_watchpoint[i] == a20addr) { BX_CPU(0)->watchpoint = a20addr; BX_CPU(0)->break_point = BREAK_POINT_READ; break; } #endif #if BX_SUPPORT_APIC bx_generic_apic_c *local_apic = &cpu->local_apic; bx_generic_apic_c *ioapic = bx_devices.ioapic; if (local_apic->is_selected (addr, len)) { local_apic->read (addr, data, len); return; } if (ioapic->is_selected (addr, len)) { ioapic->read (addr, data, len); return; } #endif if ( (a20addr + len) <= BX_MEM_THIS len ) { // all of data is within limits of physical memory if ( (a20addr & 0xfff80000) != 0x00080000 ) { if (len == 4) { ReadHostDWordFromLittleEndian(&vector[a20addr], * (Bit32u*) data); return; } if (len == 2) { ReadHostWordFromLittleEndian(&vector[a20addr], * (Bit16u*) data); return; } if (len == 1) { * (Bit8u *) data = * ((Bit8u *) (&vector[a20addr])); return; } // len == 3 case can just fall thru to special cases handling } #ifdef BX_LITTLE_ENDIAN data_ptr = (Bit8u *) data; #else // BX_BIG_ENDIAN data_ptr = (Bit8u *) data + (len - 1); #endif read_one: if ( (a20addr & 0xfff80000) != 0x00080000 ) { // addr *not* in range 00080000 .. 000FFFFF *data_ptr = vector[a20addr]; inc_one: if (len == 1) return; len--; a20addr++; #ifdef BX_LITTLE_ENDIAN data_ptr++; #else // BX_BIG_ENDIAN data_ptr--; #endif goto read_one; } // addr in range 00080000 .. 000FFFFF #if BX_SUPPORT_PCI if ( bx_options.Oi440FXSupport->get () && ((a20addr & 0xfffc0000) == 0x000c0000) ) { switch (DEV_pci_rd_memtype (a20addr)) { case 0x0: // Read from ROM *data_ptr = rom[a20addr - 0xc0000]; goto inc_one; case 0x1: // Read from ShadowRAM *data_ptr = vector[a20addr]; goto inc_one; default: BX_PANIC(("readPhysicalPage: default case")); } goto inc_one; } else #endif // #if BX_SUPPORT_PCI { if ( (a20addr & 0xfffc0000) == 0x000c0000 ) { *data_ptr = rom[a20addr - 0xc0000]; } else { *data_ptr = vector[a20addr]; } goto inc_one; } } else { // some or all of data is outside limits of physical memory #ifdef BX_LITTLE_ENDIAN data_ptr = (Bit8u *) data; #else // BX_BIG_ENDIAN data_ptr = (Bit8u *) data + (len - 1); #endif for (unsigned i = 0; i < len; i++) { if (a20addr < BX_MEM_THIS len) *data_ptr = vector[a20addr]; else if (a20addr >= 0xfffe0000) *data_ptr = rom[a20addr & 0x3ffff]; else *data_ptr = 0xff; addr++; a20addr = (addr); #ifdef BX_LITTLE_ENDIAN data_ptr++; #else // BX_BIG_ENDIAN data_ptr--; #endif } return; } } #endif // #if BX_PROVIDE_CPU_MEMORY <commit_msg>- make debugger watchpoints in device memory work again (SF patch #1309763 by Nickolai Zeldovich)<commit_after>///////////////////////////////////////////////////////////////////////// // $Id: memory.cc,v 1.41 2005/10/01 09:52:35 vruppert Exp $ ///////////////////////////////////////////////////////////////////////// // // Copyright (C) 2001 MandrakeSoft S.A. // // MandrakeSoft S.A. // 43, rue d'Aboukir // 75002 Paris - France // http://www.linux-mandrake.com/ // http://www.mandrakesoft.com/ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include "iodev/iodev.h" #define LOG_THIS BX_MEM_THIS #if BX_PROVIDE_CPU_MEMORY void BX_CPP_AttrRegparmN(3) BX_MEM_C::writePhysicalPage(BX_CPU_C *cpu, Bit32u addr, unsigned len, void *data) { Bit8u *data_ptr; Bit32u a20addr; // Note: accesses should always be contained within a single page now. #if BX_SUPPORT_IODEBUG bx_iodebug_c::mem_write(cpu, addr, len, data); #endif a20addr = A20ADDR(addr); BX_INSTR_PHY_WRITE(cpu->which_cpu(), a20addr, len); #if BX_DEBUGGER // (mch) Check for physical write break points, TODO // (bbd) Each breakpoint should have an associated CPU#, TODO for (int i = 0; i < num_write_watchpoints; i++) if (write_watchpoint[i] == a20addr) { BX_CPU(0)->watchpoint = a20addr; BX_CPU(0)->break_point = BREAK_POINT_WRITE; break; } #endif struct memory_handler_struct *memory_handler = memory_handlers[a20addr >> 20]; while (memory_handler) { if (memory_handler->begin <= a20addr && memory_handler->end >= a20addr && memory_handler->write_handler(a20addr, len, data, memory_handler->write_param)) return; memory_handler = memory_handler->next; } #if BX_SUPPORT_ICACHE if (a20addr < BX_MEM_THIS len) pageWriteStampTable.decWriteStamp(a20addr); #endif #if BX_SUPPORT_APIC bx_generic_apic_c *local_apic = &cpu->local_apic; bx_generic_apic_c *ioapic = bx_devices.ioapic; if (local_apic->is_selected (a20addr, len)) { local_apic->write (a20addr, (Bit32u *)data, len); return; } if (ioapic->is_selected (a20addr, len)) { ioapic->write (a20addr, (Bit32u *)data, len); return; } #endif if ( (a20addr + len) <= BX_MEM_THIS len ) { // all of data is within limits of physical memory if ( (a20addr & 0xfff80000) != 0x00080000 ) { if (len == 4) { WriteHostDWordToLittleEndian(&vector[a20addr], *(Bit32u*)data); BX_DBG_DIRTY_PAGE(a20addr >> 12); return; } if (len == 2) { WriteHostWordToLittleEndian(&vector[a20addr], *(Bit16u*)data); BX_DBG_DIRTY_PAGE(a20addr >> 12); return; } if (len == 1) { * ((Bit8u *) (&vector[a20addr])) = * (Bit8u *) data; BX_DBG_DIRTY_PAGE(a20addr >> 12); return; } // len == other, just fall thru to special cases handling } #ifdef BX_LITTLE_ENDIAN data_ptr = (Bit8u *) data; #else // BX_BIG_ENDIAN data_ptr = (Bit8u *) data + (len - 1); #endif write_one: if ( (a20addr & 0xfff80000) != 0x00080000 ) { // addr *not* in range 00080000 .. 000FFFFF vector[a20addr] = *data_ptr; BX_DBG_DIRTY_PAGE(a20addr >> 12); inc_one: if (len == 1) return; len--; a20addr++; #ifdef BX_LITTLE_ENDIAN data_ptr++; #else // BX_BIG_ENDIAN data_ptr--; #endif goto write_one; } // addr in range 00080000 .. 000FFFFF if (a20addr <= 0x0009ffff) { // regular memory 80000 .. 9FFFF vector[a20addr] = *data_ptr; BX_DBG_DIRTY_PAGE(a20addr >> 12); goto inc_one; } // adapter ROM C0000 .. DFFFF // ROM BIOS memory E0000 .. FFFFF #if BX_SUPPORT_PCI == 0 // ignore write to ROM #else // Write Based on 440fx Programming if ( bx_options.Oi440FXSupport->get () && ((a20addr & 0xfffc0000) == 0x000c0000) ) { switch (DEV_pci_wr_memtype(a20addr & 0xFC000)) { case 0x1: // Writes to ShadowRAM BX_DEBUG(("Writing to ShadowRAM: address %08x, data %02x", (unsigned) a20addr, *data_ptr)); vector[a20addr] = *data_ptr; BX_DBG_DIRTY_PAGE(a20addr >> 12); goto inc_one; case 0x0: // Writes to ROM, Inhibit BX_DEBUG(("Write to ROM ignored: address %08x, data %02x", (unsigned) a20addr, *data_ptr)); goto inc_one; default: BX_PANIC(("writePhysicalPage: default case")); goto inc_one; } } #endif goto inc_one; } else { // some or all of data is outside limits of physical memory #ifdef BX_LITTLE_ENDIAN data_ptr = (Bit8u *) data; #else // BX_BIG_ENDIAN data_ptr = (Bit8u *) data + (len - 1); #endif for (unsigned i = 0; i < len; i++) { if (a20addr < BX_MEM_THIS len) { vector[a20addr] = *data_ptr; BX_DBG_DIRTY_PAGE(a20addr >> 12); } // otherwise ignore byte, since it overruns memory addr++; a20addr = (addr); #ifdef BX_LITTLE_ENDIAN data_ptr++; #else // BX_BIG_ENDIAN data_ptr--; #endif } return; } } void BX_CPP_AttrRegparmN(3) BX_MEM_C::readPhysicalPage(BX_CPU_C *cpu, Bit32u addr, unsigned len, void *data) { Bit8u *data_ptr; Bit32u a20addr; #if BX_SUPPORT_IODEBUG bx_iodebug_c::mem_read(cpu, addr, len, data); #endif a20addr = A20ADDR(addr); BX_INSTR_PHY_READ(cpu->which_cpu(), a20addr, len); #if BX_DEBUGGER // (mch) Check for physical read break points, TODO // (bbd) Each breakpoint should have an associated CPU#, TODO for (int i = 0; i < num_read_watchpoints; i++) if (read_watchpoint[i] == a20addr) { BX_CPU(0)->watchpoint = a20addr; BX_CPU(0)->break_point = BREAK_POINT_READ; break; } #endif struct memory_handler_struct *memory_handler = memory_handlers[a20addr >> 20]; while (memory_handler) { if (memory_handler->begin <= a20addr && memory_handler->end >= a20addr && memory_handler->read_handler(a20addr, len, data, memory_handler->read_param)) return; memory_handler = memory_handler->next; } #if BX_SUPPORT_APIC bx_generic_apic_c *local_apic = &cpu->local_apic; bx_generic_apic_c *ioapic = bx_devices.ioapic; if (local_apic->is_selected (addr, len)) { local_apic->read (addr, data, len); return; } if (ioapic->is_selected (addr, len)) { ioapic->read (addr, data, len); return; } #endif if ( (a20addr + len) <= BX_MEM_THIS len ) { // all of data is within limits of physical memory if ( (a20addr & 0xfff80000) != 0x00080000 ) { if (len == 4) { ReadHostDWordFromLittleEndian(&vector[a20addr], * (Bit32u*) data); return; } if (len == 2) { ReadHostWordFromLittleEndian(&vector[a20addr], * (Bit16u*) data); return; } if (len == 1) { * (Bit8u *) data = * ((Bit8u *) (&vector[a20addr])); return; } // len == 3 case can just fall thru to special cases handling } #ifdef BX_LITTLE_ENDIAN data_ptr = (Bit8u *) data; #else // BX_BIG_ENDIAN data_ptr = (Bit8u *) data + (len - 1); #endif read_one: if ( (a20addr & 0xfff80000) != 0x00080000 ) { // addr *not* in range 00080000 .. 000FFFFF *data_ptr = vector[a20addr]; inc_one: if (len == 1) return; len--; a20addr++; #ifdef BX_LITTLE_ENDIAN data_ptr++; #else // BX_BIG_ENDIAN data_ptr--; #endif goto read_one; } // addr in range 00080000 .. 000FFFFF #if BX_SUPPORT_PCI if ( bx_options.Oi440FXSupport->get () && ((a20addr & 0xfffc0000) == 0x000c0000) ) { switch (DEV_pci_rd_memtype (a20addr)) { case 0x0: // Read from ROM *data_ptr = rom[a20addr - 0xc0000]; goto inc_one; case 0x1: // Read from ShadowRAM *data_ptr = vector[a20addr]; goto inc_one; default: BX_PANIC(("readPhysicalPage: default case")); } goto inc_one; } else #endif // #if BX_SUPPORT_PCI { if ( (a20addr & 0xfffc0000) == 0x000c0000 ) { *data_ptr = rom[a20addr - 0xc0000]; } else { *data_ptr = vector[a20addr]; } goto inc_one; } } else { // some or all of data is outside limits of physical memory #ifdef BX_LITTLE_ENDIAN data_ptr = (Bit8u *) data; #else // BX_BIG_ENDIAN data_ptr = (Bit8u *) data + (len - 1); #endif for (unsigned i = 0; i < len; i++) { if (a20addr < BX_MEM_THIS len) *data_ptr = vector[a20addr]; else if (a20addr >= 0xfffe0000) *data_ptr = rom[a20addr & 0x3ffff]; else *data_ptr = 0xff; addr++; a20addr = (addr); #ifdef BX_LITTLE_ENDIAN data_ptr++; #else // BX_BIG_ENDIAN data_ptr--; #endif } return; } } #endif // #if BX_PROVIDE_CPU_MEMORY <|endoftext|>
<commit_before>/* * Copyright (C) 2016 Hong Jen Yee (PCMan) <pcman.tw@gmail.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * */ #include "pathbar.h" #include "pathbar_p.h" #include <QToolButton> #include <QScrollArea> #include <QScrollBar> #include <QHBoxLayout> #include <QResizeEvent> #include <QContextMenuEvent> #include <QMenu> #include <QClipboard> #include <QApplication> #include <QTimer> #include <QDebug> #include "pathedit.h" namespace Fm { PathBar::PathBar(QWidget* parent): QWidget(parent), tempPathEdit_(nullptr), toggledBtn_(nullptr) { QHBoxLayout* topLayout = new QHBoxLayout(this); topLayout->setContentsMargins(0, 0, 0, 0); topLayout->setSpacing(0); bool rtl(layoutDirection() == Qt::RightToLeft); // the arrow button used to scroll to start of the path scrollToStart_ = new QToolButton(this); scrollToStart_->setArrowType(rtl ? Qt::RightArrow : Qt::LeftArrow); scrollToStart_->setAutoRepeat(true); scrollToStart_->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::MinimumExpanding); connect(scrollToStart_, &QToolButton::clicked, this, &PathBar::onScrollButtonClicked); topLayout->addWidget(scrollToStart_); // there might be too many buttons when the path is long, so make it scrollable. scrollArea_ = new QScrollArea(this); scrollArea_->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); scrollArea_->setFrameShape(QFrame::NoFrame); scrollArea_->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); scrollArea_->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); scrollArea_->setSizeAdjustPolicy(QAbstractScrollArea::AdjustToContents); scrollArea_->verticalScrollBar()->setDisabled(true); connect(scrollArea_->horizontalScrollBar(), &QAbstractSlider::valueChanged, this, &PathBar::setArrowEnabledState); topLayout->addWidget(scrollArea_, 1); // stretch factor=1, make it expandable // the arrow button used to scroll to end of the path scrollToEnd_ = new QToolButton(this); scrollToEnd_->setArrowType(rtl ? Qt::LeftArrow : Qt::RightArrow); scrollToEnd_->setAutoRepeat(true); scrollToEnd_->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::MinimumExpanding); connect(scrollToEnd_, &QToolButton::clicked, this, &PathBar::onScrollButtonClicked); topLayout->addWidget(scrollToEnd_); // container widget of the path buttons buttonsWidget_ = new QWidget(this); buttonsWidget_->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); buttonsLayout_ = new QHBoxLayout(buttonsWidget_); buttonsLayout_->setContentsMargins(0, 0, 0, 0); buttonsLayout_->setSpacing(0); buttonsLayout_->setSizeConstraint(QLayout::SetFixedSize); // required when added to scroll area according to QScrollArea doc. scrollArea_->setWidget(buttonsWidget_); // make the buttons widget scrollable if the path is too long } void PathBar::resizeEvent(QResizeEvent* event) { QWidget::resizeEvent(event); updateScrollButtonVisibility(); QTimer::singleShot(0, this, SLOT(ensureToggledVisible())); } void PathBar::wheelEvent(QWheelEvent* event) { QWidget::wheelEvent(event); QAbstractSlider::SliderAction action = QAbstractSlider::SliderNoAction; int vDelta = event->angleDelta().y(); if(vDelta > 0) { if(scrollToStart_->isEnabled()) { action = QAbstractSlider::SliderSingleStepSub; } } else if(vDelta < 0) { if(scrollToEnd_->isEnabled()) { action = QAbstractSlider::SliderSingleStepAdd; } } scrollArea_->horizontalScrollBar()->triggerAction(action); } void PathBar::mousePressEvent(QMouseEvent* event) { QWidget::mousePressEvent(event); if(event->button() == Qt::LeftButton) { openEditor(); } else if(event->button() == Qt::MiddleButton) { PathButton* btn = qobject_cast<PathButton*>(childAt(event->x(), event->y())); if(btn != nullptr) { scrollArea_->ensureWidgetVisible(btn, 1); // a harmless compensation for a miscalculation in Qt Q_EMIT middleClickChdir(pathForButton(btn)); } } } void PathBar::contextMenuEvent(QContextMenuEvent* event) { QMenu* menu = new QMenu(this); connect(menu, &QMenu::aboutToHide, menu, &QMenu::deleteLater); QAction* action = menu->addAction(tr("&Edit Path")); connect(action, &QAction::triggered, this, &PathBar::openEditor); action = menu->addAction(tr("&Copy Path")); connect(action, &QAction::triggered, this, &PathBar::copyPath); menu->popup(mapToGlobal(event->pos())); } void PathBar::updateScrollButtonVisibility() { // Wait for the horizontal scrollbar to be completely shaped. // Without this, the enabled state of arrow buttons might be // wrong when the pathbar is created for the first time. QTimer::singleShot(0, this, SLOT(setScrollButtonVisibility())); } void PathBar::setScrollButtonVisibility() { bool showScrollers; if(tempPathEdit_ != nullptr) { showScrollers = false; } else { showScrollers = (buttonsLayout_->sizeHint().width() > width()); } scrollToStart_->setVisible(showScrollers); scrollToEnd_->setVisible(showScrollers); if(showScrollers) { QScrollBar* sb = scrollArea_->horizontalScrollBar(); int value = sb->value(); scrollToStart_->setEnabled(value != sb->minimum()); scrollToEnd_->setEnabled(value != sb->maximum()); } } Fm::FilePath PathBar::pathForButton(PathButton* btn) { std::string fullPath; int buttonCount = buttonsLayout_->count() - 1; // the last item is a spacer for(int i = 0; i < buttonCount; ++i) { if(!fullPath.empty() && fullPath.back() != '/') { fullPath += '/'; } PathButton* elem = static_cast<PathButton*>(buttonsLayout_->itemAt(i)->widget()); fullPath += elem->name(); if(elem == btn) break; } return Fm::FilePath::fromPathStr(fullPath.c_str()); } void PathBar::onButtonToggled(bool checked) { if(checked) { PathButton* btn = static_cast<PathButton*>(sender()); toggledBtn_ = btn; currentPath_ = pathForButton(btn); Q_EMIT chdir(currentPath_); // since scrolling to the toggled buton will happen correctly only when the // layout is updated and because the update is disabled on creating buttons // in setPath(), the update status can be used as a sign to know when to wait if(updatesEnabled()) { scrollArea_->ensureWidgetVisible(btn, 1); } else { QTimer::singleShot(0, this, SLOT(ensureToggledVisible())); } } } void PathBar::ensureToggledVisible() { if(toggledBtn_ != nullptr && tempPathEdit_ == nullptr) { scrollArea_->ensureWidgetVisible(toggledBtn_, 1); } } void PathBar::onScrollButtonClicked() { QToolButton* btn = static_cast<QToolButton*>(sender()); QAbstractSlider::SliderAction action = QAbstractSlider::SliderNoAction; if(btn == scrollToEnd_) { action = QAbstractSlider::SliderSingleStepAdd; } else if(btn == scrollToStart_) { action = QAbstractSlider::SliderSingleStepSub; } scrollArea_->horizontalScrollBar()->triggerAction(action); } void PathBar::setPath(Fm::FilePath path) { if(currentPath_ == path) { // same path, do nothing return; } auto oldPath = std::move(currentPath_); currentPath_ = std::move(path); // check if we already have a button for this path int buttonCount = buttonsLayout_->count() - 1; // the last item is a spacer if(oldPath && currentPath_.isPrefixOf(oldPath)) { for(int i = buttonCount - 1; i >= 0; --i) { auto btn = static_cast<PathButton*>(buttonsLayout_->itemAt(i)->widget()); if(pathForButton(btn) == currentPath_) { btn->setChecked(true); // toggle the button /* we don't need to emit chdir signal here since later * toggled signal will be triggered on the button, which * in turns emit chdir. */ return; } } } /* FIXME: if the new path is the subdir of our full path, actually * we can append several new buttons rather than re-create * all of the buttons. This can reduce flickers. */ setUpdatesEnabled(false); toggledBtn_ = nullptr; // we do not have the path in the buttons list // destroy existing path element buttons and the spacer QLayoutItem* item; while((item = buttonsLayout_->takeAt(0)) != nullptr) { delete item->widget(); delete item; } // create new buttons for the new path auto btnPath = currentPath_; while(btnPath) { Fm::CStrPtr name; Fm::CStrPtr displayName; auto parent = btnPath.parent(); // FIXME: some buggy uri types, such as menu://, fail to return NULL when there is no parent path. // Instead, the path itself is returned. So we check if the parent path is the same as current path. auto isRoot = !parent.isValid() || parent == btnPath; if(isRoot) { displayName = btnPath.displayName(); name = btnPath.toString(); } else { name = btnPath.baseName(); } auto btn = new PathButton(name.get(), displayName ? QString::fromUtf8(displayName.get()) : QString::fromUtf8(name.get()), isRoot, buttonsWidget_); btn->show(); connect(btn, &QAbstractButton::toggled, this, &PathBar::onButtonToggled); buttonsLayout_->insertWidget(0, btn); if(isRoot) { // this is the root element of the path break; } btnPath = parent; } buttonsLayout_->addStretch(1); // add a spacer at the tail of the buttons // we don't want to scroll vertically. make the scroll area fit the height of the buttons // FIXME: this is a little bit hackish :-( scrollArea_->setFixedHeight(buttonsLayout_->sizeHint().height()); updateScrollButtonVisibility(); // to guarantee that the button will be scrolled to correctly, // it should be toggled only after the layout update starts above buttonCount = buttonsLayout_->count() - 1; if(buttonCount > 0) { PathButton* lastBtn = static_cast<PathButton*>(buttonsLayout_->itemAt(buttonCount - 1)->widget()); // we don't have to emit the chdir signal since the "onButtonToggled()" slot will be triggered by this. lastBtn->setChecked(true); } setUpdatesEnabled(true); } void PathBar::openEditor() { if(tempPathEdit_ == nullptr) { tempPathEdit_ = new PathEdit(this); delete layout()->replaceWidget(scrollArea_, tempPathEdit_, Qt::FindDirectChildrenOnly); scrollArea_->hide(); scrollToStart_->setVisible(false); scrollToEnd_->setVisible(false); tempPathEdit_->setText(QString::fromUtf8(currentPath_.toString().get())); connect(tempPathEdit_, &PathEdit::returnPressed, this, &PathBar::onReturnPressed); connect(tempPathEdit_, &PathEdit::editingFinished, this, &PathBar::closeEditor); } tempPathEdit_->selectAll(); QApplication::clipboard()->setText(tempPathEdit_->text(), QClipboard::Selection); QTimer::singleShot(0, tempPathEdit_, SLOT(setFocus())); } void PathBar::closeEditor() { if(tempPathEdit_ == nullptr) { return; } // If a menu has popped up synchronously (with QMenu::exec), the path buttons may be drawn // but the path-edit may not disappear until the menu is closed. So, we hide it here. // However, since hiding the path-edit makes it lose focus and emit editingFinished(), // we should first disconnect from it to avoid recursive calling of the current function. tempPathEdit_->disconnect(); tempPathEdit_->setVisible(false); delete layout()->replaceWidget(tempPathEdit_, scrollArea_, Qt::FindDirectChildrenOnly); scrollArea_->show(); if(buttonsLayout_->sizeHint().width() > width()) { scrollToStart_->setVisible(true); scrollToEnd_->setVisible(true); } tempPathEdit_->deleteLater(); tempPathEdit_ = nullptr; updateScrollButtonVisibility(); Q_EMIT editingFinished(); } void PathBar::copyPath() { QApplication::clipboard()->setText(QString::fromUtf8(currentPath_.toString().get())); } void PathBar::onReturnPressed() { QByteArray pathStr = tempPathEdit_->text().toLocal8Bit(); setPath(Fm::FilePath::fromPathStr(pathStr.constData())); } void PathBar::setArrowEnabledState(int value) { if(buttonsLayout_->sizeHint().width() > width()) { QScrollBar* sb = scrollArea_->horizontalScrollBar(); scrollToStart_->setEnabled(value != sb->minimum()); scrollToEnd_->setEnabled(value != sb->maximum()); } } } // namespace Fm <commit_msg>Corrected path button "hidden" names<commit_after>/* * Copyright (C) 2016 Hong Jen Yee (PCMan) <pcman.tw@gmail.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * */ #include "pathbar.h" #include "pathbar_p.h" #include <QToolButton> #include <QScrollArea> #include <QScrollBar> #include <QHBoxLayout> #include <QResizeEvent> #include <QContextMenuEvent> #include <QMenu> #include <QClipboard> #include <QApplication> #include <QTimer> #include <QDebug> #include "pathedit.h" namespace Fm { PathBar::PathBar(QWidget* parent): QWidget(parent), tempPathEdit_(nullptr), toggledBtn_(nullptr) { QHBoxLayout* topLayout = new QHBoxLayout(this); topLayout->setContentsMargins(0, 0, 0, 0); topLayout->setSpacing(0); bool rtl(layoutDirection() == Qt::RightToLeft); // the arrow button used to scroll to start of the path scrollToStart_ = new QToolButton(this); scrollToStart_->setArrowType(rtl ? Qt::RightArrow : Qt::LeftArrow); scrollToStart_->setAutoRepeat(true); scrollToStart_->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::MinimumExpanding); connect(scrollToStart_, &QToolButton::clicked, this, &PathBar::onScrollButtonClicked); topLayout->addWidget(scrollToStart_); // there might be too many buttons when the path is long, so make it scrollable. scrollArea_ = new QScrollArea(this); scrollArea_->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); scrollArea_->setFrameShape(QFrame::NoFrame); scrollArea_->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); scrollArea_->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); scrollArea_->setSizeAdjustPolicy(QAbstractScrollArea::AdjustToContents); scrollArea_->verticalScrollBar()->setDisabled(true); connect(scrollArea_->horizontalScrollBar(), &QAbstractSlider::valueChanged, this, &PathBar::setArrowEnabledState); topLayout->addWidget(scrollArea_, 1); // stretch factor=1, make it expandable // the arrow button used to scroll to end of the path scrollToEnd_ = new QToolButton(this); scrollToEnd_->setArrowType(rtl ? Qt::LeftArrow : Qt::RightArrow); scrollToEnd_->setAutoRepeat(true); scrollToEnd_->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::MinimumExpanding); connect(scrollToEnd_, &QToolButton::clicked, this, &PathBar::onScrollButtonClicked); topLayout->addWidget(scrollToEnd_); // container widget of the path buttons buttonsWidget_ = new QWidget(this); buttonsWidget_->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); buttonsLayout_ = new QHBoxLayout(buttonsWidget_); buttonsLayout_->setContentsMargins(0, 0, 0, 0); buttonsLayout_->setSpacing(0); buttonsLayout_->setSizeConstraint(QLayout::SetFixedSize); // required when added to scroll area according to QScrollArea doc. scrollArea_->setWidget(buttonsWidget_); // make the buttons widget scrollable if the path is too long } void PathBar::resizeEvent(QResizeEvent* event) { QWidget::resizeEvent(event); updateScrollButtonVisibility(); QTimer::singleShot(0, this, SLOT(ensureToggledVisible())); } void PathBar::wheelEvent(QWheelEvent* event) { QWidget::wheelEvent(event); QAbstractSlider::SliderAction action = QAbstractSlider::SliderNoAction; int vDelta = event->angleDelta().y(); if(vDelta > 0) { if(scrollToStart_->isEnabled()) { action = QAbstractSlider::SliderSingleStepSub; } } else if(vDelta < 0) { if(scrollToEnd_->isEnabled()) { action = QAbstractSlider::SliderSingleStepAdd; } } scrollArea_->horizontalScrollBar()->triggerAction(action); } void PathBar::mousePressEvent(QMouseEvent* event) { QWidget::mousePressEvent(event); if(event->button() == Qt::LeftButton) { openEditor(); } else if(event->button() == Qt::MiddleButton) { PathButton* btn = qobject_cast<PathButton*>(childAt(event->x(), event->y())); if(btn != nullptr) { scrollArea_->ensureWidgetVisible(btn, 1); // a harmless compensation for a miscalculation in Qt Q_EMIT middleClickChdir(pathForButton(btn)); } } } void PathBar::contextMenuEvent(QContextMenuEvent* event) { QMenu* menu = new QMenu(this); connect(menu, &QMenu::aboutToHide, menu, &QMenu::deleteLater); QAction* action = menu->addAction(tr("&Edit Path")); connect(action, &QAction::triggered, this, &PathBar::openEditor); action = menu->addAction(tr("&Copy Path")); connect(action, &QAction::triggered, this, &PathBar::copyPath); menu->popup(mapToGlobal(event->pos())); } void PathBar::updateScrollButtonVisibility() { // Wait for the horizontal scrollbar to be completely shaped. // Without this, the enabled state of arrow buttons might be // wrong when the pathbar is created for the first time. QTimer::singleShot(0, this, SLOT(setScrollButtonVisibility())); } void PathBar::setScrollButtonVisibility() { bool showScrollers; if(tempPathEdit_ != nullptr) { showScrollers = false; } else { showScrollers = (buttonsLayout_->sizeHint().width() > width()); } scrollToStart_->setVisible(showScrollers); scrollToEnd_->setVisible(showScrollers); if(showScrollers) { QScrollBar* sb = scrollArea_->horizontalScrollBar(); int value = sb->value(); scrollToStart_->setEnabled(value != sb->minimum()); scrollToEnd_->setEnabled(value != sb->maximum()); } } Fm::FilePath PathBar::pathForButton(PathButton* btn) { std::string fullPath; int buttonCount = buttonsLayout_->count() - 1; // the last item is a spacer for(int i = 0; i < buttonCount; ++i) { if(!fullPath.empty() && fullPath.back() != '/') { fullPath += '/'; } PathButton* elem = static_cast<PathButton*>(buttonsLayout_->itemAt(i)->widget()); fullPath += elem->name(); if(elem == btn) break; } return Fm::FilePath::fromPathStr(fullPath.c_str()); } void PathBar::onButtonToggled(bool checked) { if(checked) { PathButton* btn = static_cast<PathButton*>(sender()); toggledBtn_ = btn; currentPath_ = pathForButton(btn); Q_EMIT chdir(currentPath_); // since scrolling to the toggled buton will happen correctly only when the // layout is updated and because the update is disabled on creating buttons // in setPath(), the update status can be used as a sign to know when to wait if(updatesEnabled()) { scrollArea_->ensureWidgetVisible(btn, 1); } else { QTimer::singleShot(0, this, SLOT(ensureToggledVisible())); } } } void PathBar::ensureToggledVisible() { if(toggledBtn_ != nullptr && tempPathEdit_ == nullptr) { scrollArea_->ensureWidgetVisible(toggledBtn_, 1); } } void PathBar::onScrollButtonClicked() { QToolButton* btn = static_cast<QToolButton*>(sender()); QAbstractSlider::SliderAction action = QAbstractSlider::SliderNoAction; if(btn == scrollToEnd_) { action = QAbstractSlider::SliderSingleStepAdd; } else if(btn == scrollToStart_) { action = QAbstractSlider::SliderSingleStepSub; } scrollArea_->horizontalScrollBar()->triggerAction(action); } void PathBar::setPath(Fm::FilePath path) { if(currentPath_ == path) { // same path, do nothing return; } auto oldPath = std::move(currentPath_); currentPath_ = std::move(path); // check if we already have a button for this path int buttonCount = buttonsLayout_->count() - 1; // the last item is a spacer if(oldPath && currentPath_.isPrefixOf(oldPath)) { for(int i = buttonCount - 1; i >= 0; --i) { auto btn = static_cast<PathButton*>(buttonsLayout_->itemAt(i)->widget()); if(pathForButton(btn) == currentPath_) { btn->setChecked(true); // toggle the button /* we don't need to emit chdir signal here since later * toggled signal will be triggered on the button, which * in turns emit chdir. */ return; } } } /* FIXME: if the new path is the subdir of our full path, actually * we can append several new buttons rather than re-create * all of the buttons. This can reduce flickers. */ setUpdatesEnabled(false); toggledBtn_ = nullptr; // we do not have the path in the buttons list // destroy existing path element buttons and the spacer QLayoutItem* item; while((item = buttonsLayout_->takeAt(0)) != nullptr) { delete item->widget(); delete item; } // create new buttons for the new path auto btnPath = currentPath_; while(btnPath) { Fm::CStrPtr name; Fm::CStrPtr displayName; auto parent = btnPath.parent(); // FIXME: some buggy uri types, such as menu://, fail to return NULL when there is no parent path. // Instead, the path itself is returned. So we check if the parent path is the same as current path. auto isRoot = !parent.isValid() || parent == btnPath; if(isRoot) { displayName = btnPath.displayName(); name = btnPath.toString(); } else { displayName = btnPath.baseName(); // "name" is used for making the path from its components in PathBar::pathForButton(). // So, it should be extracted from g_file_get_parse_name(). // (In places like trash:///, FilePath::baseName() cannot be used to make a full path.) name = CStrPtr{g_path_get_basename(btnPath.displayName().get())}; } auto btn = new PathButton(name.get(), QString::fromUtf8(displayName.get()), isRoot, buttonsWidget_); btn->show(); connect(btn, &QAbstractButton::toggled, this, &PathBar::onButtonToggled); buttonsLayout_->insertWidget(0, btn); if(isRoot) { // this is the root element of the path break; } btnPath = parent; } buttonsLayout_->addStretch(1); // add a spacer at the tail of the buttons // we don't want to scroll vertically. make the scroll area fit the height of the buttons // FIXME: this is a little bit hackish :-( scrollArea_->setFixedHeight(buttonsLayout_->sizeHint().height()); updateScrollButtonVisibility(); // to guarantee that the button will be scrolled to correctly, // it should be toggled only after the layout update starts above buttonCount = buttonsLayout_->count() - 1; if(buttonCount > 0) { PathButton* lastBtn = static_cast<PathButton*>(buttonsLayout_->itemAt(buttonCount - 1)->widget()); // we don't have to emit the chdir signal since the "onButtonToggled()" slot will be triggered by this. lastBtn->setChecked(true); } setUpdatesEnabled(true); } void PathBar::openEditor() { if(tempPathEdit_ == nullptr) { tempPathEdit_ = new PathEdit(this); delete layout()->replaceWidget(scrollArea_, tempPathEdit_, Qt::FindDirectChildrenOnly); scrollArea_->hide(); scrollToStart_->setVisible(false); scrollToEnd_->setVisible(false); tempPathEdit_->setText(QString::fromUtf8(currentPath_.toString().get())); connect(tempPathEdit_, &PathEdit::returnPressed, this, &PathBar::onReturnPressed); connect(tempPathEdit_, &PathEdit::editingFinished, this, &PathBar::closeEditor); } tempPathEdit_->selectAll(); QApplication::clipboard()->setText(tempPathEdit_->text(), QClipboard::Selection); QTimer::singleShot(0, tempPathEdit_, SLOT(setFocus())); } void PathBar::closeEditor() { if(tempPathEdit_ == nullptr) { return; } // If a menu has popped up synchronously (with QMenu::exec), the path buttons may be drawn // but the path-edit may not disappear until the menu is closed. So, we hide it here. // However, since hiding the path-edit makes it lose focus and emit editingFinished(), // we should first disconnect from it to avoid recursive calling of the current function. tempPathEdit_->disconnect(); tempPathEdit_->setVisible(false); delete layout()->replaceWidget(tempPathEdit_, scrollArea_, Qt::FindDirectChildrenOnly); scrollArea_->show(); if(buttonsLayout_->sizeHint().width() > width()) { scrollToStart_->setVisible(true); scrollToEnd_->setVisible(true); } tempPathEdit_->deleteLater(); tempPathEdit_ = nullptr; updateScrollButtonVisibility(); Q_EMIT editingFinished(); } void PathBar::copyPath() { QApplication::clipboard()->setText(QString::fromUtf8(currentPath_.toString().get())); } void PathBar::onReturnPressed() { QByteArray pathStr = tempPathEdit_->text().toLocal8Bit(); setPath(Fm::FilePath::fromPathStr(pathStr.constData())); } void PathBar::setArrowEnabledState(int value) { if(buttonsLayout_->sizeHint().width() > width()) { QScrollBar* sb = scrollArea_->horizontalScrollBar(); scrollToStart_->setEnabled(value != sb->minimum()); scrollToEnd_->setEnabled(value != sb->maximum()); } } } // namespace Fm <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkPLYReader.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkPLYReader.h" #include "vtkCellArray.h" #include "vtkCellData.h" #include "vtkPointData.h" #include "vtkFloatArray.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkObjectFactory.h" #include "vtkPLY.h" #include "vtkPolyData.h" #include <ctype.h> #include <stddef.h> vtkStandardNewMacro(vtkPLYReader); // Construct object with merging set to true. vtkPLYReader::vtkPLYReader() { this->FileName = NULL; this->SetNumberOfInputPorts(0); } vtkPLYReader::~vtkPLYReader() { delete [] this->FileName; } typedef struct _plyVertex { float x[3]; // the usual 3-space position of a vertex unsigned char red; unsigned char green; unsigned char blue; } plyVertex; typedef struct _plyFace { unsigned char intensity; // optional face attributes unsigned char red; unsigned char green; unsigned char blue; unsigned char nverts; // number of vertex indices in list int *verts; // vertex index list } plyFace; int vtkPLYReader::RequestData( vtkInformation *vtkNotUsed(request), vtkInformationVector **vtkNotUsed(inputVector), vtkInformationVector *outputVector) { // get the info object vtkInformation *outInfo = outputVector->GetInformationObject(0); // get the ouptut vtkPolyData *output = vtkPolyData::SafeDownCast( outInfo->Get(vtkDataObject::DATA_OBJECT())); PlyProperty vertProps[] = { {"x", PLY_FLOAT, PLY_FLOAT, static_cast<int>(offsetof(plyVertex,x)), 0, 0, 0, 0}, {"y", PLY_FLOAT, PLY_FLOAT, static_cast<int>(offsetof(plyVertex,x)+sizeof(float)), 0, 0, 0, 0}, {"z", PLY_FLOAT, PLY_FLOAT, static_cast<int>(offsetof(plyVertex,x)+sizeof(float)+sizeof(float)), 0, 0, 0, 0}, {"red", PLY_UCHAR, PLY_UCHAR, static_cast<int>(offsetof(plyVertex,red)), 0, 0, 0, 0}, {"green", PLY_UCHAR, PLY_UCHAR, static_cast<int>(offsetof(plyVertex,green)), 0, 0, 0, 0}, {"blue", PLY_UCHAR, PLY_UCHAR, static_cast<int>(offsetof(plyVertex,blue)), 0, 0, 0, 0}, }; PlyProperty faceProps[] = { {"vertex_indices", PLY_INT, PLY_INT, static_cast<int>(offsetof(plyFace,verts)), 1, PLY_UCHAR, PLY_UCHAR, static_cast<int>(offsetof(plyFace,nverts))}, {"intensity", PLY_UCHAR, PLY_UCHAR, static_cast<int>(offsetof(plyFace,intensity)), 0, 0, 0, 0}, {"red", PLY_UCHAR, PLY_UCHAR, static_cast<int>(offsetof(plyFace,red)), 0, 0, 0, 0}, {"green", PLY_UCHAR, PLY_UCHAR, static_cast<int>(offsetof(plyFace,green)), 0, 0, 0, 0}, {"blue", PLY_UCHAR, PLY_UCHAR, static_cast<int>(offsetof(plyFace,blue)), 0, 0, 0, 0}, }; if (!this->FileName) { vtkErrorMacro(<<"A File Name must be specified."); return 0; } // open a PLY file for reading PlyFile *ply; int nelems, fileType, numElems, nprops; char **elist, *elemName; float version; if ( !(ply = vtkPLY::ply_open_for_reading(this->FileName, &nelems, &elist, &fileType, &version)) ) { vtkWarningMacro(<<"Could not open PLY file"); return 0; } // Check to make sure that we can read geometry PlyElement *elem; int index; if ( (elem = vtkPLY::find_element (ply, "vertex")) == NULL || vtkPLY::find_property (elem, "x", &index) == NULL || vtkPLY::find_property (elem, "y", &index) == NULL || vtkPLY::find_property (elem, "z", &index) == NULL || (elem = vtkPLY::find_element (ply, "face")) == NULL || vtkPLY::find_property (elem, "vertex_indices", &index) == NULL ) { vtkErrorMacro(<<"Cannot read geometry"); vtkPLY::ply_close (ply); } // Check for optional attribute data. We can handle intensity; and the // triplet red, green, blue. bool intensityAvailable=false; vtkUnsignedCharArray *intensity=NULL; if ( (elem = vtkPLY::find_element (ply, "face")) != NULL && vtkPLY::find_property (elem, "intensity", &index) != NULL ) { intensity = vtkUnsignedCharArray::New(); intensity->SetName("intensity"); intensityAvailable = true; output->GetCellData()->AddArray(intensity); output->GetCellData()->SetActiveScalars("intensity"); intensity->Delete(); } bool RGBCellsAvailable=false; vtkUnsignedCharArray *RGBCells=NULL; if ( (elem = vtkPLY::find_element (ply, "face")) != NULL && vtkPLY::find_property (elem, "red", &index) != NULL && vtkPLY::find_property (elem, "green", &index) != NULL && vtkPLY::find_property (elem, "blue", &index) != NULL ) { RGBCells = vtkUnsignedCharArray::New(); RGBCells->SetName("RGB"); RGBCellsAvailable = true; output->GetCellData()->AddArray(RGBCells); output->GetCellData()->SetActiveScalars("RGB"); RGBCells->Delete(); } bool RGBPointsAvailable=false; vtkUnsignedCharArray *RGBPoints=NULL; if ( (elem = vtkPLY::find_element (ply, "vertex")) != NULL && vtkPLY::find_property (elem, "red", &index) != NULL && vtkPLY::find_property (elem, "green", &index) != NULL && vtkPLY::find_property (elem, "blue", &index) != NULL ) { RGBPoints = vtkUnsignedCharArray::New(); RGBPointsAvailable = true; RGBPoints->SetName("RGB"); output->GetPointData()->SetScalars(RGBPoints); RGBPoints->Delete(); } // Okay, now we can grab the data int numPts=0, numPolys=0; for (int i = 0; i < nelems; i++) { //get the description of the first element */ elemName = elist[i]; vtkPLY::ply_get_element_description (ply, elemName, &numElems, &nprops); // if we're on vertex elements, read them in if ( elemName && !strcmp ("vertex", elemName) ) { // Create a list of points numPts = numElems; vtkPoints *pts = vtkPoints::New(); pts->SetDataTypeToFloat(); pts->SetNumberOfPoints(numPts); // Setup to read the PLY elements vtkPLY::ply_get_property (ply, elemName, &vertProps[0]); vtkPLY::ply_get_property (ply, elemName, &vertProps[1]); vtkPLY::ply_get_property (ply, elemName, &vertProps[2]); if ( RGBPointsAvailable ) { vtkPLY::ply_get_property (ply, elemName, &vertProps[3]); vtkPLY::ply_get_property (ply, elemName, &vertProps[4]); vtkPLY::ply_get_property (ply, elemName, &vertProps[5]); RGBPoints->SetNumberOfComponents(3); RGBPoints->SetNumberOfTuples(numPts); } plyVertex vertex; for (int j=0; j < numPts; j++) { vtkPLY::ply_get_element (ply, (void *) &vertex); pts->SetPoint (j, vertex.x); if ( RGBPointsAvailable ) { RGBPoints->SetTuple3(j,vertex.red,vertex.green,vertex.blue); } } output->SetPoints(pts); pts->Delete(); }//if vertex else if ( elemName && !strcmp ("face", elemName) ) { // Create a polygonal array numPolys = numElems; vtkCellArray *polys = vtkCellArray::New(); polys->Allocate(polys->EstimateSize(numPolys,3),numPolys/2); plyFace face; int verts[256]; vtkIdType vtkVerts[256]; // Get the face properties vtkPLY::ply_get_property (ply, elemName, &faceProps[0]); if ( intensityAvailable ) { vtkPLY::ply_get_property (ply, elemName, &faceProps[1]); RGBCells->SetNumberOfComponents(1); RGBCells->SetNumberOfTuples(numPolys); } if ( RGBCellsAvailable ) { vtkPLY::ply_get_property (ply, elemName, &faceProps[2]); vtkPLY::ply_get_property (ply, elemName, &faceProps[3]); vtkPLY::ply_get_property (ply, elemName, &faceProps[4]); RGBCells->SetNumberOfComponents(3); RGBCells->SetNumberOfTuples(numPolys); } // grab all the face elements for (int j=0; j < numPolys; j++) { //grab and element from the file face.verts = verts; vtkPLY::ply_get_element (ply, (void *) &face); for (int k=0; k<face.nverts; k++) { vtkVerts[k] = face.verts[k]; } polys->InsertNextCell(face.nverts,vtkVerts); if ( intensityAvailable ) { intensity->SetValue(j,face.intensity); } if ( RGBCellsAvailable ) { RGBCells->SetValue(3*j,face.red); RGBCells->SetValue(3*j+1,face.green); RGBCells->SetValue(3*j+2,face.blue); } } output->SetPolys(polys); polys->Delete(); }//if face free(elist[i]); //allocated by ply_open_for_reading elist[i] = NULL; }//for all elements of the PLY file free(elist); //allocated by ply_open_for_reading vtkDebugMacro( <<"Read: " << numPts << " points, " << numPolys << " polygons"); // close the PLY file vtkPLY::ply_close (ply); return 1; } int vtkPLYReader::CanReadFile(const char *filename) { FILE *fd = fopen(filename, "rb"); if (!fd) return 0; char line[4] = {}; const char *result = fgets(line, sizeof(line), fd); fclose(fd); return (result && strncmp(result, "ply", 3) == 0); } void vtkPLYReader::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "File Name: " << (this->FileName ? this->FileName : "(none)") << "\n"; } <commit_msg>Add support for texture coordinates and per vertices normals in PLY Reader<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkPLYReader.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkPLYReader.h" #include "vtkCellArray.h" #include "vtkCellData.h" #include "vtkPointData.h" #include "vtkFloatArray.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkObjectFactory.h" #include "vtkPLY.h" #include "vtkPolyData.h" #include <vtkSmartPointer.h> #include <ctype.h> #include <stddef.h> vtkStandardNewMacro(vtkPLYReader); // Construct object with merging set to true. vtkPLYReader::vtkPLYReader() { this->FileName = NULL; this->SetNumberOfInputPorts(0); } vtkPLYReader::~vtkPLYReader() { delete [] this->FileName; } typedef struct _plyVertex { float x[3]; // the usual 3-space position of a vertex float tex[2]; float normal[3]; unsigned char red; unsigned char green; unsigned char blue; } plyVertex; typedef struct _plyFace { unsigned char intensity; // optional face attributes unsigned char red; unsigned char green; unsigned char blue; unsigned char nverts; // number of vertex indices in list int *verts; // vertex index list } plyFace; int vtkPLYReader::RequestData( vtkInformation *vtkNotUsed(request), vtkInformationVector **vtkNotUsed(inputVector), vtkInformationVector *outputVector) { // get the info object vtkInformation *outInfo = outputVector->GetInformationObject(0); // get the ouptut vtkPolyData *output = vtkPolyData::SafeDownCast( outInfo->Get(vtkDataObject::DATA_OBJECT())); PlyProperty vertProps[] = { {"x", PLY_FLOAT, PLY_FLOAT, static_cast<int>(offsetof(plyVertex,x)), 0, 0, 0, 0}, {"y", PLY_FLOAT, PLY_FLOAT, static_cast<int>(offsetof(plyVertex,x)+sizeof(float)), 0, 0, 0, 0}, {"z", PLY_FLOAT, PLY_FLOAT, static_cast<int>(offsetof(plyVertex,x)+sizeof(float)+sizeof(float)), 0, 0, 0, 0}, {"u", PLY_FLOAT, PLY_FLOAT, static_cast<int>(offsetof(plyVertex,tex)), 0, 0, 0, 0}, {"v", PLY_FLOAT, PLY_FLOAT, static_cast<int>(offsetof(plyVertex,tex)+sizeof(float)), 0, 0, 0, 0}, {"nx", PLY_FLOAT, PLY_FLOAT, static_cast<int>(offsetof(plyVertex,normal)), 0, 0, 0, 0}, {"ny", PLY_FLOAT, PLY_FLOAT, static_cast<int>(offsetof(plyVertex,normal)+sizeof(float)), 0, 0, 0, 0}, {"nz", PLY_FLOAT, PLY_FLOAT, static_cast<int>(offsetof(plyVertex,normal)+2*sizeof(float)), 0, 0, 0, 0}, {"red", PLY_UCHAR, PLY_UCHAR, static_cast<int>(offsetof(plyVertex,red)), 0, 0, 0, 0}, {"green", PLY_UCHAR, PLY_UCHAR, static_cast<int>(offsetof(plyVertex,green)), 0, 0, 0, 0}, {"blue", PLY_UCHAR, PLY_UCHAR, static_cast<int>(offsetof(plyVertex,blue)), 0, 0, 0, 0}, }; PlyProperty faceProps[] = { {"vertex_indices", PLY_INT, PLY_INT, static_cast<int>(offsetof(plyFace,verts)), 1, PLY_UCHAR, PLY_UCHAR, static_cast<int>(offsetof(plyFace,nverts))}, {"intensity", PLY_UCHAR, PLY_UCHAR, static_cast<int>(offsetof(plyFace,intensity)), 0, 0, 0, 0}, {"red", PLY_UCHAR, PLY_UCHAR, static_cast<int>(offsetof(plyFace,red)), 0, 0, 0, 0}, {"green", PLY_UCHAR, PLY_UCHAR, static_cast<int>(offsetof(plyFace,green)), 0, 0, 0, 0}, {"blue", PLY_UCHAR, PLY_UCHAR, static_cast<int>(offsetof(plyFace,blue)), 0, 0, 0, 0}, }; if (!this->FileName) { vtkErrorMacro(<<"A File Name must be specified."); return 0; } // open a PLY file for reading PlyFile *ply; int nelems, fileType, numElems, nprops; char **elist, *elemName; float version; if ( !(ply = vtkPLY::ply_open_for_reading(this->FileName, &nelems, &elist, &fileType, &version)) ) { vtkWarningMacro(<<"Could not open PLY file"); return 0; } std::cout << "PLY file type = " << fileType << std::endl; // Check to make sure that we can read geometry PlyElement *elem; int index; if ( (elem = vtkPLY::find_element (ply, "vertex")) == NULL || vtkPLY::find_property (elem, "x", &index) == NULL || vtkPLY::find_property (elem, "y", &index) == NULL || vtkPLY::find_property (elem, "z", &index) == NULL || (elem = vtkPLY::find_element (ply, "face")) == NULL || vtkPLY::find_property (elem, "vertex_indices", &index) == NULL ) { vtkErrorMacro(<<"Cannot read geometry"); vtkPLY::ply_close (ply); } // Check for optional attribute data. We can handle intensity; and the // triplet red, green, blue. bool intensityAvailable = false; vtkUnsignedCharArray *intensity = NULL; if ( (elem = vtkPLY::find_element (ply, "face")) != NULL && vtkPLY::find_property (elem, "intensity", &index) != NULL ) { intensity = vtkUnsignedCharArray::New(); intensity->SetName("intensity"); intensityAvailable = true; output->GetCellData()->AddArray(intensity); output->GetCellData()->SetActiveScalars("intensity"); intensity->Delete(); } bool RGBCellsAvailable = false; vtkSmartPointer<vtkUnsignedCharArray> RGBCells = NULL; if ( (elem = vtkPLY::find_element (ply, "face")) != NULL && vtkPLY::find_property (elem, "red", &index) != NULL && vtkPLY::find_property (elem, "green", &index) != NULL && vtkPLY::find_property (elem, "blue", &index) != NULL ) { RGBCells = vtkSmartPointer<vtkUnsignedCharArray>::New(); RGBCells->SetName("RGB"); RGBCellsAvailable = true; output->GetCellData()->AddArray(RGBCells); output->GetCellData()->SetActiveScalars("RGB"); } bool RGBPointsAvailable = false; vtkSmartPointer<vtkUnsignedCharArray> RGBPoints = NULL; if ( (elem = vtkPLY::find_element (ply, "vertex")) != NULL && vtkPLY::find_property (elem, "red", &index) != NULL && vtkPLY::find_property (elem, "green", &index) != NULL && vtkPLY::find_property (elem, "blue", &index) != NULL ) { RGBPoints = vtkUnsignedCharArray::New(); RGBPointsAvailable = true; RGBPoints->SetName("RGB"); RGBPoints->SetNumberOfComponents(3); output->GetPointData()->SetScalars(RGBPoints); } bool NormalPointsAvailable=false; vtkSmartPointer<vtkFloatArray> Normals = NULL; if ( (elem = vtkPLY::find_element (ply, "vertex")) != NULL && vtkPLY::find_property (elem, "nx", &index) != NULL && vtkPLY::find_property (elem, "ny", &index) != NULL && vtkPLY::find_property (elem, "nz", &index) != NULL ) { Normals = vtkSmartPointer<vtkFloatArray>::New(); NormalPointsAvailable = true; Normals->SetName("Normals"); Normals->SetNumberOfComponents(3); output->GetPointData()->SetNormals(Normals); } bool TexCoordsPointsAvailable = false; vtkSmartPointer<vtkFloatArray> TexCoordsPoints = NULL; if ( (elem = vtkPLY::find_element (ply, "vertex")) != NULL && vtkPLY::find_property (elem, "u", &index) != NULL && vtkPLY::find_property (elem, "v", &index) != NULL) { TexCoordsPoints = vtkSmartPointer<vtkFloatArray>::New(); TexCoordsPointsAvailable = true; TexCoordsPoints->SetName("TCoords"); TexCoordsPoints->SetNumberOfComponents(2); output->GetPointData()->SetTCoords(TexCoordsPoints); } // Okay, now we can grab the data int numPts = 0, numPolys = 0; for (int i = 0; i < nelems; i++) { //get the description of the first element */ elemName = elist[i]; vtkPLY::ply_get_element_description (ply, elemName, &numElems, &nprops); // if we're on vertex elements, read them in if ( elemName && !strcmp ("vertex", elemName) ) { // Create a list of points numPts = numElems; vtkPoints *pts = vtkPoints::New(); pts->SetDataTypeToFloat(); pts->SetNumberOfPoints(numPts); // Setup to read the PLY elements vtkPLY::ply_get_property (ply, elemName, &vertProps[0]); vtkPLY::ply_get_property (ply, elemName, &vertProps[1]); vtkPLY::ply_get_property (ply, elemName, &vertProps[2]); if ( TexCoordsPointsAvailable ) { vtkPLY::ply_get_property (ply, elemName, &vertProps[3]); vtkPLY::ply_get_property (ply, elemName, &vertProps[4]); TexCoordsPoints->SetNumberOfTuples(numPts); } if ( NormalPointsAvailable ) { vtkPLY::ply_get_property (ply, elemName, &vertProps[5]); vtkPLY::ply_get_property (ply, elemName, &vertProps[6]); vtkPLY::ply_get_property (ply, elemName, &vertProps[7]); Normals->SetNumberOfTuples(numPts); } if ( RGBPointsAvailable ) { vtkPLY::ply_get_property (ply, elemName, &vertProps[8]); vtkPLY::ply_get_property (ply, elemName, &vertProps[9]); vtkPLY::ply_get_property (ply, elemName, &vertProps[10]); RGBPoints->SetNumberOfTuples(numPts); } plyVertex vertex; for (int j=0; j < numPts; j++) { vtkPLY::ply_get_element (ply, (void *) &vertex); pts->SetPoint (j, vertex.x); if ( TexCoordsPointsAvailable ) { TexCoordsPoints->SetTuple2(j, vertex.tex[0], vertex.tex[1]); } if ( NormalPointsAvailable ) { Normals->SetTuple3(j, vertex.normal[0], vertex.normal[1], vertex.normal[2]); } if ( RGBPointsAvailable ) { RGBPoints->SetTuple3(j, vertex.red, vertex.green, vertex.blue); } } output->SetPoints(pts); pts->Delete(); }//if vertex else if ( elemName && !strcmp ("face", elemName) ) { // Create a polygonal array numPolys = numElems; vtkCellArray *polys = vtkCellArray::New(); polys->Allocate(polys->EstimateSize(numPolys,3),numPolys/2); plyFace face; int verts[256]; vtkIdType vtkVerts[256]; // Get the face properties vtkPLY::ply_get_property (ply, elemName, &faceProps[0]); if ( intensityAvailable ) { vtkPLY::ply_get_property (ply, elemName, &faceProps[1]); RGBCells->SetNumberOfComponents(1); RGBCells->SetNumberOfTuples(numPolys); } if ( RGBCellsAvailable ) { vtkPLY::ply_get_property (ply, elemName, &faceProps[2]); vtkPLY::ply_get_property (ply, elemName, &faceProps[3]); vtkPLY::ply_get_property (ply, elemName, &faceProps[4]); RGBCells->SetNumberOfComponents(3); RGBCells->SetNumberOfTuples(numPolys); } // grab all the face elements for (int j=0; j < numPolys; j++) { //grab and element from the file face.verts = verts; vtkPLY::ply_get_element (ply, (void *) &face); for (int k=0; k < face.nverts; k++) { vtkVerts[k] = face.verts[k]; } polys->InsertNextCell(face.nverts,vtkVerts); if ( intensityAvailable ) { intensity->SetValue(j,face.intensity); } if ( RGBCellsAvailable ) { RGBCells->SetValue(3*j,face.red); RGBCells->SetValue(3*j+1,face.green); RGBCells->SetValue(3*j+2,face.blue); } } output->SetPolys(polys); polys->Delete(); }//if face free(elist[i]); //allocated by ply_open_for_reading elist[i] = NULL; }//for all elements of the PLY file free(elist); //allocated by ply_open_for_reading vtkDebugMacro( <<"Read: " << numPts << " points, " << numPolys << " polygons"); // close the PLY file vtkPLY::ply_close (ply); return 1; } int vtkPLYReader::CanReadFile(const char *filename) { FILE *fd = fopen(filename, "rb"); if (!fd) return 0; char line[4] = {}; const char *result = fgets(line, sizeof(line), fd); fclose(fd); return (result && strncmp(result, "ply", 3) == 0); } void vtkPLYReader::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "File Name: " << (this->FileName ? this->FileName : "(none)") << "\n"; } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkUGFacetReader.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen 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 name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. * Modified source versions must be plainly marked as such, and must not be misrepresented as being the original software. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. =========================================================================*/ #include "vtkUGFacetReader.h" #include "vtkByteSwap.h" #include "vtkMergePoints.h" #include "vtkObjectFactory.h" //------------------------------------------------------------------------------ vtkUGFacetReader* vtkUGFacetReader::New() { // First try to create the object from the vtkObjectFactory vtkObject* ret = vtkObjectFactory::CreateInstance("vtkUGFacetReader"); if(ret) { return (vtkUGFacetReader*)ret; } // If the factory was unable to create the object, then create it here. return new vtkUGFacetReader; } // Construct object to extract all parts, and with point merging // turned on. vtkUGFacetReader::vtkUGFacetReader() { this->FileName = NULL; this->PartColors = NULL; this->PartNumber = (-1); //extract all parts this->Merging = 1; this->Locator = NULL; } vtkUGFacetReader::~vtkUGFacetReader() { if ( this->FileName ) { delete [] this->FileName; } if ( this->PartColors ) { this->PartColors->Delete(); } if (this->Locator != NULL) { this->Locator->UnRegister(this); this->Locator = NULL; } } // Overload standard modified time function. If locator is modified, // then this object is modified as well. unsigned long vtkUGFacetReader::GetMTime() { unsigned long mTime1=this->vtkPolyDataSource::GetMTime(); unsigned long mTime2; if (this->Locator) { mTime2 = this->Locator->GetMTime(); mTime1 = ( mTime1 > mTime2 ? mTime1 : mTime2 ); } return mTime1; } void vtkUGFacetReader::Execute() { FILE *fp; char header[36]; struct {float v1[3], v2[3], v3[3], n1[3], n2[3], n3[3];} facet; vtkIdType ptId[3]; short ugiiColor, direction; int numberTris, numFacetSets, setNumber, facetNumber; vtkPoints *newPts, *mergedPts; vtkNormals *newNormals, *mergedNormals; vtkCellArray *newPolys, *mergedPolys; vtkPolyData *output = this->GetOutput(); fpos_t pos; int triEstimate; vtkDebugMacro(<<"Reading UG facet file..."); if ( this->FileName == NULL ) { vtkErrorMacro(<<"No FileName specified...please specify one."); return; } // open the file if ( (fp = fopen(this->FileName, "rb")) == NULL) { vtkErrorMacro(<<"Cannot open file specified."); return; } // read the header stuff if ( fread (header, 1, 2, fp) <= 0 || fread (&numFacetSets, 4, 1, fp) <= 0 || fread (header, 1, 36, fp) <= 0 ) { vtkErrorMacro(<<"File ended prematurely"); return; } // swap bytes since this is a binary file format vtkByteSwap::Swap4BE(&numFacetSets); // Estimate how much space we need - find out the size of the // file and divide by 72 bytes per triangle fgetpos( fp, &pos ); fseek( fp, 0L, SEEK_END ); triEstimate = ftell( fp ) / 72; fsetpos( fp, &pos ); // allocate memory if ( ! this->PartColors ) { this->PartColors = vtkShortArray::New(); this->PartColors->Allocate(100); } else { this->PartColors->Reset(); } newPts = vtkPoints::New(); newPts->Allocate(triEstimate,triEstimate); newNormals = vtkNormals::New(); newNormals->Allocate(triEstimate,triEstimate); newPolys = vtkCellArray::New(); newPolys->Allocate(newPolys->EstimateSize(triEstimate,3),triEstimate); // loop over all facet sets, extracting triangles for (setNumber=0; setNumber < numFacetSets; setNumber++) { if ( fread (&ugiiColor, 2, 1, fp) <= 0 || fread (&direction, 2, 1, fp) <= 0 || fread (&numberTris, 4, 1, fp) <= 0 ) { vtkErrorMacro(<<"File ended prematurely"); break; } // swap bytes if necc vtkByteSwap::Swap4BE(&numberTris); vtkByteSwap::Swap2BERange(&ugiiColor,1); vtkByteSwap::Swap2BERange(&direction,1); this->PartColors->InsertNextValue(ugiiColor); for (facetNumber=0; facetNumber < numberTris; facetNumber++) { if ( fread(&facet,72,1,fp) <= 0 ) { vtkErrorMacro(<<"File ended prematurely"); break; } // swap bytes if necc vtkByteSwap::Swap4BERange((float *)(&facet),18); if ( this->PartNumber == -1 || this->PartNumber == setNumber ) { ptId[0] = newPts->InsertNextPoint(facet.v1); ptId[1] = newPts->InsertNextPoint(facet.v2); ptId[2] = newPts->InsertNextPoint(facet.v3); newNormals->InsertNormal(ptId[0],facet.n1); newNormals->InsertNormal(ptId[1],facet.n2); newNormals->InsertNormal(ptId[2],facet.n3); newPolys->InsertNextCell(3,ptId); }//if appropriate part }//for all facets in this set }//for this facet set // update output vtkDebugMacro(<<"Read " << newPts->GetNumberOfPoints() << " points, " << newPolys->GetNumberOfCells() << " triangles."); fclose(fp); // // Merge points/triangles if requested // if ( this->Merging ) { int i; vtkIdType *pts, nodes[3], npts; float *x; mergedPts = vtkPoints::New(); mergedPts->Allocate(newPts->GetNumberOfPoints()/3); mergedNormals = vtkNormals::New(); mergedNormals->Allocate(newNormals->GetNumberOfNormals()/3); mergedPolys = vtkCellArray::New(); mergedPolys->Allocate(newPolys->GetSize()); if ( this->Locator == NULL ) { this->CreateDefaultLocator(); } this->Locator->InitPointInsertion (mergedPts, newPts->GetBounds()); for (newPolys->InitTraversal(); newPolys->GetNextCell(npts,pts); ) { for (i=0; i < 3; i++) { x = newPts->GetPoint(pts[i]); if ( this->Locator->InsertUniquePoint(x, nodes[i]) ) { mergedNormals->InsertNormal(nodes[i],newNormals->GetNormal(pts[i])); } } if ( nodes[0] != nodes[1] && nodes[0] != nodes[2] && nodes[1] != nodes[2] ) { mergedPolys->InsertNextCell(3,nodes); } } newPts->Delete(); newNormals->Delete(); newPolys->Delete(); vtkDebugMacro(<< "Merged to: " << mergedPts->GetNumberOfPoints() << " points, " << mergedPolys->GetNumberOfCells() << " triangles"); } else { mergedPts = newPts; mergedNormals = newNormals; mergedPolys = newPolys; } // // Update ourselves // output->SetPoints(mergedPts); mergedPts->Delete(); output->GetPointData()->SetNormals(mergedNormals); mergedNormals->Delete(); output->SetPolys(mergedPolys); mergedPolys->Delete(); if (this->Locator) { this->Locator->Initialize(); //free storage } output->Squeeze(); } int vtkUGFacetReader::GetNumberOfParts() { char header[36]; FILE *fp; int numberOfParts; if ( this->FileName == NULL ) { vtkErrorMacro(<<"No FileName specified...please specify one."); return 0; } // open the file if ( (fp = fopen(this->FileName, "rb")) == NULL) { vtkErrorMacro(<<"Cannot open file specified."); return 0; } // read the header stuff if ( fread (header, 1, 2, fp) <= 0 || fread (&numberOfParts, 4, 1, fp) <= 0 || fread (header, 1, 36, fp) <= 0 ) { vtkErrorMacro(<<"File ended prematurely"); fclose(fp); return 0; } // swap bytes if necc vtkByteSwap::Swap4BE(&numberOfParts); fclose(fp); return numberOfParts; } // Retrieve color index for the parts in the file. short vtkUGFacetReader::GetPartColorIndex(int partId) { if ( this->PartColors == NULL ) { this->Update(); } if ( !this->PartColors || partId < 0 || partId > this->PartColors->GetMaxId() ) { return 0; } else { return this->PartColors->GetValue(partId); } } // Specify a spatial locator for merging points. By // default an instance of vtkMergePoints is used. void vtkUGFacetReader::SetLocator(vtkPointLocator *locator) { if ( this->Locator == locator ) { return; } if (this->Locator != NULL) { this->Locator->UnRegister(this); this->Locator = NULL; } if (locator != NULL) { locator->Register(this); } this->Locator = locator; this->Modified(); } void vtkUGFacetReader::CreateDefaultLocator() { if ( this->Locator == NULL ) { this->Locator = vtkMergePoints::New(); } } void vtkUGFacetReader::PrintSelf(ostream& os, vtkIndent indent) { vtkPolyDataSource::PrintSelf(os,indent); os << indent << "File Name: " << (this->FileName ? this->FileName : "(none)") << "\n"; os << indent << "Part Number: " << this->PartNumber << "\n"; os << indent << "Merging: " << (this->Merging ? "On\n" : "Off\n"); if ( this->Locator ) { os << indent << "Locator: " << this->Locator << "\n"; } else { os << indent << "Locator: (none)\n"; } } <commit_msg>better checking<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkUGFacetReader.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen 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 name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. * Modified source versions must be plainly marked as such, and must not be misrepresented as being the original software. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. =========================================================================*/ #include "vtkUGFacetReader.h" #include "vtkByteSwap.h" #include "vtkMergePoints.h" #include "vtkObjectFactory.h" //------------------------------------------------------------------------------ vtkUGFacetReader* vtkUGFacetReader::New() { // First try to create the object from the vtkObjectFactory vtkObject* ret = vtkObjectFactory::CreateInstance("vtkUGFacetReader"); if(ret) { return (vtkUGFacetReader*)ret; } // If the factory was unable to create the object, then create it here. return new vtkUGFacetReader; } // Construct object to extract all parts, and with point merging // turned on. vtkUGFacetReader::vtkUGFacetReader() { this->FileName = NULL; this->PartColors = NULL; this->PartNumber = (-1); //extract all parts this->Merging = 1; this->Locator = NULL; } vtkUGFacetReader::~vtkUGFacetReader() { if ( this->FileName ) { delete [] this->FileName; } if ( this->PartColors ) { this->PartColors->Delete(); } if (this->Locator != NULL) { this->Locator->UnRegister(this); this->Locator = NULL; } } // Overload standard modified time function. If locator is modified, // then this object is modified as well. unsigned long vtkUGFacetReader::GetMTime() { unsigned long mTime1=this->vtkPolyDataSource::GetMTime(); unsigned long mTime2; if (this->Locator) { mTime2 = this->Locator->GetMTime(); mTime1 = ( mTime1 > mTime2 ? mTime1 : mTime2 ); } return mTime1; } void vtkUGFacetReader::Execute() { FILE *fp; char header[36]; struct {float v1[3], v2[3], v3[3], n1[3], n2[3], n3[3];} facet; vtkIdType ptId[3]; short ugiiColor, direction; int numberTris, numFacetSets, setNumber, facetNumber; vtkPoints *newPts, *mergedPts; vtkNormals *newNormals, *mergedNormals; vtkCellArray *newPolys, *mergedPolys; vtkPolyData *output = this->GetOutput(); fpos_t pos; int triEstimate; vtkDebugMacro(<<"Reading UG facet file..."); if ( this->FileName == NULL || strlen(this->FileName) == 0) { vtkErrorMacro(<<"No FileName specified...please specify one."); return; } // open the file if ( (fp = fopen(this->FileName, "rb")) == NULL) { vtkErrorMacro(<<"Cannot open file specified."); return; } // read the header stuff if ( fread (header, 1, 2, fp) <= 0 || fread (&numFacetSets, 4, 1, fp) <= 0 || fread (header, 1, 36, fp) <= 0 ) { vtkErrorMacro(<<"File ended prematurely"); return; } // swap bytes since this is a binary file format vtkByteSwap::Swap4BE(&numFacetSets); // Estimate how much space we need - find out the size of the // file and divide by 72 bytes per triangle fgetpos( fp, &pos ); fseek( fp, 0L, SEEK_END ); triEstimate = ftell( fp ) / 72; fsetpos( fp, &pos ); // allocate memory if ( ! this->PartColors ) { this->PartColors = vtkShortArray::New(); this->PartColors->Allocate(100); } else { this->PartColors->Reset(); } newPts = vtkPoints::New(); newPts->Allocate(triEstimate,triEstimate); newNormals = vtkNormals::New(); newNormals->Allocate(triEstimate,triEstimate); newPolys = vtkCellArray::New(); newPolys->Allocate(newPolys->EstimateSize(triEstimate,3),triEstimate); // loop over all facet sets, extracting triangles for (setNumber=0; setNumber < numFacetSets; setNumber++) { if ( fread (&ugiiColor, 2, 1, fp) <= 0 || fread (&direction, 2, 1, fp) <= 0 || fread (&numberTris, 4, 1, fp) <= 0 ) { vtkErrorMacro(<<"File ended prematurely"); break; } // swap bytes if necc vtkByteSwap::Swap4BE(&numberTris); vtkByteSwap::Swap2BERange(&ugiiColor,1); vtkByteSwap::Swap2BERange(&direction,1); this->PartColors->InsertNextValue(ugiiColor); for (facetNumber=0; facetNumber < numberTris; facetNumber++) { if ( fread(&facet,72,1,fp) <= 0 ) { vtkErrorMacro(<<"File ended prematurely"); break; } // swap bytes if necc vtkByteSwap::Swap4BERange((float *)(&facet),18); if ( this->PartNumber == -1 || this->PartNumber == setNumber ) { ptId[0] = newPts->InsertNextPoint(facet.v1); ptId[1] = newPts->InsertNextPoint(facet.v2); ptId[2] = newPts->InsertNextPoint(facet.v3); newNormals->InsertNormal(ptId[0],facet.n1); newNormals->InsertNormal(ptId[1],facet.n2); newNormals->InsertNormal(ptId[2],facet.n3); newPolys->InsertNextCell(3,ptId); }//if appropriate part }//for all facets in this set }//for this facet set // update output vtkDebugMacro(<<"Read " << newPts->GetNumberOfPoints() << " points, " << newPolys->GetNumberOfCells() << " triangles."); fclose(fp); // // Merge points/triangles if requested // if ( this->Merging ) { int i; vtkIdType *pts, nodes[3], npts; float *x; mergedPts = vtkPoints::New(); mergedPts->Allocate(newPts->GetNumberOfPoints()/3); mergedNormals = vtkNormals::New(); mergedNormals->Allocate(newNormals->GetNumberOfNormals()/3); mergedPolys = vtkCellArray::New(); mergedPolys->Allocate(newPolys->GetSize()); if ( this->Locator == NULL ) { this->CreateDefaultLocator(); } this->Locator->InitPointInsertion (mergedPts, newPts->GetBounds()); for (newPolys->InitTraversal(); newPolys->GetNextCell(npts,pts); ) { for (i=0; i < 3; i++) { x = newPts->GetPoint(pts[i]); if ( this->Locator->InsertUniquePoint(x, nodes[i]) ) { mergedNormals->InsertNormal(nodes[i],newNormals->GetNormal(pts[i])); } } if ( nodes[0] != nodes[1] && nodes[0] != nodes[2] && nodes[1] != nodes[2] ) { mergedPolys->InsertNextCell(3,nodes); } } newPts->Delete(); newNormals->Delete(); newPolys->Delete(); vtkDebugMacro(<< "Merged to: " << mergedPts->GetNumberOfPoints() << " points, " << mergedPolys->GetNumberOfCells() << " triangles"); } else { mergedPts = newPts; mergedNormals = newNormals; mergedPolys = newPolys; } // // Update ourselves // output->SetPoints(mergedPts); mergedPts->Delete(); output->GetPointData()->SetNormals(mergedNormals); mergedNormals->Delete(); output->SetPolys(mergedPolys); mergedPolys->Delete(); if (this->Locator) { this->Locator->Initialize(); //free storage } output->Squeeze(); } int vtkUGFacetReader::GetNumberOfParts() { char header[36]; FILE *fp; int numberOfParts; if ( this->FileName == NULL || strlen(this->FileName) == 0) { vtkErrorMacro(<<"No FileName specified...please specify one."); return 0; } // open the file if ( (fp = fopen(this->FileName, "rb")) == NULL) { vtkErrorMacro(<<"Cannot open file specified."); return 0; } // read the header stuff if ( fread (header, 1, 2, fp) <= 0 || fread (&numberOfParts, 4, 1, fp) <= 0 || fread (header, 1, 36, fp) <= 0 ) { vtkErrorMacro(<<"File ended prematurely"); fclose(fp); return 0; } // swap bytes if necc vtkByteSwap::Swap4BE(&numberOfParts); fclose(fp); return numberOfParts; } // Retrieve color index for the parts in the file. short vtkUGFacetReader::GetPartColorIndex(int partId) { if ( this->PartColors == NULL ) { this->Update(); } if ( !this->PartColors || partId < 0 || partId > this->PartColors->GetMaxId() ) { return 0; } else { return this->PartColors->GetValue(partId); } } // Specify a spatial locator for merging points. By // default an instance of vtkMergePoints is used. void vtkUGFacetReader::SetLocator(vtkPointLocator *locator) { if ( this->Locator == locator ) { return; } if (this->Locator != NULL) { this->Locator->UnRegister(this); this->Locator = NULL; } if (locator != NULL) { locator->Register(this); } this->Locator = locator; this->Modified(); } void vtkUGFacetReader::CreateDefaultLocator() { if ( this->Locator == NULL ) { this->Locator = vtkMergePoints::New(); } } void vtkUGFacetReader::PrintSelf(ostream& os, vtkIndent indent) { vtkPolyDataSource::PrintSelf(os,indent); os << indent << "File Name: " << (this->FileName ? this->FileName : "(none)") << "\n"; os << indent << "Part Number: " << this->PartNumber << "\n"; os << indent << "Merging: " << (this->Merging ? "On\n" : "Off\n"); if ( this->Locator ) { os << indent << "Locator: " << this->Locator << "\n"; } else { os << indent << "Locator: (none)\n"; } } <|endoftext|>
<commit_before>/* * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "src/trace_processor/importers/proto/android_camera_event_module.h" #include <sstream> #include "include/perfetto/ext/base/string_utils.h" #include "perfetto/ext/base/string_view.h" #include "perfetto/protozero/field.h" #include "protos/perfetto/trace/android/camera_event.pbzero.h" #include "protos/perfetto/trace/trace_packet.pbzero.h" #include "src/trace_processor/importers/common/slice_tracker.h" #include "src/trace_processor/importers/common/track_tracker.h" #include "src/trace_processor/importers/proto/async_track_set_tracker.h" #include "src/trace_processor/storage/trace_storage.h" #include "src/trace_processor/tables/slice_tables.h" #include "src/trace_processor/tables/track_tables.h" #include "src/trace_processor/timestamped_trace_piece.h" #include "src/trace_processor/trace_sorter.h" namespace perfetto { namespace trace_processor { using perfetto::protos::pbzero::TracePacket; AndroidCameraEventModule::AndroidCameraEventModule( TraceProcessorContext* context) : context_(context) { RegisterForField(TracePacket::kAndroidCameraFrameEventFieldNumber, context); } AndroidCameraEventModule::~AndroidCameraEventModule() = default; ModuleResult AndroidCameraEventModule::TokenizePacket( const protos::pbzero::TracePacket::Decoder& decoder, TraceBlobView* packet, int64_t /*packet_timestamp*/, PacketSequenceState* state, uint32_t field_id) { if (field_id != TracePacket::kAndroidCameraFrameEventFieldNumber) { return ModuleResult::Ignored(); } const auto android_camera_frame_event = protos::pbzero::AndroidCameraFrameEvent::Decoder( decoder.android_camera_frame_event()); context_->sorter->PushTracePacket( android_camera_frame_event.request_processing_started_ns(), state, std::move(*packet)); return ModuleResult::Handled(); } void AndroidCameraEventModule::ParsePacket(const TracePacket::Decoder& decoder, const TimestampedTracePiece& /*ttp*/, uint32_t field_id) { if (field_id != TracePacket::kAndroidCameraFrameEventFieldNumber) { return; } InsertCameraFrameSlice(decoder.android_camera_frame_event()); } void AndroidCameraEventModule::InsertCameraFrameSlice( protozero::ConstBytes bytes) { const auto android_camera_frame_event = protos::pbzero::AndroidCameraFrameEvent::Decoder(bytes); StringId track_name = context_->storage->InternString( base::StackString<32>("Camera %d Frames", android_camera_frame_event.camera_id()) .string_view()); StringId slice_name = context_->storage->InternString( base::StackString<32>("Frame %" PRId64, android_camera_frame_event.frame_number()) .string_view()); int64_t ts = android_camera_frame_event.request_processing_started_ns(); int64_t dur = android_camera_frame_event.responses_all_sent_ns() - android_camera_frame_event.request_processing_started_ns(); auto track_set_id = context_->async_track_set_tracker->InternGlobalTrackSet(track_name); auto track_id = context_->async_track_set_tracker->Scoped(track_set_id, ts, dur); context_->slice_tracker->Scoped(ts, track_id, /*category=*/kNullStringId, slice_name, dur); } } // namespace trace_processor } // namespace perfetto <commit_msg>tp: fix compile in G3 am: 92a6e426c4<commit_after>/* * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "src/trace_processor/importers/proto/android_camera_event_module.h" #include "perfetto/ext/base/string_utils.h" #include "protos/perfetto/trace/android/camera_event.pbzero.h" #include "protos/perfetto/trace/trace_packet.pbzero.h" #include "src/trace_processor/importers/common/slice_tracker.h" #include "src/trace_processor/importers/common/track_tracker.h" #include "src/trace_processor/importers/proto/async_track_set_tracker.h" #include "src/trace_processor/storage/trace_storage.h" #include "src/trace_processor/timestamped_trace_piece.h" #include "src/trace_processor/trace_sorter.h" namespace perfetto { namespace trace_processor { using perfetto::protos::pbzero::TracePacket; AndroidCameraEventModule::AndroidCameraEventModule( TraceProcessorContext* context) : context_(context) { RegisterForField(TracePacket::kAndroidCameraFrameEventFieldNumber, context); } AndroidCameraEventModule::~AndroidCameraEventModule() = default; ModuleResult AndroidCameraEventModule::TokenizePacket( const protos::pbzero::TracePacket::Decoder& decoder, TraceBlobView* packet, int64_t /*packet_timestamp*/, PacketSequenceState* state, uint32_t field_id) { if (field_id != TracePacket::kAndroidCameraFrameEventFieldNumber) { return ModuleResult::Ignored(); } const auto android_camera_frame_event = protos::pbzero::AndroidCameraFrameEvent::Decoder( decoder.android_camera_frame_event()); context_->sorter->PushTracePacket( android_camera_frame_event.request_processing_started_ns(), state, std::move(*packet)); return ModuleResult::Handled(); } void AndroidCameraEventModule::ParsePacket(const TracePacket::Decoder& decoder, const TimestampedTracePiece& /*ttp*/, uint32_t field_id) { if (field_id != TracePacket::kAndroidCameraFrameEventFieldNumber) { return; } InsertCameraFrameSlice(decoder.android_camera_frame_event()); } void AndroidCameraEventModule::InsertCameraFrameSlice( protozero::ConstBytes bytes) { const auto android_camera_frame_event = protos::pbzero::AndroidCameraFrameEvent::Decoder(bytes); StringId track_name = context_->storage->InternString( base::StackString<32>("Camera %d Frames", android_camera_frame_event.camera_id()) .string_view()); StringId slice_name = context_->storage->InternString( base::StackString<32>("Frame %" PRId64, android_camera_frame_event.frame_number()) .string_view()); int64_t ts = android_camera_frame_event.request_processing_started_ns(); int64_t dur = android_camera_frame_event.responses_all_sent_ns() - android_camera_frame_event.request_processing_started_ns(); auto track_set_id = context_->async_track_set_tracker->InternGlobalTrackSet(track_name); auto track_id = context_->async_track_set_tracker->Scoped(track_set_id, ts, dur); context_->slice_tracker->Scoped(ts, track_id, /*category=*/kNullStringId, slice_name, dur); } } // namespace trace_processor } // namespace perfetto <|endoftext|>
<commit_before>#ifndef INCLUDE_AL_BUFFER_HPP #define INCLUDE_AL_BUFFER_HPP /* * AlloSphere Research Group / Media Arts & Technology, UCSB, 2009 */ /* Copyright (C) 2006-2008. The Regents of the University of California (REGENTS). All Rights Reserved. Permission to use, copy, modify, distribute, and distribute modified versions of this software and its documentation without fee and without a signed licensing agreement, is hereby granted, provided that the above copyright notice, the list of contributors, this paragraph and the following two paragraphs appear in all copies, modifications, and distributions. IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ #include <vector> namespace al{ /// Buffer /// /// template <class T, class Alloc=std::allocator<T> > class Buffer : protected Alloc{ typedef Alloc super; public: /// @param[in] size Initial size explicit Buffer(int size=0) : mSize(size), mFill(0), mPos(size-1), mElems(size) {} /// @param[in] size Initial size /// @param[in] capacity Initial capacity Buffer(int size, int capacity) : mSize(size), mFill(0), mPos(size-1), mElems(capacity) {} ~Buffer(){} int capacity() const { return mElems.capacity(); } ///< Returns total capacity int fill() const { return mFill; } ///< Returns buffer fill amount int pos() const { return mPos; } ///< Returns write position int size() const { return mSize; } ///< Returns size T * elems(){ return &mElems[0]; } ///< Returns C-style pointer to elements /// Set element at absolute index T& operator[](int i){ return atAbs(i); } /// Get element at absolute index const T& operator[](int i) const { return atAbs(i); } /// Assign value to elements /// This function fills a Buffer with n copies of the given value. Note that /// the assignment completely changes the buffer and that the resulting size /// is the same as the number of elements assigned. Old data may be lost. void assign(int n, const T& v){ mElems.assign(n,v); } /// Set element at absolute index T& atAbs(int i){ return mElems[i]; } /// Get element at absolute index const T& atAbs(int i) const { return mElems[i]; } /// Set element at relative index T& atRel(int i){ return mElems[wrapOnce(pos()-i, size())]; } /// Get element at relative index const T& atRel(int i) const { return mElems[wrapOnce(pos()-i, size())]; } /// Get last element const T& last() const { return mElems[mPos-1]; } /// Clear void clear(){ mSize=mFill=0; mPos=-1; } /// Resize buffer /// This will set both the size and capacity of the buffer to the requested /// size. If the number is smaller than the current size the buffer is /// truncated, otherwise the buffer is extended and new elements are /// default-constructed. void resize(int n){ mElems.resize(n); setSize(n); } /// Set size of buffer /// If the requested size is larger than the current capacity, then the /// buffer will be resized. void size(int n){ if(capacity() < n) resize(n); else setSize(n); } /// Appends element to end of buffer growing its size if necessary void append(const T& v, double growFactor=2){ if(size() >= capacity()){ // double array size if too small mElems.resize((size() ? size() : 4)*growFactor); } super::construct(elems()+size(), v); mPos=mSize; ++mSize; } /// synonym for append(): void push_back(const T& v, double growFactor=2) { append(v, growFactor); } /// Write new element to ring buffer void write(const T& v){ ++mPos; if(pos() == size()){ mPos=0; } Alloc::construct(elems()+pos(), v); if(fill() < size()) ++mFill; } private: int mSize; // number of elements in array int mFill; // number of elements written to buffer (up to size()) int mPos; // circular buffer write position std::vector<T, Alloc> mElems; void setSize(int n){ mSize=n; if(mFill>=n) mFill = n-1; if(mPos >=n) mPos = n-1; } // Moves value one period closer to interval [0, max) static int wrapOnce(int v, int max){ if(v < 0) return v+max; if(v >= max) return v-max; return v; } }; template <int N, class T> struct Multi{ typedef Multi M; // Multi(){} // Multi(const T& e ){ mem::set(elems, N, e); } // Multi(const T* es){ mem::copy(elems, es, N); } T elems[N]; /// Set element at index with no bounds checking T& operator[](int i){ return elems[i];} /// Get element at index with no bounds checking const T& operator[](int i) const { return elems[i]; } #define DO for(int i=0; i<N; ++i) bool operator !=(const M& v){ DO{ if((*this)[i] == v[i]) return false; } return true; } bool operator !=(const T& v){ DO{ if((*this)[i] == v ) return false; } return true; } M& operator = (const M& v){ DO{ (*this)[i] = v[i]; } return *this; } M& operator = (const T& v){ DO{ (*this)[i] = v; } return *this; } bool operator ==(const M& v){ DO{ if((*this)[i] != v[i]) return false; } return true; } bool operator ==(const T& v){ DO{ if((*this)[i] != v ) return false; } return true; } #undef DO /// Returns size of array static int size(){ return N; } /// Zeros all elements. void zero(){ memset(elems, 0, N * sizeof(T)); } }; /// Fixed size shift buffer template <int N, class T> struct ShiftBuffer : public Multi<N,T>{ typedef Multi<N,T> Base; using Base::elems; using Base::operator=; ShiftBuffer(const T& v=T()){ *this = v; } /// Push new element onto buffer. Newest element is at index 0. void operator()(const T& v){ for(int i=N-1; i>0; --i) elems[i] = elems[i-1]; elems[0]=v; } }; } // al:: #endif <commit_msg>fixed invalid memory bug in Buffer::append<commit_after>#ifndef INCLUDE_AL_BUFFER_HPP #define INCLUDE_AL_BUFFER_HPP /* * AlloSphere Research Group / Media Arts & Technology, UCSB, 2009 */ /* Copyright (C) 2006-2008. The Regents of the University of California (REGENTS). All Rights Reserved. Permission to use, copy, modify, distribute, and distribute modified versions of this software and its documentation without fee and without a signed licensing agreement, is hereby granted, provided that the above copyright notice, the list of contributors, this paragraph and the following two paragraphs appear in all copies, modifications, and distributions. IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ #include <vector> namespace al{ /// Buffer /// /// template <class T, class Alloc=std::allocator<T> > class Buffer : protected Alloc{ typedef Alloc super; public: /// @param[in] size Initial size explicit Buffer(int size=0) : mSize(size), mFill(0), mPos(size-1), mElems(size) {} /// @param[in] size Initial size /// @param[in] capacity Initial capacity Buffer(int size, int capacity) : mSize(size), mFill(0), mPos(size-1), mElems(capacity) {} ~Buffer(){} int capacity() const { return mElems.capacity(); } ///< Returns total capacity int fill() const { return mFill; } ///< Returns buffer fill amount int pos() const { return mPos; } ///< Returns write position int size() const { return mSize; } ///< Returns size T * elems(){ return &mElems[0]; } ///< Returns C-style pointer to elements /// Set element at absolute index T& operator[](int i){ return atAbs(i); } /// Get element at absolute index const T& operator[](int i) const { return atAbs(i); } /// Assign value to elements /// This function fills a Buffer with n copies of the given value. Note that /// the assignment completely changes the buffer and that the resulting size /// is the same as the number of elements assigned. Old data may be lost. void assign(int n, const T& v){ mElems.assign(n,v); } /// Set element at absolute index T& atAbs(int i){ return mElems[i]; } /// Get element at absolute index const T& atAbs(int i) const { return mElems[i]; } /// Set element at relative index T& atRel(int i){ return mElems[wrapOnce(pos()-i, size())]; } /// Get element at relative index const T& atRel(int i) const { return mElems[wrapOnce(pos()-i, size())]; } /// Get last element const T& last() const { return mElems[mPos-1]; } /// Clear void clear(){ mSize=mFill=0; mPos=-1; } /// Resize buffer /// This will set both the size and capacity of the buffer to the requested /// size. If the number is smaller than the current size the buffer is /// truncated, otherwise the buffer is extended and new elements are /// default-constructed. void resize(int n){ mElems.resize(n); setSize(n); } /// Set size of buffer /// If the requested size is larger than the current capacity, then the /// buffer will be resized. void size(int n){ if(capacity() < n) resize(n); else setSize(n); } /// Appends element to end of buffer growing its size if necessary void append(const T& v, double growFactor=2){ if(size() >= capacity()){ // double array size if too small // Copy argument since it may be an element in current memory range // which may become invalid after the resize. const T vsafecopy = v; mElems.resize((size() ? size() : 4)*growFactor); super::construct(elems()+size(), vsafecopy); } else{ super::construct(elems()+size(), v); } mPos=size(); ++mSize; } /// synonym for append(): void push_back(const T& v, double growFactor=2) { append(v, growFactor); } /// Write new element to ring buffer void write(const T& v){ ++mPos; if(pos() == size()){ mPos=0; } Alloc::construct(elems()+pos(), v); if(fill() < size()) ++mFill; } private: int mSize; // number of elements in array int mFill; // number of elements written to buffer (up to size()) int mPos; // circular buffer write position std::vector<T, Alloc> mElems; void setSize(int n){ mSize=n; if(mFill>=n) mFill = n-1; if(mPos >=n) mPos = n-1; } // Moves value one period closer to interval [0, max) static int wrapOnce(int v, int max){ if(v < 0) return v+max; if(v >= max) return v-max; return v; } }; template <int N, class T> struct Multi{ typedef Multi M; // Multi(){} // Multi(const T& e ){ mem::set(elems, N, e); } // Multi(const T* es){ mem::copy(elems, es, N); } T elems[N]; /// Set element at index with no bounds checking T& operator[](int i){ return elems[i];} /// Get element at index with no bounds checking const T& operator[](int i) const { return elems[i]; } #define DO for(int i=0; i<N; ++i) bool operator !=(const M& v){ DO{ if((*this)[i] == v[i]) return false; } return true; } bool operator !=(const T& v){ DO{ if((*this)[i] == v ) return false; } return true; } M& operator = (const M& v){ DO{ (*this)[i] = v[i]; } return *this; } M& operator = (const T& v){ DO{ (*this)[i] = v; } return *this; } bool operator ==(const M& v){ DO{ if((*this)[i] != v[i]) return false; } return true; } bool operator ==(const T& v){ DO{ if((*this)[i] != v ) return false; } return true; } #undef DO /// Returns size of array static int size(){ return N; } /// Zeros all elements. void zero(){ memset(elems, 0, N * sizeof(T)); } }; /// Fixed size shift buffer template <int N, class T> struct ShiftBuffer : public Multi<N,T>{ typedef Multi<N,T> Base; using Base::elems; using Base::operator=; ShiftBuffer(const T& v=T()){ *this = v; } /// Push new element onto buffer. Newest element is at index 0. void operator()(const T& v){ for(int i=N-1; i>0; --i) elems[i] = elems[i-1]; elems[0]=v; } }; } // al:: #endif <|endoftext|>
<commit_before>/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow_lite_support/c/task/audio/audio_classifier.h" #include <string.h> #include "tensorflow/lite/core/shims/cc/shims_test_util.h" #include "tensorflow_lite_support/c/common.h" #include "tensorflow_lite_support/c/task/audio/core/audio_buffer.h" #include "tensorflow_lite_support/c/task/processor/classification_result.h" #include "tensorflow_lite_support/cc/port/gmock.h" #include "tensorflow_lite_support/cc/port/gtest.h" #include "tensorflow_lite_support/cc/port/status_matchers.h" #include "tensorflow_lite_support/cc/port/statusor.h" #include "tensorflow_lite_support/cc/task/audio/utils/wav_io.h" #include "tensorflow_lite_support/cc/test/test_utils.h" namespace tflite { namespace task { namespace audio { namespace { using ::testing::HasSubstr; using ::tflite::support::StatusOr; using ::tflite::task::JoinPath; constexpr char kTestDataDirectory[] = "/tensorflow_lite_support/cc/test/testdata/task/" "audio/"; // Quantized model. constexpr char kYamNetAudioClassifierWithMetadata[] = "yamnet_audio_classifier_with_metadata.tflite"; StatusOr<TfLiteAudioBuffer> LoadAudioBufferFromFileNamed( const std::string wav_file, int buffer_size) { std::string contents = ReadFile( JoinPath("./" /*test src dir*/, kTestDataDirectory, wav_file)); int offset = 0; uint32_t decoded_sample_count; uint16_t decoded_channel_count; uint32_t decoded_sample_rate; std::vector<float> wav_data; absl::Status read_audio_file_status = DecodeLin16WaveAsFloatVector( contents, &wav_data, offset, &decoded_sample_count, &decoded_channel_count, &decoded_sample_rate); if (decoded_sample_count > buffer_size) { decoded_sample_count = buffer_size; } if (!read_audio_file_status.ok()) { return read_audio_file_status; } float* c_wav_data = (float*)malloc(sizeof(float) * wav_data.size()); if (!c_wav_data) { exit(-1); } memcpy(c_wav_data, wav_data.data(), sizeof(float) * wav_data.size()); TfLiteAudioBuffer audio_buffer = { .format = {.channels = decoded_channel_count, .sample_rate = static_cast<int>(decoded_sample_rate)}, .data = c_wav_data, .size = static_cast<int>(decoded_sample_count)}; return audio_buffer; } void Verify(TfLiteClassificationResult* classification_result, int expected_classifications_size) { EXPECT_NE(classification_result, nullptr); EXPECT_EQ(classification_result->size, expected_classifications_size); EXPECT_NE(classification_result->classifications, nullptr); } void Verify(TfLiteClassifications& classifications, int expected_categories_size, int expected_head_index, char const* expected_head_name) { EXPECT_EQ(classifications.size, expected_categories_size); EXPECT_EQ(classifications.head_index, expected_head_index); ASSERT_NE(classifications.head_name, nullptr); if (expected_head_name) { EXPECT_EQ(strcmp(classifications.head_name, expected_head_name), 0); } EXPECT_NE(classifications.categories, nullptr); } void Verify(TfLiteCategory& category, int expected_index, char const* expected_label, float expected_score) { const float kPrecision = 1e-6; EXPECT_EQ(category.index, expected_index); EXPECT_NE(category.label, nullptr); if (category.label && expected_label) { EXPECT_EQ(strcmp(category.label, expected_label), 0); } EXPECT_EQ(category.display_name, nullptr); EXPECT_NEAR(category.score, expected_score, kPrecision); } void Verify(TfLiteSupportError* error, TfLiteSupportErrorCode error_code, char const* message) { ASSERT_NE(error, nullptr); EXPECT_EQ(error->code, kInvalidArgumentError); EXPECT_NE(error->message, nullptr); EXPECT_THAT(error->message, HasSubstr(message)); } class AudioClassifierFromOptionsTest : public tflite_shims::testing::Test {}; TEST_F(AudioClassifierFromOptionsTest, FailsWithMissingModelPathAndError) { TfLiteAudioClassifierOptions options = TfLiteAudioClassifierOptionsCreate(); TfLiteSupportError* error = nullptr; TfLiteAudioClassifier* audio_classifier = TfLiteAudioClassifierFromOptions(&options, &error); EXPECT_EQ(audio_classifier, nullptr); if (audio_classifier) TfLiteAudioClassifierDelete(audio_classifier); Verify(error, kInvalidArgumentError, "INVALID_ARGUMENT: Missing mandatory `model_file` field in " "`base_options`"); TfLiteSupportErrorDelete(error); } TEST_F(AudioClassifierFromOptionsTest, SucceedsWithModelPath) { std::string model_path = JoinPath("./" /*test src dir*/, kTestDataDirectory, kYamNetAudioClassifierWithMetadata); TfLiteAudioClassifierOptions options = TfLiteAudioClassifierOptionsCreate(); options.base_options.model_file.file_path = model_path.data(); TfLiteAudioClassifier* audio_classifier = TfLiteAudioClassifierFromOptions(&options, nullptr); EXPECT_NE(audio_classifier, nullptr); TfLiteAudioClassifierDelete(audio_classifier); } class AudioClassifierClassifyTest : public tflite_shims::testing::Test { protected: void SetUp() override { std::string model_path = JoinPath("./" /*test src dir*/, kTestDataDirectory, kYamNetAudioClassifierWithMetadata); TfLiteAudioClassifierOptions options = TfLiteAudioClassifierOptionsCreate(); options.base_options.model_file.file_path = model_path.data(); audio_classifier = TfLiteAudioClassifierFromOptions(&options, nullptr); ASSERT_NE(audio_classifier, nullptr); } void TearDown() override { TfLiteAudioClassifierDelete(audio_classifier); } TfLiteAudioClassifier* audio_classifier; }; TEST_F(AudioClassifierClassifyTest, SucceedsWithAudioFile) { int input_buffer_size = TfLiteAudioClassifierGetRequiredInputBufferSize( audio_classifier, nullptr); ASSERT_NE(input_buffer_size, -1); SUPPORT_ASSERT_OK_AND_ASSIGN( TfLiteAudioBuffer audio_buffer, LoadAudioBufferFromFileNamed("speech.wav", input_buffer_size)); TfLiteSupportError* classifyError = NULL; TfLiteClassificationResult* classification_result = TfLiteAudioClassifierClassify(audio_classifier, &audio_buffer, &classifyError); TfLiteAudioBufferDeleteData(audio_buffer); Verify(classification_result, 1); Verify(classification_result->classifications[0], 521, 0, "scores"); Verify(classification_result->classifications[0].categories[0], 0, "Speech", 0.917969); Verify(classification_result->classifications[0].categories[1], 500, "Inside, small room", 0.058594); Verify(classification_result->classifications[0].categories[2], 494, "Silence", 0.011719); TfLiteClassificationResultDelete(classification_result); } } // namespace } // namespace audio } // namespace task } // namespace tflite <commit_msg>Updated C audio classifier test to account for changes<commit_after>/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow_lite_support/c/task/audio/audio_classifier.h" #include <string.h> #include "tensorflow/lite/core/shims/cc/shims_test_util.h" #include "tensorflow_lite_support/c/common.h" #include "tensorflow_lite_support/c/task/audio/core/audio_buffer.h" #include "tensorflow_lite_support/c/task/processor/classification_result.h" #include "tensorflow_lite_support/cc/port/gmock.h" #include "tensorflow_lite_support/cc/port/gtest.h" #include "tensorflow_lite_support/cc/port/status_matchers.h" #include "tensorflow_lite_support/cc/port/statusor.h" #include "tensorflow_lite_support/cc/task/audio/utils/wav_io.h" #include "tensorflow_lite_support/cc/test/test_utils.h" namespace tflite { namespace task { namespace audio { namespace { using ::testing::HasSubstr; using ::tflite::support::StatusOr; using ::tflite::task::JoinPath; constexpr char kTestDataDirectory[] = "/tensorflow_lite_support/cc/test/testdata/task/" "audio/"; // Quantized model. constexpr char kYamNetAudioClassifierWithMetadata[] = "yamnet_audio_classifier_with_metadata.tflite"; StatusOr<TfLiteAudioBuffer> LoadAudioBufferFromFileNamed( const std::string wav_file, int buffer_size) { std::string contents = ReadFile( JoinPath("./" /*test src dir*/, kTestDataDirectory, wav_file)); uint32_t offset = 0; uint32_t decoded_sample_count; uint16_t decoded_channel_count; uint32_t decoded_sample_rate; std::vector<float> wav_data; absl::Status read_audio_file_status = DecodeLin16WaveAsFloatVector( contents, &wav_data, &offset, &decoded_sample_count, &decoded_channel_count, &decoded_sample_rate); if (decoded_sample_count > buffer_size) { decoded_sample_count = buffer_size; } if (!read_audio_file_status.ok()) { return read_audio_file_status; } float* c_wav_data = (float*)malloc(sizeof(float) * wav_data.size()); if (!c_wav_data) { exit(-1); } memcpy(c_wav_data, wav_data.data(), sizeof(float) * wav_data.size()); TfLiteAudioBuffer audio_buffer = { .format = {.channels = decoded_channel_count, .sample_rate = static_cast<int>(decoded_sample_rate)}, .data = c_wav_data, .size = static_cast<int>(decoded_sample_count)}; return audio_buffer; } void Verify(TfLiteClassificationResult* classification_result, int expected_classifications_size) { EXPECT_NE(classification_result, nullptr); EXPECT_EQ(classification_result->size, expected_classifications_size); EXPECT_NE(classification_result->classifications, nullptr); } void Verify(TfLiteClassifications& classifications, int expected_categories_size, int expected_head_index, char const* expected_head_name) { EXPECT_EQ(classifications.size, expected_categories_size); EXPECT_EQ(classifications.head_index, expected_head_index); ASSERT_NE(classifications.head_name, nullptr); if (expected_head_name) { EXPECT_EQ(strcmp(classifications.head_name, expected_head_name), 0); } EXPECT_NE(classifications.categories, nullptr); } void Verify(TfLiteCategory& category, int expected_index, char const* expected_label, float expected_score) { const float kPrecision = 1e-6; EXPECT_EQ(category.index, expected_index); EXPECT_NE(category.label, nullptr); if (category.label && expected_label) { EXPECT_EQ(strcmp(category.label, expected_label), 0); } EXPECT_EQ(category.display_name, nullptr); EXPECT_NEAR(category.score, expected_score, kPrecision); } void Verify(TfLiteSupportError* error, TfLiteSupportErrorCode error_code, char const* message) { ASSERT_NE(error, nullptr); EXPECT_EQ(error->code, kInvalidArgumentError); EXPECT_NE(error->message, nullptr); EXPECT_THAT(error->message, HasSubstr(message)); } class AudioClassifierFromOptionsTest : public tflite_shims::testing::Test {}; TEST_F(AudioClassifierFromOptionsTest, FailsWithMissingModelPathAndError) { TfLiteAudioClassifierOptions options = TfLiteAudioClassifierOptionsCreate(); TfLiteSupportError* error = nullptr; TfLiteAudioClassifier* audio_classifier = TfLiteAudioClassifierFromOptions(&options, &error); EXPECT_EQ(audio_classifier, nullptr); if (audio_classifier) TfLiteAudioClassifierDelete(audio_classifier); Verify(error, kInvalidArgumentError, "INVALID_ARGUMENT: Missing mandatory `model_file` field in " "`base_options`"); TfLiteSupportErrorDelete(error); } TEST_F(AudioClassifierFromOptionsTest, SucceedsWithModelPath) { std::string model_path = JoinPath("./" /*test src dir*/, kTestDataDirectory, kYamNetAudioClassifierWithMetadata); TfLiteAudioClassifierOptions options = TfLiteAudioClassifierOptionsCreate(); options.base_options.model_file.file_path = model_path.data(); TfLiteAudioClassifier* audio_classifier = TfLiteAudioClassifierFromOptions(&options, nullptr); EXPECT_NE(audio_classifier, nullptr); TfLiteAudioClassifierDelete(audio_classifier); } class AudioClassifierClassifyTest : public tflite_shims::testing::Test { protected: void SetUp() override { std::string model_path = JoinPath("./" /*test src dir*/, kTestDataDirectory, kYamNetAudioClassifierWithMetadata); TfLiteAudioClassifierOptions options = TfLiteAudioClassifierOptionsCreate(); options.base_options.model_file.file_path = model_path.data(); audio_classifier = TfLiteAudioClassifierFromOptions(&options, nullptr); ASSERT_NE(audio_classifier, nullptr); } void TearDown() override { TfLiteAudioClassifierDelete(audio_classifier); } TfLiteAudioClassifier* audio_classifier; }; TEST_F(AudioClassifierClassifyTest, SucceedsWithAudioFile) { int input_buffer_size = TfLiteAudioClassifierGetRequiredInputBufferSize( audio_classifier, nullptr); ASSERT_NE(input_buffer_size, -1); SUPPORT_ASSERT_OK_AND_ASSIGN( TfLiteAudioBuffer audio_buffer, LoadAudioBufferFromFileNamed("speech.wav", input_buffer_size)); TfLiteSupportError* classifyError = NULL; TfLiteClassificationResult* classification_result = TfLiteAudioClassifierClassify(audio_classifier, &audio_buffer, &classifyError); TfLiteAudioBufferDeleteData(audio_buffer); Verify(classification_result, 1); Verify(classification_result->classifications[0], 521, 0, "scores"); Verify(classification_result->classifications[0].categories[0], 0, "Speech", 0.917969); Verify(classification_result->classifications[0].categories[1], 500, "Inside, small room", 0.058594); Verify(classification_result->classifications[0].categories[2], 494, "Silence", 0.011719); TfLiteClassificationResultDelete(classification_result); } } // namespace } // namespace audio } // namespace task } // namespace tflite <|endoftext|>
<commit_before>#ifndef COMPASS_CT_MSVC_IMPL_H_ #include "detail/ct/detect_compiler.hpp" #ifdef COMPASS_CT_COMP_MSVC #define COMPASS_CT_MSVC_IMPL_H_ #include "intrin.h" #include <array> #include <bitset> #include <cstdint> #include "detail/tags.hpp" #include "detail/definitions.hpp" namespace compass { namespace runtime { static std::array<std::uint32_t, 4> cpuid(std::uint32_t level, std::uint32_t in_eax = 0, std::uint32_t in_ebx = 0, std::uint32_t in_ecx = 0, std::uint32_t in_edx = 0) { std::array<std::uint32_t, 4> regs = { in_eax,in_ebx,in_ecx,in_edx }; std::int32_t* regs_ptr = reinterpret_cast<std::int32_t*>(regs.data()); __cpuid(regs_ptr, (std::int32_t)level); /* if (!(regs[ct::eax] || regs[ct::ebx] || regs[ct::ecx] || regs[ct::edx])) { return regs; }*/ return regs; } }; }; #endif /* COMPASS_CT_COMP_MSVC */ #endif /* COMPASS_CT_MSVC_IMPL_H_ */ <commit_msg>fixed cpuid use with visual studio<commit_after>#ifndef COMPASS_CT_MSVC_IMPL_H_ #include "detail/ct/detect_compiler.hpp" #ifdef COMPASS_CT_COMP_MSVC #define COMPASS_CT_MSVC_IMPL_H_ #include "intrin.h" #include <array> #include <bitset> #include <cstdint> #include "detail/tags.hpp" #include "detail/definitions.hpp" namespace compass { namespace runtime { static std::array<std::uint32_t, 4> cpuid(std::uint32_t in_eax = 0, std::uint32_t in_ebx = 0, std::uint32_t in_ecx = 0, std::uint32_t in_edx = 0) { std::array<std::uint32_t, 4> regs = { in_eax,in_ebx,in_ecx,in_edx }; std::int32_t* regs_ptr = reinterpret_cast<std::int32_t*>(regs.data()); __cpuidex(regs_ptr, (std::int32_t)in_eax, (std::int32_t)in_ecx ); return regs; } }; }; #endif /* COMPASS_CT_COMP_MSVC */ #endif /* COMPASS_CT_MSVC_IMPL_H_ */ <|endoftext|>
<commit_before>// // fiber_group.hpp // fibio // // Created by Chen Xu on 14-3-20. // Copyright (c) 2014 0d0a.com. All rights reserved. // #ifndef fibio_fiber_group_hpp #define fibio_fiber_group_hpp #include <list> #include <algorithm> #include <fibio/fibers/fiber.hpp> #include <fibio/fibers/shared_mutex.hpp> namespace fibio { namespace fibers { /// fiber_group class fiber_group { private: /// fiber_group is non-copyable fiber_group(fiber_group const&)=delete; fiber_group& operator=(fiber_group const&)=delete; public: /// constructor fiber_group() {} /// destructor ~fiber_group() { for(std::list<fiber*>::iterator it=fibers_.begin(), end=fibers_.end(); it!=end; ++it) { delete *it; } } /** * check if the current fiber is in the fiber group */ bool is_this_fiber_in() { fiber::id id = this_fiber::get_id(); shared_lock<shared_timed_mutex> guard(m_); for(std::list<fiber*>::iterator it=fibers_.begin(),end=fibers_.end(); it!=end; ++it) { if ((*it)->get_id() == id) return true; } return false; } /** * check if the given fiber is in the fiber group */ bool is_fiber_in(fiber* thrd) { if(thrd) { fiber::id id = thrd->get_id(); shared_lock<shared_timed_mutex> guard(m_); for(std::list<fiber*>::iterator it=fibers_.begin(),end=fibers_.end(); it!=end; ++it) { if ((*it)->get_id() == id) return true; } return false; } else { return false; } } /** * create a new fiber in the fiber group */ template<typename Fn, typename... Args> fiber* create_fiber(Fn &&fn, Args&&... args) { lock_guard<shared_timed_mutex> guard(m_); std::unique_ptr<fiber> new_fiber(new fiber(std::forward<Fn>(fn), std::forward<Args>(args)...)); fibers_.push_back(new_fiber.get()); return new_fiber.release(); } /** * add an existing fiber into the fiber group */ void add_fiber(fiber* thrd) { if(thrd) { lock_guard<shared_timed_mutex> guard(m_); fibers_.push_back(thrd); } } /** * remove a fiber from the fiber group */ void remove_fiber(fiber* thrd) { lock_guard<shared_timed_mutex> guard(m_); std::list<fiber*>::iterator const it=std::find(fibers_.begin(),fibers_.end(),thrd); if(it!=fibers_.end()) { fibers_.erase(it); } } /** * wait until all fibers exit */ void join_all() { shared_lock<shared_timed_mutex> guard(m_); for(std::list<fiber*>::iterator it=fibers_.begin(),end=fibers_.end(); it!=end; ++it) { if ((*it)->joinable()) (*it)->join(); } } /** * returns the number of fibers in the group */ size_t size() const { shared_lock<shared_timed_mutex> guard(m_); return fibers_.size(); } private: std::list<fiber*> fibers_; mutable shared_timed_mutex m_; }; }} // End of namespace fibio::fibers namespace fibio { using fibers::fiber_group; } // End of namespace fibio #endif <commit_msg>join_all before destruction<commit_after>// // fiber_group.hpp // fibio // // Created by Chen Xu on 14-3-20. // Copyright (c) 2014 0d0a.com. All rights reserved. // #ifndef fibio_fiber_group_hpp #define fibio_fiber_group_hpp #include <list> #include <algorithm> #include <fibio/fibers/fiber.hpp> #include <fibio/fibers/shared_mutex.hpp> namespace fibio { namespace fibers { /// fiber_group class fiber_group { private: /// fiber_group is non-copyable fiber_group(fiber_group const&)=delete; fiber_group& operator=(fiber_group const&)=delete; public: /// constructor fiber_group() {} /// destructor ~fiber_group() { join_all(); for(std::list<fiber*>::iterator it=fibers_.begin(), end=fibers_.end(); it!=end; ++it) { delete *it; } } /** * check if the current fiber is in the fiber group */ bool is_this_fiber_in() { fiber::id id = this_fiber::get_id(); shared_lock<shared_timed_mutex> guard(m_); for(std::list<fiber*>::iterator it=fibers_.begin(),end=fibers_.end(); it!=end; ++it) { if ((*it)->get_id() == id) return true; } return false; } /** * check if the given fiber is in the fiber group */ bool is_fiber_in(fiber* thrd) { if(thrd) { fiber::id id = thrd->get_id(); shared_lock<shared_timed_mutex> guard(m_); for(std::list<fiber*>::iterator it=fibers_.begin(),end=fibers_.end(); it!=end; ++it) { if ((*it)->get_id() == id) return true; } return false; } else { return false; } } /** * create a new fiber in the fiber group */ template<typename Fn, typename... Args> fiber* create_fiber(Fn &&fn, Args&&... args) { lock_guard<shared_timed_mutex> guard(m_); std::unique_ptr<fiber> new_fiber(new fiber(std::forward<Fn>(fn), std::forward<Args>(args)...)); fibers_.push_back(new_fiber.get()); return new_fiber.release(); } /** * add an existing fiber into the fiber group */ void add_fiber(fiber* thrd) { if(thrd) { lock_guard<shared_timed_mutex> guard(m_); fibers_.push_back(thrd); } } /** * remove a fiber from the fiber group */ void remove_fiber(fiber* thrd) { lock_guard<shared_timed_mutex> guard(m_); std::list<fiber*>::iterator const it=std::find(fibers_.begin(),fibers_.end(),thrd); if(it!=fibers_.end()) { fibers_.erase(it); } } /** * wait until all fibers exit */ void join_all() { shared_lock<shared_timed_mutex> guard(m_); for(std::list<fiber*>::iterator it=fibers_.begin(),end=fibers_.end(); it!=end; ++it) { if ((*it)->joinable()) (*it)->join(); } } /** * returns the number of fibers in the group */ size_t size() const { shared_lock<shared_timed_mutex> guard(m_); return fibers_.size(); } private: std::list<fiber*> fibers_; mutable shared_timed_mutex m_; }; }} // End of namespace fibio::fibers namespace fibio { using fibers::fiber_group; } // End of namespace fibio #endif <|endoftext|>
<commit_before> #include "Gameboy.hpp" #include "OpenGLWindow.hpp" #include "DbWindow.hpp" #include "registerAddr.hpp" #include "Cpu.hpp" #include "Gpu.hpp" #include "Memory.hpp" #include "Timer.hpp" #include "Audio.hpp" void setLowBit(Memory *memory, uint16_t addr, uint8_t bit) { memory->write_byte(addr, (uint8_t)((0x01 << bit) ^ memory->read_byte(addr)), true); } void setHightBit(Memory *memory, uint16_t addr, uint8_t bit) { memory->write_byte(addr, (uint8_t)((0x01 << bit) | memory->read_byte(addr)), true); } Gameboy::Gameboy(const char *path) : _window(OpenGLWindow::Instance()) , _windowDebug(nullptr) , _thread(nullptr) , _romPath(path) { _stepMode.store(false); _willRun.store(false); connect(_window, &OpenGLWindow::openRomSign, this, &Gameboy::openRomSlot); connect(_window, &OpenGLWindow::gbDbSign, this, &Gameboy::gbDbSlot); connect(_window, &OpenGLWindow::keyPressSign, this, &Gameboy::KeyPress); connect(_window, &OpenGLWindow::keyReleaseSign, this, &Gameboy::KeyRelease); connect(_window, &OpenGLWindow::gbTypeSign, this, &Gameboy::gbTypeSlot); connect(_window, &OpenGLWindow::gbComPlay, this, &Gameboy::switchPlaySlot); connect(_window, &OpenGLWindow::gbComPause, this, &Gameboy::switchPauseSlot); connect(_window, &OpenGLWindow::gbComStop, this, &Gameboy::resetPressedSlot); connect(_window, &OpenGLWindow::gbSoundSign, this, &Gameboy::soundSlot); _window->show(); _window->setWindowTitle("GBmu"); #ifdef DEBUG gbDbSlot(); // Open Debug window. WARNING: Peux generer SGFAULT random reset(); #endif } Gameboy::~Gameboy() { this->_memory->saverom(); delete this->_windowDebug; this->stopThread(); } void Gameboy::stopThread() { _stepMode.store(true); _willRun.store(false); if (_thread) { _thread->join(); delete _thread; _thread = nullptr; } } void Gameboy::gstep() { step(); if (isBreakpoint(_cpu->_cpuRegister.PC)) _stepMode.store(true); } void Gameboy::run() { while (_willRun.load()) { if (!_stepMode.load()) { gstep(); } } } void Gameboy::reset(void) { if (_willRun.load()) { stopThread(); } if (_romPath.length()) { this->_memory->reset(); this->_memory->setAudio(_audio); this->_clock->reset(); this->_audio->reset(_memory->getRomType() == GBC); this->_cyclesAcc = 0; if (_memory->loadRom(_romPath.c_str(), this->_hardware) == 0) { htype hardRom; hardRom = (this->_hardware == AUTO) ? this->_memory->getRomType() : this->_hardware; this->_cpu->init(hardRom); this->_gpu->init(); // TODO pour passer hardware au gpu: this->_gpu->init(hardRom) _window->setWindowTitle(_memory->romTitle()); _willRun.store(true); _thread = new std::thread(&Gameboy::run, this); } } else std::cerr << "Gameboy: No rom path defined" << std::endl; } void Gameboy::gbTypeSlot(htype hardware) { this->_hardware = hardware; } void Gameboy::stepPressedSlot(unsigned int count) { _stepMode.store(true); while (count--) { gstep(); if (isBreakpoint(_cpu->_cpuRegister.PC)) break ; } } #include "registerAddr.hpp" void Gameboy::framePressedSlot() { _stepMode.store(true); bool cte = true; uint16_t start; start = _memory->read_byte(REGISTER_LY); while (start == _memory->read_byte(REGISTER_LY) && cte) { gstep(); cte = !isBreakpoint(_cpu->_cpuRegister.PC); } while (start != _memory->read_byte(REGISTER_LY) && cte) { gstep(); cte = !isBreakpoint(_cpu->_cpuRegister.PC); } } void Gameboy::resetPressedSlot() { _stepMode.store(true); reset(); } void Gameboy::openRomSlot(std::string path) { _romPath = path; reset(); _stepMode.store(false); } void Gameboy::gbDbSlot() { _windowDebug = new DbWindow(&_cpu->_cpuRegister, _memory, &_breakpoints); connect(_windowDebug, &DbWindow::stepPressedSign, this, &Gameboy::stepPressedSlot); connect(_windowDebug, &DbWindow::framePressedSign, this, &Gameboy::framePressedSlot); connect(_windowDebug, &DbWindow::runPressedSign, this, &Gameboy::switchStepModeSlot); connect(_windowDebug, &DbWindow::resetPressedSign, this, &Gameboy::resetPressedSlot); connect(_windowDebug, &DbWindow::openPressedSign, this, &Gameboy::openRomSlot); connect(_windowDebug, &DbWindow::bpAddSign, this, &Gameboy::addBreakpointSlot); connect(_windowDebug, &DbWindow::bpDelSign, this, &Gameboy::delBreakpointSlot); _windowDebug->show(); _stepMode.store(true); } void Gameboy::switchPlaySlot(void) { _stepMode.store(false); } void Gameboy::switchPauseSlot(void) { _stepMode.store(true); } void Gameboy::soundSlot(bool on) { _audio->enable(on); } void Gameboy::switchStepModeSlot(void) { _stepMode.store(!_stepMode.load()); } void Gameboy::addBreakpointSlot(uint16_t addr) { auto it = std::find(_breakpoints.begin(), _breakpoints.end(), addr); if (it == _breakpoints.end()) _breakpoints.push_back(addr); } void Gameboy::delBreakpointSlot(uint16_t addr) { _breakpoints.remove(addr); } bool Gameboy::isBreakpoint(uint16_t addr) { auto it = std::find(_breakpoints.begin(), _breakpoints.end(), addr); return (it != _breakpoints.end()); } void Gameboy::KeyPress(int key) { switch(key) { case RIGHT: _memory->key[0] &= 0x0e; setLowBit(_memory, REGISTER_INPUT, 0); setHightBit(_memory, REGISTER_IF, 4); _cpu->setStop(false); break; case A_BUTTON: _memory->key[1] &= 0x0e; setLowBit(_memory, REGISTER_INPUT, 0); setHightBit(_memory, REGISTER_IF, 4); _cpu->setStop(false); break; case LEFT: _memory->key[0] &= 0x0D; setLowBit(_memory, REGISTER_INPUT, 1); setHightBit(_memory, REGISTER_IF, 4); _cpu->setStop(false); break; case B_BUTTON: _memory->key[1] &= 0x0D; setLowBit(_memory, REGISTER_INPUT, 1); setHightBit(_memory, REGISTER_IF, 4); _cpu->setStop(false); break; case UP: _memory->key[0] &= 0x0B; setLowBit(_memory, REGISTER_INPUT, 2); setHightBit(_memory, REGISTER_IF, 4); _cpu->setStop(false); break; case SELECT: _memory->key[1] &= 0x0B; setLowBit(_memory, REGISTER_INPUT, 2); setHightBit(_memory, REGISTER_IF, 4); _cpu->setStop(false); break; case DOWN: _memory->key[0] &= 0x07; setLowBit(_memory, REGISTER_INPUT, 3); setHightBit(_memory, REGISTER_IF, 4); _cpu->setStop(false); break; case START: _memory->key[1] &= 0x07; setLowBit(_memory, REGISTER_INPUT, 3); setHightBit(_memory, REGISTER_IF, 4); _cpu->setStop(false); break; } } void Gameboy::KeyRelease(int key) { switch(key) { case RIGHT: _memory->key[0] |= 0x01; setHightBit(_memory, REGISTER_INPUT, 0); _cpu->setStop(false); break; case A_BUTTON: _memory->key[1] |= 0x01; setHightBit(_memory, REGISTER_INPUT, 0); _cpu->setStop(false); break; case LEFT: _memory->key[0] |= 0x02; setHightBit(_memory, REGISTER_INPUT, 1); _cpu->setStop(false); break; case B_BUTTON: _memory->key[1] |= 0x02; setHightBit(_memory, REGISTER_INPUT, 1); _cpu->setStop(false); break; case UP: _memory->key[0] |= 0x04; setHightBit(_memory, REGISTER_INPUT, 2); _cpu->setStop(false); break; case SELECT: _memory->key[1] |= 0x04; setHightBit(_memory, REGISTER_INPUT, 2); _cpu->setStop(false); break; case DOWN: _memory->key[0] |= 0x08; setHightBit(_memory, REGISTER_INPUT, 3); _cpu->setStop(false); break; case START: _memory->key[1] |= 0x08; setHightBit(_memory, REGISTER_INPUT, 3); _cpu->setStop(false); break; } } <commit_msg>reinitialisation affichage si bad ROM<commit_after> #include "Gameboy.hpp" #include "OpenGLWindow.hpp" #include "DbWindow.hpp" #include "registerAddr.hpp" #include "Cpu.hpp" #include "Gpu.hpp" #include "Memory.hpp" #include "Timer.hpp" #include "Audio.hpp" void setLowBit(Memory *memory, uint16_t addr, uint8_t bit) { memory->write_byte(addr, (uint8_t)((0x01 << bit) ^ memory->read_byte(addr)), true); } void setHightBit(Memory *memory, uint16_t addr, uint8_t bit) { memory->write_byte(addr, (uint8_t)((0x01 << bit) | memory->read_byte(addr)), true); } Gameboy::Gameboy(const char *path) : _window(OpenGLWindow::Instance()) , _windowDebug(nullptr) , _thread(nullptr) , _romPath(path) { _stepMode.store(false); _willRun.store(false); connect(_window, &OpenGLWindow::openRomSign, this, &Gameboy::openRomSlot); connect(_window, &OpenGLWindow::gbDbSign, this, &Gameboy::gbDbSlot); connect(_window, &OpenGLWindow::keyPressSign, this, &Gameboy::KeyPress); connect(_window, &OpenGLWindow::keyReleaseSign, this, &Gameboy::KeyRelease); connect(_window, &OpenGLWindow::gbTypeSign, this, &Gameboy::gbTypeSlot); connect(_window, &OpenGLWindow::gbComPlay, this, &Gameboy::switchPlaySlot); connect(_window, &OpenGLWindow::gbComPause, this, &Gameboy::switchPauseSlot); connect(_window, &OpenGLWindow::gbComStop, this, &Gameboy::resetPressedSlot); connect(_window, &OpenGLWindow::gbSoundSign, this, &Gameboy::soundSlot); _window->show(); _window->setWindowTitle("GBmu"); #ifdef DEBUG gbDbSlot(); // Open Debug window. WARNING: Peux generer SGFAULT random reset(); #endif } Gameboy::~Gameboy() { this->_memory->saverom(); delete this->_windowDebug; this->stopThread(); } void Gameboy::stopThread() { _stepMode.store(true); _willRun.store(false); if (_thread) { _thread->join(); delete _thread; _thread = nullptr; } } void Gameboy::gstep() { step(); if (isBreakpoint(_cpu->_cpuRegister.PC)) _stepMode.store(true); } void Gameboy::run() { while (_willRun.load()) { if (!_stepMode.load()) { gstep(); } } } void Gameboy::reset(void) { if (_willRun.load()) { stopThread(); } if (_romPath.length()) { this->_memory->reset(); this->_memory->setAudio(_audio); this->_clock->reset(); this->_audio->reset(_memory->getRomType() == GBC); this->_cyclesAcc = 0; if (_memory->loadRom(_romPath.c_str(), this->_hardware) == 0) { htype hardRom; hardRom = (this->_hardware == AUTO) ? this->_memory->getRomType() : this->_hardware; this->_cpu->init(hardRom); this->_gpu->init(); // TODO pour passer hardware au gpu: this->_gpu->init(hardRom) _window->setWindowTitle(_memory->romTitle()); _willRun.store(true); _thread = new std::thread(&Gameboy::run, this); } else _window->initialize(); } else std::cerr << "Gameboy: No rom path defined" << std::endl; } void Gameboy::gbTypeSlot(htype hardware) { this->_hardware = hardware; } void Gameboy::stepPressedSlot(unsigned int count) { _stepMode.store(true); while (count--) { gstep(); if (isBreakpoint(_cpu->_cpuRegister.PC)) break ; } } #include "registerAddr.hpp" void Gameboy::framePressedSlot() { _stepMode.store(true); bool cte = true; uint16_t start; start = _memory->read_byte(REGISTER_LY); while (start == _memory->read_byte(REGISTER_LY) && cte) { gstep(); cte = !isBreakpoint(_cpu->_cpuRegister.PC); } while (start != _memory->read_byte(REGISTER_LY) && cte) { gstep(); cte = !isBreakpoint(_cpu->_cpuRegister.PC); } } void Gameboy::resetPressedSlot() { _stepMode.store(true); reset(); } void Gameboy::openRomSlot(std::string path) { _romPath = path; reset(); _stepMode.store(false); } void Gameboy::gbDbSlot() { _windowDebug = new DbWindow(&_cpu->_cpuRegister, _memory, &_breakpoints); connect(_windowDebug, &DbWindow::stepPressedSign, this, &Gameboy::stepPressedSlot); connect(_windowDebug, &DbWindow::framePressedSign, this, &Gameboy::framePressedSlot); connect(_windowDebug, &DbWindow::runPressedSign, this, &Gameboy::switchStepModeSlot); connect(_windowDebug, &DbWindow::resetPressedSign, this, &Gameboy::resetPressedSlot); connect(_windowDebug, &DbWindow::openPressedSign, this, &Gameboy::openRomSlot); connect(_windowDebug, &DbWindow::bpAddSign, this, &Gameboy::addBreakpointSlot); connect(_windowDebug, &DbWindow::bpDelSign, this, &Gameboy::delBreakpointSlot); _windowDebug->show(); _stepMode.store(true); } void Gameboy::switchPlaySlot(void) { _stepMode.store(false); } void Gameboy::switchPauseSlot(void) { _stepMode.store(true); } void Gameboy::soundSlot(bool on) { _audio->enable(on); } void Gameboy::switchStepModeSlot(void) { _stepMode.store(!_stepMode.load()); } void Gameboy::addBreakpointSlot(uint16_t addr) { auto it = std::find(_breakpoints.begin(), _breakpoints.end(), addr); if (it == _breakpoints.end()) _breakpoints.push_back(addr); } void Gameboy::delBreakpointSlot(uint16_t addr) { _breakpoints.remove(addr); } bool Gameboy::isBreakpoint(uint16_t addr) { auto it = std::find(_breakpoints.begin(), _breakpoints.end(), addr); return (it != _breakpoints.end()); } void Gameboy::KeyPress(int key) { switch(key) { case RIGHT: _memory->key[0] &= 0x0e; setLowBit(_memory, REGISTER_INPUT, 0); setHightBit(_memory, REGISTER_IF, 4); _cpu->setStop(false); break; case A_BUTTON: _memory->key[1] &= 0x0e; setLowBit(_memory, REGISTER_INPUT, 0); setHightBit(_memory, REGISTER_IF, 4); _cpu->setStop(false); break; case LEFT: _memory->key[0] &= 0x0D; setLowBit(_memory, REGISTER_INPUT, 1); setHightBit(_memory, REGISTER_IF, 4); _cpu->setStop(false); break; case B_BUTTON: _memory->key[1] &= 0x0D; setLowBit(_memory, REGISTER_INPUT, 1); setHightBit(_memory, REGISTER_IF, 4); _cpu->setStop(false); break; case UP: _memory->key[0] &= 0x0B; setLowBit(_memory, REGISTER_INPUT, 2); setHightBit(_memory, REGISTER_IF, 4); _cpu->setStop(false); break; case SELECT: _memory->key[1] &= 0x0B; setLowBit(_memory, REGISTER_INPUT, 2); setHightBit(_memory, REGISTER_IF, 4); _cpu->setStop(false); break; case DOWN: _memory->key[0] &= 0x07; setLowBit(_memory, REGISTER_INPUT, 3); setHightBit(_memory, REGISTER_IF, 4); _cpu->setStop(false); break; case START: _memory->key[1] &= 0x07; setLowBit(_memory, REGISTER_INPUT, 3); setHightBit(_memory, REGISTER_IF, 4); _cpu->setStop(false); break; } } void Gameboy::KeyRelease(int key) { switch(key) { case RIGHT: _memory->key[0] |= 0x01; setHightBit(_memory, REGISTER_INPUT, 0); _cpu->setStop(false); break; case A_BUTTON: _memory->key[1] |= 0x01; setHightBit(_memory, REGISTER_INPUT, 0); _cpu->setStop(false); break; case LEFT: _memory->key[0] |= 0x02; setHightBit(_memory, REGISTER_INPUT, 1); _cpu->setStop(false); break; case B_BUTTON: _memory->key[1] |= 0x02; setHightBit(_memory, REGISTER_INPUT, 1); _cpu->setStop(false); break; case UP: _memory->key[0] |= 0x04; setHightBit(_memory, REGISTER_INPUT, 2); _cpu->setStop(false); break; case SELECT: _memory->key[1] |= 0x04; setHightBit(_memory, REGISTER_INPUT, 2); _cpu->setStop(false); break; case DOWN: _memory->key[0] |= 0x08; setHightBit(_memory, REGISTER_INPUT, 3); _cpu->setStop(false); break; case START: _memory->key[1] |= 0x08; setHightBit(_memory, REGISTER_INPUT, 3); _cpu->setStop(false); break; } } <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2011 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_MEMORY_FEATURESET_HPP #define MAPNIK_MEMORY_FEATURESET_HPP // mapnik #include <mapnik/memory_datasource.hpp> // boost #include <boost/utility.hpp> namespace mapnik { class memory_featureset : public Featureset, private boost::noncopyable { public: memory_featureset(box2d<double> const& bbox, memory_datasource const& ds) : bbox_(bbox), pos_(ds.features_.begin()), end_(ds.features_.end()) {} memory_featureset(box2d<double> const& bbox, std::vector<feature_ptr> const& features) : bbox_(bbox), pos_(features.begin()), end_(features.end()) {} virtual ~memory_featureset() {} feature_ptr next() { while (pos_ != end_) { for (unsigned i=0; i<(*pos_)->num_geometries();++i) { geometry_type & geom = (*pos_)->get_geometry(i); #ifdef MAPNIK_DEBUG std::clog << "bbox_=" << bbox_ << ", geom.envelope=" << geom.envelope() << "\n"; #endif if (bbox_.intersects(geom.envelope())) { return *pos_++; } } ++pos_; } return feature_ptr(); } private: box2d<double> bbox_; std::vector<feature_ptr>::const_iterator pos_; std::vector<feature_ptr>::const_iterator end_; }; } #endif // MAPNIK_MEMORY_FEATURESET_HPP <commit_msg>+ base class already derived from boost::noncopyable<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2011 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_MEMORY_FEATURESET_HPP #define MAPNIK_MEMORY_FEATURESET_HPP // mapnik #include <mapnik/memory_datasource.hpp> // boost #include <boost/utility.hpp> namespace mapnik { class memory_featureset : public Featureset { public: memory_featureset(box2d<double> const& bbox, memory_datasource const& ds) : bbox_(bbox), pos_(ds.features_.begin()), end_(ds.features_.end()) {} memory_featureset(box2d<double> const& bbox, std::vector<feature_ptr> const& features) : bbox_(bbox), pos_(features.begin()), end_(features.end()) {} virtual ~memory_featureset() {} feature_ptr next() { while (pos_ != end_) { for (unsigned i=0; i<(*pos_)->num_geometries();++i) { geometry_type & geom = (*pos_)->get_geometry(i); #ifdef MAPNIK_DEBUG std::clog << "bbox_=" << bbox_ << ", geom.envelope=" << geom.envelope() << "\n"; #endif if (bbox_.intersects(geom.envelope())) { return *pos_++; } } ++pos_; } return feature_ptr(); } private: box2d<double> bbox_; std::vector<feature_ptr>::const_iterator pos_; std::vector<feature_ptr>::const_iterator end_; }; } #endif // MAPNIK_MEMORY_FEATURESET_HPP <|endoftext|>
<commit_before>#ifndef PROTO_RPC_MESSAGE_CODING #define PROTO_RPC_MESSAGE_CODING #include <iostream> #include <utility> // for pair #include <boost/asio/read_until.hpp> // for is_match_condition #include <boost/asio/streambuf.hpp> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/io/zero_copy_stream_impl.h> #include <google/protobuf/message.h> #include <proto_rpc/namespace.hpp> namespace proto_rpc { static inline void encode(const gp::Message &message, ba::streambuf &buffer) { // triple-wrapping of the buffer is required ... std::ostream os(&buffer); gp::io::OstreamOutputStream oos(&os); gp::io::CodedOutputStream output(&oos); // write the message length and then the message data to the buffer output.WriteVarint32(message.ByteSize()); message.SerializeWithCachedSizes(&output); } class Decode { public: Decode(gp::Message &message) : message_(message) {} virtual ~Decode() {} template < typename Iterator > std::pair< Iterator, bool > operator()(Iterator begin, Iterator end) const { // convert the given range to an input stream gp::io::CodedInputStream input(reinterpret_cast< const gp::uint8 * >(&(*begin)), static_cast< int >(end - begin)); // read the message length gp::uint32 message_size; if (!input.ReadVarint32(&message_size)) { return std::pair< Iterator, bool >(begin, false); } // check if the buffer length is enough to be read message data { const void *data; int size; input.GetDirectBufferPointer(&data, &size); if (static_cast< int >(message_size) > size) { return std::pair< Iterator, bool >(begin, false); } } // read the message data input.PushLimit(message_size); message_.ParsePartialFromCodedStream(&input); return std::pair< Iterator, bool >(begin + input.CurrentPosition(), true); } private: gp::Message &message_; }; } // export Decode to boost.asio namespace boost { namespace asio { template <> struct is_match_condition< proto_rpc::Decode > : public boost::true_type {}; } } #endif // PROTO_RPC_MESSAGE_CODING<commit_msg>bugfix<commit_after>#ifndef PROTO_RPC_MESSAGE_CODING #define PROTO_RPC_MESSAGE_CODING #include <iostream> #include <utility> // for pair #include <boost/asio/read_until.hpp> // for is_match_condition #include <boost/asio/streambuf.hpp> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/io/zero_copy_stream_impl.h> #include <google/protobuf/message.h> #include <proto_rpc/namespace.hpp> namespace proto_rpc { static inline void encode(const gp::Message &message, ba::streambuf &buffer) { // triple-wrapping of the buffer is required ... std::ostream os(&buffer); gp::io::OstreamOutputStream oos(&os); gp::io::CodedOutputStream output(&oos); // write the message length and then the message data to the buffer output.WriteVarint32(message.ByteSize()); message.SerializeWithCachedSizes(&output); } class Decode { public: Decode(gp::Message &message) : message_(message) {} virtual ~Decode() {} template < typename Iterator > std::pair< Iterator, bool > operator()(Iterator begin, Iterator end) const { // convert the given range to an input stream gp::io::CodedInputStream input(reinterpret_cast< const gp::uint8 * >(&(*begin)), static_cast< int >(end - begin)); // read the message length gp::uint32 message_size; if (!input.ReadVarint32(&message_size)) { return std::pair< Iterator, bool >(begin, false); } // check if the buffer length is enough to be read message data { const void *data; int size; if (!input.GetDirectBufferPointer(&data, &size)) { size = 0; } if (static_cast< int >(message_size) > size) { return std::pair< Iterator, bool >(begin, false); } } // read the message data input.PushLimit(message_size); message_.ParsePartialFromCodedStream(&input); return std::pair< Iterator, bool >(begin + input.CurrentPosition(), true); } private: gp::Message &message_; }; } // export Decode to boost.asio namespace boost { namespace asio { template <> struct is_match_condition< proto_rpc::Decode > : public boost::true_type {}; } } #endif // PROTO_RPC_MESSAGE_CODING<|endoftext|>
<commit_before>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <string.h> #include <algorithm> #include <cmath> #include <memory> #include <string> #include <unordered_map> #include <vector> #include "tensorflow/contrib/lite/toco/graph_transformations/graph_transformations.h" #include "tensorflow/contrib/lite/toco/model.h" #include "tensorflow/contrib/lite/toco/runtime/types.h" #include "tensorflow/contrib/lite/toco/tooling_util.h" #include "tensorflow/core/platform/logging.h" namespace toco { bool ResolveConstantUnaryOperator::Run(Model* model, std::size_t op_index) { const auto unary_it = model->operators.begin() + op_index; const auto* unary_op = unary_it->get(); // Test for unary ops of types that we know how to resolve if (unary_op->type != OperatorType::kCast && unary_op->type != OperatorType::kNeg && unary_op->type != OperatorType::kTensorFlowRsqrt && unary_op->type != OperatorType::kTensorFlowSqrt && unary_op->type != OperatorType::kTensorFlowSquare && unary_op->type != OperatorType::kTensorFlowSum && unary_op->type != OperatorType::kTensorFlowMin && unary_op->type != OperatorType::kTensorFlowMax && unary_op->type != OperatorType::kTensorFlowReshape) { return false; } // Check if the input is a constant parameter. if (!IsConstantParameterArray(*model, unary_op->inputs[0])) { return false; } // if the unary op involves a tensor required by a rnn state, ignore it for (const auto& rnn_state : model->flags.rnn_states()) { if (unary_op->inputs[0] == rnn_state.back_edge_source_array()) { return false; } if (unary_op->inputs[0] == rnn_state.state_array()) { return false; } } auto& output_array = model->GetArray(unary_op->outputs[0]); if (!output_array.has_shape()) { // Yield until the output array dims have been resolved. return false; } // At the moment we don't want to care about fused activation functions. // The idea is that we should do the present constants-propagation before // activation functions get fused. if (unary_op->fused_activation_function != FusedActivationFunctionType::kNone) { AddMessageF( "Not resolving constant %s " " because it has a fused activation function", LogName(*unary_op)); return false; } const auto& input_array = model->GetArray(unary_op->inputs[0]); // We have already tested above for existence of buffers (synonymous to being // a constant param). CHECK(input_array.buffer); std::vector<DataType<ArrayDataType::kFloat>> const* input_float_data; if (unary_op->type == OperatorType::kCast) { CastOperator const* cast_op = static_cast<CastOperator const*>(unary_op); if (cast_op->dst_data_type != ArrayDataType::kFloat) { AddMessageF( "Not resolving constant %s because we currently only support casting " "to float", LogName(*unary_op)); return false; } if (cast_op->src_data_type != input_array.buffer->type) { AddMessageF( "Not resolving constant %s because cast op source type does not " "match input type", LogName(*unary_op)); } } else { if (input_array.buffer->type != ArrayDataType::kFloat) { return false; } input_float_data = &(input_array.GetBuffer<ArrayDataType::kFloat>().data); } // Create a float buffer on the output array, which are always constant. const Shape& output_shape = output_array.shape(); const int output_dims_count = output_shape.dimensions_count(); const int output_buffer_size = RequiredBufferSizeForShape(output_shape); auto& output_float_data = output_array.GetMutableBuffer<ArrayDataType::kFloat>().data; output_float_data.resize(output_buffer_size); const Shape& input_shape = input_array.shape(); const int input_buffer_size = RequiredBufferSizeForShape(input_shape); if (unary_op->type == OperatorType::kCast) { for (int i = 0; i < output_buffer_size; i++) { float outval = 0.0f; if (input_array.buffer->type == ArrayDataType::kFloat) { outval = static_cast<float>( input_array.GetBuffer<ArrayDataType::kFloat>().data[i]); } else if (input_array.buffer->type == ArrayDataType::kUint8) { outval = static_cast<float>( input_array.GetBuffer<ArrayDataType::kUint8>().data[i]); } else if (input_array.buffer->type == ArrayDataType::kInt32) { outval = static_cast<float>( input_array.GetBuffer<ArrayDataType::kInt32>().data[i]); } else if (input_array.buffer->type == ArrayDataType::kInt64) { outval = static_cast<float>( input_array.GetBuffer<ArrayDataType::kInt64>().data[i]); } else { LOG(FATAL) << "Unsupported cast op input type"; } output_float_data[i] = outval; } } else if (unary_op->type == OperatorType::kTensorFlowReshape) { CHECK(input_buffer_size == output_buffer_size); memcpy(output_float_data.data(), (*input_float_data).data(), output_buffer_size * sizeof(output_float_data[0])); } else if (unary_op->type == OperatorType::kTensorFlowSum) { // At the moment only full reduction across all dimensions is supported. float sum = 0.f; for (int i = 0; i < input_buffer_size; i++) { sum += (*input_float_data)[i]; } for (int i = 0; i < output_buffer_size; ++i) { output_float_data[i] = sum; } } else if (unary_op->type == OperatorType::kTensorFlowMin) { // At the moment only full reduction across all dimensions is supported. // TODO(starka): Output should not be padded. for (int i = 0; i < output_dims_count; i++) { CHECK_EQ(output_shape.dims(i), 1); } float min = (*input_float_data)[0]; for (int i = 0; i < input_buffer_size; i++) { min = std::min(min, (*input_float_data)[i]); } output_float_data[0] = min; } else if (unary_op->type == OperatorType::kTensorFlowMax) { // At the moment only full reduction across all dimensions is supported. // TODO(starka): Output should not be padded. for (int i = 0; i < output_dims_count; i++) { CHECK_EQ(output_shape.dims(i), 1); } float max = (*input_float_data)[0]; for (int i = 0; i < input_buffer_size; i++) { max = std::max(max, (*input_float_data)[i]); } output_float_data[0] = max; } else if (unary_op->type == OperatorType::kNeg || unary_op->type == OperatorType::kTensorFlowRsqrt || unary_op->type == OperatorType::kTensorFlowSqrt || unary_op->type == OperatorType::kTensorFlowSquare) { // Element-wise ops. Should have perfectly matching sizes here. for (int i = 0; i < output_dims_count; i++) { CHECK_EQ(output_shape.dims(i), input_shape.dims(i)); } for (int i = 0; i < output_buffer_size; i++) { const float val = (*input_float_data)[i]; float outval = 0.f; if (unary_op->type == OperatorType::kNeg) { outval = -val; } else if (unary_op->type == OperatorType::kTensorFlowRsqrt) { outval = 1.0f / std::sqrt(val); } else if (unary_op->type == OperatorType::kTensorFlowSqrt) { outval = std::sqrt(val); } else if (unary_op->type == OperatorType::kTensorFlowSquare) { outval = val * val; } else { LOG(FATAL) << "should not get here."; } output_float_data[i] = outval; } } else { LOG(FATAL) << "should not get here."; } for (const auto& input : unary_op->inputs) { if (CountOpsWithInput(*model, input) == 1) { model->EraseArray(input); } } AddMessageF("Resolved constant %s to the equivalent constant array", LogName(*unary_op)); model->operators.erase(unary_it); return true; } } // namespace toco <commit_msg>Fixed tf.reduce_sum usage on 2-D tensors.<commit_after>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <string.h> #include <algorithm> #include <cmath> #include <memory> #include <string> #include <unordered_map> #include <vector> #include "tensorflow/contrib/lite/toco/graph_transformations/graph_transformations.h" #include "tensorflow/contrib/lite/toco/model.h" #include "tensorflow/contrib/lite/toco/runtime/types.h" #include "tensorflow/contrib/lite/toco/tooling_util.h" #include "tensorflow/core/platform/logging.h" namespace toco { bool ResolveConstantUnaryOperator::Run(Model* model, std::size_t op_index) { const auto unary_it = model->operators.begin() + op_index; const auto* unary_op = unary_it->get(); // Test for unary ops of types that we know how to resolve if (unary_op->type != OperatorType::kCast && unary_op->type != OperatorType::kNeg && unary_op->type != OperatorType::kTensorFlowRsqrt && unary_op->type != OperatorType::kTensorFlowSqrt && unary_op->type != OperatorType::kTensorFlowSquare && unary_op->type != OperatorType::kTensorFlowSum && unary_op->type != OperatorType::kTensorFlowMin && unary_op->type != OperatorType::kTensorFlowMax && unary_op->type != OperatorType::kTensorFlowReshape) { return false; } // Check if the input is a constant parameter. if (!IsConstantParameterArray(*model, unary_op->inputs[0])) { return false; } // if the unary op involves a tensor required by a rnn state, ignore it for (const auto& rnn_state : model->flags.rnn_states()) { if (unary_op->inputs[0] == rnn_state.back_edge_source_array()) { return false; } if (unary_op->inputs[0] == rnn_state.state_array()) { return false; } } auto& output_array = model->GetArray(unary_op->outputs[0]); if (!output_array.has_shape()) { // Yield until the output array dims have been resolved. return false; } // At the moment we don't want to care about fused activation functions. // The idea is that we should do the present constants-propagation before // activation functions get fused. if (unary_op->fused_activation_function != FusedActivationFunctionType::kNone) { AddMessageF( "Not resolving constant %s " " because it has a fused activation function", LogName(*unary_op)); return false; } const auto& input_array = model->GetArray(unary_op->inputs[0]); // We have already tested above for existence of buffers (synonymous to being // a constant param). CHECK(input_array.buffer); std::vector<DataType<ArrayDataType::kFloat>> const* input_float_data; if (unary_op->type == OperatorType::kCast) { CastOperator const* cast_op = static_cast<CastOperator const*>(unary_op); if (cast_op->dst_data_type != ArrayDataType::kFloat) { AddMessageF( "Not resolving constant %s because we currently only support casting " "to float", LogName(*unary_op)); return false; } if (cast_op->src_data_type != input_array.buffer->type) { AddMessageF( "Not resolving constant %s because cast op source type does not " "match input type", LogName(*unary_op)); } } else { if (input_array.buffer->type != ArrayDataType::kFloat) { return false; } input_float_data = &(input_array.GetBuffer<ArrayDataType::kFloat>().data); } // Create a float buffer on the output array, which are always constant. const Shape& output_shape = output_array.shape(); const int output_dims_count = output_shape.dimensions_count(); const int output_buffer_size = RequiredBufferSizeForShape(output_shape); auto& output_float_data = output_array.GetMutableBuffer<ArrayDataType::kFloat>().data; output_float_data.resize(output_buffer_size); const Shape& input_shape = input_array.shape(); const int input_buffer_size = RequiredBufferSizeForShape(input_shape); if (unary_op->type == OperatorType::kCast) { for (int i = 0; i < output_buffer_size; i++) { float outval = 0.0f; if (input_array.buffer->type == ArrayDataType::kFloat) { outval = static_cast<float>( input_array.GetBuffer<ArrayDataType::kFloat>().data[i]); } else if (input_array.buffer->type == ArrayDataType::kUint8) { outval = static_cast<float>( input_array.GetBuffer<ArrayDataType::kUint8>().data[i]); } else if (input_array.buffer->type == ArrayDataType::kInt32) { outval = static_cast<float>( input_array.GetBuffer<ArrayDataType::kInt32>().data[i]); } else if (input_array.buffer->type == ArrayDataType::kInt64) { outval = static_cast<float>( input_array.GetBuffer<ArrayDataType::kInt64>().data[i]); } else { LOG(FATAL) << "Unsupported cast op input type"; } output_float_data[i] = outval; } } else if (unary_op->type == OperatorType::kTensorFlowReshape) { CHECK(input_buffer_size == output_buffer_size); memcpy(output_float_data.data(), (*input_float_data).data(), output_buffer_size * sizeof(output_float_data[0])); } else if (unary_op->type == OperatorType::kTensorFlowSum) { CHECK_EQ(unary_op->inputs.size(), 2) << "Sum needs 2 inputs"; if (!IsConstantParameterArray(*model, unary_op->inputs[1])) { AddMessageF("Axis input is non-constant"); return false; } auto& axis_array = model->GetArray(unary_op->inputs[1]); CHECK(axis_array.data_type == ArrayDataType::kInt32); int axis = axis_array.GetBuffer<ArrayDataType::kInt32>().data[0]; CHECK_LT(axis, input_shape.dimensions_count()) << "Axis out of bounds"; // We currently only handle reduction on axis 0. CHECK_EQ(axis, 0) << "Only reduction along axis 0 is supported"; // We currently only handle 1-D and 2-D input tensors. CHECK_LE(input_shape.dimensions_count(), 2) << "Rank >2 not yet supported"; // We only support keep_dims=true; shape prop will need to change otherwise. auto sum_op = static_cast<const TensorFlowSumOperator*>(unary_op); CHECK(sum_op->keep_dims) << "Only keep_dims=true is supported"; std::vector<int> indices(input_shape.dimensions_count()); for (int i = 0; i < input_shape.dims(1); ++i) { indices[1] = i; float sum = 0.f; for (int j = 0; j < input_shape.dims(0); ++j) { indices[0] = j; sum += (*input_float_data)[Offset(input_shape, indices)]; } output_float_data[i] = sum; } } else if (unary_op->type == OperatorType::kTensorFlowMin) { // At the moment only full reduction across all dimensions is supported. // TODO(starka): Output should not be padded. for (int i = 0; i < output_dims_count; i++) { CHECK_EQ(output_shape.dims(i), 1); } float min = (*input_float_data)[0]; for (int i = 0; i < input_buffer_size; i++) { min = std::min(min, (*input_float_data)[i]); } output_float_data[0] = min; } else if (unary_op->type == OperatorType::kTensorFlowMax) { // At the moment only full reduction across all dimensions is supported. // TODO(starka): Output should not be padded. for (int i = 0; i < output_dims_count; i++) { CHECK_EQ(output_shape.dims(i), 1); } float max = (*input_float_data)[0]; for (int i = 0; i < input_buffer_size; i++) { max = std::max(max, (*input_float_data)[i]); } output_float_data[0] = max; } else if (unary_op->type == OperatorType::kNeg || unary_op->type == OperatorType::kTensorFlowRsqrt || unary_op->type == OperatorType::kTensorFlowSqrt || unary_op->type == OperatorType::kTensorFlowSquare) { // Element-wise ops. Should have perfectly matching sizes here. for (int i = 0; i < output_dims_count; i++) { CHECK_EQ(output_shape.dims(i), input_shape.dims(i)); } for (int i = 0; i < output_buffer_size; i++) { const float val = (*input_float_data)[i]; float outval = 0.f; if (unary_op->type == OperatorType::kNeg) { outval = -val; } else if (unary_op->type == OperatorType::kTensorFlowRsqrt) { outval = 1.0f / std::sqrt(val); } else if (unary_op->type == OperatorType::kTensorFlowSqrt) { outval = std::sqrt(val); } else if (unary_op->type == OperatorType::kTensorFlowSquare) { outval = val * val; } else { LOG(FATAL) << "should not get here."; } output_float_data[i] = outval; } } else { LOG(FATAL) << "should not get here."; } for (const auto& input : unary_op->inputs) { if (CountOpsWithInput(*model, input) == 1) { model->EraseArray(input); } } AddMessageF("Resolved constant %s to the equivalent constant array", LogName(*unary_op)); model->operators.erase(unary_it); return true; } } // namespace toco <|endoftext|>
<commit_before>#pragma once #include "rapidcheck/detail/ApplyTuple.h" #include "rapidcheck/seq/Create.h" namespace rc { namespace seq { namespace detail { template <typename T> class DropSeq { public: DropSeq(std::size_t n, Seq<T> seq) : m_drop(n) , m_seq(std::move(seq)) {} Maybe<T> operator()() { while (m_drop > 0) { if (!m_seq.next()) { m_seq = Seq<T>(); m_drop = 0; return Nothing; } m_drop--; } return m_seq.next(); } private: std::size_t m_drop; Seq<T> m_seq; }; template <typename T> class TakeSeq { public: TakeSeq(std::size_t n, Seq<T> seq) : m_take(n) , m_seq(std::move(seq)) {} Maybe<T> operator()() { if (m_take == 0) { return Nothing; } m_take--; return m_seq.next(); } private: std::size_t m_take; Seq<T> m_seq; }; template <typename Predicate, typename T> class DropWhileSeq { public: template <typename PredArg> DropWhileSeq(Seq<T> seq, PredArg &&pred) : m_pred(std::forward<PredArg>(pred)) , m_dropped(false) , m_seq(std::move(seq)) {} Maybe<T> operator()() { while (!m_dropped) { auto value = m_seq.next(); if (!value) { m_dropped = true; m_seq = Seq<T>(); return Nothing; } if (!m_pred(*value)) { m_dropped = true; return value; } } return m_seq.next(); } private: Predicate m_pred; bool m_dropped; Seq<T> m_seq; }; template <typename Predicate, typename T> class TakeWhileSeq { public: template <typename PredArg> TakeWhileSeq(Seq<T> seq, PredArg &&pred) : m_pred(std::forward<PredArg>(pred)) , m_seq(std::move(seq)) {} Maybe<T> operator()() { auto value = m_seq.next(); if (!value) { return Nothing; } if (!m_pred(*value)) { m_seq = Seq<T>(); return Nothing; } return value; } private: Predicate m_pred; Seq<T> m_seq; }; template <typename Mapper, typename T> class MapSeq { public: using U = Decay<typename std::result_of<Mapper(T)>::type>; template <typename MapperArg> MapSeq(Seq<T> seq, MapperArg &&mapper) : m_mapper(std::forward<MapperArg>(mapper)) , m_seq(std::move(seq)) {} Maybe<U> operator()() { auto value = m_seq.next(); if (!value) { m_seq = Seq<T>(); return Nothing; } return m_mapper(std::move(*value)); } private: Mapper m_mapper; Seq<T> m_seq; }; template <typename Zipper, typename... Ts> class ZipWithSeq { public: using U = Decay<typename std::result_of<Zipper(Ts...)>::type>; template <typename ZipperArg> ZipWithSeq(ZipperArg &&zipper, Seq<Ts>... seqs) : m_zipper(std::forward<ZipperArg>(zipper)) , m_seqs(std::move(seqs)...) {} Maybe<U> operator()() { return rc::detail::applyTuple( m_seqs, [this](Seq<Ts> &... seqs) { return mapMaybes(seqs.next()...); }); } private: Maybe<U> mapMaybes(Maybe<Ts> &&... maybes) { if (!allTrue(maybes...)) { m_seqs = std::tuple<Seq<Ts>...>(); return Nothing; } return m_zipper(std::move(*maybes)...); } static bool allTrue() { return true; } template <typename MaybeT, typename... MaybeTs> static bool allTrue(const MaybeT &arg, const MaybeTs &... args) { return arg && allTrue(args...); } Zipper m_zipper; std::tuple<Seq<Ts>...> m_seqs; }; template <typename Predicate, typename T> class FilterSeq { public: template <typename PredArg> FilterSeq(Seq<T> seq, PredArg predicate) : m_predicate(std::forward<PredArg>(predicate)) , m_seq(std::move(seq)) {} Maybe<T> operator()() { while (true) { auto value = m_seq.next(); if (!value) { m_seq = Seq<T>(); return Nothing; } if (m_predicate(*value)) { return value; } } } private: Predicate m_predicate; Seq<T> m_seq; }; template <typename T> class JoinSeq { public: JoinSeq(Seq<Seq<T>> seqs) : m_seqs(std::move(seqs)) {} Maybe<T> operator()() { while (true) { auto value = m_seq.next(); if (value) { return value; } // Otherwise, next Seq auto seq = m_seqs.next(); if (!seq) { m_seq = Seq<T>(); m_seqs = Seq<Seq<T>>(); return Nothing; } m_seq = std::move(*seq); } } private: Seq<T> m_seq; Seq<Seq<T>> m_seqs; }; template <typename T, std::size_t N> class ConcatSeq { public: template <typename... Ts> ConcatSeq(Seq<Ts>... seqs) : m_seqs{std::move(seqs)...} {} Maybe<T> operator()() { while (m_i < N) { auto value = m_seqs[m_i].next(); if (value) { return value; } m_i++; } return Nothing; } private: Seq<T> m_seqs[N]; std::size_t m_i; }; template <typename Mapper, typename T> class MapcatSeq { public: using U = typename std::result_of<Mapper(T)>::type::ValueType; template <typename MapperArg> MapcatSeq(Seq<T> seq, MapperArg &&mapper) : m_mapper(std::forward<MapperArg>(mapper)) , m_seqT(std::move(seq)) {} Maybe<U> operator()() { while (true) { auto valueU = m_seqU.next(); if (valueU) { return valueU; } auto valueT = m_seqT.next(); if (!valueT) { m_seqT = Seq<T>(); m_seqU = Seq<U>(); return Nothing; } m_seqU = m_mapper(std::move(*valueT)); } } private: Mapper m_mapper; Seq<T> m_seqT; Seq<U> m_seqU; }; } // namespace detail template <typename T> Seq<T> drop(std::size_t n, Seq<T> seq) { if (n == 0) { return seq; } return makeSeq<detail::DropSeq<T>>(n, std::move(seq)); } template <typename T> Seq<T> take(std::size_t n, Seq<T> seq) { if (n == 0) { return Seq<T>(); } return makeSeq<detail::TakeSeq<T>>(n, std::move(seq)); } template <typename T, typename Predicate> Seq<T> dropWhile(Seq<T> seq, Predicate &&pred) { return makeSeq<detail::DropWhileSeq<Decay<Predicate>, T>>( std::move(seq), std::forward<Predicate>(pred)); } template <typename T, typename Predicate> Seq<T> takeWhile(Seq<T> seq, Predicate &&pred) { return makeSeq<detail::TakeWhileSeq<Decay<Predicate>, T>>( std::move(seq), std::forward<Predicate>(pred)); } template <typename T, typename Mapper> Seq<Decay<typename std::result_of<Mapper(T)>::type>> map(Seq<T> seq, Mapper &&mapper) { return makeSeq<detail::MapSeq<Decay<Mapper>, T>>( std::move(seq), std::forward<Mapper>(mapper)); } template <typename... Ts, typename Zipper> Seq<Decay<typename std::result_of<Zipper(Ts...)>::type>> zipWith(Zipper &&zipper, Seq<Ts>... seqs) { return makeSeq<detail::ZipWithSeq<Decay<Zipper>, Ts...>>( std::forward<Zipper>(zipper), std::move(seqs)...); } template <typename T, typename Predicate> Seq<T> filter(Seq<T> seq, Predicate &&pred) { return makeSeq<detail::FilterSeq<Decay<Predicate>, T>>( std::move(seq), std::forward<Predicate>(pred)); } template <typename T> Seq<T> join(Seq<Seq<T>> seqs) { return makeSeq<detail::JoinSeq<T>>(std::move(seqs)); } template <typename T, typename... Ts> Seq<T> concat(Seq<T> seq, Seq<Ts>... seqs) { return makeSeq<detail::ConcatSeq<T, sizeof...(Ts) + 1>>(std::move(seq), std::move(seqs)...); } template <typename T, typename Mapper> Seq<typename std::result_of<Mapper(T)>::type::ValueType> mapcat(Seq<T> seq, Mapper &&mapper) { return makeSeq<detail::MapcatSeq<Decay<Mapper>, T>>( std::move(seq), std::forward<Mapper>(mapper)); } template <typename T, typename Mapper> Seq<typename std::result_of<Mapper(T)>::type::ValueType> mapMaybe(Seq<T> seq, Mapper &&mapper) { using U = typename std::result_of<Mapper(T)>::type::ValueType; return seq::map( seq::filter(seq::map(std::move(seq), std::forward<Mapper>(mapper)), [](const Maybe<U> &x) { return !!x; }), [](Maybe<U> &&x) { return std::move(*x); }); } template <typename T> Seq<T> cycle(Seq<T> seq) { return seq::join(seq::repeat(std::move(seq))); } template <typename T, typename U> Seq<T> cast(Seq<U> seq) { return seq::map(std::move(seq), [](U &&x) { return static_cast<T>(std::move(x)); }); } } // namespace seq } // namespace rc <commit_msg>Fix uninitialized value in seq::concat<commit_after>#pragma once #include "rapidcheck/detail/ApplyTuple.h" #include "rapidcheck/seq/Create.h" namespace rc { namespace seq { namespace detail { template <typename T> class DropSeq { public: DropSeq(std::size_t n, Seq<T> seq) : m_drop(n) , m_seq(std::move(seq)) {} Maybe<T> operator()() { while (m_drop > 0) { if (!m_seq.next()) { m_seq = Seq<T>(); m_drop = 0; return Nothing; } m_drop--; } return m_seq.next(); } private: std::size_t m_drop; Seq<T> m_seq; }; template <typename T> class TakeSeq { public: TakeSeq(std::size_t n, Seq<T> seq) : m_take(n) , m_seq(std::move(seq)) {} Maybe<T> operator()() { if (m_take == 0) { return Nothing; } m_take--; return m_seq.next(); } private: std::size_t m_take; Seq<T> m_seq; }; template <typename Predicate, typename T> class DropWhileSeq { public: template <typename PredArg> DropWhileSeq(Seq<T> seq, PredArg &&pred) : m_pred(std::forward<PredArg>(pred)) , m_dropped(false) , m_seq(std::move(seq)) {} Maybe<T> operator()() { while (!m_dropped) { auto value = m_seq.next(); if (!value) { m_dropped = true; m_seq = Seq<T>(); return Nothing; } if (!m_pred(*value)) { m_dropped = true; return value; } } return m_seq.next(); } private: Predicate m_pred; bool m_dropped; Seq<T> m_seq; }; template <typename Predicate, typename T> class TakeWhileSeq { public: template <typename PredArg> TakeWhileSeq(Seq<T> seq, PredArg &&pred) : m_pred(std::forward<PredArg>(pred)) , m_seq(std::move(seq)) {} Maybe<T> operator()() { auto value = m_seq.next(); if (!value) { return Nothing; } if (!m_pred(*value)) { m_seq = Seq<T>(); return Nothing; } return value; } private: Predicate m_pred; Seq<T> m_seq; }; template <typename Mapper, typename T> class MapSeq { public: using U = Decay<typename std::result_of<Mapper(T)>::type>; template <typename MapperArg> MapSeq(Seq<T> seq, MapperArg &&mapper) : m_mapper(std::forward<MapperArg>(mapper)) , m_seq(std::move(seq)) {} Maybe<U> operator()() { auto value = m_seq.next(); if (!value) { m_seq = Seq<T>(); return Nothing; } return m_mapper(std::move(*value)); } private: Mapper m_mapper; Seq<T> m_seq; }; template <typename Zipper, typename... Ts> class ZipWithSeq { public: using U = Decay<typename std::result_of<Zipper(Ts...)>::type>; template <typename ZipperArg> ZipWithSeq(ZipperArg &&zipper, Seq<Ts>... seqs) : m_zipper(std::forward<ZipperArg>(zipper)) , m_seqs(std::move(seqs)...) {} Maybe<U> operator()() { return rc::detail::applyTuple( m_seqs, [this](Seq<Ts> &... seqs) { return mapMaybes(seqs.next()...); }); } private: Maybe<U> mapMaybes(Maybe<Ts> &&... maybes) { if (!allTrue(maybes...)) { m_seqs = std::tuple<Seq<Ts>...>(); return Nothing; } return m_zipper(std::move(*maybes)...); } static bool allTrue() { return true; } template <typename MaybeT, typename... MaybeTs> static bool allTrue(const MaybeT &arg, const MaybeTs &... args) { return arg && allTrue(args...); } Zipper m_zipper; std::tuple<Seq<Ts>...> m_seqs; }; template <typename Predicate, typename T> class FilterSeq { public: template <typename PredArg> FilterSeq(Seq<T> seq, PredArg predicate) : m_predicate(std::forward<PredArg>(predicate)) , m_seq(std::move(seq)) {} Maybe<T> operator()() { while (true) { auto value = m_seq.next(); if (!value) { m_seq = Seq<T>(); return Nothing; } if (m_predicate(*value)) { return value; } } } private: Predicate m_predicate; Seq<T> m_seq; }; template <typename T> class JoinSeq { public: JoinSeq(Seq<Seq<T>> seqs) : m_seqs(std::move(seqs)) {} Maybe<T> operator()() { while (true) { auto value = m_seq.next(); if (value) { return value; } // Otherwise, next Seq auto seq = m_seqs.next(); if (!seq) { m_seq = Seq<T>(); m_seqs = Seq<Seq<T>>(); return Nothing; } m_seq = std::move(*seq); } } private: Seq<T> m_seq; Seq<Seq<T>> m_seqs; }; template <typename T, std::size_t N> class ConcatSeq { public: template <typename... Ts> ConcatSeq(Seq<Ts>... seqs) : m_seqs{std::move(seqs)...} , m_i(0) {} Maybe<T> operator()() { while (m_i < N) { auto value = m_seqs[m_i].next(); if (value) { return value; } m_i++; } return Nothing; } private: Seq<T> m_seqs[N]; std::size_t m_i; }; template <typename Mapper, typename T> class MapcatSeq { public: using U = typename std::result_of<Mapper(T)>::type::ValueType; template <typename MapperArg> MapcatSeq(Seq<T> seq, MapperArg &&mapper) : m_mapper(std::forward<MapperArg>(mapper)) , m_seqT(std::move(seq)) {} Maybe<U> operator()() { while (true) { auto valueU = m_seqU.next(); if (valueU) { return valueU; } auto valueT = m_seqT.next(); if (!valueT) { m_seqT = Seq<T>(); m_seqU = Seq<U>(); return Nothing; } m_seqU = m_mapper(std::move(*valueT)); } } private: Mapper m_mapper; Seq<T> m_seqT; Seq<U> m_seqU; }; } // namespace detail template <typename T> Seq<T> drop(std::size_t n, Seq<T> seq) { if (n == 0) { return seq; } return makeSeq<detail::DropSeq<T>>(n, std::move(seq)); } template <typename T> Seq<T> take(std::size_t n, Seq<T> seq) { if (n == 0) { return Seq<T>(); } return makeSeq<detail::TakeSeq<T>>(n, std::move(seq)); } template <typename T, typename Predicate> Seq<T> dropWhile(Seq<T> seq, Predicate &&pred) { return makeSeq<detail::DropWhileSeq<Decay<Predicate>, T>>( std::move(seq), std::forward<Predicate>(pred)); } template <typename T, typename Predicate> Seq<T> takeWhile(Seq<T> seq, Predicate &&pred) { return makeSeq<detail::TakeWhileSeq<Decay<Predicate>, T>>( std::move(seq), std::forward<Predicate>(pred)); } template <typename T, typename Mapper> Seq<Decay<typename std::result_of<Mapper(T)>::type>> map(Seq<T> seq, Mapper &&mapper) { return makeSeq<detail::MapSeq<Decay<Mapper>, T>>( std::move(seq), std::forward<Mapper>(mapper)); } template <typename... Ts, typename Zipper> Seq<Decay<typename std::result_of<Zipper(Ts...)>::type>> zipWith(Zipper &&zipper, Seq<Ts>... seqs) { return makeSeq<detail::ZipWithSeq<Decay<Zipper>, Ts...>>( std::forward<Zipper>(zipper), std::move(seqs)...); } template <typename T, typename Predicate> Seq<T> filter(Seq<T> seq, Predicate &&pred) { return makeSeq<detail::FilterSeq<Decay<Predicate>, T>>( std::move(seq), std::forward<Predicate>(pred)); } template <typename T> Seq<T> join(Seq<Seq<T>> seqs) { return makeSeq<detail::JoinSeq<T>>(std::move(seqs)); } template <typename T, typename... Ts> Seq<T> concat(Seq<T> seq, Seq<Ts>... seqs) { return makeSeq<detail::ConcatSeq<T, sizeof...(Ts) + 1>>(std::move(seq), std::move(seqs)...); } template <typename T, typename Mapper> Seq<typename std::result_of<Mapper(T)>::type::ValueType> mapcat(Seq<T> seq, Mapper &&mapper) { return makeSeq<detail::MapcatSeq<Decay<Mapper>, T>>( std::move(seq), std::forward<Mapper>(mapper)); } template <typename T, typename Mapper> Seq<typename std::result_of<Mapper(T)>::type::ValueType> mapMaybe(Seq<T> seq, Mapper &&mapper) { using U = typename std::result_of<Mapper(T)>::type::ValueType; return seq::map( seq::filter(seq::map(std::move(seq), std::forward<Mapper>(mapper)), [](const Maybe<U> &x) { return !!x; }), [](Maybe<U> &&x) { return std::move(*x); }); } template <typename T> Seq<T> cycle(Seq<T> seq) { return seq::join(seq::repeat(std::move(seq))); } template <typename T, typename U> Seq<T> cast(Seq<U> seq) { return seq::map(std::move(seq), [](U &&x) { return static_cast<T>(std::move(x)); }); } } // namespace seq } // namespace rc <|endoftext|>
<commit_before>/** * @file llleap_test.cpp * @author Nat Goodspeed * @date 2012-02-21 * @brief Test for llleap. * * $LicenseInfo:firstyear=2012&license=viewerlgpl$ * Copyright (c) 2012, Linden Research, Inc. * $/LicenseInfo$ */ // Precompiled header #include "linden_common.h" // associated header #include "llleap.h" // STL headers // std headers // external library headers #include <boost/assign/list_of.hpp> #include <boost/lambda/lambda.hpp> #include <boost/foreach.hpp> // other Linden headers #include "../test/lltut.h" #include "../test/namedtempfile.h" #include "../test/manageapr.h" #include "../test/catch_and_store_what_in.h" #include "wrapllerrs.h" #include "llevents.h" #include "llprocess.h" #include "stringize.h" #include "StringVec.h" using boost::assign::list_of; static ManageAPR manager; StringVec sv(const StringVec& listof) { return listof; } #if defined(LL_WINDOWS) #define sleep(secs) _sleep((secs) * 1000) #endif void waitfor(const std::vector<LLLeap*>& instances) { int i, timeout = 60; for (i = 0; i < timeout; ++i) { // Every iteration, test whether any of the passed LLLeap instances // still exist (are still running). std::vector<LLLeap*>::const_iterator vli(instances.begin()), vlend(instances.end()); for ( ; vli != vlend; ++vli) { // getInstance() returns NULL if it's terminated/gone, non-NULL if // it's still running if (LLLeap::getInstance(*vli)) break; } // If we made it through all of 'instances' without finding one that's // still running, we're done. if (vli == vlend) return; // Found an instance that's still running. Wait and pump LLProcess. sleep(1); LLEventPumps::instance().obtain("mainloop").post(LLSD()); } tut::ensure("timed out without terminating", i < timeout); } void waitfor(LLLeap* instance) { std::vector<LLLeap*> instances; instances.push_back(instance); waitfor(instances); } /***************************************************************************** * TUT *****************************************************************************/ namespace tut { struct llleap_data { llleap_data(): reader(".py", // This logic is adapted from vita.viewerclient.receiveEvent() "import sys\n" "LEFTOVER = ''\n" "class ProtocolError(Exception):\n" " pass\n" "def get():\n" " global LEFTOVER\n" " hdr = LEFTOVER\n" " if ':' not in hdr:\n" " hdr += sys.stdin.read(20)\n" " if not hdr:\n" " sys.exit(0)\n" " parts = hdr.split(':', 1)\n" " if len(parts) != 2:\n" " raise ProtocolError('Expected len:data, got %r' % hdr)\n" " try:\n" " length = int(parts[0])\n" " except ValueError:\n" " raise ProtocolError('Non-numeric len %r' % parts[0])\n" " del parts[0]\n" " received = len(parts[0])\n" " while received < length:\n" " parts.append(sys.stdin.read(length - received))\n" " received += len(parts[-1])\n" " if received > length:\n" " excess = length - received\n" " LEFTOVER = parts[-1][excess:]\n" " parts[-1] = parts[-1][:excess]\n" " data = ''.join(parts)\n" " assert len(data) == length\n" " return data\n"), // Get the actual pathname of the NamedExtTempFile and trim off // the ".py" extension. (We could cache reader.getName() in a // separate member variable, but I happen to know getName() just // returns a NamedExtTempFile member rather than performing any // computation, so I don't mind calling it twice.) Then take the // basename. reader_module(LLProcess::basename( reader.getName().substr(0, reader.getName().length()-3))), pPYTHON(getenv("PYTHON")), PYTHON(pPYTHON? pPYTHON : "") { ensure("Set PYTHON to interpreter pathname", pPYTHON); } NamedExtTempFile reader; const std::string reader_module; const char* pPYTHON; const std::string PYTHON; }; typedef test_group<llleap_data> llleap_group; typedef llleap_group::object object; llleap_group llleapgrp("llleap"); template<> template<> void object::test<1>() { set_test_name("multiple LLLeap instances"); NamedTempFile script("py", "import time\n" "time.sleep(1)\n"); std::vector<LLLeap*> instances; instances.push_back(LLLeap::create(get_test_name(), sv(list_of(PYTHON)(script.getName())))); instances.push_back(LLLeap::create(get_test_name(), sv(list_of(PYTHON)(script.getName())))); // In this case we're simply establishing that two LLLeap instances // can coexist without throwing exceptions or bombing in any other // way. Wait for them to terminate. waitfor(instances); } template<> template<> void object::test<2>() { set_test_name("stderr to log"); NamedTempFile script("py", "import sys\n" "sys.stderr.write('''Hello from Python!\n" "note partial line''')\n"); CaptureLog log(LLError::LEVEL_INFO); waitfor(LLLeap::create(get_test_name(), sv(list_of(PYTHON)(script.getName())))); log.messageWith("Hello from Python!"); log.messageWith("note partial line"); } template<> template<> void object::test<3>() { set_test_name("empty plugin vector"); std::string threw; try { LLLeap::create("empty", StringVec()); } CATCH_AND_STORE_WHAT_IN(threw, LLLeap::Error) ensure_contains("LLLeap::Error", threw, "no plugin"); // try the suppress-exception variant ensure("bad launch returned non-NULL", ! LLLeap::create("empty", StringVec(), false)); } template<> template<> void object::test<4>() { set_test_name("bad launch"); // Synthesize bogus executable name std::string BADPYTHON(PYTHON.substr(0, PYTHON.length()-1) + "x"); CaptureLog log; std::string threw; try { LLLeap::create("bad exe", BADPYTHON); } CATCH_AND_STORE_WHAT_IN(threw, LLLeap::Error) ensure_contains("LLLeap::create() didn't throw", threw, "failed"); log.messageWith("failed"); log.messageWith(BADPYTHON); // try the suppress-exception variant ensure("bad launch returned non-NULL", ! LLLeap::create("bad exe", BADPYTHON, false)); } // Mimic a dummy little LLEventAPI that merely sends a reply back to its // requester on the "reply" pump. struct API { API(): mPump("API", true) { mPump.listen("API", boost::bind(&API::entry, this, _1)); } bool entry(const LLSD& request) { LLEventPumps::instance().obtain(request["reply"]).post("ack"); return false; } LLEventStream mPump; }; template<> template<> void object::test<5>() { set_test_name("round trip"); API api; NamedTempFile script("py", boost::lambda::_1 << "import re\n" "import sys\n" "from " << reader_module << " import get\n" // this will throw if the initial write to stdin // doesn't follow len:data protocol "initial = get()\n" "match = re.search(r\"'pump':'(.*?)'\", initial)\n" // this will throw if we couldn't find // 'pump':'etc.' in the initial write "reply = match.group(1)\n" "req = '''\\\n" "{'pump':'" << api.mPump.getName() << "','data':{'reply':'%s'}}\\\n" "''' % reply\n" // make a request on our little API "sys.stdout.write(':'.join((str(len(req)), req)))\n" "sys.stdout.flush()\n" // wait for its response "resp = get()\n" // it would be cleverer to be order-insensitive // about 'data' and 'pump'; hopefully the C++ // serializer doesn't change its rules soon "result = 'good' if (resp == \"{'data':'ack','pump':'%s'}\" % reply)\\\n" " else 'bad: ' + resp\n" // write 'good' or 'bad' to the log so we can observe "sys.stderr.write(result)\n"); CaptureLog log(LLError::LEVEL_INFO); waitfor(LLLeap::create(get_test_name(), sv(list_of(PYTHON)(script.getName())))); log.messageWith("good"); } } // namespace tut <commit_msg>Refactor llleap_test.cpp to streamline adding more unit tests. Migrate logic from specific test to common reader module, notably parsing the wakeup message containing the reply-pump name. Make test script post to Result struct to communicate success/failure to C++ TUT test, rather than just writing to log. Make test script insensitive to key order in serialized LLSD::Map.<commit_after>/** * @file llleap_test.cpp * @author Nat Goodspeed * @date 2012-02-21 * @brief Test for llleap. * * $LicenseInfo:firstyear=2012&license=viewerlgpl$ * Copyright (c) 2012, Linden Research, Inc. * $/LicenseInfo$ */ // Precompiled header #include "linden_common.h" // associated header #include "llleap.h" // STL headers // std headers // external library headers #include <boost/assign/list_of.hpp> #include <boost/lambda/lambda.hpp> #include <boost/foreach.hpp> // other Linden headers #include "../test/lltut.h" #include "../test/namedtempfile.h" #include "../test/manageapr.h" #include "../test/catch_and_store_what_in.h" #include "wrapllerrs.h" #include "llevents.h" #include "llprocess.h" #include "stringize.h" #include "StringVec.h" using boost::assign::list_of; static ManageAPR manager; StringVec sv(const StringVec& listof) { return listof; } #if defined(LL_WINDOWS) #define sleep(secs) _sleep((secs) * 1000) #endif void waitfor(const std::vector<LLLeap*>& instances) { int i, timeout = 60; for (i = 0; i < timeout; ++i) { // Every iteration, test whether any of the passed LLLeap instances // still exist (are still running). std::vector<LLLeap*>::const_iterator vli(instances.begin()), vlend(instances.end()); for ( ; vli != vlend; ++vli) { // getInstance() returns NULL if it's terminated/gone, non-NULL if // it's still running if (LLLeap::getInstance(*vli)) break; } // If we made it through all of 'instances' without finding one that's // still running, we're done. if (vli == vlend) return; // Found an instance that's still running. Wait and pump LLProcess. sleep(1); LLEventPumps::instance().obtain("mainloop").post(LLSD()); } tut::ensure("timed out without terminating", i < timeout); } void waitfor(LLLeap* instance) { std::vector<LLLeap*> instances; instances.push_back(instance); waitfor(instances); } /***************************************************************************** * TUT *****************************************************************************/ namespace tut { struct llleap_data { llleap_data(): reader(".py", // This logic is adapted from vita.viewerclient.receiveEvent() "import re\n" "import sys\n" "LEFTOVER = ''\n" "class ProtocolError(Exception):\n" " pass\n" "def get():\n" " global LEFTOVER\n" " hdr = LEFTOVER\n" " if ':' not in hdr:\n" " hdr += sys.stdin.read(20)\n" " if not hdr:\n" " sys.exit(0)\n" " parts = hdr.split(':', 1)\n" " if len(parts) != 2:\n" " raise ProtocolError('Expected len:data, got %r' % hdr)\n" " try:\n" " length = int(parts[0])\n" " except ValueError:\n" " raise ProtocolError('Non-numeric len %r' % parts[0])\n" " del parts[0]\n" " received = len(parts[0])\n" " while received < length:\n" " parts.append(sys.stdin.read(length - received))\n" " received += len(parts[-1])\n" " if received > length:\n" " excess = length - received\n" " LEFTOVER = parts[-1][excess:]\n" " parts[-1] = parts[-1][:excess]\n" " data = ''.join(parts)\n" " assert len(data) == length\n" " return data\n" "\n" "def put(req):\n" " sys.stdout.write(':'.join((str(len(req)), req)))\n" " sys.stdout.flush()\n" "\n" "# deal with initial stdin message\n" // this will throw if the initial write to stdin // doesn't follow len:data protocol "_initial = get()\n" "_match = re.search(r\"'pump':'(.*?)'\", _initial)\n" // this will throw if we couldn't find // 'pump':'etc.' in the initial write "_reply = _match.group(1)\n" "\n" "def replypump():\n" " return _reply\n" "\n" "def escape(str):\n" " return ''.join(('\\\\'+c if c in r\"\\'\" else c) for c in str)\n" "\n" "def quote(str):\n" " return \"'%s'\" % escape(str)\n"), // Get the actual pathname of the NamedExtTempFile and trim off // the ".py" extension. (We could cache reader.getName() in a // separate member variable, but I happen to know getName() just // returns a NamedExtTempFile member rather than performing any // computation, so I don't mind calling it twice.) Then take the // basename. reader_module(LLProcess::basename( reader.getName().substr(0, reader.getName().length()-3))), pPYTHON(getenv("PYTHON")), PYTHON(pPYTHON? pPYTHON : "") { ensure("Set PYTHON to interpreter pathname", pPYTHON); } NamedExtTempFile reader; const std::string reader_module; const char* pPYTHON; const std::string PYTHON; }; typedef test_group<llleap_data> llleap_group; typedef llleap_group::object object; llleap_group llleapgrp("llleap"); template<> template<> void object::test<1>() { set_test_name("multiple LLLeap instances"); NamedTempFile script("py", "import time\n" "time.sleep(1)\n"); std::vector<LLLeap*> instances; instances.push_back(LLLeap::create(get_test_name(), sv(list_of(PYTHON)(script.getName())))); instances.push_back(LLLeap::create(get_test_name(), sv(list_of(PYTHON)(script.getName())))); // In this case we're simply establishing that two LLLeap instances // can coexist without throwing exceptions or bombing in any other // way. Wait for them to terminate. waitfor(instances); } template<> template<> void object::test<2>() { set_test_name("stderr to log"); NamedTempFile script("py", "import sys\n" "sys.stderr.write('''Hello from Python!\n" "note partial line''')\n"); CaptureLog log(LLError::LEVEL_INFO); waitfor(LLLeap::create(get_test_name(), sv(list_of(PYTHON)(script.getName())))); log.messageWith("Hello from Python!"); log.messageWith("note partial line"); } template<> template<> void object::test<3>() { set_test_name("empty plugin vector"); std::string threw; try { LLLeap::create("empty", StringVec()); } CATCH_AND_STORE_WHAT_IN(threw, LLLeap::Error) ensure_contains("LLLeap::Error", threw, "no plugin"); // try the suppress-exception variant ensure("bad launch returned non-NULL", ! LLLeap::create("empty", StringVec(), false)); } template<> template<> void object::test<4>() { set_test_name("bad launch"); // Synthesize bogus executable name std::string BADPYTHON(PYTHON.substr(0, PYTHON.length()-1) + "x"); CaptureLog log; std::string threw; try { LLLeap::create("bad exe", BADPYTHON); } CATCH_AND_STORE_WHAT_IN(threw, LLLeap::Error) ensure_contains("LLLeap::create() didn't throw", threw, "failed"); log.messageWith("failed"); log.messageWith(BADPYTHON); // try the suppress-exception variant ensure("bad launch returned non-NULL", ! LLLeap::create("bad exe", BADPYTHON, false)); } // Generic self-contained listener: derive from this and override its // call() method, then tell somebody to post on the pump named getName(). // Control will reach your call() override. struct ListenerBase { // Pass the pump name you want; will tweak for uniqueness. ListenerBase(const std::string& name): mPump(name, true) { mPump.listen(name, boost::bind(&ListenerBase::call, this, _1)); } virtual bool call(const LLSD& request) { return false; } LLEventPump& getPump() { return mPump; } const LLEventPump& getPump() const { return mPump; } std::string getName() const { return mPump.getName(); } void post(const LLSD& data) { mPump.post(data); } LLEventStream mPump; }; // Mimic a dummy little LLEventAPI that merely sends a reply back to its // requester on the "reply" pump. struct API: public ListenerBase { API(): ListenerBase("API") {} virtual bool call(const LLSD& request) { LLEventPumps::instance().obtain(request["reply"]).post("ack"); return false; } }; // Give LLLeap script a way to post success/failure. struct Result: public ListenerBase { Result(): ListenerBase("Result") {} virtual bool call(const LLSD& request) { mData = request; return false; } void ensure() const { tut::ensure(std::string("never posted to ") + getName(), mData.isDefined()); // Post an empty string for success, non-empty string is failure message. tut::ensure(mData, mData.asString().empty()); } LLSD mData; }; template<> template<> void object::test<5>() { set_test_name("round trip"); API api; Result result; NamedTempFile script("py", boost::lambda::_1 << "import sys\n" "from " << reader_module << " import *\n" // make a request on our little API "put(\"{'pump':'" << api.getName() << "','data':{'reply':'%s'}}\" %\n" " replypump())\n" // wait for its response "resp = get()\n" // We expect "{'data':'ack','pump':'%s'}", but // don't depend on the order of the keys. "result = 'bad: ' + resp\n" "if resp.startswith('{') and resp.endswith('}'):\n" " expect = set((\"'data':'ack'\", \"'pump':'%s'\" % replypump()))\n" " actual = set(resp[1:-1].split(','))\n" " if actual == expect:\n" " result = ''\n" "put(\"{'pump':'" << result.getName() << "','data':%s}\" %\n" " quote(result))\n"); waitfor(LLLeap::create(get_test_name(), sv(list_of(PYTHON)(script.getName())))); result.ensure(); } } // namespace tut <|endoftext|>
<commit_before>#include <tiramisu/tiramisu.h> #include "configure.h" using namespace tiramisu; int main(int argc, char **argv) { init("conv_tiramisu"); // ------------------------------------------------------- // Layer I // ------------------------------------------------------- var x("x", 0, N), y("y", 0, N), n("n", 0, BATCH_SIZE); var k_x("k_x", 0, K), k_y("k_y", 0, K); var fin_b("fin_b", 0, FIN_NB_BLOCKS), ffin("ffin", 0, FIN_BLOCKING); var fout_b("fout_b", 0, FOUT_NB_BLOCKS), ffout("ffout", 0, FOUT_BLOCKING); var x_pad("x_pad", 0, N + 2), y_pad("y_pad", 0, N + 2); input c_input("c_input", {n, fin_b, y_pad, x_pad, ffin}, p_float32); input filter("filter", {fout_b, fin_b, k_y, k_x, ffin, ffout}, p_float32); input bias("bias", {fout_b, ffout}, p_float32); computation conv_init("conv_init", {n, y, fout_b, x, ffout}, bias(fout_b, ffout)); view conv_out("conv_out", {n, y, x, fout_b, ffout}, p_float32); // x_bound is used to have the width dimension divisible by X_BLOCKING // in the conv computation. var x_bound("x_bound", 0, X_BOUND); var x_conclude("x_conclude", X_BOUND, N); /* Pattern 0 * * 1 1 1 * 0 0 0 * 0 0 0 * */ computation conv_P0( "conv_P0", {n, y, fin_b, x_bound, ffin, fout_b, ffout}, ((fin_b*FIN_BLOCKING + ffin) >= ZERO_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL) && ((fin_b*FIN_BLOCKING + ffin) < ZERO_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL + PATTERN_0_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL), conv_out(n, y, x_bound, fout_b, ffout) + filter(fout_b, fin_b, 0, 0, ffin, ffout) * c_input(n, fin_b, y + 0, x_bound + 0, ffin) + filter(fout_b, fin_b, 0, 1, ffin, ffout) * c_input(n, fin_b, y + 0, x_bound + 1, ffin) + filter(fout_b, fin_b, 0, 2, ffin, ffout) * c_input(n, fin_b, y + 0, x_bound + 2, ffin)); // Compute convolution from 0 to x_bound computation conv( "conv", {n, y, fin_b, x_bound, k_y, k_x, ffin, fout_b, ffout}, (fin_b*FIN_BLOCKING + ffin) >= ZERO_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL + PATTERN_0_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL, conv_out(n, y, x_bound, fout_b, ffout) + filter(fout_b, fin_b, k_y, k_x, ffin, ffout) * c_input(n, fin_b, y + k_y, x_bound + k_x, ffin) ); // Compute convolution from x_bound to N computation conv_conclude( "conv_conclude", {n, y, fin_b, k_y, k_x, ffin, fout_b, ffout, x_conclude}, (fin_b*FIN_BLOCKING + ffin) >= ZERO_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL, conv_out(n, y, x_conclude, fout_b, ffout) + filter(fout_b, fin_b, k_y, k_x, ffin, ffout) * c_input(n, fin_b, y + k_y, x_conclude + k_x, ffin) ); // ------------------------------------------------------- // Layer II // ------------------------------------------------------- // schedule for conv computation // We introduce those two computations to do register blocking computation reg_load( "reg_load", {n, y, fin_b, x_bound, fout_b, ffout}, conv_init(n, y, fout_b, x_bound, ffout) ); computation reg_store( "reg_store", {n, y, fin_b, x_bound, fout_b, ffout}, conv(n, y, fin_b, x_bound, 0, 0, 0, fout_b, ffout) ); // Split over dimension x var x_b, xx; conv.split(x_bound, X_BLOCKING, x_b, xx); conv_P0.split(x_bound, X_BLOCKING, x_b, xx); conv.interchange(xx, k_y); conv.interchange(xx, k_x); conv.interchange(xx, ffin); conv.interchange(xx, fout_b); conv.interchange(xx, ffout); conv_P0.interchange(xx, ffin); conv_P0.interchange(xx, fout_b); conv_P0.interchange(xx, ffout); reg_load.split(x_bound, X_BLOCKING, x_b, xx); reg_store.split(x_bound, X_BLOCKING, x_b, xx); reg_load.interchange(xx, fout_b); reg_load.interchange(xx, ffout); reg_store.interchange(xx, fout_b); reg_store.interchange(xx, ffout); // Vectorize and unroll reg_load.tag_vector_level(ffout, FOUT_BLOCKING); conv.tag_vector_level(ffout, FOUT_BLOCKING); conv_P0.tag_vector_level(ffout, FOUT_BLOCKING); reg_store.tag_vector_level(ffout, FOUT_BLOCKING); conv.tag_unroll_level(xx); conv.tag_unroll_level(fout_b); conv_P0.tag_unroll_level(xx); conv_P0.tag_unroll_level(fout_b); reg_load.tag_unroll_level(xx); reg_load.tag_unroll_level(fout_b); reg_store.tag_unroll_level(xx); reg_store.tag_unroll_level(fout_b); // schedule for conv_conclude // This schedule is the same as conv computation computation reg_load_conclude( "reg_load_conclude", {n, y, fin_b, fout_b, ffout, x_conclude}, conv_init(n, y, fout_b, x_conclude, ffout) ); computation reg_store_conclude( "reg_store_conclude", {n, y, fin_b, fout_b, ffout, x_conclude}, conv_conclude(n, y, fin_b, 0, 0, 0, fout_b, ffout, x_conclude) ); reg_load_conclude.tag_vector_level(ffout, FOUT_BLOCKING); conv_conclude.tag_vector_level(ffout, FOUT_BLOCKING); reg_store_conclude.tag_vector_level(ffout, FOUT_BLOCKING); conv_conclude.tag_unroll_level(x_conclude); conv_conclude.tag_unroll_level(fout_b); reg_load_conclude.tag_unroll_level(x_conclude); reg_load_conclude.tag_unroll_level(fout_b); reg_store_conclude.tag_unroll_level(x_conclude); reg_store_conclude.tag_unroll_level(fout_b); // Parallelize and order conv.tag_parallel_level(y); conv.tag_parallel_level(n); conv_init.then(reg_load, y) .then(conv_P0, x_b) .then(conv, x_b) .then(reg_store, x_b) .then(reg_load_conclude, y) .then(conv_conclude, fin_b) .then(reg_store_conclude, fin_b); // ------------------------------------------------------- // Layer III // ------------------------------------------------------- buffer conv_buf("conv_buf", {BATCH_SIZE, FOUT_NB_BLOCKS, N, N, FOUT_BLOCKING}, p_float32, a_output); // This is where intermediate results of convolution will be stored. // We rely on the compiler to detect that this buffer can be mapped to CPU registers. buffer reg_buf("reg_buf", {FOUT_NB_BLOCKS, X_BLOCKING, FOUT_BLOCKING}, p_float32, a_temporary); conv_init.store_in(&conv_buf, {n, fout_b, y, x, ffout}); conv_out.store_in(&reg_buf, {fout_b, x%X_BLOCKING, ffout}); reg_load.store_in(&reg_buf, {fout_b, x_bound%X_BLOCKING, ffout}); conv.store_in(&reg_buf, {fout_b, x_bound%X_BLOCKING, ffout}); conv_P0.store_in(&reg_buf, {fout_b, x_bound%X_BLOCKING, ffout}); reg_store.store_in(&conv_buf, {n, fout_b, y, x_bound, ffout}); reg_load_conclude.store_in(&reg_buf, {fout_b, x_conclude%X_BLOCKING, ffout}); conv_conclude.store_in(&reg_buf, {fout_b, x_conclude%X_BLOCKING, ffout}); reg_store_conclude.store_in(&conv_buf, {n, fout_b, y, x_conclude, ffout}); // ------------------------------------------------------- // Code Generation // ------------------------------------------------------- tiramisu::codegen({ c_input.get_buffer(), filter.get_buffer(), bias.get_buffer(), &conv_buf },"generated_conv_layer.o"); return 0; } <commit_msg>Add pattern 1 to sparse_with_dense<commit_after>#include <tiramisu/tiramisu.h> #include "configure.h" using namespace tiramisu; int main(int argc, char **argv) { init("conv_tiramisu"); // ------------------------------------------------------- // Layer I // ------------------------------------------------------- var x("x", 0, N), y("y", 0, N), n("n", 0, BATCH_SIZE); var k_x("k_x", 0, K), k_y("k_y", 0, K); var fin_b("fin_b", 0, FIN_NB_BLOCKS), ffin("ffin", 0, FIN_BLOCKING); var fout_b("fout_b", 0, FOUT_NB_BLOCKS), ffout("ffout", 0, FOUT_BLOCKING); var x_pad("x_pad", 0, N + 2), y_pad("y_pad", 0, N + 2); input c_input("c_input", {n, fin_b, y_pad, x_pad, ffin}, p_float32); input filter("filter", {fout_b, fin_b, k_y, k_x, ffin, ffout}, p_float32); input bias("bias", {fout_b, ffout}, p_float32); computation conv_init("conv_init", {n, y, fout_b, x, ffout}, bias(fout_b, ffout)); view conv_out("conv_out", {n, y, x, fout_b, ffout}, p_float32); // x_bound is used to have the width dimension divisible by X_BLOCKING // in the conv computation. var x_bound("x_bound", 0, X_BOUND); var x_conclude("x_conclude", X_BOUND, N); /* Pattern 0 * * 1 1 1 * 0 0 0 * 0 0 0 * */ computation conv_P0( "conv_P0", {n, y, fin_b, x_bound, ffin, fout_b, ffout}, ((fin_b*FIN_BLOCKING + ffin) >= ZERO_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL) && ((fin_b*FIN_BLOCKING + ffin) < ZERO_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL + PATTERN_0_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL), conv_out(n, y, x_bound, fout_b, ffout) + filter(fout_b, fin_b, 0, 0, ffin, ffout) * c_input(n, fin_b, y + 0, x_bound + 0, ffin) + filter(fout_b, fin_b, 0, 1, ffin, ffout) * c_input(n, fin_b, y + 0, x_bound + 1, ffin) + filter(fout_b, fin_b, 0, 2, ffin, ffout) * c_input(n, fin_b, y + 0, x_bound + 2, ffin)); /* Pattern 1 * * 0 0 0 * 1 1 1 * 0 0 0 * */ computation conv_P1( "conv_P1", {n, y, fin_b, x_bound, ffin, fout_b, ffout}, ((fin_b*FIN_BLOCKING + ffin) >= ZERO_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL + PATTERN_0_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL) && ((fin_b*FIN_BLOCKING + ffin) < ZERO_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL + PATTERN_0_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL + PATTERN_1_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL), conv_out(n, y, x_bound, fout_b, ffout) + filter(fout_b, fin_b, 1, 0, ffin, ffout) * c_input(n, fin_b, y + 1, x_bound + 0, ffin) + filter(fout_b, fin_b, 1, 1, ffin, ffout) * c_input(n, fin_b, y + 1, x_bound + 1, ffin) + filter(fout_b, fin_b, 1, 2, ffin, ffout) * c_input(n, fin_b, y + 1, x_bound + 2, ffin)); // Compute convolution from 0 to x_bound computation conv( "conv", {n, y, fin_b, x_bound, k_y, k_x, ffin, fout_b, ffout}, (fin_b*FIN_BLOCKING + ffin) >= ZERO_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL + PATTERN_0_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL + PATTERN_1_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL, conv_out(n, y, x_bound, fout_b, ffout) + filter(fout_b, fin_b, k_y, k_x, ffin, ffout) * c_input(n, fin_b, y + k_y, x_bound + k_x, ffin) ); // Compute convolution from x_bound to N computation conv_conclude( "conv_conclude", {n, y, fin_b, k_y, k_x, ffin, fout_b, ffout, x_conclude}, (fin_b*FIN_BLOCKING + ffin) >= ZERO_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL, conv_out(n, y, x_conclude, fout_b, ffout) + filter(fout_b, fin_b, k_y, k_x, ffin, ffout) * c_input(n, fin_b, y + k_y, x_conclude + k_x, ffin) ); // ------------------------------------------------------- // Layer II // ------------------------------------------------------- // schedule for conv computation // We introduce those two computations to do register blocking computation reg_load( "reg_load", {n, y, fin_b, x_bound, fout_b, ffout}, conv_init(n, y, fout_b, x_bound, ffout) ); computation reg_store( "reg_store", {n, y, fin_b, x_bound, fout_b, ffout}, conv(n, y, fin_b, x_bound, 0, 0, 0, fout_b, ffout) ); // Split over dimension x var x_b, xx; conv.split(x_bound, X_BLOCKING, x_b, xx); conv_P0.split(x_bound, X_BLOCKING, x_b, xx); conv_P1.split(x_bound, X_BLOCKING, x_b, xx); conv.interchange(xx, k_y); conv.interchange(xx, k_x); conv.interchange(xx, ffin); conv.interchange(xx, fout_b); conv.interchange(xx, ffout); conv_P0.interchange(xx, ffin); conv_P0.interchange(xx, fout_b); conv_P0.interchange(xx, ffout); conv_P1.interchange(xx, ffin); conv_P1.interchange(xx, fout_b); conv_P1.interchange(xx, ffout); reg_load.split(x_bound, X_BLOCKING, x_b, xx); reg_store.split(x_bound, X_BLOCKING, x_b, xx); reg_load.interchange(xx, fout_b); reg_load.interchange(xx, ffout); reg_store.interchange(xx, fout_b); reg_store.interchange(xx, ffout); // Vectorize and unroll reg_load.tag_vector_level(ffout, FOUT_BLOCKING); conv.tag_vector_level(ffout, FOUT_BLOCKING); conv_P0.tag_vector_level(ffout, FOUT_BLOCKING); conv_P1.tag_vector_level(ffout, FOUT_BLOCKING); reg_store.tag_vector_level(ffout, FOUT_BLOCKING); conv.tag_unroll_level(xx); conv.tag_unroll_level(fout_b); conv_P0.tag_unroll_level(xx); conv_P0.tag_unroll_level(fout_b); conv_P1.tag_unroll_level(xx); conv_P1.tag_unroll_level(fout_b); reg_load.tag_unroll_level(xx); reg_load.tag_unroll_level(fout_b); reg_store.tag_unroll_level(xx); reg_store.tag_unroll_level(fout_b); // schedule for conv_conclude // This schedule is the same as conv computation computation reg_load_conclude( "reg_load_conclude", {n, y, fin_b, fout_b, ffout, x_conclude}, conv_init(n, y, fout_b, x_conclude, ffout) ); computation reg_store_conclude( "reg_store_conclude", {n, y, fin_b, fout_b, ffout, x_conclude}, conv_conclude(n, y, fin_b, 0, 0, 0, fout_b, ffout, x_conclude) ); reg_load_conclude.tag_vector_level(ffout, FOUT_BLOCKING); conv_conclude.tag_vector_level(ffout, FOUT_BLOCKING); reg_store_conclude.tag_vector_level(ffout, FOUT_BLOCKING); conv_conclude.tag_unroll_level(x_conclude); conv_conclude.tag_unroll_level(fout_b); reg_load_conclude.tag_unroll_level(x_conclude); reg_load_conclude.tag_unroll_level(fout_b); reg_store_conclude.tag_unroll_level(x_conclude); reg_store_conclude.tag_unroll_level(fout_b); // Parallelize and order conv.tag_parallel_level(y); conv.tag_parallel_level(n); conv_init.then(reg_load, y) .then(conv_P0, x_b) .then(conv_P1, x_b) .then(conv, x_b) .then(reg_store, x_b) .then(reg_load_conclude, y) .then(conv_conclude, fin_b) .then(reg_store_conclude, fin_b); // ------------------------------------------------------- // Layer III // ------------------------------------------------------- buffer conv_buf("conv_buf", {BATCH_SIZE, FOUT_NB_BLOCKS, N, N, FOUT_BLOCKING}, p_float32, a_output); // This is where intermediate results of convolution will be stored. // We rely on the compiler to detect that this buffer can be mapped to CPU registers. buffer reg_buf("reg_buf", {FOUT_NB_BLOCKS, X_BLOCKING, FOUT_BLOCKING}, p_float32, a_temporary); conv_init.store_in(&conv_buf, {n, fout_b, y, x, ffout}); conv_out.store_in(&reg_buf, {fout_b, x%X_BLOCKING, ffout}); reg_load.store_in(&reg_buf, {fout_b, x_bound%X_BLOCKING, ffout}); conv.store_in(&reg_buf, {fout_b, x_bound%X_BLOCKING, ffout}); conv_P0.store_in(&reg_buf, {fout_b, x_bound%X_BLOCKING, ffout}); conv_P1.store_in(&reg_buf, {fout_b, x_bound%X_BLOCKING, ffout}); reg_store.store_in(&conv_buf, {n, fout_b, y, x_bound, ffout}); reg_load_conclude.store_in(&reg_buf, {fout_b, x_conclude%X_BLOCKING, ffout}); conv_conclude.store_in(&reg_buf, {fout_b, x_conclude%X_BLOCKING, ffout}); reg_store_conclude.store_in(&conv_buf, {n, fout_b, y, x_conclude, ffout}); // ------------------------------------------------------- // Code Generation // ------------------------------------------------------- tiramisu::codegen({ c_input.get_buffer(), filter.get_buffer(), bias.get_buffer(), &conv_buf },"generated_conv_layer.o"); return 0; } <|endoftext|>
<commit_before>#include <nds.h> #include <stdio.h> #include "panel.h" #include "ball.h" #include "stats.h" #include "game.h" #define ERR_INIT_SBOX_FAILED 1 #define COLOR_BLACK 0 int main(void) { panel player1; panel player2; ball gameBall; scoreBox sBox; if(!initScoreBox(&sBox)) exit(ERR_INIT_SBOX_FAILED); int score[2] = {1,2}; setScore(&sBox, score); // consoleDemoInit(); initGame(&player1, &player2, &gameBall); videoSetMode(MODE_FB0); vramSetBankA(VRAM_A_LCD); printf("%d : %d",sBox.score[0],sBox.score[1]); while(1) { drawObject(player1.box, COLOR_BLACK); drawObject(player2.box, COLOR_BLACK); drawObject(gameBall.box, COLOR_BLACK); drawObject(player1.box, player1.color); drawObject(player2.box, player2.color); drawObject(gameBall.box, gameBall.color); movePanelOne(&player1, 0); movePanelTwo(&player2, 0); swiWaitForVBlank(); //consoleClear(); } return 0; } <commit_msg>removed error flag<commit_after>#include <nds.h> #include <stdio.h> #include "panel.h" #include "ball.h" #include "stats.h" #include "game.h" #define COLOR_BLACK 0 int main(void) { panel player1; panel player2; ball gameBall; scoreBox sBox; if(!initScoreBox(&sBox)) exit(1); int score[2] = {1,2}; setScore(&sBox, score); // consoleDemoInit(); initGame(&player1, &player2, &gameBall); videoSetMode(MODE_FB0); vramSetBankA(VRAM_A_LCD); printf("%d : %d",sBox.score[0],sBox.score[1]); while(1) { drawObject(player1.box, COLOR_BLACK); drawObject(player2.box, COLOR_BLACK); drawObject(gameBall.box, COLOR_BLACK); drawObject(player1.box, player1.color); drawObject(player2.box, player2.color); drawObject(gameBall.box, gameBall.color); movePanelOne(&player1, 0); movePanelTwo(&player2, 0); swiWaitForVBlank(); //consoleClear(); } return 0; } <|endoftext|>
<commit_before>//#define BOOST_ASIO_SEPARATE_COMPILATION #include <boost/thread.hpp> #include <boost/bind.hpp> #include <boost/asio.hpp> #include <iostream> using namespace std; using namespace boost::asio; io_service service; ip::tcp::socket sock(service); char buff_read[1024], buff_write[1024] = "ok"; void on_read(const boost::system::error_code &err, std::size_t bytes); void on_write(const boost::system::error_code &err, std::size_t bytes) { sock.async_read_some(buffer(buff_read), on_read); } void on_read(const boost::system::error_code &err, std::size_t bytes) { // ... process the read ... sock.async_write_some(buffer(buff_write, 3), on_write); } void on_connect(const boost::system::error_code &err) { sock.async_read_some(buffer(buff_read), on_read); } /* service.run(), . , on_connect, . on_connect (read). on_read, , (write). on_write, , . on_write (read). , . */ int main(int argc, char* argv[]) { setlocale(LC_ALL, "Russian"); std::cout << " CLIENT" << endl; ip::tcp::endpoint ep(ip::address::from_string("127.0.0.1"), 2001); sock.async_connect(ep, on_connect); service.run(); } // : /*using boost::asio; typedef boost::shared_ptr<ip::tcp::socket> socket_ptr; io_service service; ip::tcp::endpoint ep(ip::tcp::v4(), 2001)); // listen on 2001 ip::tcp::acceptor acc(service, ep); socket_ptr sock(new ip::tcp::socket(service)); start_accept(sock); service.run(); void start_accept(socket_ptr sock) { acc.async_accept(*sock, boost::bind(handle_accept, sock, _1)); } void handle_accept(socket_ptr sock, const boost::system::error_code & err) { if (err) return; // at this point, you can read/write to the socket socket_ptr sock(new ip::tcp::socket(service)); start_accept(sock); }*/ //------------------------------------- /*, 100 : bool read = false; void deadline_handler(const boost::system::error_code &) { std::cout << (read ? "read successfully" : "read failed") << std::endl; } void read_handler(const boost::system::error_code &) { read = true; } ip::tcp::socket sock(service); read = false; char data[512]; sock.async_read_some(buffer(data, 512)); deadline_timer t(service, boost::posix_time::milliseconds(100)); t.async_wait(&deadline_handler); service.run(); */ /* .run() , , service.run() , . . connect_handler, . , : typedef boost::shared_ptr<io_service::work> work_ptr; work_ptr dummy_work(new io_service::work(service_)); service_.run() useservice_.stop() dummy_work.reset(0); // destroy dummy_work. */<commit_msg>udp client<commit_after>// Client #ifdef WIN32 #define _WIN32_WINNT 0x0501 #include <stdio.h> #endif #include <boost/thread.hpp> #include <boost/bind.hpp> #include <boost/asio.hpp> #include <boost/shared_ptr.hpp> #include <boost/enable_shared_from_this.hpp> using namespace boost::asio; io_service service; ip::udp::endpoint ep(ip::address::from_string("127.0.0.1"), 8001); void sync_echo(std::string msg) { ip::udp::socket sock(service, ip::udp::endpoint(ip::udp::v4(), 0)); sock.send_to(buffer(msg), ep); char buff[1024]; ip::udp::endpoint sender_ep; int bytes = sock.receive_from(buffer(buff), sender_ep); std::string copy(buff, bytes); std::cout << "server echoed our " << msg << ": " << (copy == msg ? "OK" : "FAIL") << std::endl; sock.close(); } int main(int argc, char* argv[]) { // connect several clients char* messages[] = { "John says hi", "so does James", "Lucy just got home", 0 }; boost::thread_group threads; for (char ** message = messages; *message; ++message) { threads.create_thread(boost::bind(sync_echo, *message)); boost::this_thread::sleep(boost::posix_time::millisec(100)); } threads.join_all(); //system("pause"); //return 1; } /*#ifdef WIN32 #define _WIN32_WINNT 0x0501 #include <stdio.h> #endif #include <boost/thread.hpp> #include <boost/bind.hpp> #include <boost/asio.hpp> #include <boost/shared_ptr.hpp> #include <boost/enable_shared_from_this.hpp> using namespace boost::asio; io_service service; ip::udp::endpoint ep(ip::address::from_string("127.0.0.1"), 8001); void sync_echo(std::string msg) { ip::udp::socket sock(service, ip::udp::endpoint(ip::udp::v4(), 0)); sock.send_to(buffer(msg), ep); char buff[1024]; ip::udp::endpoint sender_ep; int bytes = sock.receive_from(buffer(buff), sender_ep); std::string copy(buff, bytes); std::cout << "server echoed our " << msg << ": " << (copy == msg ? "OK" : "FAIL") << std::endl; sock.close(); } int main(int argc, char* argv[]) { // connect several clients char* messages[] = { "John says hi", "so does James", "Lucy just got home", 0 }; boost::thread_group threads; for (char ** message = messages; *message; ++message) { threads.create_thread(boost::bind(sync_echo, *message)); boost::this_thread::sleep(boost::posix_time::millisec(100)); } threads.join_all(); }*/ //#define BOOST_ASIO_SEPARATE_COMPILATION ///------------------------------------- /* #include <boost/thread.hpp> #include <boost/bind.hpp> #include <boost/asio.hpp> #include <iostream> using namespace std; using namespace boost::asio; io_service service; void handle_connections() { char buff[1024]; ip::udp::socket sock(service, ip::udp::endpoint(ip::udp::v4(), 8001)); while (true) { ip::udp::endpoint sender_ep; int bytes = sock.receive_from(buffer(buff), sender_ep); std::string msg(buff, bytes); sock.send_to(buffer(msg), sender_ep); } } int main(int argc, char* argv[]) { std::cout << "UDP Server is start" << endl; handle_connections(); return 0; } */ /* ///-------------------------------------///------------------------------------- struct connection : boost::enable_shared_from_this<connection> { typedef boost::system::error_code error_code; typedef boost::shared_ptr<connection> ptr; connection() : sock_(service), started_(true) {} void start(ip::tcp::endpoint ep) { sock_.async_connect(ep, boost::bind(&connection::on_connect, shared_from_this(), _1)); } void stop() { if (!started_) return; started_ = false; sock_.close(); } bool started() { return started_; } private: void on_connect(const error_code & err) { // here you decide what to do with the connection: read or write if (!err) do_read(); else stop(); } void on_read(const error_code & err, size_t bytes) { if (!started()) return; std::string msg(read_buffer_, bytes); if (msg == "can_login") do_write("access_data"); else if (msg.find("data ") == 0) process_data(msg); else if (msg == "login_fail") stop(); } void on_write(const error_code & err, size_t bytes) { do_read(); } void do_read() { sock_.async_read_some(buffer(read_buffer_), boost::bind(&connection::on_read, shared_from_this(), _1, _2)); } void do_write(const std::string & msg) { if (!started()) return; // note: in case you want to send several messages before // doing another async_read, you'll need several write buffers! std::copy(msg.begin(), msg.end(), write_buffer_); sock_.async_write_some(buffer(write_buffer_, msg.size()), boost::bind(&connection::on_write, shared_from_this(), _1, _2)); } void process_data(const std::string & msg) { // process what comes from server, and then perform another write } private: ip::tcp::socket sock_; enum { max_msg = 1024 }; char read_buffer_[max_msg]; char write_buffer_[max_msg]; bool started_; }; int main(int argc, char* argv[]) { ip::tcp::endpoint ep(ip::address::from_string("127.0.0.1"), 8001); connection::ptr(new connection)->start(ep); system("pause"); }*/ ///-------------------------------------///------------------------------------- /*char buff_read[1024], buff_write[1024] = "ok"; void on_read(const boost::system::error_code &err, std::size_t bytes); void on_write(const boost::system::error_code &err, std::size_t bytes) { sock.async_read_some(buffer(buff_read), on_read); } void on_read(const boost::system::error_code &err, std::size_t bytes) { // ... process the read ... sock.async_write_some(buffer(buff_write, 3), on_write); } void on_connect(const boost::system::error_code &err) { sock.async_read_some(buffer(buff_read), on_read); }*/ /* service.run(), . , on_connect, . on_connect (read). on_read, , (write). on_write, , . on_write (read). , . */ /*int main(int argc, char* argv[]) { setlocale(LC_ALL, "Russian"); std::cout << " CLIENT" << endl; ip::tcp::endpoint ep(ip::address::from_string("127.0.0.1"), 2001); sock.async_connect(ep, on_connect); service.run(); }*/ // : /*using boost::asio; typedef boost::shared_ptr<ip::tcp::socket> socket_ptr; io_service service; ip::tcp::endpoint ep(ip::tcp::v4(), 2001)); // listen on 2001 ip::tcp::acceptor acc(service, ep); socket_ptr sock(new ip::tcp::socket(service)); start_accept(sock); service.run(); void start_accept(socket_ptr sock) { acc.async_accept(*sock, boost::bind(handle_accept, sock, _1)); } void handle_accept(socket_ptr sock, const boost::system::error_code & err) { if (err) return; // at this point, you can read/write to the socket socket_ptr sock(new ip::tcp::socket(service)); start_accept(sock); }*/ //------------------------------------- /*, 100 : bool read = false; void deadline_handler(const boost::system::error_code &) { std::cout << (read ? "read successfully" : "read failed") << std::endl; } void read_handler(const boost::system::error_code &) { read = true; } ip::tcp::socket sock(service); read = false; char data[512]; sock.async_read_some(buffer(data, 512)); deadline_timer t(service, boost::posix_time::milliseconds(100)); t.async_wait(&deadline_handler); service.run(); */ /* .run() , , service.run() , . . connect_handler, . , : typedef boost::shared_ptr<io_service::work> work_ptr; work_ptr dummy_work(new io_service::work(service_)); service_.run() useservice_.stop() dummy_work.reset(0); // destroy dummy_work. */<|endoftext|>
<commit_before>/** * Usage: ./Bat [options] * * Options: * -h, --help Displays this help. * -v, --version Displays version information. * -t, --title <title> Sets the window title on start. * -s, --size <WxH> Sets the BAT window size. * -d, --document <path/to/file.html> The path to the document you want BAT to * load. * -u, --undecorate Starts BAT with an undecorated window. * -m, --most If TOP is provided, then the window is * keept on the top of the other windows. If * BOTTOM is provided, the window will be in * the behind of all windows. * --debug Starts BAT in the debug mode. * */ #include <QApplication> #include "mainwindow.h" #include <QtWidgets> #include <QWebFrame> #include <QWebInspector> QWebView *webView; bool debugMode = false; QStringList applicationArguments; /* * Javascript API * */ class BatJavaScriptOperations : public QObject { Q_OBJECT public: /* * Close window * BAT.closeWindow(); * **/ Q_INVOKABLE void closeWindow () { if (debugMode) { qDebug() << "[INFO] Closing window."; } webView->close(); } /* * Resize * BAT.resize(width, height); * **/ Q_INVOKABLE void resize (int width, int height) { if (debugMode) { qDebug() << "[INFO] Resizing window: width=" << width << "px; height=" << height << "px." ; } webView->resize(width, height); } /* * Set window flags * BAT.setWindowFlags (type) * - UNDECORATED * * */ Q_INVOKABLE void setWindowFlags (QString type) { if (debugMode) { qDebug() << "[INFO] Setting window flag: " << type; } QStringList options; options << "UNDECORATED" << "BOTTOM_MOST" << "TOP_MOST" << "REMOVE_MINIMIZE" << "REMOVE_MAXIMIZE" << "REMOVE_CLOSE" << "TOOLTIP"; switch (options.indexOf(type)) { case 0: webView->setWindowFlags(Qt::FramelessWindowHint | webView->windowFlags()); break; case 1: webView->setWindowFlags(Qt::WindowStaysOnBottomHint | webView->windowFlags()); break; case 2: webView->setWindowFlags(Qt::WindowStaysOnTopHint | webView->windowFlags()); break; case 3: webView->setWindowFlags(webView->windowFlags() & ~Qt::WindowMinimizeButtonHint); break; case 4: webView->setWindowFlags(webView->windowFlags() & ~Qt::WindowMaximizeButtonHint); break; case 5: webView->setWindowFlags(webView->windowFlags() & ~Qt::WindowCloseButtonHint); case 6: webView->setWindowFlags(webView->windowFlags() & ~Qt::ToolTip); break; // TODO Other cases } webView->show(); } /* * Set window state * BAT.setWindowState (value) * - MAXIMIZED * - MINIMIZED * - FULLSCREEN * - ACTIVE * */ Q_INVOKABLE void setWindowState (QString type) { if (debugMode) { qDebug() << "[INFO] Setting window state: " << type; } QStringList options; options << "MAXIMIZED" << "MINIMIZED" << "FULLSCREEN" << "ACTIVATE" << "RESTORED"; switch (options.indexOf(type)) { case 0: webView->setWindowState(Qt::WindowMaximized); break; case 1: webView->setWindowState(Qt::WindowMinimized); break; case 2: webView->setWindowState(Qt::WindowFullScreen); break; case 3: webView->setWindowState(Qt::WindowActive); break; case 4: webView->setWindowState(Qt::WindowNoState); break; } } /* * Get window size * BAT.getWindowSize () * */ Q_INVOKABLE QObject *getWindowSize () { if (debugMode) { qDebug() << "[INFO] Getting the window size."; } QObject *size = new QObject(); QSize winSize = webView->size(); size->setProperty("width", winSize.width()); size->setProperty("height", winSize.height()); return size; } /* * Get screen size * BAT.getScreenSize () * * */ Q_INVOKABLE QObject *getScreenSize () { if (debugMode) { qDebug() << "[INFO] Getting screen size."; } QObject *size = new QObject(); QSize screenSize = qApp->primaryScreen()->size(); size->setProperty("width", screenSize.width()); size->setProperty("height", screenSize.height()); return size; } /* * Set window position * BAT.setWindowPosition (left, top) * */ Q_INVOKABLE void setWindowPosition (int left, int top) { if (debugMode) { qDebug() << "[INFO] Setting the window position: left=" << left << "px; top=" << top << "px."; } webView->move(left, top); } /* * Get window position * BAT.getWindowPosition (left, top) * */ Q_INVOKABLE QObject *getWindowPosition () { if (debugMode) { qDebug() << "[INFO] Getting the window position."; } QObject *position = new QObject(); QPoint point = webView->pos(); position->setProperty("left", point.x()); position->setProperty("top", point.y()); return position; } /* * Get mouse position * BAT.getMousePosition() * * */ Q_INVOKABLE QObject *getMousePosition () { if (debugMode) { qDebug() << "[INFO] Getting the mouse position."; } QObject *position = new QObject(); QPoint point = QCursor::pos(); position->setProperty("left", point.x()); position->setProperty("top", point.y()); return position; } /* * Set mouse position * BAT.setMousePosition() * * */ Q_INVOKABLE void setMousePosition (int x, int y) { if (debugMode) { qDebug() << "[INFO] Setting the mouse position: x=" << x << "px; y=" << y << "px."; } QCursor::setPos(x, y); } /* * Creates a new window * BAT.newWindow(options); * */ // TODO Is this really needed? // Q_INVOKABLE void newWindow () { // QWindow newWindow = new QWindow(); // newWindow.show(); // } /* * Sets the title of the current window * BAT.setWindowTitle(newTitle) * * */ Q_INVOKABLE void setWindowTitle (QString newTitle) { if (debugMode) { qDebug() << "[INFO] Setting the window title: " << newTitle; } webView->setWindowTitle(newTitle); } /* * Writes content to file * BAT.writeFile (path, content); * * */ Q_INVOKABLE void writeFile (QString path, QString content) { if (debugMode) { qDebug() << "[INFO] Writting to file: " << path; } QFile file(path); if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) { if (debugMode) { qDebug() << "[WARNING] Cannot write file."; } return; } QTextStream out(&file); out << content; } /* * Returns the content content of a file * BAT.readFile (path); * * */ Q_INVOKABLE QString readFile (QString path) { if (debugMode) { qDebug() << "[INFO] Reading from file: " << path; } QFile file(path); if(!file.open(QIODevice::ReadOnly)) { if (debugMode) { qDebug() << "[WARNING] Cannot open file."; } return ""; } QTextStream in(&file); QString fileContent = in.readAll(); return fileContent; } /* * Debug * BAT.debug(message) * * */ Q_INVOKABLE void debug (QString message) { // if (debugMode) { // qDebug() << "[INFO] Printing debug message: " << message; // } qDebug() << message; } /* * Insepct element * BAT.inspectElement() * * */ Q_INVOKABLE void inspectElement () { if (debugMode) { qDebug() << "[INFO] Activating inspect element."; } webView->page()->settings()->setAttribute(QWebSettings::DeveloperExtrasEnabled, true); QWebInspector inspector; inspector.setPage(webView->page()); inspector.setVisible(true); } /* * Run bash commands * BAT.debug(command) * * */ Q_INVOKABLE QObject *runBash (QString command) { if (debugMode) { qDebug() << "[INFO] Running bash command: " << command; } QObject *bashOutput = new QObject(); QProcess process; process.start(command); // will wait forever until finished process.waitForFinished(-1); QString stdout = process.readAllStandardOutput(); QString stderr = process.readAllStandardError(); bashOutput->setProperty("stdout", stdout); bashOutput->setProperty("stderr", stderr); return bashOutput; } /* * Get application arguments * BAT.argv() * * */ Q_INVOKABLE QStringList argv () { if (debugMode) { qDebug() << "[INFO] Getting application arguments."; } return applicationArguments; } /* * Enable/Disable debug mode * BAT.setDebugMode(true/false) * * */ Q_INVOKABLE void setDebugMode (bool debug) { if (debugMode) { qDebug() << "[INFO] Setting debug mode: " << debug; } debugMode = debug; } /* * Get debug mode * BAT.getDebugMode(true/false) * * */ Q_INVOKABLE bool getDebugMode () { if (debugMode) { qDebug() << "[INFO] Getting debug mode."; } return debugMode; } /* * Get dirname * BAT.getDirname() * * */ Q_INVOKABLE QString getDirname () { if (debugMode) { qDebug() << "[INFO] Getting directory name."; } return QDir::current().absolutePath(); } }; int main(int argc, char *argv[]) { QApplication app(argc, argv); QWebView *view = new QWebView(); // Local storage QWebSettings *settings = view->settings(); settings->setAttribute(QWebSettings::LocalStorageEnabled, true); settings->setLocalStoragePath("/tmp"); QCoreApplication::setApplicationName("BAT"); QCoreApplication::setApplicationVersion("1.1.0"); // Defaults int WINDOW_WIDTH = 800; int WINDOW_HEIGHT = 600; // Save arguments applicationArguments = app.arguments(); // Parse command line arguments QCommandLineParser parser; parser.addHelpOption(); parser.addVersionOption(); QCommandLineOption titleOption(QStringList() << "t" << "title", "Sets the window title on start.", "title", "BAT"); parser.addOption(titleOption); QCommandLineOption sizeOption(QStringList() << "s" << "size", "Sets the BAT window size.", "WxH", QString::number(WINDOW_WIDTH) + "x" + QString::number(WINDOW_HEIGHT)); parser.addOption(sizeOption); QCommandLineOption sourceOption(QStringList() << "d" << "document", "The path to the document you want BAT to load.", "path/to/file.html", "~/.bat/welcome.html"); parser.addOption(sourceOption); QCommandLineOption undecorateOption(QStringList() << "u" << "undecorate", "Starts BAT with an undecorated window."); parser.addOption(undecorateOption); QCommandLineOption toolTipOption(QStringList() << "t" << "tooltip", "Starts BAT with a tooltip window."); parser.addOption(toolTipOption); QCommandLineOption positionMost(QStringList() << "m" << "most", "If TOP is provided, then the window is keept on the top of the other windows. If BOTTOM is provided, the window will be in the behind of all windows."); parser.addOption(positionMost); QCommandLineOption debugOption("debug", QCoreApplication::translate("main", "Starts BAT in the debug mode.")); parser.addOption(debugOption); parser.process(app); // Set the webview global webView = view; // Get the HTML path QString htmlPath = parser.value(sourceOption); // Handle local files if (!htmlPath.startsWith("http")) { // Absolute path if (htmlPath.startsWith("/")) { htmlPath = "file://" + htmlPath; } else if (htmlPath.startsWith("~")) { htmlPath = "file://" + htmlPath.replace(QRegularExpression("^~"), QDir::homePath()); } else { htmlPath = "file://" + QDir::current().absolutePath() + QDir::separator() + htmlPath; } } QString size = parser.value(sizeOption); // Get window width and height int windowWidth = size.split('x')[0].toInt(); int windowHeight = size.split('x')[1].toInt(); // Handle "UNDECORATED" flag if (parser.isSet(undecorateOption)) { QPalette pal = view->palette(); pal.setBrush(QPalette::Base, Qt::transparent); view->page()->setPalette(pal); view->setAttribute(Qt::WA_TranslucentBackground); view->setWindowFlags(Qt::FramelessWindowHint | view->windowFlags()); } // Tool tip if (parser.isSet(toolTipOption)) { view->setWindowFlags(Qt::ToolTip | view->windowFlags()); } // Handle the debug mode if (parser.isSet(debugOption)) { qDebug() << " * Debug mode."; debugMode = true; view->page()->settings()->setAttribute(QWebSettings::DeveloperExtrasEnabled, true); QWebInspector inspector; inspector.setPage(view->page()); inspector.setVisible(true); } QString btMost = parser.value(positionMost); if (btMost == "BOTTOM") { view->setWindowFlags(Qt::WindowStaysOnBottomHint | view->windowFlags()); } else if (btMost == "TOP") { view->setWindowFlags(Qt::WindowStaysOnTopHint | view->windowFlags()); } // Add the JavaScript API view->page()->mainFrame()->addToJavaScriptWindowObject("BAT", new BatJavaScriptOperations); view->resize(windowWidth, windowHeight); view->load(QUrl(htmlPath)); view->show(); webView->setWindowTitle(parser.value(titleOption)); return app.exec(); } #include "main.moc" <commit_msg>Fixed t conflict.<commit_after>/** * Usage: ./Bat [options] * * Options: * -h, --help Displays this help. * -v, --version Displays version information. * -t, --title <title> Sets the window title on start. * -s, --size <WxH> Sets the BAT window size. * -d, --document <path/to/file.html> The path to the document you want BAT to * load. * -u, --undecorate Starts BAT with an undecorated window. * -m, --most If TOP is provided, then the window is * keept on the top of the other windows. If * BOTTOM is provided, the window will be in * the behind of all windows. * --debug Starts BAT in the debug mode. * */ #include <QApplication> #include "mainwindow.h" #include <QtWidgets> #include <QWebFrame> #include <QWebInspector> QWebView *webView; bool debugMode = false; QStringList applicationArguments; /* * Javascript API * */ class BatJavaScriptOperations : public QObject { Q_OBJECT public: /* * Close window * BAT.closeWindow(); * **/ Q_INVOKABLE void closeWindow () { if (debugMode) { qDebug() << "[INFO] Closing window."; } webView->close(); } /* * Resize * BAT.resize(width, height); * **/ Q_INVOKABLE void resize (int width, int height) { if (debugMode) { qDebug() << "[INFO] Resizing window: width=" << width << "px; height=" << height << "px." ; } webView->resize(width, height); } /* * Set window flags * BAT.setWindowFlags (type) * - UNDECORATED * * */ Q_INVOKABLE void setWindowFlags (QString type) { if (debugMode) { qDebug() << "[INFO] Setting window flag: " << type; } QStringList options; options << "UNDECORATED" << "BOTTOM_MOST" << "TOP_MOST" << "REMOVE_MINIMIZE" << "REMOVE_MAXIMIZE" << "REMOVE_CLOSE" << "TOOLTIP"; switch (options.indexOf(type)) { case 0: webView->setWindowFlags(Qt::FramelessWindowHint | webView->windowFlags()); break; case 1: webView->setWindowFlags(Qt::WindowStaysOnBottomHint | webView->windowFlags()); break; case 2: webView->setWindowFlags(Qt::WindowStaysOnTopHint | webView->windowFlags()); break; case 3: webView->setWindowFlags(webView->windowFlags() & ~Qt::WindowMinimizeButtonHint); break; case 4: webView->setWindowFlags(webView->windowFlags() & ~Qt::WindowMaximizeButtonHint); break; case 5: webView->setWindowFlags(webView->windowFlags() & ~Qt::WindowCloseButtonHint); case 6: webView->setWindowFlags(webView->windowFlags() & ~Qt::ToolTip); break; // TODO Other cases } webView->show(); } /* * Set window state * BAT.setWindowState (value) * - MAXIMIZED * - MINIMIZED * - FULLSCREEN * - ACTIVE * */ Q_INVOKABLE void setWindowState (QString type) { if (debugMode) { qDebug() << "[INFO] Setting window state: " << type; } QStringList options; options << "MAXIMIZED" << "MINIMIZED" << "FULLSCREEN" << "ACTIVATE" << "RESTORED"; switch (options.indexOf(type)) { case 0: webView->setWindowState(Qt::WindowMaximized); break; case 1: webView->setWindowState(Qt::WindowMinimized); break; case 2: webView->setWindowState(Qt::WindowFullScreen); break; case 3: webView->setWindowState(Qt::WindowActive); break; case 4: webView->setWindowState(Qt::WindowNoState); break; } } /* * Get window size * BAT.getWindowSize () * */ Q_INVOKABLE QObject *getWindowSize () { if (debugMode) { qDebug() << "[INFO] Getting the window size."; } QObject *size = new QObject(); QSize winSize = webView->size(); size->setProperty("width", winSize.width()); size->setProperty("height", winSize.height()); return size; } /* * Get screen size * BAT.getScreenSize () * * */ Q_INVOKABLE QObject *getScreenSize () { if (debugMode) { qDebug() << "[INFO] Getting screen size."; } QObject *size = new QObject(); QSize screenSize = qApp->primaryScreen()->size(); size->setProperty("width", screenSize.width()); size->setProperty("height", screenSize.height()); return size; } /* * Set window position * BAT.setWindowPosition (left, top) * */ Q_INVOKABLE void setWindowPosition (int left, int top) { if (debugMode) { qDebug() << "[INFO] Setting the window position: left=" << left << "px; top=" << top << "px."; } webView->move(left, top); } /* * Get window position * BAT.getWindowPosition (left, top) * */ Q_INVOKABLE QObject *getWindowPosition () { if (debugMode) { qDebug() << "[INFO] Getting the window position."; } QObject *position = new QObject(); QPoint point = webView->pos(); position->setProperty("left", point.x()); position->setProperty("top", point.y()); return position; } /* * Get mouse position * BAT.getMousePosition() * * */ Q_INVOKABLE QObject *getMousePosition () { if (debugMode) { qDebug() << "[INFO] Getting the mouse position."; } QObject *position = new QObject(); QPoint point = QCursor::pos(); position->setProperty("left", point.x()); position->setProperty("top", point.y()); return position; } /* * Set mouse position * BAT.setMousePosition() * * */ Q_INVOKABLE void setMousePosition (int x, int y) { if (debugMode) { qDebug() << "[INFO] Setting the mouse position: x=" << x << "px; y=" << y << "px."; } QCursor::setPos(x, y); } /* * Creates a new window * BAT.newWindow(options); * */ // TODO Is this really needed? // Q_INVOKABLE void newWindow () { // QWindow newWindow = new QWindow(); // newWindow.show(); // } /* * Sets the title of the current window * BAT.setWindowTitle(newTitle) * * */ Q_INVOKABLE void setWindowTitle (QString newTitle) { if (debugMode) { qDebug() << "[INFO] Setting the window title: " << newTitle; } webView->setWindowTitle(newTitle); } /* * Writes content to file * BAT.writeFile (path, content); * * */ Q_INVOKABLE void writeFile (QString path, QString content) { if (debugMode) { qDebug() << "[INFO] Writting to file: " << path; } QFile file(path); if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) { if (debugMode) { qDebug() << "[WARNING] Cannot write file."; } return; } QTextStream out(&file); out << content; } /* * Returns the content content of a file * BAT.readFile (path); * * */ Q_INVOKABLE QString readFile (QString path) { if (debugMode) { qDebug() << "[INFO] Reading from file: " << path; } QFile file(path); if(!file.open(QIODevice::ReadOnly)) { if (debugMode) { qDebug() << "[WARNING] Cannot open file."; } return ""; } QTextStream in(&file); QString fileContent = in.readAll(); return fileContent; } /* * Debug * BAT.debug(message) * * */ Q_INVOKABLE void debug (QString message) { // if (debugMode) { // qDebug() << "[INFO] Printing debug message: " << message; // } qDebug() << message; } /* * Insepct element * BAT.inspectElement() * * */ Q_INVOKABLE void inspectElement () { if (debugMode) { qDebug() << "[INFO] Activating inspect element."; } webView->page()->settings()->setAttribute(QWebSettings::DeveloperExtrasEnabled, true); QWebInspector inspector; inspector.setPage(webView->page()); inspector.setVisible(true); } /* * Run bash commands * BAT.debug(command) * * */ Q_INVOKABLE QObject *runBash (QString command) { if (debugMode) { qDebug() << "[INFO] Running bash command: " << command; } QObject *bashOutput = new QObject(); QProcess process; process.start(command); // will wait forever until finished process.waitForFinished(-1); QString stdout = process.readAllStandardOutput(); QString stderr = process.readAllStandardError(); bashOutput->setProperty("stdout", stdout); bashOutput->setProperty("stderr", stderr); return bashOutput; } /* * Get application arguments * BAT.argv() * * */ Q_INVOKABLE QStringList argv () { if (debugMode) { qDebug() << "[INFO] Getting application arguments."; } return applicationArguments; } /* * Enable/Disable debug mode * BAT.setDebugMode(true/false) * * */ Q_INVOKABLE void setDebugMode (bool debug) { if (debugMode) { qDebug() << "[INFO] Setting debug mode: " << debug; } debugMode = debug; } /* * Get debug mode * BAT.getDebugMode(true/false) * * */ Q_INVOKABLE bool getDebugMode () { if (debugMode) { qDebug() << "[INFO] Getting debug mode."; } return debugMode; } /* * Get dirname * BAT.getDirname() * * */ Q_INVOKABLE QString getDirname () { if (debugMode) { qDebug() << "[INFO] Getting directory name."; } return QDir::current().absolutePath(); } }; int main(int argc, char *argv[]) { QApplication app(argc, argv); QWebView *view = new QWebView(); // Local storage QWebSettings *settings = view->settings(); settings->setAttribute(QWebSettings::LocalStorageEnabled, true); settings->setLocalStoragePath("/tmp"); QCoreApplication::setApplicationName("BAT"); QCoreApplication::setApplicationVersion("1.1.0"); // Defaults int WINDOW_WIDTH = 800; int WINDOW_HEIGHT = 600; // Save arguments applicationArguments = app.arguments(); // Parse command line arguments QCommandLineParser parser; parser.addHelpOption(); parser.addVersionOption(); QCommandLineOption titleOption(QStringList() << "t" << "title", "Sets the window title on start.", "title", "BAT"); parser.addOption(titleOption); QCommandLineOption sizeOption(QStringList() << "s" << "size", "Sets the BAT window size.", "WxH", QString::number(WINDOW_WIDTH) + "x" + QString::number(WINDOW_HEIGHT)); parser.addOption(sizeOption); QCommandLineOption sourceOption(QStringList() << "d" << "document", "The path to the document you want BAT to load.", "path/to/file.html", "~/.bat/welcome.html"); parser.addOption(sourceOption); QCommandLineOption undecorateOption(QStringList() << "u" << "undecorate", "Starts BAT with an undecorated window."); parser.addOption(undecorateOption); QCommandLineOption toolTipOption(QStringList() << "tt" << "tooltip", "Starts BAT with a tooltip window."); parser.addOption(toolTipOption); QCommandLineOption positionMost(QStringList() << "m" << "most", "If TOP is provided, then the window is keept on the top of the other windows. If BOTTOM is provided, the window will be in the behind of all windows."); parser.addOption(positionMost); QCommandLineOption debugOption("debug", QCoreApplication::translate("main", "Starts BAT in the debug mode.")); parser.addOption(debugOption); parser.process(app); // Set the webview global webView = view; // Get the HTML path QString htmlPath = parser.value(sourceOption); // Handle local files if (!htmlPath.startsWith("http")) { // Absolute path if (htmlPath.startsWith("/")) { htmlPath = "file://" + htmlPath; } else if (htmlPath.startsWith("~")) { htmlPath = "file://" + htmlPath.replace(QRegularExpression("^~"), QDir::homePath()); } else { htmlPath = "file://" + QDir::current().absolutePath() + QDir::separator() + htmlPath; } } QString size = parser.value(sizeOption); // Get window width and height int windowWidth = size.split('x')[0].toInt(); int windowHeight = size.split('x')[1].toInt(); // Handle "UNDECORATED" flag if (parser.isSet(undecorateOption)) { QPalette pal = view->palette(); pal.setBrush(QPalette::Base, Qt::transparent); view->page()->setPalette(pal); view->setAttribute(Qt::WA_TranslucentBackground); view->setWindowFlags(Qt::FramelessWindowHint | view->windowFlags()); } // Tool tip if (parser.isSet(toolTipOption)) { view->setWindowFlags(Qt::ToolTip | view->windowFlags()); } // Handle the debug mode if (parser.isSet(debugOption)) { qDebug() << " * Debug mode."; debugMode = true; view->page()->settings()->setAttribute(QWebSettings::DeveloperExtrasEnabled, true); QWebInspector inspector; inspector.setPage(view->page()); inspector.setVisible(true); } QString btMost = parser.value(positionMost); if (btMost == "BOTTOM") { view->setWindowFlags(Qt::WindowStaysOnBottomHint | view->windowFlags()); } else if (btMost == "TOP") { view->setWindowFlags(Qt::WindowStaysOnTopHint | view->windowFlags()); } // Add the JavaScript API view->page()->mainFrame()->addToJavaScriptWindowObject("BAT", new BatJavaScriptOperations); view->resize(windowWidth, windowHeight); view->load(QUrl(htmlPath)); view->show(); webView->setWindowTitle(parser.value(titleOption)); return app.exec(); } #include "main.moc" <|endoftext|>
<commit_before>//----------------------------------------------------------------------------- // Copyright (c) 2015, Jeff Hutchinson // 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 D3D11Test nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //----------------------------------------------------------------------------- #include <stdlib.h> #include <SDL.h> // SDL2 hack. #ifdef main #undef main #endif // main // Require MSVC compiler for this application #ifndef _MSC_VER #error "You must use MSVC to compile this application." #endif // _MSC_VER int main(int argc, const char **argv) { SDL_Init(SDL_INIT_VIDEO); SDL_Event event; bool running = true; while (running) { // Run event loop. while (SDL_PollEvent(&event)) { // check to see if we fired a quit event. If we did, we're done // running the program. if (event.type == SDL_QUIT) { running = false; break; } } } SDL_Quit(); return 0; }<commit_msg>create a window<commit_after>//----------------------------------------------------------------------------- // Copyright (c) 2015, Jeff Hutchinson // 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 D3D11Test nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //----------------------------------------------------------------------------- #include <stdlib.h> #include <SDL.h> // SDL2 hack. #ifdef main #undef main #endif // main // Require MSVC compiler for this application #ifndef _MSC_VER #error "You must use MSVC to compile this application." #endif // _MSC_VER int main(int argc, const char **argv) { SDL_Init(SDL_INIT_VIDEO); // create window SDL_Window *window = SDL_CreateWindow("D3D11 Test Application", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1366, 768, SDL_WINDOW_SHOWN); if (window == nullptr) { SDL_Quit(); return 1; } SDL_Event event; bool running = true; while (running) { // Run event loop. while (SDL_PollEvent(&event)) { // check to see if we fired a quit event. If we did, we're done // running the program. if (event.type == SDL_QUIT) { running = false; break; } } } SDL_Quit(); return 0; }<|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <string> #include <cstdlib> #include <cstdio> int getparam (std::string input) { if(input.size() <= 3) { return -1;} int result = 0; for (int i = 3; i < input.size(); i++) { if ( input[i] < '0' || input[i] > '9') { return -2; } result = result * 10; result += input[i] - '0'; } return result; } std::string getstringparam(std::string input) { std::string result; for (int i = 3; i < input.size(); i++) { result.push_back(input[i]); } return result; } void readpreset( unsigned int values[], std::string & filename ) { std::ifstream presetfile ("preset"); presetfile >> filename; for (int i = 0; i < 9; i++ ) { presetfile >> values[i]; } presetfile.close(); } void writepreset( unsigned int values[], std::string filename ) { std::ofstream presetfile ("preset"); presetfile << filename; for (int i = 0; i < 9; i++ ) { presetfile << values[i]; presetfile << "\n"; } presetfile.close(); } void writesh( unsigned int values[], std::string filename ) { std::ofstream shfile ("run.sh"); shfile << "ffmpeg -i " << filename << " -f flv -re "; if (values[0] != 0 && values[1] != 0) { shfile << "-s " << values[0] << "x" << values[1] << " "; } if (values[2] != 0) { shfile << "-b " << values[2] << " "; } if (values[3] != 0) { shfile << "-gop " << values[3] << " "; } if (values[4] != 0) { shfile << "-r " << values[4] << " "; } if (values[5] != 0) { shfile << "-ab " << values[5] << " "; } if (values[6] != 0) { shfile << "-ar " << values[6] << " "; } shfile << "rtmp://projectlivestream.com/oflaDemo/test"; shfile.close(); } int main() { unsigned int values[9]; std::string inputcommand = ""; bool connection = true; int tempresult; std::string filename = ""; readpreset(values, filename); while (connection) { std::cin >> inputcommand; switch (inputcommand[0]) { case 'G': switch (inputcommand[1]) { case 'S': switch(inputcommand[2]) { case 'H': std::cout << "OK" << values[0] << "\n"; break; case 'W': std::cout << "OK" << values[1] << "\n"; break; default: std::cout << "ER\n"; break; } break; case 'V': switch(inputcommand[2]) { case 'B': std::cout << "OK" << values[2] << "\n"; break; case 'G': std::cout << "OK" << values[3] << "\n"; break; case 'R': std::cout << "OK" << values[4] << "\n"; break; default: std::cout << "ER\n"; break; } break; case 'A': switch(inputcommand[2]) { case 'B': std::cout << "OK" << values[5] << "\n"; break; case 'R': std::cout << "OK" << values[6] << "\n"; break; default: std::cout << "ER\n"; break; } break; case 'U': switch(inputcommand[2]) { case 'F': std::cout << "OK" << values[7] << "\n"; break; case 'P': std::cout << "OK" << values[8] << "\n"; break; default: std::cout << "ER\n"; break; } break; case 'F': switch(inputcommand[2]) { case 'N': std::cout << "OK" << filename << "\n"; break; default: std::cout << "ER\n"; break; } break; default: std::cout << "ER\n"; break; } break; case 'S': switch (inputcommand[1]) { case 'S': switch(inputcommand[2]) { case 'H': tempresult = getparam(inputcommand); if (tempresult < 0) { std::cout << "ER\n"; } else { values[0] = tempresult; std::cout << "OK\n"; } break; case 'W': tempresult = getparam(inputcommand); tempresult = getparam(inputcommand); if (tempresult < 0) { std::cout << "ER\n"; } else { values[1] = tempresult; std::cout << "OK\n"; } break; default: std::cout << "ER\n"; break; } break; case 'V': switch(inputcommand[2]) { case 'B': tempresult = getparam(inputcommand); if (tempresult < 0) { std::cout << "ER\n"; } else { values[2] = tempresult; std::cout << "OK\n"; } break; case 'G': tempresult = getparam(inputcommand); if (tempresult < 0) { std::cout << "ER\n"; } else { values[3] = tempresult; std::cout << "OK\n"; } break; case 'R': tempresult = getparam(inputcommand); if (tempresult < 0) { std::cout << "ER\n"; } else { values[4] = tempresult; std::cout << "OK\n"; } break; default: std::cout << "ER\n"; break; } break; case 'A': switch(inputcommand[2]) { case 'B': tempresult = getparam(inputcommand); if (tempresult < 0) { std::cout << "ER\n"; } else { values[5] = tempresult; std::cout << "OK\n"; } break; case 'R': tempresult = getparam(inputcommand); if (tempresult < 0) { std::cout << "ER\n"; } else { values[6] = tempresult; std::cout << "OK\n"; } break; default: std::cout << "ER\n"; break; } break; case 'U': switch(inputcommand[2]) { case 'F': tempresult = getparam(inputcommand); if (tempresult < 0) { std::cout << "ER\n"; } else { values[7] = tempresult; std::cout << "OK\n"; } break; case 'P': tempresult = getparam(inputcommand); if (tempresult < 0) { std::cout << "ER\n"; } else { values[8] = tempresult; std::cout << "OK\n"; } break; default: std::cout << "ER\n"; break; } break; case 'F': switch(inputcommand[2]) { case 'N': filename = getstringparam(inputcommand); std::cout << "OK\n"; break; default: std::cout << "ER\n"; break; } break; default: std::cout << "ER\n"; break; } break; case 'C': switch (inputcommand[1] ) { case 'C': switch (inputcommand[2]) { case 'D': std::cout << "OK\n"; connection = false; break; default: std::cout << "ER\n"; break; } break; case 'S': switch (inputcommand[2]) { case 'R': std::cout << "OK\n"; readpreset(values, filename); break; case 'S': std::cout << "OK\n"; writepreset(values, filename); break; case 'A': std::cout << "OK\n"; writesh(values, filename); break; default: std::cout << "ER\n"; break; } break; default: std::cout << "ER\n"; break; } break; default: std::cout << "ER\n"; break; } } return 0; } <commit_msg>Daadwerkelijke restarten werkend en getest<commit_after>#include <iostream> #include <fstream> #include <string> #include <cstdlib> #include <cstdio> #include <stdlib.h> int getparam (std::string input) { if(input.size() <= 3) { return -1;} int result = 0; for (int i = 3; i < input.size(); i++) { if ( input[i] < '0' || input[i] > '9') { return -2; } result = result * 10; result += input[i] - '0'; } return result; } std::string getstringparam(std::string input) { std::string result; for (int i = 3; i < input.size(); i++) { result.push_back(input[i]); } return result; } void readpreset( unsigned int values[], std::string & filename ) { std::ifstream presetfile ("preset"); presetfile >> filename; for (int i = 0; i < 9; i++ ) { presetfile >> values[i]; } presetfile.close(); } void writepreset( unsigned int values[], std::string filename ) { std::ofstream presetfile ("preset"); presetfile << filename; for (int i = 0; i < 9; i++ ) { presetfile << values[i]; presetfile << "\n"; } presetfile.close(); } void writesh( unsigned int values[], std::string filename ) { std::ofstream shfile ("run.sh"); shfile << "ffmpeg -i " << filename << " -f flv -re "; if (values[0] != 0 && values[1] != 0) { shfile << "-s " << values[0] << "x" << values[1] << " "; } if (values[2] != 0) { shfile << "-b " << values[2] << " "; } if (values[3] != 0) { shfile << "-gop " << values[3] << " "; } if (values[4] != 0) { shfile << "-r " << values[4] << " "; } if (values[5] != 0) { shfile << "-ab " << values[5] << " "; } if (values[6] != 0) { shfile << "-ar " << values[6] << " "; } shfile << "rtmp://projectlivestream.com/oflaDemo/test &"; shfile.close(); system("sh ./run.sh"); } int main() { unsigned int values[9]; std::string inputcommand = ""; bool connection = true; int tempresult; std::string filename = ""; readpreset(values, filename); while (connection) { std::cin >> inputcommand; switch (inputcommand[0]) { case 'G': switch (inputcommand[1]) { case 'S': switch(inputcommand[2]) { case 'H': std::cout << "OK" << values[0] << "\n"; break; case 'W': std::cout << "OK" << values[1] << "\n"; break; default: std::cout << "ER\n"; break; } break; case 'V': switch(inputcommand[2]) { case 'B': std::cout << "OK" << values[2] << "\n"; break; case 'G': std::cout << "OK" << values[3] << "\n"; break; case 'R': std::cout << "OK" << values[4] << "\n"; break; default: std::cout << "ER\n"; break; } break; case 'A': switch(inputcommand[2]) { case 'B': std::cout << "OK" << values[5] << "\n"; break; case 'R': std::cout << "OK" << values[6] << "\n"; break; default: std::cout << "ER\n"; break; } break; case 'U': switch(inputcommand[2]) { case 'F': std::cout << "OK" << values[7] << "\n"; break; case 'P': std::cout << "OK" << values[8] << "\n"; break; default: std::cout << "ER\n"; break; } break; case 'F': switch(inputcommand[2]) { case 'N': std::cout << "OK" << filename << "\n"; break; default: std::cout << "ER\n"; break; } break; default: std::cout << "ER\n"; break; } break; case 'S': switch (inputcommand[1]) { case 'S': switch(inputcommand[2]) { case 'H': tempresult = getparam(inputcommand); if (tempresult < 0) { std::cout << "ER\n"; } else { values[0] = tempresult; std::cout << "OK\n"; } break; case 'W': tempresult = getparam(inputcommand); tempresult = getparam(inputcommand); if (tempresult < 0) { std::cout << "ER\n"; } else { values[1] = tempresult; std::cout << "OK\n"; } break; default: std::cout << "ER\n"; break; } break; case 'V': switch(inputcommand[2]) { case 'B': tempresult = getparam(inputcommand); if (tempresult < 0) { std::cout << "ER\n"; } else { values[2] = tempresult; std::cout << "OK\n"; } break; case 'G': tempresult = getparam(inputcommand); if (tempresult < 0) { std::cout << "ER\n"; } else { values[3] = tempresult; std::cout << "OK\n"; } break; case 'R': tempresult = getparam(inputcommand); if (tempresult < 0) { std::cout << "ER\n"; } else { values[4] = tempresult; std::cout << "OK\n"; } break; default: std::cout << "ER\n"; break; } break; case 'A': switch(inputcommand[2]) { case 'B': tempresult = getparam(inputcommand); if (tempresult < 0) { std::cout << "ER\n"; } else { values[5] = tempresult; std::cout << "OK\n"; } break; case 'R': tempresult = getparam(inputcommand); if (tempresult < 0) { std::cout << "ER\n"; } else { values[6] = tempresult; std::cout << "OK\n"; } break; default: std::cout << "ER\n"; break; } break; case 'U': switch(inputcommand[2]) { case 'F': tempresult = getparam(inputcommand); if (tempresult < 0) { std::cout << "ER\n"; } else { values[7] = tempresult; std::cout << "OK\n"; } break; case 'P': tempresult = getparam(inputcommand); if (tempresult < 0) { std::cout << "ER\n"; } else { values[8] = tempresult; std::cout << "OK\n"; } break; default: std::cout << "ER\n"; break; } break; case 'F': switch(inputcommand[2]) { case 'N': filename = getstringparam(inputcommand); std::cout << "OK\n"; break; default: std::cout << "ER\n"; break; } break; default: std::cout << "ER\n"; break; } break; case 'C': switch (inputcommand[1] ) { case 'C': switch (inputcommand[2]) { case 'D': std::cout << "OK\n"; connection = false; break; default: std::cout << "ER\n"; break; } break; case 'S': switch (inputcommand[2]) { case 'R': std::cout << "OK\n"; readpreset(values, filename); break; case 'S': std::cout << "OK\n"; writepreset(values, filename); break; case 'A': std::cout << "OK\n"; writesh(values, filename); break; default: std::cout << "ER\n"; break; } break; default: std::cout << "ER\n"; break; } break; default: std::cout << "ER\n"; break; } } return 0; } <|endoftext|>
<commit_before>// // Created by everettjf // Copyright © 2017 everettjf. All rights reserved. // #include "tablecontentview.h" #include "../../utility/utility.h" #include <QHBoxLayout> #include <QDebug> TableContentView::TableContentView(QWidget *parent) : ContentViewInterface(parent) { controller = nullptr; tableView = new QTableView(this); QHBoxLayout *layout = new QHBoxLayout(this); layout->setMargin(0); layout->addWidget(tableView); setLayout(layout); } void TableContentView::showViewData(moex::ViewData *data) { moex::TableViewData *node = static_cast<moex::TableViewData*>(data); if(controller) delete controller; controller = new TableContentController(); qDebug()<<data; qDebug()<<node; qDebug()<<controller; controller->InitModel(node); qDebug()<<"after"; tableView->setModel(controller->model()); tableView->setEditTriggers(QAbstractItemView::NoEditTriggers); for(uint32_t idx = 0; idx < node->widths.size(); ++idx){ tableView->setColumnWidth(idx,node->widths.at(idx)); } } <commit_msg>row height<commit_after>// // Created by everettjf // Copyright © 2017 everettjf. All rights reserved. // #include "tablecontentview.h" #include "../../utility/utility.h" #include <QHBoxLayout> #include <QDebug> #include <QHeaderView> TableContentView::TableContentView(QWidget *parent) : ContentViewInterface(parent) { controller = nullptr; tableView = new QTableView(this); QHBoxLayout *layout = new QHBoxLayout(this); layout->setMargin(0); layout->addWidget(tableView); setLayout(layout); QHeaderView *verticalHeader = tableView->verticalHeader(); verticalHeader->setSectionResizeMode(QHeaderView::Fixed); verticalHeader->setDefaultSectionSize(24); } void TableContentView::showViewData(moex::ViewData *data) { moex::TableViewData *node = static_cast<moex::TableViewData*>(data); if(controller) delete controller; controller = new TableContentController(); qDebug()<<data; qDebug()<<node; qDebug()<<controller; controller->InitModel(node); qDebug()<<"after"; tableView->setModel(controller->model()); tableView->setEditTriggers(QAbstractItemView::NoEditTriggers); for(uint32_t idx = 0; idx < node->widths.size(); ++idx){ tableView->setColumnWidth(idx,node->widths.at(idx)); } } <|endoftext|>
<commit_before>/*========================================================================= Library: CTK Copyright (c) Kitware Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.txt Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =========================================================================*/ // Qt includes #include <QSqlQuery> #include <QSqlRecord> #include <QVariant> #include <QDate> #include <QStringList> #include <QSet> #include <QFile> #include <QDirIterator> #include <QFileInfo> #include <QDebug> // ctkDICOMCore includes #include "ctkDICOMQuery.h" #include "ctkLogger.h" // DCMTK includes #ifndef WIN32 #define HAVE_CONFIG_H #endif #include "dcmtk/dcmnet/dimse.h" #include "dcmtk/dcmnet/diutil.h" #include <dcmtk/dcmdata/dcfilefo.h> #include <dcmtk/dcmdata/dcfilefo.h> #include <dcmtk/dcmdata/dcdeftag.h> #include <dcmtk/dcmdata/dcdatset.h> #include <dcmtk/ofstd/ofcond.h> #include <dcmtk/ofstd/ofstring.h> #include <dcmtk/ofstd/ofstd.h> /* for class OFStandard */ #include <dcmtk/dcmdata/dcddirif.h> /* for class DicomDirInterface */ #include <dcmtk/dcmnet/scu.h> static ctkLogger logger ( "org.commontk.dicom.DICOMQuery" ); //------------------------------------------------------------------------------ class ctkDICOMQueryPrivate { public: ctkDICOMQueryPrivate(); ~ctkDICOMQueryPrivate(); /// Add a StudyInstanceUID to be queried void addStudyInstanceUID(const QString& StudyInstanceUID ); QString CallingAETitle; QString CalledAETitle; QString Host; int Port; QMap<QString,QVariant> Filters; DcmSCU SCU; DcmDataset* Query; QStringList StudyInstanceUIDList; }; //------------------------------------------------------------------------------ // ctkDICOMQueryPrivate methods //------------------------------------------------------------------------------ ctkDICOMQueryPrivate::ctkDICOMQueryPrivate() { this->Query = new DcmDataset(); this->Port = 0; } //------------------------------------------------------------------------------ ctkDICOMQueryPrivate::~ctkDICOMQueryPrivate() { delete this->Query; } //------------------------------------------------------------------------------ void ctkDICOMQueryPrivate::addStudyInstanceUID( const QString& s ) { this->StudyInstanceUIDList.append ( s ); } //------------------------------------------------------------------------------ // ctkDICOMQuery methods //------------------------------------------------------------------------------ ctkDICOMQuery::ctkDICOMQuery(QObject* parentObject) : QObject(parentObject) , d_ptr(new ctkDICOMQueryPrivate) { } //------------------------------------------------------------------------------ ctkDICOMQuery::~ctkDICOMQuery() { } /// Set methods for connectivity //------------------------------------------------------------------------------ void ctkDICOMQuery::setCallingAETitle( const QString& callingAETitle ) { Q_D(ctkDICOMQuery); d->CallingAETitle = callingAETitle; } //------------------------------------------------------------------------------ QString ctkDICOMQuery::callingAETitle() const { Q_D(const ctkDICOMQuery); return d->CallingAETitle; } //------------------------------------------------------------------------------ void ctkDICOMQuery::setCalledAETitle( const QString& calledAETitle ) { Q_D(ctkDICOMQuery); d->CalledAETitle = calledAETitle; } //------------------------------------------------------------------------------ QString ctkDICOMQuery::calledAETitle()const { Q_D(const ctkDICOMQuery); return d->CalledAETitle; } //------------------------------------------------------------------------------ void ctkDICOMQuery::setHost( const QString& host ) { Q_D(ctkDICOMQuery); d->Host = host; } //------------------------------------------------------------------------------ QString ctkDICOMQuery::host() const { Q_D(const ctkDICOMQuery); return d->Host; } //------------------------------------------------------------------------------ void ctkDICOMQuery::setPort ( int port ) { Q_D(ctkDICOMQuery); d->Port = port; } //------------------------------------------------------------------------------ int ctkDICOMQuery::port()const { Q_D(const ctkDICOMQuery); return d->Port; } //------------------------------------------------------------------------------ void ctkDICOMQuery::setFilters( const QMap<QString,QVariant>& filters ) { Q_D(ctkDICOMQuery); d->Filters = filters; } //------------------------------------------------------------------------------ QMap<QString,QVariant> ctkDICOMQuery::filters()const { Q_D(const ctkDICOMQuery); return d->Filters; } //------------------------------------------------------------------------------ QStringList ctkDICOMQuery::studyInstanceUIDQueried()const { Q_D(const ctkDICOMQuery); return d->StudyInstanceUIDList; } //------------------------------------------------------------------------------ bool ctkDICOMQuery::query(ctkDICOMDatabase& database ) { // ctkDICOMDatabase::setDatabase ( database ); Q_D(ctkDICOMQuery); // In the following, we emit progress(int) after progress(QString), this // is in case the connected object doesn't refresh its ui when the progress // message is updated but only if the progress value is (e.g. QProgressDialog) if ( database.database().isOpen() ) { logger.debug ( "DB open in Query" ); emit progress("DB open in Query"); } else { logger.debug ( "DB not open in Query" ); emit progress("DB not open in Query"); } emit progress(0); d->StudyInstanceUIDList.clear(); d->SCU.setAETitle ( OFString(this->callingAETitle().toStdString().c_str()) ); d->SCU.setPeerAETitle ( OFString(this->calledAETitle().toStdString().c_str()) ); d->SCU.setPeerHostName ( OFString(this->host().toStdString().c_str()) ); d->SCU.setPeerPort ( this->port() ); logger.error ( "Setting Transfer Syntaxes" ); emit progress("Setting Transfer Syntaxes"); emit progress(10); OFList<OFString> transferSyntaxes; transferSyntaxes.push_back ( UID_LittleEndianExplicitTransferSyntax ); transferSyntaxes.push_back ( UID_BigEndianExplicitTransferSyntax ); transferSyntaxes.push_back ( UID_LittleEndianImplicitTransferSyntax ); d->SCU.addPresentationContext ( UID_FINDStudyRootQueryRetrieveInformationModel, transferSyntaxes ); // d->SCU.addPresentationContext ( UID_VerificationSOPClass, transferSyntaxes ); if ( !d->SCU.initNetwork().good() ) { logger.error( "Error initializing the network" ); emit progress("Error initializing the network"); emit progress(100); return false; } logger.debug ( "Negotiating Association" ); emit progress("Negatiating Association"); emit progress(20); OFCondition result = d->SCU.negotiateAssociation(); if (result.bad()) { logger.error( "Error negotiating the association: " + QString(result.text()) ); emit progress("Error negotiating the association"); emit progress(100); return false; } // Clear the query d->Query->clear(); // Insert all keys that we like to receive values for d->Query->insertEmptyElement ( DCM_PatientID ); d->Query->insertEmptyElement ( DCM_PatientName ); d->Query->insertEmptyElement ( DCM_PatientBirthDate ); d->Query->insertEmptyElement ( DCM_StudyID ); d->Query->insertEmptyElement ( DCM_StudyInstanceUID ); d->Query->insertEmptyElement ( DCM_StudyDescription ); d->Query->insertEmptyElement ( DCM_StudyDate ); d->Query->insertEmptyElement ( DCM_StudyTime ); d->Query->insertEmptyElement ( DCM_ModalitiesInStudy ); d->Query->insertEmptyElement ( DCM_AccessionNumber ); d->Query->insertEmptyElement ( DCM_NumberOfSeriesRelatedInstances ); // Number of images in the series d->Query->insertEmptyElement ( DCM_NumberOfStudyRelatedInstances ); // Number of images in the series d->Query->insertEmptyElement ( DCM_NumberOfStudyRelatedSeries ); // Number of images in the series // Make clear we define our search values in ISO Latin 1 (default would be ASCII) d->Query->putAndInsertOFStringArray(DCM_SpecificCharacterSet, "ISO_IR 100"); d->Query->putAndInsertString ( DCM_QueryRetrieveLevel, "STUDY" ); /* Now, for all keys that the user provided for filtering on STUDY level, * overwrite empty keys with value. For now, only Patient's Name, Patient ID, * Study Description, Modalities in Study, and Study Date are used. */ QString seriesDescription; foreach( QString key, d->Filters.keys() ) { if ( key == QString("Name") ) { // make the filter a wildcard in dicom style d->Query->putAndInsertString( DCM_PatientName, (QString("*") + d->Filters[key].toString() + QString("*")).toAscii().data()); } else if ( key == QString("Study") ) { // make the filter a wildcard in dicom style d->Query->putAndInsertString( DCM_StudyDescription, (QString("*") + d->Filters[key].toString() + QString("*")).toAscii().data()); } else if ( key == QString("ID") ) { // make the filter a wildcard in dicom style d->Query->putAndInsertString( DCM_PatientID, (QString("*") + d->Filters[key].toString() + QString("*")).toAscii().data()); } else if ( key == QString("Modalities") ) { // make the filter be an "OR" of modalities using backslash (dicom-style) QString modalitySearch(""); foreach (const QString& modality, d->Filters[key].toStringList()) { modalitySearch += modality + QString("\\"); } modalitySearch.chop(1); // remove final backslash logger.debug("modalityInStudySearch " + modalitySearch); d->Query->putAndInsertString( DCM_ModalitiesInStudy, modalitySearch.toAscii().data() ); } // Rememer Series Description for later series query if we go through the keys now else if ( key == QString("Series") ) { // make the filter a wildcard in dicom style seriesDescription = "*" + d->Filters[key].toString() + "*"; } else { logger.debug("Ignoring unknown search key: " + key); } } if ( d->Filters.keys().contains("StartDate") && d->Filters.keys().contains("EndDate") ) { QString dateRange = d->Filters["StartDate"].toString() + QString("-") + d->Filters["EndDate"].toString(); d->Query->putAndInsertString ( DCM_StudyDate, dateRange.toAscii().data() ); logger.debug("Query on study date " + dateRange); } emit progress(30); FINDResponses *responses = new FINDResponses(); Uint16 presentationContext = 0; // Check for any accepted presentation context for FIND in study root (dont care about transfer syntax) presentationContext = d->SCU.findPresentationContextID ( UID_FINDStudyRootQueryRetrieveInformationModel, ""); if ( presentationContext == 0 ) { logger.error ( "Failed to find acceptable presentation context" ); emit progress("Failed to find acceptable presentation context"); } else { logger.info ( "Found useful presentation context" ); emit progress("Found useful presentation context"); } emit progress(40); OFCondition status = d->SCU.sendFINDRequest ( presentationContext, d->Query, responses ); if ( !status.good() ) { logger.error ( "Find failed" ); emit progress("Find failed"); d->SCU.closeAssociation ( DCMSCU_RELEASE_ASSOCIATION ); emit progress(100); delete responses; return false; } logger.debug ( "Find succeded"); emit progress("Find succeded"); emit progress(50); for ( OFListIterator(FINDResponse*) it = responses->begin(); it != responses->end(); it++ ) { DcmDataset *dataset = (*it)->m_dataset; if ( dataset != NULL ) // the last response is always empty { database.insert ( dataset, false /* do not store to disk*/, false /* no thumbnail*/); OFString StudyInstanceUID; dataset->findAndGetOFString ( DCM_StudyInstanceUID, StudyInstanceUID ); d->addStudyInstanceUID ( StudyInstanceUID.c_str() ); } } delete responses; /* Only ask for series attributes now. This requires kicking out the rest of former query. */ d->Query->clear(); d->Query->insertEmptyElement ( DCM_SeriesNumber ); d->Query->insertEmptyElement ( DCM_SeriesDescription ); d->Query->insertEmptyElement ( DCM_SeriesInstanceUID ); d->Query->insertEmptyElement ( DCM_SeriesDate ); d->Query->insertEmptyElement ( DCM_SeriesTime ); d->Query->insertEmptyElement ( DCM_Modality ); /* Add user-defined filters */ d->Query->putAndInsertOFStringArray(DCM_SeriesDescription, seriesDescription.toLatin1().data()); // Now search each within each Study that was identified d->Query->putAndInsertString ( DCM_QueryRetrieveLevel, "SERIES" ); float progressRatio = 25. / d->StudyInstanceUIDList.count(); int i = 0; foreach ( QString StudyInstanceUID, d->StudyInstanceUIDList ) { logger.debug ( "Starting Series C-FIND for Study: " + StudyInstanceUID ); emit progress(QString("Starting Series C-FIND for Study: ") + StudyInstanceUID); emit progress(50 + (progressRatio * i++)); d->Query->putAndInsertString ( DCM_StudyInstanceUID, StudyInstanceUID.toStdString().c_str() ); responses = new FINDResponses(); status = d->SCU.sendFINDRequest ( presentationContext, d->Query, responses ); if ( status.good() ) { for ( OFListIterator(FINDResponse*) it = responses->begin(); it != responses->end(); it++ ) { DcmDataset *dataset = (*it)->m_dataset; if ( dataset != NULL ) { database.insert ( dataset, false /* do not store */, false /* no thumbnail */ ); } } logger.debug ( "Find succeded on Series level for Study: " + StudyInstanceUID ); emit progress(QString("Find succeded on Series level for Study: ") + StudyInstanceUID); } else { logger.error ( "Find on Series level failed for Study: " + StudyInstanceUID ); emit progress(QString("Find on Series level failed for Study: ") + StudyInstanceUID); } emit progress(50 + (progressRatio * i++)); delete responses; } d->SCU.closeAssociation ( DCMSCU_RELEASE_ASSOCIATION ); emit progress(100); return true; } <commit_msg>Fixed assignments of query attributs from study to series level. Prevented empty search fields to be padded with one or more asterisks (*).<commit_after>/*========================================================================= Library: CTK Copyright (c) Kitware Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.txt Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =========================================================================*/ // Qt includes #include <QSqlQuery> #include <QSqlRecord> #include <QVariant> #include <QDate> #include <QStringList> #include <QSet> #include <QFile> #include <QDirIterator> #include <QFileInfo> #include <QDebug> // ctkDICOMCore includes #include "ctkDICOMQuery.h" #include "ctkLogger.h" // DCMTK includes #ifndef WIN32 #define HAVE_CONFIG_H #endif #include "dcmtk/dcmnet/dimse.h" #include "dcmtk/dcmnet/diutil.h" #include <dcmtk/dcmdata/dcfilefo.h> #include <dcmtk/dcmdata/dcfilefo.h> #include <dcmtk/dcmdata/dcdeftag.h> #include <dcmtk/dcmdata/dcdatset.h> #include <dcmtk/ofstd/ofcond.h> #include <dcmtk/ofstd/ofstring.h> #include <dcmtk/ofstd/ofstd.h> /* for class OFStandard */ #include <dcmtk/dcmdata/dcddirif.h> /* for class DicomDirInterface */ #include <dcmtk/dcmnet/scu.h> static ctkLogger logger ( "org.commontk.dicom.DICOMQuery" ); //------------------------------------------------------------------------------ class ctkDICOMQueryPrivate { public: ctkDICOMQueryPrivate(); ~ctkDICOMQueryPrivate(); /// Add a StudyInstanceUID to be queried void addStudyInstanceUID(const QString& StudyInstanceUID ); QString CallingAETitle; QString CalledAETitle; QString Host; int Port; QMap<QString,QVariant> Filters; DcmSCU SCU; DcmDataset* Query; QStringList StudyInstanceUIDList; }; //------------------------------------------------------------------------------ // ctkDICOMQueryPrivate methods //------------------------------------------------------------------------------ ctkDICOMQueryPrivate::ctkDICOMQueryPrivate() { this->Query = new DcmDataset(); this->Port = 0; } //------------------------------------------------------------------------------ ctkDICOMQueryPrivate::~ctkDICOMQueryPrivate() { delete this->Query; } //------------------------------------------------------------------------------ void ctkDICOMQueryPrivate::addStudyInstanceUID( const QString& s ) { this->StudyInstanceUIDList.append ( s ); } //------------------------------------------------------------------------------ // ctkDICOMQuery methods //------------------------------------------------------------------------------ ctkDICOMQuery::ctkDICOMQuery(QObject* parentObject) : QObject(parentObject) , d_ptr(new ctkDICOMQueryPrivate) { } //------------------------------------------------------------------------------ ctkDICOMQuery::~ctkDICOMQuery() { } /// Set methods for connectivity //------------------------------------------------------------------------------ void ctkDICOMQuery::setCallingAETitle( const QString& callingAETitle ) { Q_D(ctkDICOMQuery); d->CallingAETitle = callingAETitle; } //------------------------------------------------------------------------------ QString ctkDICOMQuery::callingAETitle() const { Q_D(const ctkDICOMQuery); return d->CallingAETitle; } //------------------------------------------------------------------------------ void ctkDICOMQuery::setCalledAETitle( const QString& calledAETitle ) { Q_D(ctkDICOMQuery); d->CalledAETitle = calledAETitle; } //------------------------------------------------------------------------------ QString ctkDICOMQuery::calledAETitle()const { Q_D(const ctkDICOMQuery); return d->CalledAETitle; } //------------------------------------------------------------------------------ void ctkDICOMQuery::setHost( const QString& host ) { Q_D(ctkDICOMQuery); d->Host = host; } //------------------------------------------------------------------------------ QString ctkDICOMQuery::host() const { Q_D(const ctkDICOMQuery); return d->Host; } //------------------------------------------------------------------------------ void ctkDICOMQuery::setPort ( int port ) { Q_D(ctkDICOMQuery); d->Port = port; } //------------------------------------------------------------------------------ int ctkDICOMQuery::port()const { Q_D(const ctkDICOMQuery); return d->Port; } //------------------------------------------------------------------------------ void ctkDICOMQuery::setFilters( const QMap<QString,QVariant>& filters ) { Q_D(ctkDICOMQuery); d->Filters = filters; } //------------------------------------------------------------------------------ QMap<QString,QVariant> ctkDICOMQuery::filters()const { Q_D(const ctkDICOMQuery); return d->Filters; } //------------------------------------------------------------------------------ QStringList ctkDICOMQuery::studyInstanceUIDQueried()const { Q_D(const ctkDICOMQuery); return d->StudyInstanceUIDList; } //------------------------------------------------------------------------------ bool ctkDICOMQuery::query(ctkDICOMDatabase& database ) { // ctkDICOMDatabase::setDatabase ( database ); Q_D(ctkDICOMQuery); // In the following, we emit progress(int) after progress(QString), this // is in case the connected object doesn't refresh its ui when the progress // message is updated but only if the progress value is (e.g. QProgressDialog) if ( database.database().isOpen() ) { logger.debug ( "DB open in Query" ); emit progress("DB open in Query"); } else { logger.debug ( "DB not open in Query" ); emit progress("DB not open in Query"); } emit progress(0); d->StudyInstanceUIDList.clear(); d->SCU.setAETitle ( OFString(this->callingAETitle().toStdString().c_str()) ); d->SCU.setPeerAETitle ( OFString(this->calledAETitle().toStdString().c_str()) ); d->SCU.setPeerHostName ( OFString(this->host().toStdString().c_str()) ); d->SCU.setPeerPort ( this->port() ); logger.error ( "Setting Transfer Syntaxes" ); emit progress("Setting Transfer Syntaxes"); emit progress(10); OFList<OFString> transferSyntaxes; transferSyntaxes.push_back ( UID_LittleEndianExplicitTransferSyntax ); transferSyntaxes.push_back ( UID_BigEndianExplicitTransferSyntax ); transferSyntaxes.push_back ( UID_LittleEndianImplicitTransferSyntax ); d->SCU.addPresentationContext ( UID_FINDStudyRootQueryRetrieveInformationModel, transferSyntaxes ); // d->SCU.addPresentationContext ( UID_VerificationSOPClass, transferSyntaxes ); if ( !d->SCU.initNetwork().good() ) { logger.error( "Error initializing the network" ); emit progress("Error initializing the network"); emit progress(100); return false; } logger.debug ( "Negotiating Association" ); emit progress("Negatiating Association"); emit progress(20); OFCondition result = d->SCU.negotiateAssociation(); if (result.bad()) { logger.error( "Error negotiating the association: " + QString(result.text()) ); emit progress("Error negotiating the association"); emit progress(100); return false; } // Clear the query d->Query->clear(); // Insert all keys that we like to receive values for d->Query->insertEmptyElement ( DCM_PatientID ); d->Query->insertEmptyElement ( DCM_PatientName ); d->Query->insertEmptyElement ( DCM_PatientBirthDate ); d->Query->insertEmptyElement ( DCM_StudyID ); d->Query->insertEmptyElement ( DCM_StudyInstanceUID ); d->Query->insertEmptyElement ( DCM_StudyDescription ); d->Query->insertEmptyElement ( DCM_StudyDate ); d->Query->insertEmptyElement ( DCM_StudyTime ); d->Query->insertEmptyElement ( DCM_ModalitiesInStudy ); d->Query->insertEmptyElement ( DCM_AccessionNumber ); d->Query->insertEmptyElement ( DCM_NumberOfStudyRelatedInstances ); // Number of images in the series d->Query->insertEmptyElement ( DCM_NumberOfStudyRelatedSeries ); // Number of series in the study // Make clear we define our search values in ISO Latin 1 (default would be ASCII) d->Query->putAndInsertOFStringArray(DCM_SpecificCharacterSet, "ISO_IR 100"); d->Query->putAndInsertString ( DCM_QueryRetrieveLevel, "STUDY" ); /* Now, for all keys that the user provided for filtering on STUDY level, * overwrite empty keys with value. For now, only Patient's Name, Patient ID, * Study Description, Modalities in Study, and Study Date are used. */ QString seriesDescription; foreach( QString key, d->Filters.keys() ) { if ( key == QString("Name") && !d->Filters[key].toString().isEmpty()) { // make the filter a wildcard in dicom style d->Query->putAndInsertString( DCM_PatientName, (QString("*") + d->Filters[key].toString() + QString("*")).toAscii().data()); } else if ( key == QString("Study") && !d->Filters[key].toString().isEmpty()) { // make the filter a wildcard in dicom style d->Query->putAndInsertString( DCM_StudyDescription, (QString("*") + d->Filters[key].toString() + QString("*")).toAscii().data()); } else if ( key == QString("ID") && !d->Filters[key].toString().isEmpty()) { // make the filter a wildcard in dicom style d->Query->putAndInsertString( DCM_PatientID, (QString("*") + d->Filters[key].toString() + QString("*")).toAscii().data()); } else if ( key == QString("Modalities") && !d->Filters[key].toString().isEmpty()) { // make the filter be an "OR" of modalities using backslash (dicom-style) QString modalitySearch(""); foreach (const QString& modality, d->Filters[key].toStringList()) { modalitySearch += modality + QString("\\"); } modalitySearch.chop(1); // remove final backslash logger.debug("modalityInStudySearch " + modalitySearch); d->Query->putAndInsertString( DCM_ModalitiesInStudy, modalitySearch.toAscii().data() ); } // Rememer Series Description for later series query if we go through the keys now else if ( key == QString("Series") && !d->Filters[key].toString().isEmpty()) { // make the filter a wildcard in dicom style seriesDescription = "*" + d->Filters[key].toString() + "*"; } else { logger.debug("Ignoring unknown search key: " + key); } } if ( d->Filters.keys().contains("StartDate") && d->Filters.keys().contains("EndDate") ) { QString dateRange = d->Filters["StartDate"].toString() + QString("-") + d->Filters["EndDate"].toString(); d->Query->putAndInsertString ( DCM_StudyDate, dateRange.toAscii().data() ); logger.debug("Query on study date " + dateRange); } emit progress(30); FINDResponses *responses = new FINDResponses(); Uint16 presentationContext = 0; // Check for any accepted presentation context for FIND in study root (dont care about transfer syntax) presentationContext = d->SCU.findPresentationContextID ( UID_FINDStudyRootQueryRetrieveInformationModel, ""); if ( presentationContext == 0 ) { logger.error ( "Failed to find acceptable presentation context" ); emit progress("Failed to find acceptable presentation context"); } else { logger.info ( "Found useful presentation context" ); emit progress("Found useful presentation context"); } emit progress(40); OFCondition status = d->SCU.sendFINDRequest ( presentationContext, d->Query, responses ); if ( !status.good() ) { logger.error ( "Find failed" ); emit progress("Find failed"); d->SCU.closeAssociation ( DCMSCU_RELEASE_ASSOCIATION ); emit progress(100); delete responses; return false; } logger.debug ( "Find succeded"); emit progress("Find succeded"); emit progress(50); for ( OFListIterator(FINDResponse*) it = responses->begin(); it != responses->end(); it++ ) { DcmDataset *dataset = (*it)->m_dataset; if ( dataset != NULL ) // the last response is always empty { database.insert ( dataset, false /* do not store to disk*/, false /* no thumbnail*/); OFString StudyInstanceUID; dataset->findAndGetOFString ( DCM_StudyInstanceUID, StudyInstanceUID ); d->addStudyInstanceUID ( StudyInstanceUID.c_str() ); } } delete responses; /* Only ask for series attributes now. This requires kicking out the rest of former query. */ d->Query->clear(); d->Query->insertEmptyElement ( DCM_SeriesNumber ); d->Query->insertEmptyElement ( DCM_SeriesDescription ); d->Query->insertEmptyElement ( DCM_SeriesInstanceUID ); d->Query->insertEmptyElement ( DCM_SeriesDate ); d->Query->insertEmptyElement ( DCM_SeriesTime ); d->Query->insertEmptyElement ( DCM_Modality ); d->Query->insertEmptyElement ( DCM_NumberOfSeriesRelatedInstances ); // Number of images in the series /* Add user-defined filters */ d->Query->putAndInsertOFStringArray(DCM_SeriesDescription, seriesDescription.toLatin1().data()); // Now search each within each Study that was identified d->Query->putAndInsertString ( DCM_QueryRetrieveLevel, "SERIES" ); float progressRatio = 25. / d->StudyInstanceUIDList.count(); int i = 0; foreach ( QString StudyInstanceUID, d->StudyInstanceUIDList ) { logger.debug ( "Starting Series C-FIND for Study: " + StudyInstanceUID ); emit progress(QString("Starting Series C-FIND for Study: ") + StudyInstanceUID); emit progress(50 + (progressRatio * i++)); d->Query->putAndInsertString ( DCM_StudyInstanceUID, StudyInstanceUID.toStdString().c_str() ); responses = new FINDResponses(); status = d->SCU.sendFINDRequest ( presentationContext, d->Query, responses ); if ( status.good() ) { for ( OFListIterator(FINDResponse*) it = responses->begin(); it != responses->end(); it++ ) { DcmDataset *dataset = (*it)->m_dataset; if ( dataset != NULL ) { database.insert ( dataset, false /* do not store */, false /* no thumbnail */ ); } } logger.debug ( "Find succeded on Series level for Study: " + StudyInstanceUID ); emit progress(QString("Find succeded on Series level for Study: ") + StudyInstanceUID); } else { logger.error ( "Find on Series level failed for Study: " + StudyInstanceUID ); emit progress(QString("Find on Series level failed for Study: ") + StudyInstanceUID); } emit progress(50 + (progressRatio * i++)); delete responses; } d->SCU.closeAssociation ( DCMSCU_RELEASE_ASSOCIATION ); emit progress(100); return true; } <|endoftext|>
<commit_before>#include "voxel_map.h" VoxelMap::VoxelMap() : _last_accessed_block(NULL) { for (unsigned int i = 0; i < VoxelBuffer::MAX_CHANNELS; ++i) { _default_voxel[i] = 0; } } VoxelMap::~VoxelMap() { } int VoxelMap::get_voxel(Vector3i pos, unsigned int c) { Vector3i bpos = voxel_to_block(pos); VoxelBlock * block = get_block(bpos); if (block == NULL) { return _default_voxel[c]; } return block->voxels->get_voxel(pos - block_to_voxel(bpos), c); } MeshInstance * VoxelBlock::get_mesh_instance(const Node & root) { if (mesh_instance_path.is_empty()) return NULL; Node * n = root.get_node(mesh_instance_path); if (n == NULL) return NULL; return n->cast_to<MeshInstance>(); } VoxelBlock::~VoxelBlock() { } // Helper VoxelBlock * VoxelBlock::create(Vector3i bpos, VoxelBuffer * buffer) { VoxelBlock * block = memnew(VoxelBlock); block->pos = bpos; if (buffer) { const int bs = VoxelBlock::SIZE; ERR_FAIL_COND_V(buffer->get_size() != Vector3i(bs, bs, bs), NULL); } else { buffer = memnew(VoxelBuffer); } ERR_FAIL_COND_V(buffer == NULL, NULL); block->voxels = Ref<VoxelBuffer>(buffer); //block->map = &map; return block; } void VoxelMap::set_voxel(int value, Vector3i pos, unsigned int c) { Vector3i bpos = voxel_to_block(pos); VoxelBlock * block = get_block(bpos); if (block == NULL) { block = VoxelBlock::create(bpos); set_block(bpos, block); } block->voxels->set_voxel(value, pos - block_to_voxel(bpos), c); } void VoxelMap::set_default_voxel(int value, unsigned int channel) { ERR_FAIL_INDEX(channel, VoxelBuffer::MAX_CHANNELS); _default_voxel[channel] = value; } int VoxelMap::get_default_voxel(unsigned int channel) { ERR_FAIL_INDEX_V(channel, VoxelBuffer::MAX_CHANNELS, 0); return _default_voxel[channel]; } VoxelBlock * VoxelMap::get_block(Vector3i bpos) { if (_last_accessed_block && _last_accessed_block->pos == bpos) { return _last_accessed_block; } Ref<VoxelBlock> * p = _blocks.getptr(bpos); if (p) { _last_accessed_block = p->ptr(); return _last_accessed_block; } return NULL; } void VoxelMap::set_block(Vector3i bpos, VoxelBlock * block) { if (_last_accessed_block == NULL || _last_accessed_block->pos == bpos) { _last_accessed_block = block; } _blocks.set(bpos, block); } void VoxelMap::set_block_buffer(Vector3i bpos, Ref<VoxelBuffer> buffer) { ERR_FAIL_COND(buffer.is_null()); VoxelBlock * block = get_block(bpos); if (block == NULL) { block = VoxelBlock::create(bpos, *buffer); set_block(bpos, block); } else { block->voxels = buffer; } } bool VoxelMap::has_block(Vector3i pos) const { return /*(_last_accessed_block != NULL && _last_accessed_block->pos == pos) ||*/ _blocks.has(pos); } Vector3i g_moore_neighboring_3d[26] = { Vector3i(-1,-1,-1), Vector3i(0,-1,-1), Vector3i(1,-1,-1), Vector3i(-1,-1,0), Vector3i(0,-1,0), Vector3i(1,-1,0), Vector3i(-1,-1,1), Vector3i(0,-1,1), Vector3i(1,-1,1), Vector3i(-1,0,-1), Vector3i(0,0,-1), Vector3i(1,0,-1), Vector3i(-1,0,0), //Vector3i(0,0,0), Vector3i(1,0,0), Vector3i(-1,0,1), Vector3i(0,0,1), Vector3i(1,0,1), Vector3i(-1,1,-1), Vector3i(0,1,-1), Vector3i(1,1,-1), Vector3i(-1,1,0), Vector3i(0,1,0), Vector3i(1,1,0), Vector3i(-1,1,1), Vector3i(0,1,1), Vector3i(1,1,1), }; bool VoxelMap::is_block_surrounded(Vector3i pos) const { for (unsigned int i = 0; i < 26; ++i) { Vector3i bpos = pos + g_moore_neighboring_3d[i]; if (!has_block(bpos)) { return false; } } return true; } void VoxelMap::get_buffer_copy(Vector3i min_pos, VoxelBuffer & dst_buffer, unsigned int channel) { ERR_FAIL_INDEX(channel, VoxelBuffer::MAX_CHANNELS); Vector3i max_pos = min_pos + dst_buffer.get_size(); Vector3i min_block_pos = voxel_to_block(min_pos); Vector3i max_block_pos = voxel_to_block(max_pos - Vector3i(1,1,1)) + Vector3i(1,1,1); ERR_FAIL_COND((max_block_pos - min_block_pos) != Vector3(3, 3, 3)); Vector3i bpos; for (bpos.z = min_block_pos.z; bpos.z < max_block_pos.z; ++bpos.z) { for (bpos.x = min_block_pos.x; bpos.x < max_block_pos.x; ++bpos.x) { for (bpos.y = min_block_pos.y; bpos.y < max_block_pos.y; ++bpos.y) { VoxelBlock * block = get_block(bpos); if (block) { VoxelBuffer & src_buffer = **block->voxels; Vector3i offset = block_to_voxel(bpos); // Note: copy_from takes care of clamping the area if it's on an edge dst_buffer.copy_from(src_buffer, min_pos - offset, max_pos - offset, offset - min_pos, channel); } else { Vector3i offset = block_to_voxel(bpos); dst_buffer.fill_area( _default_voxel[channel], offset - min_pos, offset - min_pos + Vector3i(VoxelBlock::SIZE,VoxelBlock::SIZE, VoxelBlock::SIZE) ); } } } } } void VoxelMap::remove_blocks_not_in_area(Vector3i min, Vector3i max) { Vector3i::sort_min_max(min, max); Vector<Vector3i> to_remove; Vector3i * key = NULL; while (_blocks.next(key)) { Ref<VoxelBlock> & block_ref = _blocks.get(*key); ERR_FAIL_COND(block_ref.is_null()); // Should never trigger VoxelBlock & block = **block_ref; if (!block.pos.is_contained_in(min, max)) { //if (_observer) // _observer->block_removed(block); to_remove.push_back(*key); if (&block == _last_accessed_block) _last_accessed_block = NULL; } } for (unsigned int i = 0; i < to_remove.size(); ++i) { _blocks.erase(to_remove[i]); } } MeshInstance *VoxelMap::_get_block_mesh_instance_binding(Vector3 bpos, Node * root) { VoxelBlock* block = get_block(Vector3i(bpos)); ERR_FAIL_COND_V(!block, NULL); return block->get_mesh_instance(*root); } void VoxelMap::_set_block_mesh_instance_binding(Vector3 bpos, Node * node) { ERR_FAIL_NULL(node); MeshInstance * mesh_instance = node->cast_to<MeshInstance>(); VoxelBlock* block = get_block(Vector3i(bpos)); if (block == NULL) { block = VoxelBlock::create(Vector3i(bpos)); set_block(bpos, block); } block->mesh_instance_path = mesh_instance->get_path(); } Ref<NavigationMesh> VoxelMap::_create_navigation_mesh_binding(Ref<Mesh> mesh) { ERR_FAIL_COND_V(mesh.is_null(), Ref<NavigationMesh>()); Ref<NavigationMesh> navigation_mesh = Ref<NavigationMesh>(memnew(NavigationMesh)); navigation_mesh->create_from_mesh(mesh); return navigation_mesh; } void VoxelMap::_bind_methods() { ObjectTypeDB::bind_method(_MD("get_voxel", "vector:Vector3", "channel:int"), &VoxelMap::_get_voxel_binding, DEFVAL(0)); ObjectTypeDB::bind_method(_MD("set_voxel", "value:int", "vector:Vector3", "channel:int"), &VoxelMap::_set_voxel_binding, DEFVAL(0)); ObjectTypeDB::bind_method(_MD("get_default_voxel", "channel"), &VoxelMap::get_default_voxel, DEFVAL(0)); ObjectTypeDB::bind_method(_MD("set_default_voxel", "value", "channel"), &VoxelMap::set_default_voxel, DEFVAL(0)); ObjectTypeDB::bind_method(_MD("has_block", "vector:Vector3"), &VoxelMap::_has_block_binding); ObjectTypeDB::bind_method(_MD("get_buffer_copy", "min_pos", "out_buffer:VoxelBuffer", "channel"), &VoxelMap::_get_buffer_copy_binding, DEFVAL(0)); ObjectTypeDB::bind_method(_MD("set_block_buffer", "block_pos", "buffer:VoxelBuffer"), &VoxelMap::_set_block_buffer_binding); ObjectTypeDB::bind_method(_MD("voxel_to_block", "voxel_pos"), &VoxelMap::_voxel_to_block_binding); ObjectTypeDB::bind_method(_MD("block_to_voxel", "block_pos"), &VoxelMap::_block_to_voxel_binding); ObjectTypeDB::bind_method(_MD("get_block_size"), &VoxelMap::get_block_size); ObjectTypeDB::bind_method(_MD("get_block_mesh_instance:MeshInstance","block_pos:Vector3", "root:Node"),&VoxelMap::_get_block_mesh_instance_binding); ObjectTypeDB::bind_method(_MD("set_block_mesh_instance","block_pos:Vector3", "mesh_instance:MeshInstance"),&VoxelMap::_set_block_mesh_instance_binding); ObjectTypeDB::bind_method(_MD("create_navigation_mesh","mesh:Mesh"),&VoxelMap::_create_navigation_mesh_binding); //ADD_PROPERTY(PropertyInfo(Variant::INT, "iterations"), _SCS("set_iterations"), _SCS("get_iterations")); } void VoxelMap::_get_buffer_copy_binding(Vector3 pos, Ref<VoxelBuffer> dst_buffer_ref, unsigned int channel) { ERR_FAIL_COND(dst_buffer_ref.is_null()); get_buffer_copy(Vector3i(pos), **dst_buffer_ref, channel); } <commit_msg>Fix: block was not initialized VoxelBlock::create<commit_after>#include "voxel_map.h" VoxelMap::VoxelMap() : _last_accessed_block(NULL) { for (unsigned int i = 0; i < VoxelBuffer::MAX_CHANNELS; ++i) { _default_voxel[i] = 0; } } VoxelMap::~VoxelMap() { } int VoxelMap::get_voxel(Vector3i pos, unsigned int c) { Vector3i bpos = voxel_to_block(pos); VoxelBlock * block = get_block(bpos); if (block == NULL) { return _default_voxel[c]; } return block->voxels->get_voxel(pos - block_to_voxel(bpos), c); } MeshInstance * VoxelBlock::get_mesh_instance(const Node & root) { if (mesh_instance_path.is_empty()) return NULL; Node * n = root.get_node(mesh_instance_path); if (n == NULL) return NULL; return n->cast_to<MeshInstance>(); } VoxelBlock::~VoxelBlock() { } // Helper VoxelBlock * VoxelBlock::create(Vector3i bpos, VoxelBuffer * buffer) { VoxelBlock * block = memnew(VoxelBlock); block->pos = bpos; if (buffer) { const int bs = VoxelBlock::SIZE; ERR_FAIL_COND_V(buffer->get_size() != Vector3i(bs, bs, bs), NULL); } else { buffer = memnew(VoxelBuffer); buffer->create(SIZE, SIZE, SIZE); } ERR_FAIL_COND_V(buffer == NULL, NULL); block->voxels = Ref<VoxelBuffer>(buffer); //block->map = &map; return block; } void VoxelMap::set_voxel(int value, Vector3i pos, unsigned int c) { Vector3i bpos = voxel_to_block(pos); VoxelBlock * block = get_block(bpos); if (block == NULL) { block = VoxelBlock::create(bpos); set_block(bpos, block); } block->voxels->set_voxel(value, pos - block_to_voxel(bpos), c); } void VoxelMap::set_default_voxel(int value, unsigned int channel) { ERR_FAIL_INDEX(channel, VoxelBuffer::MAX_CHANNELS); _default_voxel[channel] = value; } int VoxelMap::get_default_voxel(unsigned int channel) { ERR_FAIL_INDEX_V(channel, VoxelBuffer::MAX_CHANNELS, 0); return _default_voxel[channel]; } VoxelBlock * VoxelMap::get_block(Vector3i bpos) { if (_last_accessed_block && _last_accessed_block->pos == bpos) { return _last_accessed_block; } Ref<VoxelBlock> * p = _blocks.getptr(bpos); if (p) { _last_accessed_block = p->ptr(); return _last_accessed_block; } return NULL; } void VoxelMap::set_block(Vector3i bpos, VoxelBlock * block) { if (_last_accessed_block == NULL || _last_accessed_block->pos == bpos) { _last_accessed_block = block; } _blocks.set(bpos, block); } void VoxelMap::set_block_buffer(Vector3i bpos, Ref<VoxelBuffer> buffer) { ERR_FAIL_COND(buffer.is_null()); VoxelBlock * block = get_block(bpos); if (block == NULL) { block = VoxelBlock::create(bpos, *buffer); set_block(bpos, block); } else { block->voxels = buffer; } } bool VoxelMap::has_block(Vector3i pos) const { return /*(_last_accessed_block != NULL && _last_accessed_block->pos == pos) ||*/ _blocks.has(pos); } Vector3i g_moore_neighboring_3d[26] = { Vector3i(-1,-1,-1), Vector3i(0,-1,-1), Vector3i(1,-1,-1), Vector3i(-1,-1,0), Vector3i(0,-1,0), Vector3i(1,-1,0), Vector3i(-1,-1,1), Vector3i(0,-1,1), Vector3i(1,-1,1), Vector3i(-1,0,-1), Vector3i(0,0,-1), Vector3i(1,0,-1), Vector3i(-1,0,0), //Vector3i(0,0,0), Vector3i(1,0,0), Vector3i(-1,0,1), Vector3i(0,0,1), Vector3i(1,0,1), Vector3i(-1,1,-1), Vector3i(0,1,-1), Vector3i(1,1,-1), Vector3i(-1,1,0), Vector3i(0,1,0), Vector3i(1,1,0), Vector3i(-1,1,1), Vector3i(0,1,1), Vector3i(1,1,1), }; bool VoxelMap::is_block_surrounded(Vector3i pos) const { for (unsigned int i = 0; i < 26; ++i) { Vector3i bpos = pos + g_moore_neighboring_3d[i]; if (!has_block(bpos)) { return false; } } return true; } void VoxelMap::get_buffer_copy(Vector3i min_pos, VoxelBuffer & dst_buffer, unsigned int channel) { ERR_FAIL_INDEX(channel, VoxelBuffer::MAX_CHANNELS); Vector3i max_pos = min_pos + dst_buffer.get_size(); Vector3i min_block_pos = voxel_to_block(min_pos); Vector3i max_block_pos = voxel_to_block(max_pos - Vector3i(1,1,1)) + Vector3i(1,1,1); ERR_FAIL_COND((max_block_pos - min_block_pos) != Vector3(3, 3, 3)); Vector3i bpos; for (bpos.z = min_block_pos.z; bpos.z < max_block_pos.z; ++bpos.z) { for (bpos.x = min_block_pos.x; bpos.x < max_block_pos.x; ++bpos.x) { for (bpos.y = min_block_pos.y; bpos.y < max_block_pos.y; ++bpos.y) { VoxelBlock * block = get_block(bpos); if (block) { VoxelBuffer & src_buffer = **block->voxels; Vector3i offset = block_to_voxel(bpos); // Note: copy_from takes care of clamping the area if it's on an edge dst_buffer.copy_from(src_buffer, min_pos - offset, max_pos - offset, offset - min_pos, channel); } else { Vector3i offset = block_to_voxel(bpos); dst_buffer.fill_area( _default_voxel[channel], offset - min_pos, offset - min_pos + Vector3i(VoxelBlock::SIZE,VoxelBlock::SIZE, VoxelBlock::SIZE) ); } } } } } void VoxelMap::remove_blocks_not_in_area(Vector3i min, Vector3i max) { Vector3i::sort_min_max(min, max); Vector<Vector3i> to_remove; Vector3i * key = NULL; while (_blocks.next(key)) { Ref<VoxelBlock> & block_ref = _blocks.get(*key); ERR_FAIL_COND(block_ref.is_null()); // Should never trigger VoxelBlock & block = **block_ref; if (!block.pos.is_contained_in(min, max)) { //if (_observer) // _observer->block_removed(block); to_remove.push_back(*key); if (&block == _last_accessed_block) _last_accessed_block = NULL; } } for (unsigned int i = 0; i < to_remove.size(); ++i) { _blocks.erase(to_remove[i]); } } MeshInstance *VoxelMap::_get_block_mesh_instance_binding(Vector3 bpos, Node * root) { VoxelBlock* block = get_block(Vector3i(bpos)); ERR_FAIL_COND_V(!block, NULL); return block->get_mesh_instance(*root); } void VoxelMap::_set_block_mesh_instance_binding(Vector3 bpos, Node * node) { ERR_FAIL_NULL(node); MeshInstance * mesh_instance = node->cast_to<MeshInstance>(); VoxelBlock* block = get_block(Vector3i(bpos)); if (block == NULL) { block = VoxelBlock::create(Vector3i(bpos)); set_block(bpos, block); } block->mesh_instance_path = mesh_instance->get_path(); } Ref<NavigationMesh> VoxelMap::_create_navigation_mesh_binding(Ref<Mesh> mesh) { ERR_FAIL_COND_V(mesh.is_null(), Ref<NavigationMesh>()); Ref<NavigationMesh> navigation_mesh = Ref<NavigationMesh>(memnew(NavigationMesh)); navigation_mesh->create_from_mesh(mesh); return navigation_mesh; } void VoxelMap::_bind_methods() { ObjectTypeDB::bind_method(_MD("get_voxel", "vector:Vector3", "channel:int"), &VoxelMap::_get_voxel_binding, DEFVAL(0)); ObjectTypeDB::bind_method(_MD("set_voxel", "value:int", "vector:Vector3", "channel:int"), &VoxelMap::_set_voxel_binding, DEFVAL(0)); ObjectTypeDB::bind_method(_MD("get_default_voxel", "channel"), &VoxelMap::get_default_voxel, DEFVAL(0)); ObjectTypeDB::bind_method(_MD("set_default_voxel", "value", "channel"), &VoxelMap::set_default_voxel, DEFVAL(0)); ObjectTypeDB::bind_method(_MD("has_block", "vector:Vector3"), &VoxelMap::_has_block_binding); ObjectTypeDB::bind_method(_MD("get_buffer_copy", "min_pos", "out_buffer:VoxelBuffer", "channel"), &VoxelMap::_get_buffer_copy_binding, DEFVAL(0)); ObjectTypeDB::bind_method(_MD("set_block_buffer", "block_pos", "buffer:VoxelBuffer"), &VoxelMap::_set_block_buffer_binding); ObjectTypeDB::bind_method(_MD("voxel_to_block", "voxel_pos"), &VoxelMap::_voxel_to_block_binding); ObjectTypeDB::bind_method(_MD("block_to_voxel", "block_pos"), &VoxelMap::_block_to_voxel_binding); ObjectTypeDB::bind_method(_MD("get_block_size"), &VoxelMap::get_block_size); ObjectTypeDB::bind_method(_MD("get_block_mesh_instance:MeshInstance","block_pos:Vector3", "root:Node"),&VoxelMap::_get_block_mesh_instance_binding); ObjectTypeDB::bind_method(_MD("set_block_mesh_instance","block_pos:Vector3", "mesh_instance:MeshInstance"),&VoxelMap::_set_block_mesh_instance_binding); ObjectTypeDB::bind_method(_MD("create_navigation_mesh","mesh:Mesh"),&VoxelMap::_create_navigation_mesh_binding); //ADD_PROPERTY(PropertyInfo(Variant::INT, "iterations"), _SCS("set_iterations"), _SCS("get_iterations")); } void VoxelMap::_get_buffer_copy_binding(Vector3 pos, Ref<VoxelBuffer> dst_buffer_ref, unsigned int channel) { ERR_FAIL_COND(dst_buffer_ref.is_null()); get_buffer_copy(Vector3i(pos), **dst_buffer_ref, channel); } <|endoftext|>
<commit_before>/* Copyright (c) 2014 Scott Kuhl. All rights reserved. * License: This code is licensed under a 3-clause BSD license. See * the file named "LICENSE" for a full copy of the license. */ /** @file * @author Scott Kuhl */ #include <stdlib.h> #include <stdio.h> #include <map> #include <string> #ifndef MISSING_VRPN #include <vrpn_Tracker.h> #include <quat.h> #endif #ifdef __APPLE__ #include <OpenGL/gl.h> #else #include <GL/gl.h> #endif #include "kuhl-util.h" #ifndef MISSING_VRPN /** A mapping of object\@tracker strings to vrpn_Tracker_Remote objects * so we can quickly find the appropriate object given an * object\@tracker string. */ std::map<std::string, vrpn_Tracker_Remote*> nameToTracker; /** A mapping of object\@tracker strings to the data that the callback * functions store the data into. */ std::map<std::string, vrpn_TRACKERCB> nameToCallbackData; /** A callback function that will get called whenever the tracked * point moves. */ static void VRPN_CALLBACK handle_tracker(void *name, const vrpn_TRACKERCB t) { // Store the data in our map so that someone can use it later. std::string s = (char*)name; nameToCallbackData[s] = t; } #endif extern "C" { /** Uses the VRPN library to get the position and orientation of a * tracked object. * * @param object The name of the object being tracked. * * @param hostname The IP address or hostname of the VRPN server or * tracking system computer. If hostname is set to NULL, the IP * address of the Vicon tracker in the IVS lab is used. * * @param pos An array to be filled in with the position information * for the tracked object. If we are unable to track the object, a * message may be printed and pos will be set to a fixed value. * * @param orient An array to be filled in with the orientation matrix * for the tracked object. The orientation matrix is in row-major * order can be used with OpenGL. If the tracking system is moving an * object around on the screen, this matrix can be used directly. If * the tracking system is moving the OpenGL camera, this matrix may * need to be inverted. If we are unable to track the object, a * message may be printed and orient will be set to the identity * matrix. * * @return 1 if we returned data from the tracker. 0 if there was * problems connecting to the tracker. */ int vrpn_get(const char *object, const char *hostname, float pos[3], float orient[16]) { #ifndef MISSING_VRPN /* Construct an object@hostname string. */ std::string hostnamecpp; std::string objectcpp; if(hostname == NULL) hostnamecpp = "tcp://VRPN-SERVER-IP-ADDRESS"; objectcpp = object; std::string fullname = objectcpp + "@" + hostnamecpp; /* Check if we have a tracker object for that string in our map. */ if(nameToTracker.count(fullname)) { /* If we already have a tracker object, ask it to run the main * loop (and therefore call our handle_tracker() function if * there is new data). */ nameToTracker[fullname]->mainloop(); /* If our callback has been called, get the callback object * and get the data out of it. */ if(nameToCallbackData.count(fullname)) { vrpn_TRACKERCB t = nameToCallbackData[fullname]; float pos4[4]; for(int i=0; i<3; i++) pos4[i] = t.pos[i]; pos4[3]=1; double orientd[16]; // Convert quaternion into orientation matrix. q_to_ogl_matrix(orientd, t.quat); for(int i=0; i<16; i++) orient[i] = (float) orientd[i]; /* IMPORTANT NOTE: The Vicon tracking system is normally * calibrated so that: * X = points to the right (while facing screen) * Y = points into the screen * Z = up * * By default, OpenGL assumes that: * X = points to the right (while facing screen) * Y = up * Z = points OUT of the screen (i.e., -Z points into the screen) * * Below, we convert the Vicon position and orientation * information into the OpenGL convention to make it * easier to add Vicon support to an OpenGL program. * * If you are using this file with a different tracking * system, this conversion may be wrong! */ float zUpToYUp[16] = { 1,0,0,0, // column major order! 0,0,-1,0, 0,1,0,0, 0,0,0,1 }; mat4f_mult_mat4f_new(orient, zUpToYUp, orient); mat4f_mult_vec4f_new(pos4, zUpToYUp, pos4); vec3f_copy(pos,pos4); return 1; } else { /* If we don't have any data yet, return a position far from the origin. */ vec3f_set(pos, 10000,10000,10000); mat4f_identity(orient); return 0; } } else { /* If this is our first time, create a tracker for the object@hostname string, register the callback handler. */ printf("vrpn-help: Connecting to VRPN server. If this hangs, VRPN server is not running.\n"); vrpn_Tracker_Remote *tkr = new vrpn_Tracker_Remote(fullname.c_str()); nameToTracker[fullname] = tkr; tkr->register_change_handler((void*) fullname.c_str(), handle_tracker); return 0; // If we connected successfully, the next time this is called we'll return 1 } #else printf("You are missing VRPN support.\n"); mat4f_identity(orient); vec3f_set(pos, 0,0,0); return 0; #endif } } // extern C <commit_msg>ensure that tracking system data is always initialized to something.<commit_after>/* Copyright (c) 2014 Scott Kuhl. All rights reserved. * License: This code is licensed under a 3-clause BSD license. See * the file named "LICENSE" for a full copy of the license. */ /** @file * @author Scott Kuhl */ #include <stdlib.h> #include <stdio.h> #include <map> #include <string> #ifndef MISSING_VRPN #include <vrpn_Tracker.h> #include <quat.h> #endif #ifdef __APPLE__ #include <OpenGL/gl.h> #else #include <GL/gl.h> #endif #include "kuhl-util.h" #ifndef MISSING_VRPN /** A mapping of object\@tracker strings to vrpn_Tracker_Remote objects * so we can quickly find the appropriate object given an * object\@tracker string. */ std::map<std::string, vrpn_Tracker_Remote*> nameToTracker; /** A mapping of object\@tracker strings to the data that the callback * functions store the data into. */ std::map<std::string, vrpn_TRACKERCB> nameToCallbackData; /** A callback function that will get called whenever the tracked * point moves. */ static void VRPN_CALLBACK handle_tracker(void *name, const vrpn_TRACKERCB t) { // Store the data in our map so that someone can use it later. std::string s = (char*)name; nameToCallbackData[s] = t; } #endif extern "C" { /** Uses the VRPN library to get the position and orientation of a * tracked object. * * @param object The name of the object being tracked. * * @param hostname The IP address or hostname of the VRPN server or * tracking system computer. If hostname is set to NULL, the IP * address of the Vicon tracker in the IVS lab is used. * * @param pos An array to be filled in with the position information * for the tracked object. If we are unable to track the object, a * message may be printed and pos will be set to a fixed value. * * @param orient An array to be filled in with the orientation matrix * for the tracked object. The orientation matrix is in row-major * order can be used with OpenGL. If the tracking system is moving an * object around on the screen, this matrix can be used directly. If * the tracking system is moving the OpenGL camera, this matrix may * need to be inverted. If we are unable to track the object, a * message may be printed and orient will be set to the identity * matrix. * * @return 1 if we returned data from the tracker. 0 if there was * problems connecting to the tracker. */ int vrpn_get(const char *object, const char *hostname, float pos[3], float orient[16]) { /* Set to default values */ vec3f_set(pos, 10000,10000,10000); mat4f_identity(orient); #ifdef MISSING_VRPN printf("You are missing VRPN support.\n"); return 0; #else /* Construct an object@hostname string. */ std::string hostnamecpp; std::string objectcpp; if(hostname == NULL) hostnamecpp = "tcp://VRPN-SERVER-IP-ADDRESS"; objectcpp = object; std::string fullname = objectcpp + "@" + hostnamecpp; /* Check if we have a tracker object for that string in our map. */ if(nameToTracker.count(fullname)) { /* If we already have a tracker object, ask it to run the main * loop (and therefore call our handle_tracker() function if * there is new data). */ nameToTracker[fullname]->mainloop(); /* If our callback has been called, get the callback object * and get the data out of it. */ if(nameToCallbackData.count(fullname)) { vrpn_TRACKERCB t = nameToCallbackData[fullname]; float pos4[4]; for(int i=0; i<3; i++) pos4[i] = t.pos[i]; pos4[3]=1; double orientd[16]; // Convert quaternion into orientation matrix. q_to_ogl_matrix(orientd, t.quat); for(int i=0; i<16; i++) orient[i] = (float) orientd[i]; /* IMPORTANT NOTE: The Vicon tracking system is normally * calibrated so that: * X = points to the right (while facing screen) * Y = points into the screen * Z = up * * By default, OpenGL assumes that: * X = points to the right (while facing screen) * Y = up * Z = points OUT of the screen (i.e., -Z points into the screen) * * Below, we convert the Vicon position and orientation * information into the OpenGL convention to make it * easier to add Vicon support to an OpenGL program. * * If you are using this file with a different tracking * system, this conversion may be wrong! */ float zUpToYUp[16] = { 1,0,0,0, // column major order! 0,0,-1,0, 0,1,0,0, 0,0,0,1 }; mat4f_mult_mat4f_new(orient, zUpToYUp, orient); mat4f_mult_vec4f_new(pos4, zUpToYUp, pos4); vec3f_copy(pos,pos4); return 1; // we successfully collected some data } } else { /* If this is our first time, create a tracker for the object@hostname string, register the callback handler. */ printf("vrpn-help: Connecting to VRPN server. If this hangs, VRPN server is not running.\n"); vrpn_Tracker_Remote *tkr = new vrpn_Tracker_Remote(fullname.c_str()); nameToTracker[fullname] = tkr; tkr->register_change_handler((void*) fullname.c_str(), handle_tracker); } return 0; #endif } } // extern C <|endoftext|>
<commit_before>/* Copyright (c) 2014 Scott Kuhl. All rights reserved. * License: This code is licensed under a 3-clause BSD license. See * the file named "LICENSE" for a full copy of the license. */ /** @file * @author Scott Kuhl */ #include <stdlib.h> #include <stdio.h> #include <map> #include <string> #ifndef MISSING_VRPN #include <vrpn_Tracker.h> #include <quat.h> #endif #ifdef __APPLE__ #include <OpenGL/gl.h> #else #include <GL/gl.h> #endif #include "kuhl-util.h" #include "vecmat.h" #ifndef MISSING_VRPN /** A mapping of object\@tracker strings to vrpn_Tracker_Remote objects * so we can quickly find the appropriate object given an * object\@tracker string. */ std::map<std::string, vrpn_Tracker_Remote*> nameToTracker; /** A mapping of object\@tracker strings to the data that the callback * functions store the data into. */ std::map<std::string, vrpn_TRACKERCB> nameToCallbackData; /** A callback function that will get called whenever the tracked * point moves. */ static void VRPN_CALLBACK handle_tracker(void *name, const vrpn_TRACKERCB t) { // Store the data in our map so that someone can use it later. std::string s = (char*)name; nameToCallbackData[s] = t; } #endif extern "C" { /** Uses the VRPN library to get the position and orientation of a * tracked object. * * @param object The name of the object being tracked. * * @param hostname The IP address or hostname of the VRPN server or * tracking system computer. If hostname is set to NULL, the IP * address of the Vicon tracker in the IVS lab is used. * * @param pos An array to be filled in with the position information * for the tracked object. If we are unable to track the object, a * message may be printed and pos will be set to a fixed value. * * @param orient An array to be filled in with the orientation matrix * for the tracked object. The orientation matrix is in row-major * order can be used with OpenGL. If the tracking system is moving an * object around on the screen, this matrix can be used directly. If * the tracking system is moving the OpenGL camera, this matrix may * need to be inverted. If we are unable to track the object, a * message may be printed and orient will be set to the identity * matrix. * * @return 1 if we returned data from the tracker. 0 if there was * problems connecting to the tracker. */ int vrpn_get(const char *object, const char *hostname, float pos[3], float orient[16]) { /* Set to default values */ vec3f_set(pos, 10000,10000,10000); mat4f_identity(orient); #ifdef MISSING_VRPN printf("You are missing VRPN support.\n"); return 0; #else /* Construct an object@hostname string. */ std::string hostnamecpp; std::string objectcpp; if(hostname == NULL) hostnamecpp = "tcp://VRPN-SERVER-IP-ADDRESS"; objectcpp = object; std::string fullname = objectcpp + "@" + hostnamecpp; /* Check if we have a tracker object for that string in our map. */ if(nameToTracker.count(fullname)) { /* If we already have a tracker object, ask it to run the main * loop (and therefore call our handle_tracker() function if * there is new data). */ nameToTracker[fullname]->mainloop(); /* If our callback has been called, get the callback object * and get the data out of it. */ if(nameToCallbackData.count(fullname)) { vrpn_TRACKERCB t = nameToCallbackData[fullname]; float pos4[4]; for(int i=0; i<3; i++) pos4[i] = t.pos[i]; pos4[3]=1; double orientd[16]; // Convert quaternion into orientation matrix. q_to_ogl_matrix(orientd, t.quat); for(int i=0; i<16; i++) orient[i] = (float) orientd[i]; /* IMPORTANT NOTE: The Vicon tracking system is normally * calibrated so that: * X = points to the right (while facing screen) * Y = points into the screen * Z = up * * By default, OpenGL assumes that: * X = points to the right (while facing screen) * Y = up * Z = points OUT of the screen (i.e., -Z points into the screen) * * Below, we convert the Vicon position and orientation * information into the OpenGL convention to make it * easier to add Vicon support to an OpenGL program. * * If you are using this file with a different tracking * system, this conversion may be wrong! */ float zUpToYUp[16] = { 1,0,0,0, // column major order! 0,0,-1,0, 0,1,0,0, 0,0,0,1 }; mat4f_mult_mat4f_new(orient, zUpToYUp, orient); mat4f_mult_vec4f_new(pos4, zUpToYUp, pos4); vec3f_copy(pos,pos4); return 1; // we successfully collected some data } } else { /* If this is our first time, create a tracker for the object@hostname string, register the callback handler. */ printf("vrpn-help: Connecting to VRPN server. If this hangs, VRPN server is not running.\n"); vrpn_Tracker_Remote *tkr = new vrpn_Tracker_Remote(fullname.c_str()); nameToTracker[fullname] = tkr; tkr->register_change_handler((void*) fullname.c_str(), handle_tracker); } return 0; #endif } } // extern C <commit_msg>store IP address of VRPN server in a file in the users home directory instead of coded into the source code.<commit_after>/* Copyright (c) 2014 Scott Kuhl. All rights reserved. * License: This code is licensed under a 3-clause BSD license. See * the file named "LICENSE" for a full copy of the license. */ /** @file * @author Scott Kuhl */ #include <stdlib.h> #include <stdio.h> #include <map> #include <string> #ifndef MISSING_VRPN #include <vrpn_Tracker.h> #include <quat.h> #endif #ifdef __APPLE__ #include <OpenGL/gl.h> #else #include <GL/gl.h> #endif #include "kuhl-util.h" #include "vecmat.h" #ifndef MISSING_VRPN /** A mapping of object\@tracker strings to vrpn_Tracker_Remote objects * so we can quickly find the appropriate object given an * object\@tracker string. */ std::map<std::string, vrpn_Tracker_Remote*> nameToTracker; /** A mapping of object\@tracker strings to the data that the callback * functions store the data into. */ std::map<std::string, vrpn_TRACKERCB> nameToCallbackData; /** A callback function that will get called whenever the tracked * point moves. */ static void VRPN_CALLBACK handle_tracker(void *name, const vrpn_TRACKERCB t) { // Store the data in our map so that someone can use it later. std::string s = (char*)name; nameToCallbackData[s] = t; } #endif extern "C" { /** Uses the VRPN library to get the position and orientation of a * tracked object. * * @param object The name of the object being tracked. * * @param hostname The IP address or hostname of the VRPN server or * tracking system computer. If hostname is set to NULL, the IP * address of the Vicon tracker in the IVS lab is used. * * @param pos An array to be filled in with the position information * for the tracked object. If we are unable to track the object, a * message may be printed and pos will be set to a fixed value. * * @param orient An array to be filled in with the orientation matrix * for the tracked object. The orientation matrix is in row-major * order can be used with OpenGL. If the tracking system is moving an * object around on the screen, this matrix can be used directly. If * the tracking system is moving the OpenGL camera, this matrix may * need to be inverted. If we are unable to track the object, a * message may be printed and orient will be set to the identity * matrix. * * @return 1 if we returned data from the tracker. 0 if there was * problems connecting to the tracker. */ int vrpn_get(const char *object, const char *hostname, float pos[3], float orient[16]) { /* Set to default values */ vec3f_set(pos, 10000,10000,10000); mat4f_identity(orient); #ifdef MISSING_VRPN printf("You are missing VRPN support.\n"); return 0; #else /* Construct an object@hostname string. */ std::string hostnamecpp; std::string objectcpp; if(hostname == NULL) { /* Try reading VRPN server information from ~/.vrpn-server This file should contain a single line that says something like: tcp://VRPN.SERVER.IP.ADDR */ const char *homedir = getenv("HOME"); char path[1024]; snprintf(path, 1024, "%s/.vrpn-server", homedir); FILE *f = fopen(path, "r"); if(f == NULL) { printf("%s: Can't open file %s to get VRPN server information.\n", __func__, path); exit(EXIT_FAILURE); } char vrpnString[1024]; if(fscanf(f, "%1023s", vrpnString) != 1) { printf("%s: Can't read %s to get VRPN server information.\n", __func__, path); exit(EXIT_FAILURE); } // printf("%s: Found in %s: %s\n", __func__, path, vrpnString); hostnamecpp = vrpnString; exit(EXIT_FAILURE); } objectcpp = object; std::string fullname = objectcpp + "@" + hostnamecpp; /* Check if we have a tracker object for that string in our map. */ if(nameToTracker.count(fullname)) { /* If we already have a tracker object, ask it to run the main * loop (and therefore call our handle_tracker() function if * there is new data). */ nameToTracker[fullname]->mainloop(); /* If our callback has been called, get the callback object * and get the data out of it. */ if(nameToCallbackData.count(fullname)) { vrpn_TRACKERCB t = nameToCallbackData[fullname]; float pos4[4]; for(int i=0; i<3; i++) pos4[i] = t.pos[i]; pos4[3]=1; double orientd[16]; // Convert quaternion into orientation matrix. q_to_ogl_matrix(orientd, t.quat); for(int i=0; i<16; i++) orient[i] = (float) orientd[i]; /* IMPORTANT NOTE: The Vicon tracking system is normally * calibrated so that: * X = points to the right (while facing screen) * Y = points into the screen * Z = up * * By default, OpenGL assumes that: * X = points to the right (while facing screen) * Y = up * Z = points OUT of the screen (i.e., -Z points into the screen) * * Below, we convert the Vicon position and orientation * information into the OpenGL convention to make it * easier to add Vicon support to an OpenGL program. * * If you are using this file with a different tracking * system, this conversion may be wrong! */ float zUpToYUp[16] = { 1,0,0,0, // column major order! 0,0,-1,0, 0,1,0,0, 0,0,0,1 }; mat4f_mult_mat4f_new(orient, zUpToYUp, orient); mat4f_mult_vec4f_new(pos4, zUpToYUp, pos4); vec3f_copy(pos,pos4); return 1; // we successfully collected some data } } else { /* If this is our first time, create a tracker for the object@hostname string, register the callback handler. */ printf("vrpn-help: Connecting to VRPN server. If this hangs, VRPN server is not running.\n"); vrpn_Tracker_Remote *tkr = new vrpn_Tracker_Remote(fullname.c_str()); nameToTracker[fullname] = tkr; tkr->register_change_handler((void*) fullname.c_str(), handle_tracker); } return 0; #endif } } // extern C <|endoftext|>
<commit_before>/*************************************************************************** * Copyright (C) 2006 by FThauer FHammer * * f.thauer@web.de * * * * 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., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include <boost/asio.hpp> #include <iostream> #include <cstdlib> #include <ctime> #include <qapplication.h> #include <QtGui> #include <QtCore> #ifdef __APPLE__ #include <QMacStyle> #endif #include <curl/curl.h> #include "session.h" #include "startwindowimpl.h" #include "configfile.h" #include "startsplash.h" #include "game_defs.h" #include <net/socket_startup.h> #include <third_party/qtsingleapplication/qtsingleapplication.h> #ifdef _MSC_VER #ifdef _DEBUG #define _CRTDBG_MAP_ALLOC #include <crtdbg.h> #define ENABLE_LEAK_CHECK() \ { \ int tmpFlag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG); \ tmpFlag |= _CRTDBG_LEAK_CHECK_DF; \ _CrtSetDbgFlag(tmpFlag); \ } #endif #endif #ifndef ENABLE_LEAK_CHECK #define ENABLE_LEAK_CHECK() #endif //Uncomment this for RELEASE on Linux/Unix/BSD (static Qt only) //#include <QtPlugin> //Q_IMPORT_PLUGIN(qjpeg) //Q_IMPORT_PLUGIN(qgif) #ifdef _WIN32 // Always use static Qt on Windows. #include <QtPlugin> Q_IMPORT_PLUGIN(qjpeg) Q_IMPORT_PLUGIN(qgif) #endif using namespace std; class startWindowImpl; class Game; int main( int argc, char **argv ) { //ENABLE_LEAK_CHECK(); //_CrtSetBreakAlloc(49937); socket_startup(); curl_global_init(CURL_GLOBAL_NOTHING); /////// can be removed for non-qt-guis //////////// QtSingleApplication a( argc, argv ); if (a.sendMessage("Wake up!")) { return 0; } #ifdef __APPLE__ // The following needs to be done directly after the application is created. QDir dir(QApplication::applicationDirPath()); dir.cdUp(); dir.cd("plugins"); QApplication::setLibraryPaths(QStringList(dir.absolutePath())); #endif //create defaultconfig ConfigFile *myConfig = new ConfigFile(argv[0], false); // set PlastiqueStyle even for mac-version to prevent artefacts on styled widgets a.setStyle(new QPlastiqueStyle); QString myAppDataPath = QString::fromUtf8(myConfig->readConfigString("AppDataDir").c_str()); //set QApplication default font QFontDatabase::addApplicationFont (myAppDataPath +"fonts/n019003l.pfb"); QFontDatabase::addApplicationFont (myAppDataPath +"fonts/VeraBd.ttf"); QFontDatabase::addApplicationFont (myAppDataPath +"fonts/c059013l.pfb"); #ifdef _WIN32 QString font1String("QApplication, QWidget, QDialog { font-family: \"Arial\"; font-size: 12px; }"); #else #ifdef __APPLE__ // QString font1String("font-family: \"Lucida Grande\";"); QString font1String("QApplication, QWidget, QDialog { font-size: 11px; }"); #else QString font1String("QApplication, QWidget, QDialog { font-family: \"Nimbus Sans L\"; font-size: 12px; }"); #endif #endif a.setStyleSheet(font1String + " QDialogButtonBox, QMessageBox { dialogbuttonbox-buttons-have-icons: 1; dialog-ok-icon: url(:/gfx/dialog_ok_apply.png); dialog-cancel-icon: url(:/gfx/dialog_close.png); dialog-close-icon: url(:/gfx/dialog_close.png); dialog-yes-icon: url(:/gfx/dialog_ok_apply.png); dialog-no-icon: url(:/gfx/dialog_close.png) }"); QPixmap *pixmap = new QPixmap(myAppDataPath + "gfx/gui/misc/welcomepokerth.png"); StartSplash splash(*pixmap); if(!myConfig->readConfigInt("DisableSplashScreenOnStartup")) { splash.show(); splash.showMessage(QString("Version %1").arg(POKERTH_BETA_RELEASE_STRING), 0x0042, QColor(153,213,0)); } //Set translations QTranslator qtTranslator; qtTranslator.load(QString(myAppDataPath +"translations/qt_") + QString::fromStdString(myConfig->readConfigString("Language"))); a.installTranslator(&qtTranslator); QTranslator translator; translator.load(QString(myAppDataPath +"translations/pokerth_") + QString::fromStdString(myConfig->readConfigString("Language"))); a.installTranslator(&translator); qRegisterMetaType<unsigned>("unsigned"); qRegisterMetaType<boost::shared_ptr<Game> >("boost::shared_ptr<Game>"); qRegisterMetaType<ServerStats>("ServerStats"); qRegisterMetaType<DenyGameInvitationReason>("DenyGameInvitationReason"); /////////////////////////////////////////////////// startWindowImpl mainWin(myConfig); a.setActivationWindow(&mainWin, true); int retVal = a.exec(); curl_global_cleanup(); socket_cleanup(); return retVal; } <commit_msg>windows font fix<commit_after>/*************************************************************************** * Copyright (C) 2006 by FThauer FHammer * * f.thauer@web.de * * * * 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., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include <boost/asio.hpp> #include <iostream> #include <cstdlib> #include <ctime> #include <qapplication.h> #include <QtGui> #include <QtCore> #ifdef __APPLE__ #include <QMacStyle> #endif #include <curl/curl.h> #include "session.h" #include "startwindowimpl.h" #include "configfile.h" #include "startsplash.h" #include "game_defs.h" #include <net/socket_startup.h> #include <third_party/qtsingleapplication/qtsingleapplication.h> #ifdef _MSC_VER #ifdef _DEBUG #define _CRTDBG_MAP_ALLOC #include <crtdbg.h> #define ENABLE_LEAK_CHECK() \ { \ int tmpFlag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG); \ tmpFlag |= _CRTDBG_LEAK_CHECK_DF; \ _CrtSetDbgFlag(tmpFlag); \ } #endif #endif #ifndef ENABLE_LEAK_CHECK #define ENABLE_LEAK_CHECK() #endif //Uncomment this for RELEASE on Linux/Unix/BSD (static Qt only) //#include <QtPlugin> //Q_IMPORT_PLUGIN(qjpeg) //Q_IMPORT_PLUGIN(qgif) #ifdef _WIN32 // Always use static Qt on Windows. #include <QtPlugin> Q_IMPORT_PLUGIN(qjpeg) Q_IMPORT_PLUGIN(qgif) #endif using namespace std; class startWindowImpl; class Game; int main( int argc, char **argv ) { //ENABLE_LEAK_CHECK(); //_CrtSetBreakAlloc(49937); socket_startup(); curl_global_init(CURL_GLOBAL_NOTHING); /////// can be removed for non-qt-guis //////////// QtSingleApplication a( argc, argv ); if (a.sendMessage("Wake up!")) { return 0; } #ifdef __APPLE__ // The following needs to be done directly after the application is created. QDir dir(QApplication::applicationDirPath()); dir.cdUp(); dir.cd("plugins"); QApplication::setLibraryPaths(QStringList(dir.absolutePath())); #endif //create defaultconfig ConfigFile *myConfig = new ConfigFile(argv[0], false); // set PlastiqueStyle even for mac-version to prevent artefacts on styled widgets a.setStyle(new QPlastiqueStyle); QString myAppDataPath = QString::fromUtf8(myConfig->readConfigString("AppDataDir").c_str()); //set QApplication default font QFontDatabase::addApplicationFont (myAppDataPath +"fonts/n019003l.pfb"); QFontDatabase::addApplicationFont (myAppDataPath +"fonts/VeraBd.ttf"); QFontDatabase::addApplicationFont (myAppDataPath +"fonts/c059013l.pfb"); #ifdef _WIN32 QString font1String("QApplication, QWidget, QDialog { font-size: 12px; }"); #else #ifdef __APPLE__ // QString font1String("font-family: \"Lucida Grande\";"); QString font1String("QApplication, QWidget, QDialog { font-size: 11px; }"); #else QString font1String("QApplication, QWidget, QDialog { font-family: \"Nimbus Sans L\"; font-size: 12px; }"); #endif #endif a.setStyleSheet(font1String + " QDialogButtonBox, QMessageBox { dialogbuttonbox-buttons-have-icons: 1; dialog-ok-icon: url(:/gfx/dialog_ok_apply.png); dialog-cancel-icon: url(:/gfx/dialog_close.png); dialog-close-icon: url(:/gfx/dialog_close.png); dialog-yes-icon: url(:/gfx/dialog_ok_apply.png); dialog-no-icon: url(:/gfx/dialog_close.png) }"); QPixmap *pixmap = new QPixmap(myAppDataPath + "gfx/gui/misc/welcomepokerth.png"); StartSplash splash(*pixmap); if(!myConfig->readConfigInt("DisableSplashScreenOnStartup")) { splash.show(); splash.showMessage(QString("Version %1").arg(POKERTH_BETA_RELEASE_STRING), 0x0042, QColor(153,213,0)); } //Set translations QTranslator qtTranslator; qtTranslator.load(QString(myAppDataPath +"translations/qt_") + QString::fromStdString(myConfig->readConfigString("Language"))); a.installTranslator(&qtTranslator); QTranslator translator; translator.load(QString(myAppDataPath +"translations/pokerth_") + QString::fromStdString(myConfig->readConfigString("Language"))); a.installTranslator(&translator); qRegisterMetaType<unsigned>("unsigned"); qRegisterMetaType<boost::shared_ptr<Game> >("boost::shared_ptr<Game>"); qRegisterMetaType<ServerStats>("ServerStats"); qRegisterMetaType<DenyGameInvitationReason>("DenyGameInvitationReason"); /////////////////////////////////////////////////// startWindowImpl mainWin(myConfig); a.setActivationWindow(&mainWin, true); int retVal = a.exec(); curl_global_cleanup(); socket_cleanup(); return retVal; } <|endoftext|>
<commit_before>// Copyright 2019 The IREE Authors // // Licensed under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception #include "iree/compiler/Translation/IREEVM.h" #include "iree/compiler/Bindings/Native/Transforms/Passes.h" #include "iree/compiler/Bindings/TFLite/Transforms/Passes.h" #include "iree/compiler/Dialect/Flow/Transforms/Passes.h" #include "iree/compiler/Dialect/HAL/Transforms/Passes.h" #include "iree/compiler/Dialect/IREE/Transforms/Passes.h" #include "iree/compiler/Dialect/VM/Target/Bytecode/TranslationFlags.h" #include "iree/compiler/Dialect/VM/Transforms/Passes.h" #include "iree/compiler/InputConversion/MHLO/Passes.h" #include "iree/compiler/InputConversion/TOSA/Passes.h" #include "iree/compiler/Utils/TracingUtils.h" #include "mlir/IR/BuiltinOps.h" #include "mlir/Pass/PassManager.h" #include "mlir/Translation.h" #ifdef IREE_HAVE_EMITC_DIALECT #include "iree/compiler/Dialect/VM/Target/C/CModuleTarget.h" #include "iree/compiler/Dialect/VM/Target/C/TranslationFlags.h" #endif // IREE_HAVE_EMITC_DIALECT namespace mlir { namespace iree_compiler { // TODO(#3817): move all of this code to the iree-compile driver/API. // Breaking this up such that for development iree-opt runs all passes/pipelines // and iree-translate strictly does the VM dialect to bytecode/emitc files will // match upstream better, and then our own iree-compile C API/binary will do the // whole end-to-end with options for bindings/targets/etc. struct BindingOptions { // Whether to include runtime support functions for the IREE native ABI. bool native = true; // Whether to include runtime support functions required for the IREE TFLite // API compatibility bindings. bool tflite = false; }; static BindingOptions getBindingOptionsFromFlags() { static llvm::cl::OptionCategory bindingOptionsCategory( "IREE translation binding support options"); static llvm::cl::opt<bool> *bindingsNativeFlag = new llvm::cl::opt<bool>{ "iree-native-bindings-support", llvm::cl::desc( "Include runtime support for native IREE ABI-compatible bindings"), llvm::cl::init(true), llvm::cl::cat(bindingOptionsCategory)}; static llvm::cl::opt<bool> *bindingsTFLiteFlag = new llvm::cl::opt<bool>{ "iree-tflite-bindings-support", llvm::cl::desc( "Include runtime support for the IREE TFLite compatibility bindings"), llvm::cl::init(false), llvm::cl::cat(bindingOptionsCategory)}; BindingOptions bindingOptions; bindingOptions.native = *bindingsNativeFlag; bindingOptions.tflite = *bindingsTFLiteFlag; return bindingOptions; } // The transformation to apply to the input prior to main compiler execution. // These input pipelines are purposefully primitive and mainly focused on // test case/reproducers as opposed to anything that should be coming from // a user. For user/framework level interfacing, a dedicated importer likely // needs to be created in order to represent whole-module level framework // quirks. These are just about the ops in the functions. struct InputDialectOptions { enum class Type { // Applies no input transformation. Only supported core and extension ops // are supported. none, // Legalizes input defined over TOSA ops. tosa, // Legalizes input defined over MHLO ops. mhlo, }; Type type; }; static InputDialectOptions getInputDialectOptionsFromFlags() { static llvm::cl::OptionCategory inputDialectOptions( "IREE options for controlling the input transformations to apply"); static llvm::cl::opt<InputDialectOptions::Type> *typeFlag = new llvm::cl::opt<InputDialectOptions::Type>{ "iree-input-type", llvm::cl::desc("IREE input type"), llvm::cl::values(clEnumValN(InputDialectOptions::Type::none, "none", "No input dialect transformation"), clEnumValN(InputDialectOptions::Type::tosa, "tosa", "Legalize from TOSA ops"), clEnumValN(InputDialectOptions::Type::mhlo, "mhlo", "Legalize from MHLO ops")), llvm::cl::init(InputDialectOptions::Type::none), llvm::cl::cat(inputDialectOptions)}; InputDialectOptions options; options.type = *typeFlag; return options; } // Performs initial dialect conversion to get the canonical input lowered into // the IREE execution/dataflow dialect. // // This will fail if we cannot support the input yet. The hope is that any // error that happens after this point is either backend-specific (like // unsupported SPIR-V lowering) or a bug. static LogicalResult convertToFlowModule(ModuleOp moduleOp) { PassManager passManager(moduleOp.getContext()); mlir::applyPassManagerCLOptions(passManager); mlir::applyDefaultTimingPassManagerCLOptions(passManager); passManager.addInstrumentation(std::make_unique<PassTracing>()); IREE::Flow::buildFlowTransformPassPipeline(passManager); if (failed(passManager.run(moduleOp))) { return moduleOp.emitError() << "failed to run flow transformation pass pipeline"; } return success(); } // Runs the flow->HAL transform pipeline to lower a flow module and compile // executables for the specified target backends. static LogicalResult convertToHALModule( ModuleOp moduleOp, IREE::HAL::TargetOptions executableOptions) { PassManager passManager(moduleOp.getContext()); mlir::applyPassManagerCLOptions(passManager); mlir::applyDefaultTimingPassManagerCLOptions(passManager); passManager.addInstrumentation(std::make_unique<PassTracing>()); IREE::HAL::buildHALTransformPassPipeline(passManager, executableOptions); if (failed(passManager.run(moduleOp))) { return moduleOp.emitError() << "failed to run HAL transformation pass pipeline"; } return success(); } // Converts the lowered module to a canonical vm.module containing only vm ops. // This uses patterns to convert from standard ops and other dialects to their // vm ABI form. static LogicalResult convertToVMModule(ModuleOp moduleOp, IREE::VM::TargetOptions targetOptions) { PassManager passManager(moduleOp.getContext()); mlir::applyPassManagerCLOptions(passManager); mlir::applyDefaultTimingPassManagerCLOptions(passManager); passManager.addInstrumentation(std::make_unique<PassTracing>()); IREE::VM::buildVMTransformPassPipeline(passManager, targetOptions); if (failed(passManager.run(moduleOp))) { return moduleOp.emitError() << "failed to run VM transformation pass pipeline"; } return success(); } static void buildIREEVMTransformPassPipeline( BindingOptions bindingOptions, InputDialectOptions inputOptions, IREE::HAL::TargetOptions executableOptions, IREE::VM::TargetOptions targetOptions, OpPassManager &passManager) { if (bindingOptions.native) { IREE::ABI::buildTransformPassPipeline(passManager); } if (bindingOptions.tflite) { IREE::TFLite::buildTransformPassPipeline(passManager); } switch (inputOptions.type) { case InputDialectOptions::Type::none: break; case InputDialectOptions::Type::tosa: buildTOSAInputConversionPassPipeline(passManager); break; case InputDialectOptions::Type::mhlo: buildMHLOInputConversionPassPipeline(passManager); break; } IREE::Flow::buildFlowTransformPassPipeline(passManager); IREE::HAL::buildHALTransformPassPipeline(passManager, executableOptions); IREE::VM::buildVMTransformPassPipeline(passManager, targetOptions); passManager.addPass(mlir::iree_compiler::IREE::createDropCompilerHintsPass()); } void buildDefaultIREEVMTransformPassPipeline(OpPassManager &passManager) { buildIREEVMTransformPassPipeline( getBindingOptionsFromFlags(), getInputDialectOptionsFromFlags(), IREE::HAL::getTargetOptionsFromFlags(), IREE::VM::getTargetOptionsFromFlags(), passManager); } void registerIREEVMTransformPassPipeline() { PassPipelineRegistration<> transformPassPipeline( "iree-transformation-pipeline", "Runs the full IREE input to VM transformation pipeline", [](OpPassManager &passManager) { buildDefaultIREEVMTransformPassPipeline(passManager); }); } // Converts from our source to a vm.module in canonical form. // After this completes we have a non-bytecode-specific vm.module that we // could lower to other forms (LLVM IR, C, etc). static LogicalResult translateFromMLIRToVM( ModuleOp moduleOp, BindingOptions bindingOptions, InputDialectOptions inputOptions, IREE::HAL::TargetOptions executableOptions, IREE::VM::TargetOptions targetOptions) { PassManager passManager(moduleOp.getContext()); mlir::applyPassManagerCLOptions(passManager); mlir::applyDefaultTimingPassManagerCLOptions(passManager); passManager.addInstrumentation(std::make_unique<PassTracing>()); buildIREEVMTransformPassPipeline(bindingOptions, inputOptions, executableOptions, targetOptions, passManager); if (failed(passManager.run(moduleOp))) { return moduleOp.emitError() << "conversion from source -> vm failed"; } return success(); } // Translates an MLIR module containing a set of supported IREE input dialects // to an IREE VM bytecode module for loading at runtime. // // See iree/schemas/bytecode_module_def.fbs for the description of the // serialized module format. // // Exposed via the --iree-mlir-to-vm-bytecode-module translation. static LogicalResult translateFromMLIRToVMBytecodeModuleWithFlags( ModuleOp moduleOp, llvm::raw_ostream &output) { mlir::registerPassManagerCLOptions(); auto bindingOptions = getBindingOptionsFromFlags(); auto inputOptions = getInputDialectOptionsFromFlags(); auto halTargetOptions = IREE::HAL::getTargetOptionsFromFlags(); auto vmTargetOptions = IREE::VM::getTargetOptionsFromFlags(); auto bytecodeTargetOptions = IREE::VM::getBytecodeTargetOptionsFromFlags(); auto result = translateFromMLIRToVM(moduleOp, bindingOptions, inputOptions, halTargetOptions, vmTargetOptions); if (failed(result)) { return result; } return translateModuleToBytecode(moduleOp, bytecodeTargetOptions, output); } #ifdef IREE_HAVE_EMITC_DIALECT // Translates an MLIR module containing a set of supported IREE input dialects // to an IREE VM C module. // // Exposed via the --iree-mlir-to-vm-c-module translation. static LogicalResult translateFromMLIRToVMCModule( ModuleOp moduleOp, BindingOptions bindingOptions, InputDialectOptions inputOptions, IREE::HAL::TargetOptions executableOptions, IREE::VM::TargetOptions targetOptions, IREE::VM::CTargetOptions cTargetOptions, llvm::raw_ostream &output) { auto result = translateFromMLIRToVM(moduleOp, bindingOptions, inputOptions, executableOptions, targetOptions); if (failed(result)) { return result; } // Serialize to c code. return mlir::iree_compiler::IREE::VM::translateModuleToC( moduleOp, cTargetOptions, output); } static LogicalResult translateFromMLIRToVMCModuleWithFlags( ModuleOp moduleOp, llvm::raw_ostream &output) { mlir::registerPassManagerCLOptions(); auto bindingOptions = getBindingOptionsFromFlags(); auto inputOptions = getInputDialectOptionsFromFlags(); auto halTargetOptions = IREE::HAL::getTargetOptionsFromFlags(); auto vmTargetOptions = IREE::VM::getTargetOptionsFromFlags(); auto cTargetOptions = IREE::VM::getCTargetOptionsFromFlags(); return translateFromMLIRToVMCModule(moduleOp, bindingOptions, inputOptions, halTargetOptions, vmTargetOptions, cTargetOptions, output); } #endif // IREE_HAVE_EMITC_DIALECT void registerIREEVMTranslationFlags() { getBindingOptionsFromFlags(); getInputDialectOptionsFromFlags(); } void registerIREEVMTranslation() { registerIREEVMTranslationFlags(); TranslateFromMLIRRegistration toVMBytecodeModuleWithFlags( "iree-mlir-to-vm-bytecode-module", translateFromMLIRToVMBytecodeModuleWithFlags); #ifdef IREE_HAVE_EMITC_DIALECT TranslateFromMLIRRegistration toVMCModuleWithFlags( "iree-mlir-to-vm-c-module", translateFromMLIRToVMCModuleWithFlags); #endif // IREE_HAVE_EMITC_DIALECT } } // namespace iree_compiler } // namespace mlir <commit_msg>Drop `translateFromMLIRToVMCModule()` (#6308)<commit_after>// Copyright 2019 The IREE Authors // // Licensed under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception #include "iree/compiler/Translation/IREEVM.h" #include "iree/compiler/Bindings/Native/Transforms/Passes.h" #include "iree/compiler/Bindings/TFLite/Transforms/Passes.h" #include "iree/compiler/Dialect/Flow/Transforms/Passes.h" #include "iree/compiler/Dialect/HAL/Transforms/Passes.h" #include "iree/compiler/Dialect/IREE/Transforms/Passes.h" #include "iree/compiler/Dialect/VM/Target/Bytecode/TranslationFlags.h" #include "iree/compiler/Dialect/VM/Transforms/Passes.h" #include "iree/compiler/InputConversion/MHLO/Passes.h" #include "iree/compiler/InputConversion/TOSA/Passes.h" #include "iree/compiler/Utils/TracingUtils.h" #include "mlir/IR/BuiltinOps.h" #include "mlir/Pass/PassManager.h" #include "mlir/Translation.h" #ifdef IREE_HAVE_EMITC_DIALECT #include "iree/compiler/Dialect/VM/Target/C/CModuleTarget.h" #include "iree/compiler/Dialect/VM/Target/C/TranslationFlags.h" #endif // IREE_HAVE_EMITC_DIALECT namespace mlir { namespace iree_compiler { // TODO(#3817): move all of this code to the iree-compile driver/API. // Breaking this up such that for development iree-opt runs all passes/pipelines // and iree-translate strictly does the VM dialect to bytecode/emitc files will // match upstream better, and then our own iree-compile C API/binary will do the // whole end-to-end with options for bindings/targets/etc. struct BindingOptions { // Whether to include runtime support functions for the IREE native ABI. bool native = true; // Whether to include runtime support functions required for the IREE TFLite // API compatibility bindings. bool tflite = false; }; static BindingOptions getBindingOptionsFromFlags() { static llvm::cl::OptionCategory bindingOptionsCategory( "IREE translation binding support options"); static llvm::cl::opt<bool> *bindingsNativeFlag = new llvm::cl::opt<bool>{ "iree-native-bindings-support", llvm::cl::desc( "Include runtime support for native IREE ABI-compatible bindings"), llvm::cl::init(true), llvm::cl::cat(bindingOptionsCategory)}; static llvm::cl::opt<bool> *bindingsTFLiteFlag = new llvm::cl::opt<bool>{ "iree-tflite-bindings-support", llvm::cl::desc( "Include runtime support for the IREE TFLite compatibility bindings"), llvm::cl::init(false), llvm::cl::cat(bindingOptionsCategory)}; BindingOptions bindingOptions; bindingOptions.native = *bindingsNativeFlag; bindingOptions.tflite = *bindingsTFLiteFlag; return bindingOptions; } // The transformation to apply to the input prior to main compiler execution. // These input pipelines are purposefully primitive and mainly focused on // test case/reproducers as opposed to anything that should be coming from // a user. For user/framework level interfacing, a dedicated importer likely // needs to be created in order to represent whole-module level framework // quirks. These are just about the ops in the functions. struct InputDialectOptions { enum class Type { // Applies no input transformation. Only supported core and extension ops // are supported. none, // Legalizes input defined over TOSA ops. tosa, // Legalizes input defined over MHLO ops. mhlo, }; Type type; }; static InputDialectOptions getInputDialectOptionsFromFlags() { static llvm::cl::OptionCategory inputDialectOptions( "IREE options for controlling the input transformations to apply"); static llvm::cl::opt<InputDialectOptions::Type> *typeFlag = new llvm::cl::opt<InputDialectOptions::Type>{ "iree-input-type", llvm::cl::desc("IREE input type"), llvm::cl::values(clEnumValN(InputDialectOptions::Type::none, "none", "No input dialect transformation"), clEnumValN(InputDialectOptions::Type::tosa, "tosa", "Legalize from TOSA ops"), clEnumValN(InputDialectOptions::Type::mhlo, "mhlo", "Legalize from MHLO ops")), llvm::cl::init(InputDialectOptions::Type::none), llvm::cl::cat(inputDialectOptions)}; InputDialectOptions options; options.type = *typeFlag; return options; } // Performs initial dialect conversion to get the canonical input lowered into // the IREE execution/dataflow dialect. // // This will fail if we cannot support the input yet. The hope is that any // error that happens after this point is either backend-specific (like // unsupported SPIR-V lowering) or a bug. static LogicalResult convertToFlowModule(ModuleOp moduleOp) { PassManager passManager(moduleOp.getContext()); mlir::applyPassManagerCLOptions(passManager); mlir::applyDefaultTimingPassManagerCLOptions(passManager); passManager.addInstrumentation(std::make_unique<PassTracing>()); IREE::Flow::buildFlowTransformPassPipeline(passManager); if (failed(passManager.run(moduleOp))) { return moduleOp.emitError() << "failed to run flow transformation pass pipeline"; } return success(); } // Runs the flow->HAL transform pipeline to lower a flow module and compile // executables for the specified target backends. static LogicalResult convertToHALModule( ModuleOp moduleOp, IREE::HAL::TargetOptions executableOptions) { PassManager passManager(moduleOp.getContext()); mlir::applyPassManagerCLOptions(passManager); mlir::applyDefaultTimingPassManagerCLOptions(passManager); passManager.addInstrumentation(std::make_unique<PassTracing>()); IREE::HAL::buildHALTransformPassPipeline(passManager, executableOptions); if (failed(passManager.run(moduleOp))) { return moduleOp.emitError() << "failed to run HAL transformation pass pipeline"; } return success(); } // Converts the lowered module to a canonical vm.module containing only vm ops. // This uses patterns to convert from standard ops and other dialects to their // vm ABI form. static LogicalResult convertToVMModule(ModuleOp moduleOp, IREE::VM::TargetOptions targetOptions) { PassManager passManager(moduleOp.getContext()); mlir::applyPassManagerCLOptions(passManager); mlir::applyDefaultTimingPassManagerCLOptions(passManager); passManager.addInstrumentation(std::make_unique<PassTracing>()); IREE::VM::buildVMTransformPassPipeline(passManager, targetOptions); if (failed(passManager.run(moduleOp))) { return moduleOp.emitError() << "failed to run VM transformation pass pipeline"; } return success(); } static void buildIREEVMTransformPassPipeline( BindingOptions bindingOptions, InputDialectOptions inputOptions, IREE::HAL::TargetOptions executableOptions, IREE::VM::TargetOptions targetOptions, OpPassManager &passManager) { if (bindingOptions.native) { IREE::ABI::buildTransformPassPipeline(passManager); } if (bindingOptions.tflite) { IREE::TFLite::buildTransformPassPipeline(passManager); } switch (inputOptions.type) { case InputDialectOptions::Type::none: break; case InputDialectOptions::Type::tosa: buildTOSAInputConversionPassPipeline(passManager); break; case InputDialectOptions::Type::mhlo: buildMHLOInputConversionPassPipeline(passManager); break; } IREE::Flow::buildFlowTransformPassPipeline(passManager); IREE::HAL::buildHALTransformPassPipeline(passManager, executableOptions); IREE::VM::buildVMTransformPassPipeline(passManager, targetOptions); passManager.addPass(mlir::iree_compiler::IREE::createDropCompilerHintsPass()); } void buildDefaultIREEVMTransformPassPipeline(OpPassManager &passManager) { buildIREEVMTransformPassPipeline( getBindingOptionsFromFlags(), getInputDialectOptionsFromFlags(), IREE::HAL::getTargetOptionsFromFlags(), IREE::VM::getTargetOptionsFromFlags(), passManager); } void registerIREEVMTransformPassPipeline() { PassPipelineRegistration<> transformPassPipeline( "iree-transformation-pipeline", "Runs the full IREE input to VM transformation pipeline", [](OpPassManager &passManager) { buildDefaultIREEVMTransformPassPipeline(passManager); }); } // Converts from our source to a vm.module in canonical form. // After this completes we have a non-bytecode-specific vm.module that we // could lower to other forms (LLVM IR, C, etc). static LogicalResult translateFromMLIRToVM( ModuleOp moduleOp, BindingOptions bindingOptions, InputDialectOptions inputOptions, IREE::HAL::TargetOptions executableOptions, IREE::VM::TargetOptions targetOptions) { PassManager passManager(moduleOp.getContext()); mlir::applyPassManagerCLOptions(passManager); mlir::applyDefaultTimingPassManagerCLOptions(passManager); passManager.addInstrumentation(std::make_unique<PassTracing>()); buildIREEVMTransformPassPipeline(bindingOptions, inputOptions, executableOptions, targetOptions, passManager); if (failed(passManager.run(moduleOp))) { return moduleOp.emitError() << "conversion from source -> vm failed"; } return success(); } // Translates an MLIR module containing a set of supported IREE input dialects // to an IREE VM bytecode module for loading at runtime. // // See iree/schemas/bytecode_module_def.fbs for the description of the // serialized module format. // // Exposed via the --iree-mlir-to-vm-bytecode-module translation. static LogicalResult translateFromMLIRToVMBytecodeModuleWithFlags( ModuleOp moduleOp, llvm::raw_ostream &output) { mlir::registerPassManagerCLOptions(); auto bindingOptions = getBindingOptionsFromFlags(); auto inputOptions = getInputDialectOptionsFromFlags(); auto halTargetOptions = IREE::HAL::getTargetOptionsFromFlags(); auto vmTargetOptions = IREE::VM::getTargetOptionsFromFlags(); auto bytecodeTargetOptions = IREE::VM::getBytecodeTargetOptionsFromFlags(); auto result = translateFromMLIRToVM(moduleOp, bindingOptions, inputOptions, halTargetOptions, vmTargetOptions); if (failed(result)) { return result; } return translateModuleToBytecode(moduleOp, bytecodeTargetOptions, output); } #ifdef IREE_HAVE_EMITC_DIALECT // Translates an MLIR module containing a set of supported IREE input dialects // to an IREE VM C module. // // Exposed via the --iree-mlir-to-vm-c-module translation. static LogicalResult translateFromMLIRToVMCModuleWithFlags( ModuleOp moduleOp, llvm::raw_ostream &output) { mlir::registerPassManagerCLOptions(); auto bindingOptions = getBindingOptionsFromFlags(); auto inputOptions = getInputDialectOptionsFromFlags(); auto halTargetOptions = IREE::HAL::getTargetOptionsFromFlags(); auto vmTargetOptions = IREE::VM::getTargetOptionsFromFlags(); auto cTargetOptions = IREE::VM::getCTargetOptionsFromFlags(); auto result = translateFromMLIRToVM(moduleOp, bindingOptions, inputOptions, halTargetOptions, vmTargetOptions); if (failed(result)) { return result; } // Serialize to c code. return mlir::iree_compiler::IREE::VM::translateModuleToC( moduleOp, cTargetOptions, output); } #endif // IREE_HAVE_EMITC_DIALECT void registerIREEVMTranslationFlags() { getBindingOptionsFromFlags(); getInputDialectOptionsFromFlags(); } void registerIREEVMTranslation() { registerIREEVMTranslationFlags(); TranslateFromMLIRRegistration toVMBytecodeModuleWithFlags( "iree-mlir-to-vm-bytecode-module", translateFromMLIRToVMBytecodeModuleWithFlags); #ifdef IREE_HAVE_EMITC_DIALECT TranslateFromMLIRRegistration toVMCModuleWithFlags( "iree-mlir-to-vm-c-module", translateFromMLIRToVMCModuleWithFlags); #endif // IREE_HAVE_EMITC_DIALECT } } // namespace iree_compiler } // namespace mlir <|endoftext|>
<commit_before>#include "perspective_camera.h" PerspectiveCamera::PerspectiveCamera( void ) {} PerspectiveCamera::PerspectiveCamera( const float min_x, const float max_x, const float min_y, const float max_y, const float distance, //distance to viewport const glm::ivec2 &resolution, const glm::vec3 &position, const glm::vec3 &up_vector, const glm::vec3 &look_at ) : Camera::Camera{ resolution, position, up_vector, look_at }, min_x_{ min_x }, max_x_{ max_x }, min_y_{ min_y }, max_y_{ max_y }, distance_{ distance } {} Ray PerspectiveCamera::getWorldSpaceRay( const glm::vec2 &pixel_coord ) const { float width = max_x_ - min_x_; float height = max_y_ - min_y_; glm::vec3 direction{ ( pixel_coord[0]+0.5f )/ static_cast< float >( resolution_[0] ) * width + min_x_, ( pixel_coord[1]+0.5f )/ static_cast< float >( resolution_[1] ) * -height - min_y_, -distance_ }; return Ray{ onb_.getBasisMatrix() * position_, glm::normalize( onb_.getBasisMatrix() * direction ) }; }<commit_msg>Perspective camera bug fixes<commit_after>#include "perspective_camera.h" PerspectiveCamera::PerspectiveCamera( void ) {} PerspectiveCamera::PerspectiveCamera( const float min_x, const float max_x, const float min_y, const float max_y, const float distance, //distance to viewport const glm::ivec2 &resolution, const glm::vec3 &position, const glm::vec3 &up_vector, const glm::vec3 &look_at ) : Camera::Camera{ resolution, position, up_vector, look_at }, min_x_{ min_x }, max_x_{ max_x }, min_y_{ min_y }, max_y_{ max_y }, distance_{ distance } {} Ray PerspectiveCamera::getWorldSpaceRay( const glm::vec2 &pixel_coord ) const { float width = max_x_ - min_x_; float height = max_y_ - min_y_; glm::vec3 screen_point{ ( pixel_coord[0]+0.5f )/ static_cast< float >( resolution_[0] ) * width + min_x_, ( pixel_coord[1]+0.5f )/ static_cast< float >( resolution_[1] ) * -height + max_y_, -distance_ }; return Ray{ position_, glm::normalize( onb_.getBasisMatrix() * screen_point ) }; } <|endoftext|>
<commit_before>// Copyright (c) 2008 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 "net/proxy/proxy_script_fetcher.h" #include "base/file_path.h" #include "base/compiler_specific.h" #include "base/path_service.h" #include "net/base/net_util.h" #include "net/base/ssl_config_service_defaults.h" #include "net/base/test_completion_callback.h" #include "net/disk_cache/disk_cache.h" #include "net/http/http_cache.h" #include "net/url_request/url_request_unittest.h" #include "testing/gtest/include/gtest/gtest.h" #include "testing/platform_test.h" // TODO(eroman): // - Test canceling an outstanding request. // - Test deleting ProxyScriptFetcher while a request is in progress. const wchar_t kDocRoot[] = L"net/data/proxy_script_fetcher_unittest"; struct FetchResult { int code; std::string bytes; }; // A non-mock URL request which can access http:// and file:// urls. class RequestContext : public URLRequestContext { public: RequestContext() { net::ProxyConfig no_proxy; host_resolver_ = net::CreateSystemHostResolver(); proxy_service_ = net::ProxyService::CreateFixed(no_proxy); ssl_config_service_ = new net::SSLConfigServiceDefaults; http_transaction_factory_ = new net::HttpCache(net::HttpNetworkLayer::CreateFactory( host_resolver_, proxy_service_, ssl_config_service_), disk_cache::CreateInMemoryCacheBackend(0)); } ~RequestContext() { delete http_transaction_factory_; } }; // Required to be in net namespace by FRIEND_TEST. namespace net { // Get a file:// url relative to net/data/proxy/proxy_script_fetcher_unittest. GURL GetTestFileUrl(const std::string& relpath) { FilePath path; PathService::Get(base::DIR_SOURCE_ROOT, &path); path = path.AppendASCII("net"); path = path.AppendASCII("data"); path = path.AppendASCII("proxy_script_fetcher_unittest"); GURL base_url = FilePathToFileURL(path); return GURL(base_url.spec() + "/" + relpath); } typedef PlatformTest ProxyScriptFetcherTest; TEST_F(ProxyScriptFetcherTest, FileUrl) { scoped_refptr<URLRequestContext> context = new RequestContext; scoped_ptr<ProxyScriptFetcher> pac_fetcher( ProxyScriptFetcher::Create(context)); { // Fetch a non-existent file. std::string bytes; TestCompletionCallback callback; int result = pac_fetcher->Fetch(GetTestFileUrl("does-not-exist"), &bytes, &callback); EXPECT_EQ(ERR_IO_PENDING, result); EXPECT_EQ(ERR_FILE_NOT_FOUND, callback.WaitForResult()); EXPECT_TRUE(bytes.empty()); } { // Fetch a file that exists. std::string bytes; TestCompletionCallback callback; int result = pac_fetcher->Fetch(GetTestFileUrl("pac.txt"), &bytes, &callback); EXPECT_EQ(ERR_IO_PENDING, result); EXPECT_EQ(OK, callback.WaitForResult()); EXPECT_EQ("-pac.txt-\n", bytes); } } // Note that all mime types are allowed for PAC file, to be consistent // with other browsers. TEST_F(ProxyScriptFetcherTest, HttpMimeType) { scoped_refptr<HTTPTestServer> server = HTTPTestServer::CreateServer(kDocRoot, NULL); ASSERT_TRUE(NULL != server.get()); scoped_refptr<URLRequestContext> context = new RequestContext; scoped_ptr<ProxyScriptFetcher> pac_fetcher( ProxyScriptFetcher::Create(context)); { // Fetch a PAC with mime type "text/plain" GURL url = server->TestServerPage("files/pac.txt"); std::string bytes; TestCompletionCallback callback; int result = pac_fetcher->Fetch(url, &bytes, &callback); EXPECT_EQ(ERR_IO_PENDING, result); EXPECT_EQ(OK, callback.WaitForResult()); EXPECT_EQ("-pac.txt-\n", bytes); } { // Fetch a PAC with mime type "text/html" GURL url = server->TestServerPage("files/pac.html"); std::string bytes; TestCompletionCallback callback; int result = pac_fetcher->Fetch(url, &bytes, &callback); EXPECT_EQ(ERR_IO_PENDING, result); EXPECT_EQ(OK, callback.WaitForResult()); EXPECT_EQ("-pac.html-\n", bytes); } { // Fetch a PAC with mime type "application/x-ns-proxy-autoconfig" GURL url = server->TestServerPage("files/pac.nsproxy"); std::string bytes; TestCompletionCallback callback; int result = pac_fetcher->Fetch(url, &bytes, &callback); EXPECT_EQ(ERR_IO_PENDING, result); EXPECT_EQ(OK, callback.WaitForResult()); EXPECT_EQ("-pac.nsproxy-\n", bytes); } } TEST_F(ProxyScriptFetcherTest, HttpStatusCode) { scoped_refptr<HTTPTestServer> server = HTTPTestServer::CreateServer(kDocRoot, NULL); ASSERT_TRUE(NULL != server.get()); scoped_refptr<URLRequestContext> context = new RequestContext; scoped_ptr<ProxyScriptFetcher> pac_fetcher( ProxyScriptFetcher::Create(context)); { // Fetch a PAC which gives a 500 -- FAIL GURL url = server->TestServerPage("files/500.pac"); std::string bytes; TestCompletionCallback callback; int result = pac_fetcher->Fetch(url, &bytes, &callback); EXPECT_EQ(ERR_IO_PENDING, result); EXPECT_EQ(ERR_PAC_STATUS_NOT_OK, callback.WaitForResult()); EXPECT_TRUE(bytes.empty()); } { // Fetch a PAC which gives a 404 -- FAIL GURL url = server->TestServerPage("files/404.pac"); std::string bytes; TestCompletionCallback callback; int result = pac_fetcher->Fetch(url, &bytes, &callback); EXPECT_EQ(ERR_IO_PENDING, result); EXPECT_EQ(ERR_PAC_STATUS_NOT_OK, callback.WaitForResult()); EXPECT_TRUE(bytes.empty()); } } TEST_F(ProxyScriptFetcherTest, ContentDisposition) { scoped_refptr<HTTPTestServer> server = HTTPTestServer::CreateServer(kDocRoot, NULL); ASSERT_TRUE(NULL != server.get()); scoped_refptr<URLRequestContext> context = new RequestContext; scoped_ptr<ProxyScriptFetcher> pac_fetcher( ProxyScriptFetcher::Create(context)); // Fetch PAC scripts via HTTP with a Content-Disposition header -- should // have no effect. GURL url = server->TestServerPage("files/downloadable.pac"); std::string bytes; TestCompletionCallback callback; int result = pac_fetcher->Fetch(url, &bytes, &callback); EXPECT_EQ(ERR_IO_PENDING, result); EXPECT_EQ(OK, callback.WaitForResult()); EXPECT_EQ("-downloadable.pac-\n", bytes); } TEST_F(ProxyScriptFetcherTest, NoCache) { scoped_refptr<HTTPTestServer> server = HTTPTestServer::CreateServer(kDocRoot, NULL); ASSERT_TRUE(NULL != server.get()); scoped_refptr<URLRequestContext> context = new RequestContext; scoped_ptr<ProxyScriptFetcher> pac_fetcher( ProxyScriptFetcher::Create(context)); // Fetch a PAC script whose HTTP headers make it cacheable for 1 hour. GURL url = server->TestServerPage("files/cacheable_1hr.pac"); { std::string bytes; TestCompletionCallback callback; int result = pac_fetcher->Fetch(url, &bytes, &callback); EXPECT_EQ(ERR_IO_PENDING, result); EXPECT_EQ(OK, callback.WaitForResult()); EXPECT_EQ("-cacheable_1hr.pac-\n", bytes); } // Now kill the HTTP server. server->SendQuit(); EXPECT_TRUE(server->WaitToFinish(20000)); server = NULL; // Try to fetch the file again -- if should fail, since the server is not // running anymore. (If it were instead being loaded from cache, we would // get a success. { std::string bytes; TestCompletionCallback callback; int result = pac_fetcher->Fetch(url, &bytes, &callback); EXPECT_EQ(ERR_IO_PENDING, result); EXPECT_EQ(ERR_CONNECTION_REFUSED, callback.WaitForResult()); } } TEST_F(ProxyScriptFetcherTest, TooLarge) { scoped_refptr<HTTPTestServer> server = HTTPTestServer::CreateServer(kDocRoot, NULL); ASSERT_TRUE(NULL != server.get()); scoped_refptr<URLRequestContext> context = new RequestContext; scoped_ptr<ProxyScriptFetcher> pac_fetcher( ProxyScriptFetcher::Create(context)); // Set the maximum response size to 50 bytes. int prev_size = ProxyScriptFetcher::SetSizeConstraintForUnittest(50); // These two URLs are the same file, but are http:// vs file:// GURL urls[] = { server->TestServerPage("files/large-pac.nsproxy"), GetTestFileUrl("large-pac.nsproxy") }; // Try fetching URLs that are 101 bytes large. We should abort the request // after 50 bytes have been read, and fail with a too large error. for (size_t i = 0; i < arraysize(urls); ++i) { const GURL& url = urls[i]; std::string bytes; TestCompletionCallback callback; int result = pac_fetcher->Fetch(url, &bytes, &callback); EXPECT_EQ(ERR_IO_PENDING, result); EXPECT_EQ(ERR_FILE_TOO_BIG, callback.WaitForResult()); EXPECT_TRUE(bytes.empty()); } // Restore the original size bound. ProxyScriptFetcher::SetSizeConstraintForUnittest(prev_size); { // Make sure we can still fetch regular URLs. GURL url = server->TestServerPage("files/pac.nsproxy"); std::string bytes; TestCompletionCallback callback; int result = pac_fetcher->Fetch(url, &bytes, &callback); EXPECT_EQ(ERR_IO_PENDING, result); EXPECT_EQ(OK, callback.WaitForResult()); EXPECT_EQ("-pac.nsproxy-\n", bytes); } } TEST_F(ProxyScriptFetcherTest, Hang) { scoped_refptr<HTTPTestServer> server = HTTPTestServer::CreateServer(kDocRoot, NULL); ASSERT_TRUE(NULL != server.get()); scoped_refptr<URLRequestContext> context = new RequestContext; scoped_ptr<ProxyScriptFetcher> pac_fetcher( ProxyScriptFetcher::Create(context)); // Set the timeout period to 0.5 seconds. int prev_timeout = ProxyScriptFetcher::SetTimeoutConstraintForUnittest(500); // Try fetching a URL which takes 1.2 seconds. We should abort the request // after 500 ms, and fail with a timeout error. { GURL url = server->TestServerPage("slow/proxy.pac?1.2"); std::string bytes; TestCompletionCallback callback; int result = pac_fetcher->Fetch(url, &bytes, &callback); EXPECT_EQ(ERR_IO_PENDING, result); EXPECT_EQ(ERR_TIMED_OUT, callback.WaitForResult()); EXPECT_TRUE(bytes.empty()); } // Restore the original timeout period. ProxyScriptFetcher::SetTimeoutConstraintForUnittest(prev_timeout); { // Make sure we can still fetch regular URLs. GURL url = server->TestServerPage("files/pac.nsproxy"); std::string bytes; TestCompletionCallback callback; int result = pac_fetcher->Fetch(url, &bytes, &callback); EXPECT_EQ(ERR_IO_PENDING, result); EXPECT_EQ(OK, callback.WaitForResult()); EXPECT_EQ("-pac.nsproxy-\n", bytes); } } // The ProxyScriptFetcher should decode any content-codings // (like gzip, bzip, etc.), and apply any charset conversions to yield // UTF8. TEST_F(ProxyScriptFetcherTest, Encodings) { scoped_refptr<HTTPTestServer> server = HTTPTestServer::CreateServer(kDocRoot, NULL); ASSERT_TRUE(NULL != server.get()); scoped_refptr<URLRequestContext> context = new RequestContext; scoped_ptr<ProxyScriptFetcher> pac_fetcher( ProxyScriptFetcher::Create(context)); // Test a response that is gzip-encoded -- should get inflated. { GURL url = server->TestServerPage("files/gzipped_pac"); std::string bytes; TestCompletionCallback callback; int result = pac_fetcher->Fetch(url, &bytes, &callback); EXPECT_EQ(ERR_IO_PENDING, result); EXPECT_EQ(OK, callback.WaitForResult()); EXPECT_EQ("This data was gzipped.\n", bytes); } // Test a response that was served as UTF-16 (BE). It should // be converted to UTF8. { GURL url = server->TestServerPage("files/utf16be_pac"); std::string bytes; TestCompletionCallback callback; int result = pac_fetcher->Fetch(url, &bytes, &callback); EXPECT_EQ(ERR_IO_PENDING, result); EXPECT_EQ(OK, callback.WaitForResult()); EXPECT_EQ("This was encoded as UTF-16BE.\n", bytes); } } } // namespace net <commit_msg>Refactor: Don't send the quit command before killing test server for ProxyScriptFetcherTest.NoCache. Instead we just murder the process directly.<commit_after>// Copyright (c) 2008 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 "net/proxy/proxy_script_fetcher.h" #include "base/file_path.h" #include "base/compiler_specific.h" #include "base/path_service.h" #include "net/base/net_util.h" #include "net/base/ssl_config_service_defaults.h" #include "net/base/test_completion_callback.h" #include "net/disk_cache/disk_cache.h" #include "net/http/http_cache.h" #include "net/url_request/url_request_unittest.h" #include "testing/gtest/include/gtest/gtest.h" #include "testing/platform_test.h" // TODO(eroman): // - Test canceling an outstanding request. // - Test deleting ProxyScriptFetcher while a request is in progress. const wchar_t kDocRoot[] = L"net/data/proxy_script_fetcher_unittest"; struct FetchResult { int code; std::string bytes; }; // A non-mock URL request which can access http:// and file:// urls. class RequestContext : public URLRequestContext { public: RequestContext() { net::ProxyConfig no_proxy; host_resolver_ = net::CreateSystemHostResolver(); proxy_service_ = net::ProxyService::CreateFixed(no_proxy); ssl_config_service_ = new net::SSLConfigServiceDefaults; http_transaction_factory_ = new net::HttpCache(net::HttpNetworkLayer::CreateFactory( host_resolver_, proxy_service_, ssl_config_service_), disk_cache::CreateInMemoryCacheBackend(0)); } ~RequestContext() { delete http_transaction_factory_; } }; // Required to be in net namespace by FRIEND_TEST. namespace net { // Get a file:// url relative to net/data/proxy/proxy_script_fetcher_unittest. GURL GetTestFileUrl(const std::string& relpath) { FilePath path; PathService::Get(base::DIR_SOURCE_ROOT, &path); path = path.AppendASCII("net"); path = path.AppendASCII("data"); path = path.AppendASCII("proxy_script_fetcher_unittest"); GURL base_url = FilePathToFileURL(path); return GURL(base_url.spec() + "/" + relpath); } typedef PlatformTest ProxyScriptFetcherTest; TEST_F(ProxyScriptFetcherTest, FileUrl) { scoped_refptr<URLRequestContext> context = new RequestContext; scoped_ptr<ProxyScriptFetcher> pac_fetcher( ProxyScriptFetcher::Create(context)); { // Fetch a non-existent file. std::string bytes; TestCompletionCallback callback; int result = pac_fetcher->Fetch(GetTestFileUrl("does-not-exist"), &bytes, &callback); EXPECT_EQ(ERR_IO_PENDING, result); EXPECT_EQ(ERR_FILE_NOT_FOUND, callback.WaitForResult()); EXPECT_TRUE(bytes.empty()); } { // Fetch a file that exists. std::string bytes; TestCompletionCallback callback; int result = pac_fetcher->Fetch(GetTestFileUrl("pac.txt"), &bytes, &callback); EXPECT_EQ(ERR_IO_PENDING, result); EXPECT_EQ(OK, callback.WaitForResult()); EXPECT_EQ("-pac.txt-\n", bytes); } } // Note that all mime types are allowed for PAC file, to be consistent // with other browsers. TEST_F(ProxyScriptFetcherTest, HttpMimeType) { scoped_refptr<HTTPTestServer> server = HTTPTestServer::CreateServer(kDocRoot, NULL); ASSERT_TRUE(NULL != server.get()); scoped_refptr<URLRequestContext> context = new RequestContext; scoped_ptr<ProxyScriptFetcher> pac_fetcher( ProxyScriptFetcher::Create(context)); { // Fetch a PAC with mime type "text/plain" GURL url = server->TestServerPage("files/pac.txt"); std::string bytes; TestCompletionCallback callback; int result = pac_fetcher->Fetch(url, &bytes, &callback); EXPECT_EQ(ERR_IO_PENDING, result); EXPECT_EQ(OK, callback.WaitForResult()); EXPECT_EQ("-pac.txt-\n", bytes); } { // Fetch a PAC with mime type "text/html" GURL url = server->TestServerPage("files/pac.html"); std::string bytes; TestCompletionCallback callback; int result = pac_fetcher->Fetch(url, &bytes, &callback); EXPECT_EQ(ERR_IO_PENDING, result); EXPECT_EQ(OK, callback.WaitForResult()); EXPECT_EQ("-pac.html-\n", bytes); } { // Fetch a PAC with mime type "application/x-ns-proxy-autoconfig" GURL url = server->TestServerPage("files/pac.nsproxy"); std::string bytes; TestCompletionCallback callback; int result = pac_fetcher->Fetch(url, &bytes, &callback); EXPECT_EQ(ERR_IO_PENDING, result); EXPECT_EQ(OK, callback.WaitForResult()); EXPECT_EQ("-pac.nsproxy-\n", bytes); } } TEST_F(ProxyScriptFetcherTest, HttpStatusCode) { scoped_refptr<HTTPTestServer> server = HTTPTestServer::CreateServer(kDocRoot, NULL); ASSERT_TRUE(NULL != server.get()); scoped_refptr<URLRequestContext> context = new RequestContext; scoped_ptr<ProxyScriptFetcher> pac_fetcher( ProxyScriptFetcher::Create(context)); { // Fetch a PAC which gives a 500 -- FAIL GURL url = server->TestServerPage("files/500.pac"); std::string bytes; TestCompletionCallback callback; int result = pac_fetcher->Fetch(url, &bytes, &callback); EXPECT_EQ(ERR_IO_PENDING, result); EXPECT_EQ(ERR_PAC_STATUS_NOT_OK, callback.WaitForResult()); EXPECT_TRUE(bytes.empty()); } { // Fetch a PAC which gives a 404 -- FAIL GURL url = server->TestServerPage("files/404.pac"); std::string bytes; TestCompletionCallback callback; int result = pac_fetcher->Fetch(url, &bytes, &callback); EXPECT_EQ(ERR_IO_PENDING, result); EXPECT_EQ(ERR_PAC_STATUS_NOT_OK, callback.WaitForResult()); EXPECT_TRUE(bytes.empty()); } } TEST_F(ProxyScriptFetcherTest, ContentDisposition) { scoped_refptr<HTTPTestServer> server = HTTPTestServer::CreateServer(kDocRoot, NULL); ASSERT_TRUE(NULL != server.get()); scoped_refptr<URLRequestContext> context = new RequestContext; scoped_ptr<ProxyScriptFetcher> pac_fetcher( ProxyScriptFetcher::Create(context)); // Fetch PAC scripts via HTTP with a Content-Disposition header -- should // have no effect. GURL url = server->TestServerPage("files/downloadable.pac"); std::string bytes; TestCompletionCallback callback; int result = pac_fetcher->Fetch(url, &bytes, &callback); EXPECT_EQ(ERR_IO_PENDING, result); EXPECT_EQ(OK, callback.WaitForResult()); EXPECT_EQ("-downloadable.pac-\n", bytes); } TEST_F(ProxyScriptFetcherTest, NoCache) { scoped_refptr<HTTPTestServer> server = HTTPTestServer::CreateServer(kDocRoot, NULL); ASSERT_TRUE(NULL != server.get()); scoped_refptr<URLRequestContext> context = new RequestContext; scoped_ptr<ProxyScriptFetcher> pac_fetcher( ProxyScriptFetcher::Create(context)); // Fetch a PAC script whose HTTP headers make it cacheable for 1 hour. GURL url = server->TestServerPage("files/cacheable_1hr.pac"); { std::string bytes; TestCompletionCallback callback; int result = pac_fetcher->Fetch(url, &bytes, &callback); EXPECT_EQ(ERR_IO_PENDING, result); EXPECT_EQ(OK, callback.WaitForResult()); EXPECT_EQ("-cacheable_1hr.pac-\n", bytes); } // Now kill the HTTP server. EXPECT_TRUE(server->Stop()); // Verify it shutdown synchronously. server = NULL; // Try to fetch the file again -- if should fail, since the server is not // running anymore. (If it were instead being loaded from cache, we would // get a success. { std::string bytes; TestCompletionCallback callback; int result = pac_fetcher->Fetch(url, &bytes, &callback); EXPECT_EQ(ERR_IO_PENDING, result); EXPECT_EQ(ERR_CONNECTION_REFUSED, callback.WaitForResult()); } } TEST_F(ProxyScriptFetcherTest, TooLarge) { scoped_refptr<HTTPTestServer> server = HTTPTestServer::CreateServer(kDocRoot, NULL); ASSERT_TRUE(NULL != server.get()); scoped_refptr<URLRequestContext> context = new RequestContext; scoped_ptr<ProxyScriptFetcher> pac_fetcher( ProxyScriptFetcher::Create(context)); // Set the maximum response size to 50 bytes. int prev_size = ProxyScriptFetcher::SetSizeConstraintForUnittest(50); // These two URLs are the same file, but are http:// vs file:// GURL urls[] = { server->TestServerPage("files/large-pac.nsproxy"), GetTestFileUrl("large-pac.nsproxy") }; // Try fetching URLs that are 101 bytes large. We should abort the request // after 50 bytes have been read, and fail with a too large error. for (size_t i = 0; i < arraysize(urls); ++i) { const GURL& url = urls[i]; std::string bytes; TestCompletionCallback callback; int result = pac_fetcher->Fetch(url, &bytes, &callback); EXPECT_EQ(ERR_IO_PENDING, result); EXPECT_EQ(ERR_FILE_TOO_BIG, callback.WaitForResult()); EXPECT_TRUE(bytes.empty()); } // Restore the original size bound. ProxyScriptFetcher::SetSizeConstraintForUnittest(prev_size); { // Make sure we can still fetch regular URLs. GURL url = server->TestServerPage("files/pac.nsproxy"); std::string bytes; TestCompletionCallback callback; int result = pac_fetcher->Fetch(url, &bytes, &callback); EXPECT_EQ(ERR_IO_PENDING, result); EXPECT_EQ(OK, callback.WaitForResult()); EXPECT_EQ("-pac.nsproxy-\n", bytes); } } TEST_F(ProxyScriptFetcherTest, Hang) { scoped_refptr<HTTPTestServer> server = HTTPTestServer::CreateServer(kDocRoot, NULL); ASSERT_TRUE(NULL != server.get()); scoped_refptr<URLRequestContext> context = new RequestContext; scoped_ptr<ProxyScriptFetcher> pac_fetcher( ProxyScriptFetcher::Create(context)); // Set the timeout period to 0.5 seconds. int prev_timeout = ProxyScriptFetcher::SetTimeoutConstraintForUnittest(500); // Try fetching a URL which takes 1.2 seconds. We should abort the request // after 500 ms, and fail with a timeout error. { GURL url = server->TestServerPage("slow/proxy.pac?1.2"); std::string bytes; TestCompletionCallback callback; int result = pac_fetcher->Fetch(url, &bytes, &callback); EXPECT_EQ(ERR_IO_PENDING, result); EXPECT_EQ(ERR_TIMED_OUT, callback.WaitForResult()); EXPECT_TRUE(bytes.empty()); } // Restore the original timeout period. ProxyScriptFetcher::SetTimeoutConstraintForUnittest(prev_timeout); { // Make sure we can still fetch regular URLs. GURL url = server->TestServerPage("files/pac.nsproxy"); std::string bytes; TestCompletionCallback callback; int result = pac_fetcher->Fetch(url, &bytes, &callback); EXPECT_EQ(ERR_IO_PENDING, result); EXPECT_EQ(OK, callback.WaitForResult()); EXPECT_EQ("-pac.nsproxy-\n", bytes); } } // The ProxyScriptFetcher should decode any content-codings // (like gzip, bzip, etc.), and apply any charset conversions to yield // UTF8. TEST_F(ProxyScriptFetcherTest, Encodings) { scoped_refptr<HTTPTestServer> server = HTTPTestServer::CreateServer(kDocRoot, NULL); ASSERT_TRUE(NULL != server.get()); scoped_refptr<URLRequestContext> context = new RequestContext; scoped_ptr<ProxyScriptFetcher> pac_fetcher( ProxyScriptFetcher::Create(context)); // Test a response that is gzip-encoded -- should get inflated. { GURL url = server->TestServerPage("files/gzipped_pac"); std::string bytes; TestCompletionCallback callback; int result = pac_fetcher->Fetch(url, &bytes, &callback); EXPECT_EQ(ERR_IO_PENDING, result); EXPECT_EQ(OK, callback.WaitForResult()); EXPECT_EQ("This data was gzipped.\n", bytes); } // Test a response that was served as UTF-16 (BE). It should // be converted to UTF8. { GURL url = server->TestServerPage("files/utf16be_pac"); std::string bytes; TestCompletionCallback callback; int result = pac_fetcher->Fetch(url, &bytes, &callback); EXPECT_EQ(ERR_IO_PENDING, result); EXPECT_EQ(OK, callback.WaitForResult()); EXPECT_EQ("This was encoded as UTF-16BE.\n", bytes); } } } // namespace net <|endoftext|>
<commit_before>#pragma once #include <tuple> #include <type_traits> namespace THI { template <std::size_t N = 0, typename Func, typename... Tp, typename std::enable_if_t<N == sizeof...(Tp)>* = nullptr> void forEach(const Func&, const std::tuple<Tp...>&) { } template <std::size_t N = 0, typename Func, typename... Tp, typename std::enable_if_t<(N < sizeof...(Tp))>* = nullptr> void forEach(const Func& func, const std::tuple<Tp...>& tuple) { func(std::get<N>(tuple)); forEach<N + 1, Func, Tp...>(func, tuple); } template <std::size_t N = 0, typename Func, typename... Tp, typename std::enable_if_t<N == sizeof...(Tp)>* = nullptr> void forEachWithIndex(const Func&, const std::tuple<Tp...>&) { } template <std::size_t N = 0, typename Func, typename... Tp, typename std::enable_if_t<(N < sizeof...(Tp))>* = nullptr> void forEachWithIndex(const Func& func, const std::tuple<Tp...>& tuple) { func(N, std::get<N>(tuple)); forEachWithIndex<N + 1, Func, Tp...>(func, tuple); } template <std::size_t N = 0, typename Func, typename Identity, typename... Tp, typename std::enable_if_t<N == sizeof...(Tp)>* = nullptr> auto foldL(const Func&, const Identity& identity, const std::tuple<Tp...>&) { return identity; } template <std::size_t N = 0, typename Func, typename Identity, typename... Tp, typename std::enable_if_t<(N < sizeof...(Tp))>* = nullptr> auto foldL(const Func& func, const Identity& identity, const std::tuple<Tp...>& tuple) { return foldL<N + 1, Func, Identity, Tp...>( func, func(identity, std::get<N>(tuple)), tuple); } template <std::size_t N = 0, typename Func, typename Identity, typename... Tp, typename std::enable_if_t<N == sizeof...(Tp)>* = nullptr> auto foldR(const Func&, const Identity& identity, const std::tuple<Tp...>&) { return identity; } template <std::size_t N = 0, typename Func, typename Identity, typename... Tp, typename std::enable_if_t<(N < sizeof...(Tp))>* = nullptr> auto foldR(const Func& func, const Identity& identity, const std::tuple<Tp...>& tuple) { return func(std::get<N>(tuple), foldR<N + 1, Func, Identity, Tp...>(func, identity, tuple)); } template <std::size_t N = 0, typename... Tp, typename std::enable_if_t<N == sizeof...(Tp)>* = nullptr> auto reverse(const std::tuple<Tp...>&) { return std::make_tuple(); } template <std::size_t N = 0, typename... Tp, typename std::enable_if_t<(N < sizeof...(Tp))>* = nullptr> auto reverse(const std::tuple<Tp...>& tuple) { return std::tuple_cat(reverse<N + 1>(tuple), std::make_tuple(std::get<N>(tuple))); } } // namespace THI <commit_msg>remove unnecessary template argument<commit_after>#pragma once #include <tuple> #include <type_traits> namespace THI { template <std::size_t N = 0, typename Func, typename... Tp, typename std::enable_if_t<N == sizeof...(Tp)>* = nullptr> void forEach(const Func&, const std::tuple<Tp...>&) { } template <std::size_t N = 0, typename Func, typename... Tp, typename std::enable_if_t<(N < sizeof...(Tp))>* = nullptr> void forEach(const Func& func, const std::tuple<Tp...>& tuple) { func(std::get<N>(tuple)); forEach<N + 1>(func, tuple); } template <std::size_t N = 0, typename Func, typename... Tp, typename std::enable_if_t<N == sizeof...(Tp)>* = nullptr> void forEachWithIndex(const Func&, const std::tuple<Tp...>&) { } template <std::size_t N = 0, typename Func, typename... Tp, typename std::enable_if_t<(N < sizeof...(Tp))>* = nullptr> void forEachWithIndex(const Func& func, const std::tuple<Tp...>& tuple) { func(N, std::get<N>(tuple)); forEachWithIndex<N + 1>(func, tuple); } template <std::size_t N = 0, typename Func, typename Identity, typename... Tp, typename std::enable_if_t<N == sizeof...(Tp)>* = nullptr> auto foldL(const Func&, const Identity& identity, const std::tuple<Tp...>&) { return identity; } template <std::size_t N = 0, typename Func, typename Identity, typename... Tp, typename std::enable_if_t<(N < sizeof...(Tp))>* = nullptr> auto foldL(const Func& func, const Identity& identity, const std::tuple<Tp...>& tuple) { return foldL<N + 1>(func, func(identity, std::get<N>(tuple)), tuple); } template <std::size_t N = 0, typename Func, typename Identity, typename... Tp, typename std::enable_if_t<N == sizeof...(Tp)>* = nullptr> auto foldR(const Func&, const Identity& identity, const std::tuple<Tp...>&) { return identity; } template <std::size_t N = 0, typename Func, typename Identity, typename... Tp, typename std::enable_if_t<(N < sizeof...(Tp))>* = nullptr> auto foldR(const Func& func, const Identity& identity, const std::tuple<Tp...>& tuple) { return func(std::get<N>(tuple), foldR<N + 1>(func, identity, tuple)); } template <std::size_t N = 0, typename... Tp, typename std::enable_if_t<N == sizeof...(Tp)>* = nullptr> auto reverse(const std::tuple<Tp...>&) { return std::make_tuple(); } template <std::size_t N = 0, typename... Tp, typename std::enable_if_t<(N < sizeof...(Tp))>* = nullptr> auto reverse(const std::tuple<Tp...>& tuple) { return std::tuple_cat(reverse<N + 1>(tuple), std::make_tuple(std::get<N>(tuple))); } } // namespace THI <|endoftext|>
<commit_before>#include <stan/variational/advi.hpp> #include <gtest/gtest.h> #include <vector> #include <string> #include <boost/random/additive_combine.hpp> // L'Ecuyer RNG #include <test/test-models/good/variational/multivariate_no_constraint.hpp> typedef boost::ecuyer1988 rng_t; typedef multivariate_no_constraint_model_namespace::multivariate_no_constraint_model Model; TEST(advi_test, multivar_no_constraint_fullrank_ELBO) { // Create mock data_var_context static const std::string DATA = ""; std::stringstream data_stream(DATA); stan::io::dump dummy_context(data_stream); // Instantiate model Model my_model(dummy_context); // RNG rng_t base_rng(0); // Dummy input Eigen::VectorXd cont_params = Eigen::VectorXd::Zero(2); cont_params(0) = 0.75; cont_params(1) = 0.75; // ADVI stan::variational::advi<Model, rng_t> test_advi(my_model, cont_params, 0, 10, 1e4, // absurdly high! 0.1, base_rng, 100, &std::cout, &std::cout, &std::cout); // Create some arbitrary variational q() family to calculate the ELBO over Eigen::VectorXd mu = Eigen::VectorXd::Constant(my_model.num_params_r(), 2.5); Eigen::MatrixXd L_chol = Eigen::MatrixXd::Identity(my_model.num_params_r(), my_model.num_params_r()); stan::variational::advi_params_fullrank muL = stan::variational::advi_params_fullrank(mu, L_chol); double elbo = 0.0; elbo = test_advi.calc_ELBO(muL, 0.0);//constant_factor); std::cout << elbo << std::endl; double zeta = -0.5 * ( 3*2*log(2.0*stan::math::pi()) + 18.5 + 25 + 13 ); Eigen::VectorXd mu_J = Eigen::VectorXd::Zero(2); mu_J(0) = 10.5; mu_J(1) = 7.5; double elbo_true = 0.0; elbo_true += zeta; elbo_true += mu_J.dot(mu); elbo_true += -0.5 * ( mu.dot(mu) + 3*2 ); elbo_true += 1 + log(2.0*stan::math::pi()); std::cout << elbo_true << std::endl; // Can calculate ELBO using formula for E_normal[(something - x)^2] // (see Sam Roweis' notes on Gaussian identities) // // mu0 = np.array([3.7, 2.7]) // x1 = np.array([4.0, 3.0]) // x2 = np.array([3.5, 2.5]) // z = np.array([5, 5]) // // ELBO = - 0.5 * ( 6 + np.linalg.norm(x1-z)**2 // + np.linalg.norm(x2-z)**2 // + np.linalg.norm(z-mu0)**2 ) + 2 // // FIXME: perhaps make EPSILON depend on stan::vb::bbvb.n_monte_carlo_ ? double const EPSILON = 1.0; EXPECT_NEAR(elbo_true, elbo, EPSILON); } <commit_msg>moved the test include before the advi.hpp<commit_after>#include <test/test-models/good/variational/multivariate_no_constraint.hpp> #include <stan/variational/advi.hpp> #include <gtest/gtest.h> #include <vector> #include <string> #include <boost/random/additive_combine.hpp> // L'Ecuyer RNG typedef boost::ecuyer1988 rng_t; typedef multivariate_no_constraint_model_namespace::multivariate_no_constraint_model Model; TEST(advi_test, multivar_no_constraint_fullrank_ELBO) { // Create mock data_var_context static const std::string DATA = ""; std::stringstream data_stream(DATA); stan::io::dump dummy_context(data_stream); // Instantiate model Model my_model(dummy_context); // RNG rng_t base_rng(0); // Dummy input Eigen::VectorXd cont_params = Eigen::VectorXd::Zero(2); cont_params(0) = 0.75; cont_params(1) = 0.75; // ADVI stan::variational::advi<Model, rng_t> test_advi(my_model, cont_params, 0, 10, 1e4, // absurdly high! 0.1, base_rng, 100, &std::cout, &std::cout, &std::cout); // Create some arbitrary variational q() family to calculate the ELBO over Eigen::VectorXd mu = Eigen::VectorXd::Constant(my_model.num_params_r(), 2.5); Eigen::MatrixXd L_chol = Eigen::MatrixXd::Identity(my_model.num_params_r(), my_model.num_params_r()); stan::variational::advi_params_fullrank muL = stan::variational::advi_params_fullrank(mu, L_chol); double elbo = 0.0; elbo = test_advi.calc_ELBO(muL, 0.0);//constant_factor); std::cout << elbo << std::endl; double zeta = -0.5 * ( 3*2*log(2.0*stan::math::pi()) + 18.5 + 25 + 13 ); Eigen::VectorXd mu_J = Eigen::VectorXd::Zero(2); mu_J(0) = 10.5; mu_J(1) = 7.5; double elbo_true = 0.0; elbo_true += zeta; elbo_true += mu_J.dot(mu); elbo_true += -0.5 * ( mu.dot(mu) + 3*2 ); elbo_true += 1 + log(2.0*stan::math::pi()); std::cout << elbo_true << std::endl; // Can calculate ELBO using formula for E_normal[(something - x)^2] // (see Sam Roweis' notes on Gaussian identities) // // mu0 = np.array([3.7, 2.7]) // x1 = np.array([4.0, 3.0]) // x2 = np.array([3.5, 2.5]) // z = np.array([5, 5]) // // ELBO = - 0.5 * ( 6 + np.linalg.norm(x1-z)**2 // + np.linalg.norm(x2-z)**2 // + np.linalg.norm(z-mu0)**2 ) + 2 // // FIXME: perhaps make EPSILON depend on stan::vb::bbvb.n_monte_carlo_ ? double const EPSILON = 1.0; EXPECT_NEAR(elbo_true, elbo, EPSILON); } <|endoftext|>
<commit_before>#include <catch2/catch.hpp> #include "virtual_hid_device_utility.hpp" TEST_CASE("pqrs::karabiner::driverkit::virtual_hid_device_driver::hid_report::modifiers") { { namespace hid_report = pqrs::karabiner::driverkit::virtual_hid_device_driver::hid_report; hid_report::modifiers modifiers; modifiers.insert(hid_report::modifier::left_shift); modifiers.insert(hid_report::modifier::right_command); nlohmann::json expected = nlohmann::json::array(); expected.push_back("left_shift"); expected.push_back("right_command"); REQUIRE(nlohmann::json(modifiers).dump() == expected.dump()); } } TEST_CASE("karabiner_virtual_hid_device::hid_report::keys") { namespace hid_report = pqrs::karabiner::driverkit::virtual_hid_device_driver::hid_report; // keyboard_or_keypad { hid_report::keys keys; keys.insert(type_safe::get(*(krbn::make_hid_usage(krbn::key_code::keyboard_a)))); keys.insert(type_safe::get(*(krbn::make_hid_usage(krbn::key_code::keyboard_b)))); keys.insert(type_safe::get(*(krbn::make_hid_usage(krbn::key_code::keyboard_c)))); keys.erase(type_safe::get(*(krbn::make_hid_usage(krbn::key_code::keyboard_a)))); nlohmann::json expected = nlohmann::json::array(); expected.push_back("b"); expected.push_back("c"); REQUIRE(krbn::virtual_hid_device_utility::to_json(keys, pqrs::hid::usage_page::keyboard_or_keypad).dump() == expected.dump()); } // consumer { hid_report::keys keys; keys.insert(type_safe::get(*(krbn::make_hid_usage(krbn::consumer_key_code::rewind)))); keys.insert(type_safe::get(*(krbn::make_hid_usage(krbn::consumer_key_code::eject)))); keys.insert(type_safe::get(*(krbn::make_hid_usage(krbn::consumer_key_code::mute)))); nlohmann::json expected = nlohmann::json::array(); expected.push_back("rewind"); expected.push_back("eject"); expected.push_back("mute"); REQUIRE(krbn::virtual_hid_device_utility::to_json(keys, pqrs::hid::usage_page::consumer).dump() == expected.dump()); } // apple_vendor_top_case { hid_report::keys keys; keys.insert(type_safe::get(pqrs::hid::usage::apple_vendor_top_case::keyboard_fn)); keys.insert(type_safe::get(pqrs::hid::usage::apple_vendor_top_case::brightness_up)); keys.insert(type_safe::get(pqrs::hid::usage::apple_vendor_top_case::illumination_up)); nlohmann::json expected = nlohmann::json::array(); expected.push_back("fn"); expected.push_back("apple_top_case_display_brightness_increment"); expected.push_back("illumination_increment"); REQUIRE(krbn::virtual_hid_device_utility::to_json(keys, pqrs::hid::usage_page::apple_vendor_top_case).dump() == expected.dump()); } // apple_vendor_keyboard { hid_report::keys keys; keys.insert(type_safe::get(pqrs::hid::usage::apple_vendor_keyboard::expose_all)); keys.insert(type_safe::get(pqrs::hid::usage::apple_vendor_keyboard::launchpad)); nlohmann::json expected = nlohmann::json::array(); expected.push_back("mission_control"); expected.push_back("launchpad"); REQUIRE(krbn::virtual_hid_device_utility::to_json(keys, pqrs::hid::usage_page::apple_vendor_keyboard).dump() == expected.dump()); } } TEST_CASE("karabiner_virtual_hid_device::hid_report::buttons") { { pqrs::karabiner::driverkit::virtual_hid_device_driver::hid_report::buttons buttons; buttons.insert(1); buttons.insert(32); nlohmann::json expected = nlohmann::json::array(); expected.push_back("button1"); expected.push_back("button32"); REQUIRE(nlohmann::json(buttons).dump() == expected.dump()); } } <commit_msg>Update tests<commit_after>#include <catch2/catch.hpp> #include "virtual_hid_device_utility.hpp" TEST_CASE("pqrs::karabiner::driverkit::virtual_hid_device_driver::hid_report::modifiers") { { namespace hid_report = pqrs::karabiner::driverkit::virtual_hid_device_driver::hid_report; hid_report::modifiers modifiers; modifiers.insert(hid_report::modifier::left_shift); modifiers.insert(hid_report::modifier::right_command); nlohmann::json expected = nlohmann::json::array(); expected.push_back("left_shift"); expected.push_back("right_command"); REQUIRE(nlohmann::json(modifiers).dump() == expected.dump()); } } TEST_CASE("karabiner_virtual_hid_device::hid_report::keys") { namespace hid_report = pqrs::karabiner::driverkit::virtual_hid_device_driver::hid_report; // keyboard_or_keypad { hid_report::keys keys; keys.insert(type_safe::get(pqrs::hid::usage::keyboard_or_keypad::keyboard_a)); keys.insert(type_safe::get(pqrs::hid::usage::keyboard_or_keypad::keyboard_b)); keys.insert(type_safe::get(pqrs::hid::usage::keyboard_or_keypad::keyboard_c)); keys.erase(type_safe::get(pqrs::hid::usage::keyboard_or_keypad::keyboard_a)); nlohmann::json expected = nlohmann::json::array(); expected.push_back("b"); expected.push_back("c"); REQUIRE(krbn::virtual_hid_device_utility::to_json(keys, pqrs::hid::usage_page::keyboard_or_keypad).dump() == expected.dump()); } // consumer { hid_report::keys keys; keys.insert(type_safe::get(pqrs::hid::usage::consumer::rewind)); keys.insert(type_safe::get(pqrs::hid::usage::consumer::eject)); keys.insert(type_safe::get(pqrs::hid::usage::consumer::mute)); nlohmann::json expected = nlohmann::json::array(); expected.push_back("rewind"); expected.push_back("eject"); expected.push_back("mute"); REQUIRE(krbn::virtual_hid_device_utility::to_json(keys, pqrs::hid::usage_page::consumer).dump() == expected.dump()); } // apple_vendor_top_case { hid_report::keys keys; keys.insert(type_safe::get(pqrs::hid::usage::apple_vendor_top_case::keyboard_fn)); keys.insert(type_safe::get(pqrs::hid::usage::apple_vendor_top_case::brightness_up)); keys.insert(type_safe::get(pqrs::hid::usage::apple_vendor_top_case::illumination_up)); nlohmann::json expected = nlohmann::json::array(); expected.push_back("fn"); expected.push_back("apple_top_case_display_brightness_increment"); expected.push_back("illumination_increment"); REQUIRE(krbn::virtual_hid_device_utility::to_json(keys, pqrs::hid::usage_page::apple_vendor_top_case).dump() == expected.dump()); } // apple_vendor_keyboard { hid_report::keys keys; keys.insert(type_safe::get(pqrs::hid::usage::apple_vendor_keyboard::expose_all)); keys.insert(type_safe::get(pqrs::hid::usage::apple_vendor_keyboard::launchpad)); nlohmann::json expected = nlohmann::json::array(); expected.push_back("mission_control"); expected.push_back("launchpad"); REQUIRE(krbn::virtual_hid_device_utility::to_json(keys, pqrs::hid::usage_page::apple_vendor_keyboard).dump() == expected.dump()); } } TEST_CASE("karabiner_virtual_hid_device::hid_report::buttons") { { pqrs::karabiner::driverkit::virtual_hid_device_driver::hid_report::buttons buttons; buttons.insert(1); buttons.insert(32); nlohmann::json expected = nlohmann::json::array(); expected.push_back("button1"); expected.push_back("button32"); REQUIRE(nlohmann::json(buttons).dump() == expected.dump()); } } <|endoftext|>
<commit_before>#include "MultipleKinectsPlatformServer.h" namespace MultipleKinectsPlatformServer{ Core::Core(/*Server Address*/string address,/*Server Port*/string httpPort,string udpPort){ try { /*Upgraded the Priority Class*/ DWORD dwPriClass; dwPriClass = GetPriorityClass(GetCurrentProcess()); cout << "Current priority class is " << std::hex << dwPriClass << endl; if(!SetPriorityClass(GetCurrentProcess(),HIGH_PRIORITY_CLASS)){ cout << "Failed to upgrade priority class" << GetLastError() << endl; }else{ dwPriClass = GetPriorityClass(GetCurrentProcess()); cout << "Upgraded priority class is " << std::hex << dwPriClass << endl; } /* Communicate with a centralised time server */ unsigned short randomTimeServerId = rand()%5; string timeServer = std::to_string(randomTimeServerId)+".asia.pool.ntp.org"; this->ReportStatus("Sync with Time Server - "+ timeServer); NTPClient timeClient(timeServer); long timeFromServer = timeClient.RequestDatetime_UNIX(); this->_time = new Timer(timeFromServer); this->_time = new Timer(0); this->_time->Start(); this->ReportStatus("Create Key Objects"); /* Initialise the Client Machine List */ this->_clientList = new MultipleKinectsPlatformServer::ClientsList(this->_time); /* Create the jobs queue that process each incoming data from client machines */ this->_jobQueue = new MultipleKinectsPlatformServer::JobsQueue(); /* Create algorithm that merge the scenes */ this->_minorityViewport = new MinorityViewport(this->_time,this->_clientList); this->ReportStatus("Server Starting"); //Initialise the Server with the number of threads string docRoot = "C:\\Users\\ethanlim\\Documents\\Projects\\School\\MultipleKinectsPlatformServer\\Web"; std::size_t num_threads = boost::lexical_cast<std::size_t>(5); this->_httpServer = new http::server::server( address, httpPort, docRoot, this->_jobQueue, num_threads, this->_clientList, this->_minorityViewport ); this->ReportStatus("Server Started"); this->_udpServer = new MultipleKinectsPlatformServer::UdpServer(address,atoi(udpPort.c_str()),this->_minorityViewport); } catch (std::exception& e) { std::cerr << "exception: " << e.what() << "\n"; } } void Core::BeginListen(){ try{ this->_httpServer->run(); } catch(std::exception& e){ std::cerr << "exception: " << e.what() << "\n"; } } void Core::BeginUdpListen(){ try{ this->_udpServer->Run(); } catch(std::exception& e){ std::cerr << "exception: " << e.what() << "\n"; } } /** Depreciated void Core::ProcessJobs(){ Json::Value root; Json::Reader reader; string rawJSON; string timeStamp; while(true){ Job recvJob; JobThreadMutex.lock(); recvJob = this->_jobQueue->get(); JobThreadMutex.unlock(); rawJSON = recvJob.GetJobJSON(); timeStamp = recvJob.GetTimeStamp(); if (!rawJSON.empty()&&!timeStamp.empty()&&reader.parse(rawJSON,root)) { for(unsigned short skeletons=0;skeletons<root.size();skeletons++){ MultipleKinectsPlatformServer::Skeleton newSkeleton(root.get(skeletons,NULL),atol(timeStamp.c_str())); this->_minorityViewport->LoadSkeleton(newSkeleton); } } } } */ void Core::ReportStatus(string msg){ cout << "Core : " << msg << endl; } } int main(int argc, char **argv) { srand(time(NULL)); MultipleKinectsPlatformServer::Core *platform; if(argc==1){ throw exception("Program arguments are empty"); } try{ platform = new MultipleKinectsPlatformServer::Core(argv[1],argv[2],argv[3]); if(platform!=NULL){ thread server_thread(&MultipleKinectsPlatformServer::Core::BeginListen,platform); thread udp_thread(&MultipleKinectsPlatformServer::Core::BeginUdpListen,platform); server_thread.join(); udp_thread.join(); } }catch(exception &error){ throw error; } return 0; } <commit_msg>Remove the timeclient<commit_after>#include "MultipleKinectsPlatformServer.h" namespace MultipleKinectsPlatformServer{ Core::Core(/*Server Address*/string address,/*Server Port*/string httpPort,string udpPort){ try { /*Upgraded the Priority Class*/ DWORD dwPriClass; dwPriClass = GetPriorityClass(GetCurrentProcess()); cout << "Current priority class is " << std::hex << dwPriClass << endl; if(!SetPriorityClass(GetCurrentProcess(),HIGH_PRIORITY_CLASS)){ cout << "Failed to upgrade priority class" << GetLastError() << endl; }else{ dwPriClass = GetPriorityClass(GetCurrentProcess()); cout << "Upgraded priority class is " << std::hex << dwPriClass << endl; } /* Communicate with a centralised time server */ /* unsigned short randomTimeServerId = rand()%5; string timeServer = std::to_string(randomTimeServerId)+".asia.pool.ntp.org"; this->ReportStatus("Sync with Time Server - "+ timeServer); NTPClient timeClient(timeServer); long timeFromServer = timeClient.RequestDatetime_UNIX(); */ time_t ltime; this->_time = new Timer(time(&ltime)); this->_time->Start(); this->ReportStatus("Create Key Objects"); /* Initialise the Client Machine List */ this->_clientList = new MultipleKinectsPlatformServer::ClientsList(this->_time); /* Create the jobs queue that process each incoming data from client machines */ this->_jobQueue = new MultipleKinectsPlatformServer::JobsQueue(); /* Create algorithm that merge the scenes */ this->_minorityViewport = new MinorityViewport(this->_time,this->_clientList); this->ReportStatus("Server Starting"); //Initialise the Server with the number of threads string docRoot = "C:\\Users\\ethanlim\\Documents\\Projects\\School\\MultipleKinectsPlatformServer\\Web"; std::size_t num_threads = boost::lexical_cast<std::size_t>(5); this->_httpServer = new http::server::server( address, httpPort, docRoot, this->_jobQueue, num_threads, this->_clientList, this->_minorityViewport ); this->ReportStatus("Server Started"); this->_udpServer = new MultipleKinectsPlatformServer::UdpServer(address,atoi(udpPort.c_str()),this->_minorityViewport); } catch (std::exception& e) { std::cerr << "exception: " << e.what() << "\n"; } } void Core::BeginListen(){ try{ this->_httpServer->run(); } catch(std::exception& e){ std::cerr << "exception: " << e.what() << "\n"; } } void Core::BeginUdpListen(){ try{ this->_udpServer->Run(); } catch(std::exception& e){ std::cerr << "exception: " << e.what() << "\n"; } } /** Depreciated void Core::ProcessJobs(){ Json::Value root; Json::Reader reader; string rawJSON; string timeStamp; while(true){ Job recvJob; JobThreadMutex.lock(); recvJob = this->_jobQueue->get(); JobThreadMutex.unlock(); rawJSON = recvJob.GetJobJSON(); timeStamp = recvJob.GetTimeStamp(); if (!rawJSON.empty()&&!timeStamp.empty()&&reader.parse(rawJSON,root)) { for(unsigned short skeletons=0;skeletons<root.size();skeletons++){ MultipleKinectsPlatformServer::Skeleton newSkeleton(root.get(skeletons,NULL),atol(timeStamp.c_str())); this->_minorityViewport->LoadSkeleton(newSkeleton); } } } } */ void Core::ReportStatus(string msg){ cout << "Core : " << msg << endl; } } int main(int argc, char **argv) { srand(time(NULL)); MultipleKinectsPlatformServer::Core *platform; if(argc==1){ throw exception("Program arguments are empty"); } try{ platform = new MultipleKinectsPlatformServer::Core(argv[1],argv[2],argv[3]); if(platform!=NULL){ thread server_thread(&MultipleKinectsPlatformServer::Core::BeginListen,platform); thread udp_thread(&MultipleKinectsPlatformServer::Core::BeginUdpListen,platform); server_thread.join(); udp_thread.join(); } }catch(exception &error){ throw error; } return 0; } <|endoftext|>
<commit_before>// ------------------------------------------------------------------------- // @FileName : NFMemoryCounter.hpp // @Author : LvSheng.Huang // @Date : 2016-11-08 // @Module : NFMemoryCounter // // ------------------------------------------------------------------------- #ifndef NF_COUNTER_MEMORY_HPP #define NF_COUNTER_MEMORY_HPP #include <iostream> #include <string> #include <map> #include "NFComm/NFPluginModule/NFPlatform.h" class NFMemoryCounter { public: virtual ~NFMemoryCounter() {} void AddInstance(const std::string& strClassName) { std::map<std::string, int>::iterator it = mxCounter.find(strClassName); if(it != mxCounter.end()) { it->second++; } else { mxCounter.insert(std::map<std::string, int>::value_type(strClassName, 1)); } } void RemInstance(const std::string& strClassName) { std::map<std::string, int>::iterator it = mxCounter.find(strClassName); if (it != mxCounter.end()) { mxCounter.erase(it); } } const std::map<std::string, int>& GetCounter() { return mxCounter; } private: static std::map<std::string, int> mxCounter; }; #endif<commit_msg>fixed counter's bug<commit_after>// ------------------------------------------------------------------------- // @FileName : NFMemoryCounter.hpp // @Author : LvSheng.Huang // @Date : 2016-11-08 // @Module : NFMemoryCounter // // ------------------------------------------------------------------------- #ifndef NF_COUNTER_MEMORY_HPP #define NF_COUNTER_MEMORY_HPP #include <iostream> #include <string> #include <map> #include "NFComm/NFPluginModule/NFPlatform.h" class NFMemoryCounter { public: virtual ~NFMemoryCounter() {} void AddInstance(const std::string& strClassName) { std::map<std::string, int>::iterator it = mxCounter.find(strClassName); if(it != mxCounter.end()) { it->second++; } else { mxCounter.insert(std::map<std::string, int>::value_type(strClassName, 1)); } } void RemInstance(const std::string& strClassName) { std::map<std::string, int>::iterator it = mxCounter.find(strClassName); if (it != mxCounter.end()) { it->second--; } } const std::map<std::string, int>& GetCounter() { return mxCounter; } protected: static std::map<std::string, int> mxCounter; }; #endif<|endoftext|>
<commit_before>#include "Bot.hh" Bot::Bot() : _action(NULL), _battle(NULL), _battleState(false), _state(0) { } Bot::~Bot() { } void Bot::_saveKeyState() { _keyState = 0; for (uint8_t i = KEY_LEFT; i <= KEY_BUTTON_AUTO_B; i++) if (sdlGetButton((EKey) i)) _keyState |= (1 << i); } void Bot::_loadKeyState() { for (uint8_t i = KEY_LEFT; i <= KEY_BUTTON_AUTO_B; i++) sdlSetButton((EKey) i, (_keyState >> i) & 1); _keyState = 0; } void Bot::update() { if (Action::data->inBattle() != _battleState) (this->*(!_battleState ? &Bot::_saveKeyState : &Bot::_loadKeyState))(); _battleState = Action::data->inBattle(); if (_battleState) { if (_battle) _battle->update(); return; } if (!_action) { if (_queue.size()) { _action = _queue.front(); _queue.pop_front(); } else _state = Action::NOT_STARTED; } if (_action) { _action->update(); _state = _action->getState(); if (_state > Action::RUNNING) { delete _action; _action = NULL; } } _battleState = Action::data->inBattle(); } void Bot::queue(AAction *action) { _queue.push_back(action); } <commit_msg>add: reset Battle Action<commit_after>#include "Bot.hh" Bot::Bot() : _action(NULL), _battle(NULL), _battleState(false), _state(0) { } Bot::~Bot() { } void Bot::_saveKeyState() { _keyState = 0; for (uint8_t i = KEY_LEFT; i <= KEY_BUTTON_AUTO_B; i++) if (sdlGetButton((EKey) i)) _keyState |= (1 << i); } void Bot::_loadKeyState() { for (uint8_t i = KEY_LEFT; i <= KEY_BUTTON_AUTO_B; i++) sdlSetButton((EKey) i, (_keyState >> i) & 1); _keyState = 0; } void Bot::update() { if (Action::data->inBattle() != _battleState) { (this->*(!_battleState ? &Bot::_saveKeyState : &Bot::_loadKeyState))(); if (!_battleState && _battle) _battle->reset(); } _battleState = Action::data->inBattle(); if (_battleState) { if (_battle) _battle->update(); return; } if (!_action) { if (_queue.size()) { _action = _queue.front(); _queue.pop_front(); } else _state = Action::NOT_STARTED; } if (_action) { _action->update(); _state = _action->getState(); if (_state > Action::RUNNING) { delete _action; _action = NULL; } } } void Bot::queue(AAction *action) { _queue.push_back(action); } <|endoftext|>
<commit_before>#include <cmath> #include <Eigen/Core> #include <Eigen/Dense> #include <Eigen/LU> #include <angles/angles.h> #include <robot_kf/robot_kf.h> using namespace Eigen; namespace robot_kf { KalmanFilter::KalmanFilter(void) : x_(Vector3d::Zero()) , cov_x_(9999 * Matrix3d::Identity()) , A_(Matrix3d::Identity()) , Hgps_((Matrix<double, 2, 3>() << 1, 0, 0, 0, 1, 0).finished()) , Hcomp_((Matrix<double, 1, 3>() << 0, 0, 1).finished()) {} KalmanFilter::~KalmanFilter(void) {} Vector3d KalmanFilter::getState(void) const { return x_; } Matrix3d KalmanFilter::getCovariance(void) const { return cov_x_; } void KalmanFilter::update_encoders(Vector2d enc, Matrix2d cov_enc, double separation) { Matrix<double, 3, 2> const B = (Matrix<double, 3, 2>() << 0.5 * cos(x_[2]), 0.5 * cos(x_[2]), 0.5 * sin(x_[2]), 0.5 * sin(x_[2]), -1.0 / separation, 1.0 / separation ).finished(); // TODO: Verify that this is correct. Matrix3d const cov_process = B * cov_enc * B.transpose(); predict(enc, cov_process, A_, B); normalize_yaw(); } void KalmanFilter::update_gps(Vector2d gps, Matrix2d cov_gps) { measure(gps, cov_gps, Hgps_); } void KalmanFilter::update_compass(double compass, double cov_compass) { Matrix<double, 1, 1> mat_compass, mat_cov_compass; mat_compass << compass; mat_cov_compass << cov_compass; measure(mat_compass, mat_cov_compass, Hcomp_); normalize_yaw(); } template <int m> void KalmanFilter::predict(Matrix<double, m, 1> u, Matrix<double, 3, 3> cov_process, Matrix<double, 3, 3> A, Matrix<double, 3, m> B) { x_ = A * x_ + B * u; cov_x_ = A * cov_x_ * A.transpose() + cov_process; } template <int m> void KalmanFilter::measure(Matrix<double, m, 1> z, Matrix<double, m, m> cov_z, Matrix<double, m, 3> H) { Matrix<double, 3, m> const K = cov_x_ * H.transpose() * (H * cov_x_ * H.transpose() + cov_z).inverse(); x_ = x_ + K * (z - H * x_); cov_x_ = (Matrix3d::Identity() - K * H) * cov_x_; } void KalmanFilter::normalize_yaw(void) { x_[2] = angles::normalize_angle(x_[2]); } }; <commit_msg>fixed glitch when the compass crosses +/-pi<commit_after>#include <cmath> #include <Eigen/Core> #include <Eigen/Dense> #include <Eigen/LU> #include <angles/angles.h> #include <robot_kf/robot_kf.h> using namespace Eigen; namespace robot_kf { KalmanFilter::KalmanFilter(void) : x_(Vector3d::Zero()) , cov_x_(9999 * Matrix3d::Identity()) , A_(Matrix3d::Identity()) , Hgps_((Matrix<double, 2, 3>() << 1, 0, 0, 0, 1, 0).finished()) , Hcomp_((Matrix<double, 1, 3>() << 0, 0, 1).finished()) {} KalmanFilter::~KalmanFilter(void) {} Vector3d KalmanFilter::getState(void) const { return x_; } Matrix3d KalmanFilter::getCovariance(void) const { return cov_x_; } void KalmanFilter::update_encoders(Vector2d enc, Matrix2d cov_enc, double separation) { Matrix<double, 3, 2> const B = (Matrix<double, 3, 2>() << 0.5 * cos(x_[2]), 0.5 * cos(x_[2]), 0.5 * sin(x_[2]), 0.5 * sin(x_[2]), -1.0 / separation, 1.0 / separation ).finished(); // TODO: Verify that this is correct. Matrix3d const cov_process = B * cov_enc * B.transpose(); predict(enc, cov_process, A_, B); normalize_yaw(); } void KalmanFilter::update_gps(Vector2d gps, Matrix2d cov_gps) { measure(gps, cov_gps, Hgps_); } void KalmanFilter::update_compass(double compass, double cov_compass) { // Renormalize the compass heading so the filter behaves correctly when // crossing +/-pi. This prevents the heading from slowly drifting the "long // way" around the circle (i.e. through 0 instead of +/-pi). if (x_[2] - compass > M_PI) { compass = compass + 2 * M_PI; } else if (x_[2] - compass < -M_PI) { compass = compass - 2 * M_PI; } Matrix<double, 1, 1> mat_compass, mat_cov_compass; mat_compass << compass; mat_cov_compass << cov_compass; measure(mat_compass, mat_cov_compass, Hcomp_); normalize_yaw(); } template <int m> void KalmanFilter::predict(Matrix<double, m, 1> u, Matrix<double, 3, 3> cov_process, Matrix<double, 3, 3> A, Matrix<double, 3, m> B) { x_ = A * x_ + B * u; cov_x_ = A * cov_x_ * A.transpose() + cov_process; } template <int m> void KalmanFilter::measure(Matrix<double, m, 1> z, Matrix<double, m, m> cov_z, Matrix<double, m, 3> H) { Matrix<double, 3, m> const K = cov_x_ * H.transpose() * (H * cov_x_ * H.transpose() + cov_z).inverse(); x_ = x_ + K * (z - H * x_); cov_x_ = (Matrix3d::Identity() - K * H) * cov_x_; } void KalmanFilter::normalize_yaw(void) { x_[2] = angles::normalize_angle(x_[2]); } }; <|endoftext|>
<commit_before>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2006 Torus Knot Software Ltd Also see acknowledgements in Readme.html This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA, or go to http://www.gnu.org/copyleft/lesser.txt. You may alternatively use this source under the terms of a specific version of the OGRE Unrestricted License provided you have obtained such a license from Torus Knot Software Ltd. ----------------------------------------------------------------------------- */ #include <OgreStableHeaders.h> #include <OgreRoot.h> #include <OgreRenderSystem.h> #include "OgreILImageCodec.h" #include <OgreImage.h> #include <OgreException.h> #include "OgreILUtil.h" #include <OgreLogManager.h> #include <OgreStringConverter.h> #include <IL/il.h> #include <IL/ilu.h> namespace Ogre { bool ILImageCodec::_is_initialised = false; //--------------------------------------------------------------------- ILImageCodec::ILImageCodec(const String &type, unsigned int ilType): mType(type), mIlType(ilType) { initialiseIL(); } //--------------------------------------------------------------------- DataStreamPtr ILImageCodec::code(MemoryDataStreamPtr& input, Codec::CodecDataPtr& pData) const { OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "code to memory not implemented", "ILCodec::code"); } //--------------------------------------------------------------------- void ILImageCodec::codeToFile(MemoryDataStreamPtr& input, const String& outFileName, Codec::CodecDataPtr& pData) const { ILuint ImageName; ilGenImages( 1, &ImageName ); ilBindImage( ImageName ); ImageData* pImgData = static_cast< ImageData * >( pData.getPointer() ); PixelBox src(pImgData->width, pImgData->height, pImgData->depth, pImgData->format, input->getPtr()); // Convert image from OGRE to current IL image ILUtil::fromOgre(src); iluFlipImage(); // Implicitly pick DevIL codec ilSaveImage(const_cast< char * >( outFileName.c_str() ) ); // Check if everything was ok ILenum PossibleError = ilGetError() ; if( PossibleError != IL_NO_ERROR ) { ilDeleteImages(1, &ImageName); OGRE_EXCEPT( Exception::ERR_NOT_IMPLEMENTED, "IL Error, could not save file: " + outFileName, iluErrorString(PossibleError) ) ; } ilDeleteImages(1, &ImageName); } //--------------------------------------------------------------------- Codec::DecodeResult ILImageCodec::decode(DataStreamPtr& input) const { // DevIL variables ILuint ImageName; ILint ImageFormat, BytesPerPixel, ImageType; ImageData* imgData = new ImageData(); MemoryDataStreamPtr output; // Load the image ilGenImages( 1, &ImageName ); ilBindImage( ImageName ); // Put it right side up ilEnable(IL_ORIGIN_SET); ilSetInteger(IL_ORIGIN_MODE, IL_ORIGIN_UPPER_LEFT); // Keep DXTC(compressed) data if present ilSetInteger(IL_KEEP_DXTC_DATA, IL_TRUE); // Load image from stream, cache into memory MemoryDataStream memInput(input); ilLoadL( mIlType, memInput.getPtr(), static_cast< ILuint >(memInput.size())); // Check if everything was ok ILenum PossibleError = ilGetError() ; if( PossibleError != IL_NO_ERROR ) { OGRE_EXCEPT( Exception::ERR_NOT_IMPLEMENTED, "IL Error", iluErrorString(PossibleError) ) ; } ImageFormat = ilGetInteger( IL_IMAGE_FORMAT ); ImageType = ilGetInteger( IL_IMAGE_TYPE ); // Convert image if ImageType is incompatible with us (double or long) if(ImageType != IL_BYTE && ImageType != IL_UNSIGNED_BYTE && ImageType != IL_FLOAT && ImageType != IL_UNSIGNED_SHORT && ImageType != IL_SHORT) { ilConvertImage(ImageFormat, IL_FLOAT); ImageType = IL_FLOAT; } // Converted paletted images if(ImageFormat == IL_COLOUR_INDEX) { ilConvertImage(IL_BGRA, IL_UNSIGNED_BYTE); ImageFormat = IL_BGRA; ImageType = IL_UNSIGNED_BYTE; } // Now sets some variables BytesPerPixel = ilGetInteger( IL_IMAGE_BYTES_PER_PIXEL ); imgData->format = ILUtil::ilFormat2OgreFormat( ImageFormat, ImageType ); imgData->width = ilGetInteger( IL_IMAGE_WIDTH ); imgData->height = ilGetInteger( IL_IMAGE_HEIGHT ); imgData->depth = ilGetInteger( IL_IMAGE_DEPTH ); imgData->num_mipmaps = ilGetInteger ( IL_NUM_MIPMAPS ); imgData->flags = 0; if(imgData->format == PF_UNKNOWN) { std::stringstream err; err << "Unsupported devil format ImageFormat=" << std::hex << ImageFormat << " ImageType="<< ImageType << std::dec; ilDeleteImages( 1, &ImageName ); OGRE_EXCEPT( Exception::ERR_NOT_IMPLEMENTED, err.str(), "ILImageCodec::decode" ) ; } // Check for cubemap //ILuint cubeflags = ilGetInteger ( IL_IMAGE_CUBEFLAGS ); size_t numFaces = ilGetInteger ( IL_NUM_IMAGES ) + 1; if(numFaces == 6) imgData->flags |= IF_CUBEMAP; else numFaces = 1; // Support only 1 or 6 face images for now // Keep DXT data (if present at all and the GPU supports it) ILuint dxtFormat = ilGetInteger( IL_DXTC_DATA_FORMAT ); if(dxtFormat != IL_DXT_NO_COMP && Root::getSingleton().getRenderSystem()->getCapabilities()->hasCapability( RSC_TEXTURE_COMPRESSION_DXT )) { imgData->format = ILUtil::ilFormat2OgreFormat( dxtFormat, ImageType ); imgData->flags |= IF_COMPRESSED; // Validate that this devil version saves DXT mipmaps if(imgData->num_mipmaps>0) { ilBindImage(ImageName); ilActiveMipmap(1); if((size_t)ilGetInteger( IL_DXTC_DATA_FORMAT ) != dxtFormat) { imgData->num_mipmaps=0; LogManager::getSingleton().logMessage( "Warning: Custom mipmaps for compressed image "+input->getName()+" were ignored because they are not loaded by this DevIL version"); } } } // Calculate total size from number of mipmaps, faces and size imgData->size = Image::calculateSize(imgData->num_mipmaps, numFaces, imgData->width, imgData->height, imgData->depth, imgData->format); // Bind output buffer output.bind(new MemoryDataStream(imgData->size)); size_t offset = 0; // Dimensions of current mipmap size_t width = imgData->width; size_t height = imgData->height; size_t depth = imgData->depth; // Transfer data for(size_t mip=0; mip<=imgData->num_mipmaps; ++mip) { for(size_t i = 0; i < numFaces; ++i) { ilBindImage(ImageName); if(numFaces > 1) ilActiveImage(i); if(imgData->num_mipmaps > 0) ilActiveMipmap(mip); /// Size of this face size_t imageSize = PixelUtil::getMemorySize( width, height, depth, imgData->format); if(imgData->flags & IF_COMPRESSED) { // Compare DXT size returned by DevIL with our idea of the compressed size if(imageSize == ilGetDXTCData(NULL, 0, dxtFormat)) { // Retrieve data from DevIL ilGetDXTCData((unsigned char*)output->getPtr()+offset, imageSize, dxtFormat); } else { LogManager::getSingleton().logMessage( "Warning: compressed image "+input->getName()+" size mismatch, devilsize="+StringConverter::toString(ilGetDXTCData(NULL, 0, dxtFormat))+" oursize="+ StringConverter::toString(imageSize)); } } else { /// Retrieve data from DevIL PixelBox dst(width, height, depth, imgData->format, (unsigned char*)output->getPtr()+offset); ILUtil::toOgre(dst); } offset += imageSize; } /// Next mip if(width!=1) width /= 2; if(height!=1) height /= 2; if(depth!=1) depth /= 2; } // Restore IL state ilDisable(IL_ORIGIN_SET); ilDisable(IL_FORMAT_SET); ilDeleteImages( 1, &ImageName ); DecodeResult ret; ret.first = output; ret.second = CodecDataPtr(imgData); return ret; } //--------------------------------------------------------------------- void ILImageCodec::initialiseIL(void) { if( !_is_initialised ) { ilInit(); ilEnable( IL_FILE_OVERWRITE ); _is_initialised = true; } } //--------------------------------------------------------------------- String ILImageCodec::getType() const { return mType; } //--------------------------------------------------------------------- String ILImageCodec::magicNumberToFileExt(const char *magicNumberPtr, size_t maxbytes) const { // DevIL uses magic internally to determine file types when // necessary but does not expose the code in its API. // This makes it difficult to implement this function, but also // reduces its importance. Just for now, here is a kludge to // get Ogre to build and ensure that it always tries to load files // that DevIL might be able to load. return String("jpg"); } } <commit_msg>Patch 2825998: ILImageCodec segfault fix (for those who choose to use it)<commit_after>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2006 Torus Knot Software Ltd Also see acknowledgements in Readme.html This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA, or go to http://www.gnu.org/copyleft/lesser.txt. You may alternatively use this source under the terms of a specific version of the OGRE Unrestricted License provided you have obtained such a license from Torus Knot Software Ltd. ----------------------------------------------------------------------------- */ #include <OgreStableHeaders.h> #include <OgreRoot.h> #include <OgreRenderSystem.h> #include "OgreILImageCodec.h" #include <OgreImage.h> #include <OgreException.h> #include "OgreILUtil.h" #include <OgreLogManager.h> #include <OgreStringConverter.h> #include <IL/il.h> #include <IL/ilu.h> namespace Ogre { bool ILImageCodec::_is_initialised = false; //--------------------------------------------------------------------- ILImageCodec::ILImageCodec(const String &type, unsigned int ilType): mType(type), mIlType(ilType) { initialiseIL(); } //--------------------------------------------------------------------- DataStreamPtr ILImageCodec::code(MemoryDataStreamPtr& input, Codec::CodecDataPtr& pData) const { OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "code to memory not implemented", "ILCodec::code"); } //--------------------------------------------------------------------- void ILImageCodec::codeToFile(MemoryDataStreamPtr& input, const String& outFileName, Codec::CodecDataPtr& pData) const { ILuint ImageName; ilGenImages( 1, &ImageName ); ilBindImage( ImageName ); ImageData* pImgData = static_cast< ImageData * >( pData.getPointer() ); PixelBox src(pImgData->width, pImgData->height, pImgData->depth, pImgData->format, input->getPtr()); // Convert image from OGRE to current IL image ILUtil::fromOgre(src); iluFlipImage(); // Implicitly pick DevIL codec ilSaveImage(const_cast< char * >( outFileName.c_str() ) ); // Check if everything was ok ILenum PossibleError = ilGetError() ; if( PossibleError != IL_NO_ERROR ) { ilDeleteImages(1, &ImageName); OGRE_EXCEPT( Exception::ERR_NOT_IMPLEMENTED, "IL Error, could not save file: " + outFileName, iluErrorString(PossibleError) ) ; } ilDeleteImages(1, &ImageName); } //--------------------------------------------------------------------- Codec::DecodeResult ILImageCodec::decode(DataStreamPtr& input) const { // DevIL variables ILuint ImageName; ILint ImageFormat, BytesPerPixel, ImageType; ImageData* imgData = new ImageData(); MemoryDataStreamPtr output; // Load the image ilGenImages( 1, &ImageName ); ilBindImage( ImageName ); // Put it right side up ilEnable(IL_ORIGIN_SET); ilSetInteger(IL_ORIGIN_MODE, IL_ORIGIN_UPPER_LEFT); // Keep DXTC(compressed) data if present ilSetInteger(IL_KEEP_DXTC_DATA, IL_TRUE); // Load image from stream, cache into memory MemoryDataStream memInput(input); ilLoadL( mIlType, memInput.getPtr(), static_cast< ILuint >(memInput.size())); // Check if everything was ok ILenum PossibleError = ilGetError() ; if( PossibleError != IL_NO_ERROR ) { OGRE_EXCEPT( Exception::ERR_NOT_IMPLEMENTED, "IL Error", iluErrorString(PossibleError) ) ; } ImageFormat = ilGetInteger( IL_IMAGE_FORMAT ); ImageType = ilGetInteger( IL_IMAGE_TYPE ); // Convert image if ImageType is incompatible with us (double or long) if(ImageType != IL_BYTE && ImageType != IL_UNSIGNED_BYTE && ImageType != IL_FLOAT && ImageType != IL_UNSIGNED_SHORT && ImageType != IL_SHORT) { ilConvertImage(ImageFormat, IL_FLOAT); ImageType = IL_FLOAT; } // Converted paletted images if(ImageFormat == IL_COLOUR_INDEX) { ilConvertImage(IL_BGRA, IL_UNSIGNED_BYTE); ImageFormat = IL_BGRA; ImageType = IL_UNSIGNED_BYTE; } // Now sets some variables BytesPerPixel = ilGetInteger( IL_IMAGE_BYTES_PER_PIXEL ); imgData->format = ILUtil::ilFormat2OgreFormat( ImageFormat, ImageType ); imgData->width = ilGetInteger( IL_IMAGE_WIDTH ); imgData->height = ilGetInteger( IL_IMAGE_HEIGHT ); imgData->depth = ilGetInteger( IL_IMAGE_DEPTH ); imgData->num_mipmaps = ilGetInteger ( IL_NUM_MIPMAPS ); imgData->flags = 0; if(imgData->format == PF_UNKNOWN) { std::stringstream err; err << "Unsupported devil format ImageFormat=" << std::hex << ImageFormat << " ImageType="<< ImageType << std::dec; ilDeleteImages( 1, &ImageName ); OGRE_EXCEPT( Exception::ERR_NOT_IMPLEMENTED, err.str(), "ILImageCodec::decode" ) ; } // Check for cubemap //ILuint cubeflags = ilGetInteger ( IL_IMAGE_CUBEFLAGS ); size_t numFaces = ilGetInteger ( IL_NUM_IMAGES ) + 1; if(numFaces == 6) imgData->flags |= IF_CUBEMAP; else numFaces = 1; // Support only 1 or 6 face images for now // Keep DXT data (if present at all and the GPU supports it) ILuint dxtFormat = ilGetInteger( IL_DXTC_DATA_FORMAT ); if(dxtFormat != IL_DXT_NO_COMP && Root::getSingleton().getRenderSystem()->getCapabilities()->hasCapability( RSC_TEXTURE_COMPRESSION_DXT )) { imgData->format = ILUtil::ilFormat2OgreFormat( dxtFormat, ImageType ); imgData->flags |= IF_COMPRESSED; // Validate that this devil version saves DXT mipmaps if(imgData->num_mipmaps>0) { ilBindImage(ImageName); ilActiveMipmap(1); if((size_t)ilGetInteger( IL_DXTC_DATA_FORMAT ) != dxtFormat) { imgData->num_mipmaps=0; LogManager::getSingleton().logMessage( "Warning: Custom mipmaps for compressed image "+input->getName()+" were ignored because they are not loaded by this DevIL version"); } } } // Calculate total size from number of mipmaps, faces and size imgData->size = Image::calculateSize(imgData->num_mipmaps, numFaces, imgData->width, imgData->height, imgData->depth, imgData->format); // Bind output buffer output.bind(new MemoryDataStream(imgData->size)); size_t offset = 0; // Dimensions of current mipmap size_t width = imgData->width; size_t height = imgData->height; size_t depth = imgData->depth; // Transfer data for(size_t mip=0; mip<=imgData->num_mipmaps; ++mip) { for(size_t i = 0; i < numFaces; ++i) { ilBindImage(ImageName); if(numFaces > 1) ilActiveImage(i); if(imgData->num_mipmaps > 0) ilActiveMipmap(mip); /// Size of this face size_t imageSize = PixelUtil::getMemorySize( width, height, depth, imgData->format); if(imgData->flags & IF_COMPRESSED) { // Compare DXT size returned by DevIL with our idea of the compressed size if(imageSize == ilGetDXTCData(NULL, 0, dxtFormat)) { // Retrieve data from DevIL ilGetDXTCData((unsigned char*)output->getPtr()+offset, imageSize, dxtFormat); } else { LogManager::getSingleton().logMessage( "Warning: compressed image "+input->getName()+" size mismatch, devilsize="+StringConverter::toString(ilGetDXTCData(NULL, 0, dxtFormat))+" oursize="+ StringConverter::toString(imageSize)); } } else { /// Retrieve data from DevIL PixelBox dst(width, height, depth, imgData->format, (unsigned char*)output->getPtr()+offset); ILUtil::toOgre(dst); } offset += imageSize; } /// Next mip if(width!=1) width /= 2; if(height!=1) height /= 2; if(depth!=1) depth /= 2; } // Restore IL state ilDisable(IL_ORIGIN_SET); ilDisable(IL_FORMAT_SET); ilDeleteImages( 1, &ImageName ); DecodeResult ret; ret.first = output; ret.second = CodecDataPtr(imgData); return ret; } //--------------------------------------------------------------------- void ILImageCodec::initialiseIL(void) { if( !_is_initialised ) { ilInit(); iluInit(); ilEnable( IL_FILE_OVERWRITE ); _is_initialised = true; } } //--------------------------------------------------------------------- String ILImageCodec::getType() const { return mType; } //--------------------------------------------------------------------- String ILImageCodec::magicNumberToFileExt(const char *magicNumberPtr, size_t maxbytes) const { // DevIL uses magic internally to determine file types when // necessary but does not expose the code in its API. // This makes it difficult to implement this function, but also // reduces its importance. Just for now, here is a kludge to // get Ogre to build and ensure that it always tries to load files // that DevIL might be able to load. return String("jpg"); } } <|endoftext|>