text stringlengths 54 60.6k |
|---|
<commit_before>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/ 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 notices for more information.
=========================================================================*/
#include <ctkCommandLineParser.h>
#include <QCoreApplication>
#include <QTextStream>
#include <QDebug>
#include <QFile>
#include <QDir>
#include <cstdlib>
#include <iostream>
#include <limits>
bool readAnswer(char defaultAnswer)
{
std::string line;
std::cin >> std::noskipws >> line;
// consume the new line character
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
char answer = defaultAnswer;
if (!line.empty() && line[0] != '\n')
{
answer = std::tolower(line[0]);
}
if (answer == 'y') return true;
if (answer == 'n') return false;
if (defaultAnswer == 'y') return true;
return false;
}
void createFilePathMapping(const QString& templateName, const QString& baseInDir, const QString& baseOutDir, QHash<QString, QString>& fileNameMapping)
{
QFileInfo info(templateName);
if (info.isDir())
{
QStringList subEntries = QDir(templateName).entryList();
foreach(QString subEntry, subEntries)
{
createFilePathMapping(templateName + "/" + subEntry, baseInDir, baseOutDir, fileNameMapping);
}
return;
}
fileNameMapping[templateName] = QString(templateName).replace(baseInDir, baseOutDir);
}
QHash<QString,QString> createTemplateFileMapping(const QString& qrcBase, const QString& baseOutDir, const QHash<QString, QString>& fileNameMapping)
{
QHash<QString,QString> filePathMapping;
createFilePathMapping(qrcBase, qrcBase, baseOutDir, filePathMapping);
QMutableHashIterator<QString,QString> i(filePathMapping);
while(i.hasNext())
{
i.next();
QHashIterator<QString,QString> j(fileNameMapping);
while(j.hasNext())
{
j.next();
i.setValue(i.value().replace(j.key(), j.value()));
}
}
return filePathMapping;
}
bool generateFiles(const QHash<QString, QString>& parameters,
const QHash<QString, QString>& filePathMapping)
{
QHashIterator<QString,QString> paths(filePathMapping);
while(paths.hasNext())
{
paths.next();
QFile templ(paths.key());
templ.open(QIODevice::ReadOnly);
QByteArray templContent = templ.readAll();
QHashIterator<QString,QString> i(parameters);
while (i.hasNext())
{
i.next();
templContent.replace(i.key(), QByteArray(i.value().toLatin1()));
}
QFile outTempl(paths.value());
QDir dir(QFileInfo(outTempl).dir());
if (!dir.exists())
{
if (!dir.mkpath(dir.absolutePath()))
{
qCritical() << "Could not create directory" << dir.absolutePath();
return EXIT_FAILURE;
}
}
if (!outTempl.open(QIODevice::WriteOnly))
{
qCritical() << outTempl.errorString();
return false;
}
outTempl.write(templContent);
}
return true;
}
int main(int argc, char** argv)
{
QCoreApplication app(argc, argv);
app.setApplicationName("PluginGenerator");
app.setOrganizationName("DKFZ");
ctkCommandLineParser parser;
// Use Unix-style argument names
parser.setArgumentPrefix("--", "-");
parser.setStrictModeEnabled(true);
// Add command line argument names
parser.addArgument("help", "h", QVariant::Bool, "Show this help text");
parser.addArgument("out-dir", "o", QVariant::String, "Output directory", QDir::tempPath());
parser.addArgument("license", "l", QVariant::String, "Path to a file containing license information", ":/MITKLicense.txt");
parser.addArgument("vendor", "v", QVariant::String, "The vendor of the generated code", "DKFZ, Medical and Biological Informatics");
parser.addArgument("quiet", "q", QVariant::Bool, "Do not print additional information");
parser.addArgument("confirm-all", "y", QVariant::Bool, "Answer all questions with 'yes'");
parser.beginGroup("Plug-in options");
parser.addArgument("plugin-symbolic-name", "ps", QVariant::String, "The plugin's symbolic name");
parser.setExactMatchRegularExpression("-ps", "^[a-zA-Z]+\\.[a-zA-Z0-9._]+[^\\.]$", "Symbolic name invalid");
parser.addArgument("plugin-name", "pn", QVariant::String, "The plug-in's human readable name");
parser.beginGroup("Plug-in View options");
parser.addArgument("view-class", "vc", QVariant::String, "The View's' class name");
parser.addArgument("view-name", "vn", QVariant::String, "The View's human readable name");
parser.beginGroup("Project options");
parser.addArgument("project-copyright", "", QVariant::String, "Path to a file containing copyright information", ":/MITKCopyright.txt");
parser.addArgument("project-name", "", QVariant::String, "The project name");
parser.setExactMatchRegularExpression("--project-name", "^[a-zA-Z_\\-]+$", "Project name invalid");
parser.addArgument("project-app-name", "", QVariant::String, "The application name");
parser.setExactMatchRegularExpression("--project-app-name", "^[a-zA-Z_\\-]+$", "Project application name invalid");
parser.endGroup();
// Parse the command line arguments
bool ok = false;
QHash<QString, QVariant> parsedArgs = parser.parseArguments(QCoreApplication::arguments(), &ok);
if (!ok)
{
QTextStream(stderr, QIODevice::WriteOnly) << "Error parsing arguments: "
<< parser.errorString() << "\n";
return EXIT_FAILURE;
}
QTextStream out(stdout, QIODevice::WriteOnly);
// Show a help message
if (parsedArgs.contains("help"))
{
out << "A CTK plug-in generator for MITK\n\n"
<< parser.helpText();
return EXIT_SUCCESS;
}
// Check arguments
// Project options
QString projectName = parsedArgs["project-name"].toString();
QString projectAppName = parsedArgs["project-app-name"].toString();
QString copyrightPath = QDir::fromNativeSeparators(parsedArgs["project-copyright"].toString());
bool createProject = !projectName.isEmpty();
if (createProject && projectAppName.isEmpty())
{
projectAppName = projectName;
}
QString pluginSymbolicName = parsedArgs["plugin-symbolic-name"].toString();
if (pluginSymbolicName.isEmpty())
{
qCritical() << "Required argument 'plugin-symbolic-name' missing.";
return EXIT_FAILURE;
}
QString pluginTarget(pluginSymbolicName);
pluginTarget.replace('.', '_');
QString outDir = QDir::fromNativeSeparators(parsedArgs["out-dir"].toString());
QString licensePath = QDir::fromNativeSeparators(parsedArgs["license"].toString());
QString pluginExportDirective = pluginSymbolicName.split('.').last().toUpper() + "_EXPORT";
QString pluginName = parsedArgs["plugin-name"].toString();
if (pluginName.isEmpty())
{
QStringList toks = pluginSymbolicName.split('.');
pluginName = toks.last();
pluginName[0] = pluginName[0].toUpper();
}
QString vendor = parsedArgs["vendor"].toString();
QString viewName = parsedArgs["view-name"].toString();
if (viewName.isEmpty())
{
qCritical() << "Required argument 'view-name' missing.";
return EXIT_FAILURE;
}
QStringList toks = viewName.split(QRegExp("\\s"), QString::SkipEmptyParts);
QString viewClass = parsedArgs["view-class"].toString();
if (viewClass.isEmpty())
{
foreach(QString tok, toks)
{
QString tmp = tok;
tmp[0] = tmp[0].toUpper();
viewClass += tmp;
}
}
QString viewId;
if (viewId.isEmpty())
{
viewId = "org.mitk.views.";
foreach(QString tok, toks)
{
viewId += tok.toLower();
}
}
bool quiet = parsedArgs.contains("quiet");
bool autoConfirm = parsedArgs.contains("confirm-all");
if (!outDir.endsWith('/'))
outDir += '/';
if (createProject)
outDir += projectName;
else
outDir += pluginSymbolicName;
// Print the collected information
if(!quiet)
{
if (createProject)
{
out << "Using the following information to create a project:\n\n"
<< " Project Name: " << projectName << '\n'
<< " Application Name: " << projectAppName << '\n'
<< " Copyright File: " << QDir::toNativeSeparators(copyrightPath) << '\n';
}
else
{
out << "Using the following information to create a plug-in:\n\n";
}
out << " License File: " << QDir::toNativeSeparators(licensePath) << '\n'
<< " Plugin-SymbolicName: " << pluginSymbolicName << '\n'
<< " Plugin-Name: " << pluginName << '\n'
<< " Plugin-Vendor: " << vendor << '\n'
<< " View Name: " << viewName << '\n'
<< " View Id: " << viewId << '\n'
<< " View Class: " << viewClass << '\n' << '\n'
<< "Create in: " << outDir << '\n' << '\n';
if (!autoConfirm)
out << "Continue [Y/n]? ";
out.flush();
if(!autoConfirm && !readAnswer('y'))
{
out << "Aborting.\n";
return EXIT_SUCCESS;
}
}
// Check the output directory
if (!QDir(outDir).exists())
{
if (!autoConfirm)
{
out << "Directory '" << outDir << "' does not exist. Create it [Y/n]? ";
out.flush();
}
if (autoConfirm || readAnswer('y'))
{
if (!QDir().mkpath(outDir))
{
qCritical() << "Could not create directory:" << outDir;
return EXIT_FAILURE;
}
}
else
{
out << "Aborting.\n";
return EXIT_SUCCESS;
}
}
if (!QDir(outDir).entryList(QDir::AllEntries | QDir::NoDotAndDotDot).isEmpty())
{
if (!autoConfirm)
{
out << "Directory '" << outDir << "' is not empty. Continue [y/N]? ";
out.flush();
}
if (!autoConfirm && !readAnswer('n'))
{
out << "Aborting.\n";
return EXIT_SUCCESS;
}
}
// Extract the license text
QFile licenseFile(licensePath);
if (!licenseFile.open(QIODevice::ReadOnly))
{
qCritical() << "Cannot open file" << licenseFile.fileName();
return EXIT_FAILURE;
}
QString licenseText = licenseFile.readAll();
licenseFile.close();
QHash<QString,QString> parameters;
if (createProject)
{
// Extract the copyright
QFile copyrightFile(copyrightPath);
if (!copyrightFile.open(QIODevice::ReadOnly))
{
qCritical() << "Cannot open file" << copyrightFile.fileName();
return EXIT_FAILURE;
}
QString copyrighText = copyrightFile.readAll();
copyrightFile.close();
parameters["$(copyright)"] = copyrighText;
parameters["$(project-name)"] = projectName;
parameters["$(project-app-name)"] = projectAppName;
parameters["$(project-plugins)"] = QString("Plugins/") + pluginSymbolicName + ":ON";
QStringList toks = pluginTarget.split("_");
QString projectPluginBase = toks[0] + "_" + toks[1];
parameters["$(project-plugin-base)"] = projectPluginBase;
}
parameters["$(license)"] = licenseText;
parameters["$(plugin-name)"] = pluginName;
parameters["$(plugin-symbolic-name)"] = pluginSymbolicName;
parameters["$(vendor)"] = vendor;
parameters["$(plugin-target)"] = pluginTarget;
parameters["$(plugin-export-directive)"] = pluginExportDirective;
parameters["$(view-id)"] = viewId;
parameters["$(view-name)"] = viewName;
parameters["$(view-file-name)"] = viewClass;
parameters["$(view-class-name)"] = viewClass;
if (createProject)
{
QHash<QString,QString> projectFileNameMapping;
projectFileNameMapping["TemplateApp"] = projectAppName;
QHash<QString,QString> filePathMapping = createTemplateFileMapping(":/ProjectTemplate", outDir, projectFileNameMapping);
generateFiles(parameters, filePathMapping);
}
QHash<QString,QString> pluginFileNameMapping;
pluginFileNameMapping["QmitkTemplateView"] = viewClass;
if (createProject)
{
if (!outDir.endsWith('/'))
outDir += '/';
outDir += "Plugins/" + pluginSymbolicName;
}
QHash<QString,QString> filePathMapping = createTemplateFileMapping(":/PluginTemplate", outDir, pluginFileNameMapping);
generateFiles(parameters, filePathMapping);
return EXIT_SUCCESS;
}
<commit_msg>Added missing Windows header.<commit_after>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/ 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 notices for more information.
=========================================================================*/
#include <ctkCommandLineParser.h>
#include <QCoreApplication>
#include <QTextStream>
#include <QDebug>
#include <QFile>
#include <QDir>
#include <cstdlib>
#include <iostream>
#include <limits>
#include <cctype>
bool readAnswer(char defaultAnswer)
{
std::string line;
std::cin >> std::noskipws >> line;
// consume the new line character
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
char answer = defaultAnswer;
if (!line.empty() && line[0] != '\n')
{
answer = std::tolower(line[0]);
}
if (answer == 'y') return true;
if (answer == 'n') return false;
if (defaultAnswer == 'y') return true;
return false;
}
void createFilePathMapping(const QString& templateName, const QString& baseInDir, const QString& baseOutDir, QHash<QString, QString>& fileNameMapping)
{
QFileInfo info(templateName);
if (info.isDir())
{
QStringList subEntries = QDir(templateName).entryList();
foreach(QString subEntry, subEntries)
{
createFilePathMapping(templateName + "/" + subEntry, baseInDir, baseOutDir, fileNameMapping);
}
return;
}
fileNameMapping[templateName] = QString(templateName).replace(baseInDir, baseOutDir);
}
QHash<QString,QString> createTemplateFileMapping(const QString& qrcBase, const QString& baseOutDir, const QHash<QString, QString>& fileNameMapping)
{
QHash<QString,QString> filePathMapping;
createFilePathMapping(qrcBase, qrcBase, baseOutDir, filePathMapping);
QMutableHashIterator<QString,QString> i(filePathMapping);
while(i.hasNext())
{
i.next();
QHashIterator<QString,QString> j(fileNameMapping);
while(j.hasNext())
{
j.next();
i.setValue(i.value().replace(j.key(), j.value()));
}
}
return filePathMapping;
}
bool generateFiles(const QHash<QString, QString>& parameters,
const QHash<QString, QString>& filePathMapping)
{
QHashIterator<QString,QString> paths(filePathMapping);
while(paths.hasNext())
{
paths.next();
QFile templ(paths.key());
templ.open(QIODevice::ReadOnly);
QByteArray templContent = templ.readAll();
QHashIterator<QString,QString> i(parameters);
while (i.hasNext())
{
i.next();
templContent.replace(i.key(), QByteArray(i.value().toLatin1()));
}
QFile outTempl(paths.value());
QDir dir(QFileInfo(outTempl).dir());
if (!dir.exists())
{
if (!dir.mkpath(dir.absolutePath()))
{
qCritical() << "Could not create directory" << dir.absolutePath();
return EXIT_FAILURE;
}
}
if (!outTempl.open(QIODevice::WriteOnly))
{
qCritical() << outTempl.errorString();
return false;
}
outTempl.write(templContent);
}
return true;
}
int main(int argc, char** argv)
{
QCoreApplication app(argc, argv);
app.setApplicationName("PluginGenerator");
app.setOrganizationName("DKFZ");
ctkCommandLineParser parser;
// Use Unix-style argument names
parser.setArgumentPrefix("--", "-");
parser.setStrictModeEnabled(true);
// Add command line argument names
parser.addArgument("help", "h", QVariant::Bool, "Show this help text");
parser.addArgument("out-dir", "o", QVariant::String, "Output directory", QDir::tempPath());
parser.addArgument("license", "l", QVariant::String, "Path to a file containing license information", ":/MITKLicense.txt");
parser.addArgument("vendor", "v", QVariant::String, "The vendor of the generated code", "DKFZ, Medical and Biological Informatics");
parser.addArgument("quiet", "q", QVariant::Bool, "Do not print additional information");
parser.addArgument("confirm-all", "y", QVariant::Bool, "Answer all questions with 'yes'");
parser.beginGroup("Plug-in options");
parser.addArgument("plugin-symbolic-name", "ps", QVariant::String, "The plugin's symbolic name");
parser.setExactMatchRegularExpression("-ps", "^[a-zA-Z]+\\.[a-zA-Z0-9._]+[^\\.]$", "Symbolic name invalid");
parser.addArgument("plugin-name", "pn", QVariant::String, "The plug-in's human readable name");
parser.beginGroup("Plug-in View options");
parser.addArgument("view-class", "vc", QVariant::String, "The View's' class name");
parser.addArgument("view-name", "vn", QVariant::String, "The View's human readable name");
parser.beginGroup("Project options");
parser.addArgument("project-copyright", "", QVariant::String, "Path to a file containing copyright information", ":/MITKCopyright.txt");
parser.addArgument("project-name", "", QVariant::String, "The project name");
parser.setExactMatchRegularExpression("--project-name", "^[a-zA-Z_\\-]+$", "Project name invalid");
parser.addArgument("project-app-name", "", QVariant::String, "The application name");
parser.setExactMatchRegularExpression("--project-app-name", "^[a-zA-Z_\\-]+$", "Project application name invalid");
parser.endGroup();
// Parse the command line arguments
bool ok = false;
QHash<QString, QVariant> parsedArgs = parser.parseArguments(QCoreApplication::arguments(), &ok);
if (!ok)
{
QTextStream(stderr, QIODevice::WriteOnly) << "Error parsing arguments: "
<< parser.errorString() << "\n";
return EXIT_FAILURE;
}
QTextStream out(stdout, QIODevice::WriteOnly);
// Show a help message
if (parsedArgs.contains("help"))
{
out << "A CTK plug-in generator for MITK\n\n"
<< parser.helpText();
return EXIT_SUCCESS;
}
// Check arguments
// Project options
QString projectName = parsedArgs["project-name"].toString();
QString projectAppName = parsedArgs["project-app-name"].toString();
QString copyrightPath = QDir::fromNativeSeparators(parsedArgs["project-copyright"].toString());
bool createProject = !projectName.isEmpty();
if (createProject && projectAppName.isEmpty())
{
projectAppName = projectName;
}
QString pluginSymbolicName = parsedArgs["plugin-symbolic-name"].toString();
if (pluginSymbolicName.isEmpty())
{
qCritical() << "Required argument 'plugin-symbolic-name' missing.";
return EXIT_FAILURE;
}
QString pluginTarget(pluginSymbolicName);
pluginTarget.replace('.', '_');
QString outDir = QDir::fromNativeSeparators(parsedArgs["out-dir"].toString());
QString licensePath = QDir::fromNativeSeparators(parsedArgs["license"].toString());
QString pluginExportDirective = pluginSymbolicName.split('.').last().toUpper() + "_EXPORT";
QString pluginName = parsedArgs["plugin-name"].toString();
if (pluginName.isEmpty())
{
QStringList toks = pluginSymbolicName.split('.');
pluginName = toks.last();
pluginName[0] = pluginName[0].toUpper();
}
QString vendor = parsedArgs["vendor"].toString();
QString viewName = parsedArgs["view-name"].toString();
if (viewName.isEmpty())
{
qCritical() << "Required argument 'view-name' missing.";
return EXIT_FAILURE;
}
QStringList toks = viewName.split(QRegExp("\\s"), QString::SkipEmptyParts);
QString viewClass = parsedArgs["view-class"].toString();
if (viewClass.isEmpty())
{
foreach(QString tok, toks)
{
QString tmp = tok;
tmp[0] = tmp[0].toUpper();
viewClass += tmp;
}
}
QString viewId;
if (viewId.isEmpty())
{
viewId = "org.mitk.views.";
foreach(QString tok, toks)
{
viewId += tok.toLower();
}
}
bool quiet = parsedArgs.contains("quiet");
bool autoConfirm = parsedArgs.contains("confirm-all");
if (!outDir.endsWith('/'))
outDir += '/';
if (createProject)
outDir += projectName;
else
outDir += pluginSymbolicName;
// Print the collected information
if(!quiet)
{
if (createProject)
{
out << "Using the following information to create a project:\n\n"
<< " Project Name: " << projectName << '\n'
<< " Application Name: " << projectAppName << '\n'
<< " Copyright File: " << QDir::toNativeSeparators(copyrightPath) << '\n';
}
else
{
out << "Using the following information to create a plug-in:\n\n";
}
out << " License File: " << QDir::toNativeSeparators(licensePath) << '\n'
<< " Plugin-SymbolicName: " << pluginSymbolicName << '\n'
<< " Plugin-Name: " << pluginName << '\n'
<< " Plugin-Vendor: " << vendor << '\n'
<< " View Name: " << viewName << '\n'
<< " View Id: " << viewId << '\n'
<< " View Class: " << viewClass << '\n' << '\n'
<< "Create in: " << outDir << '\n' << '\n';
if (!autoConfirm)
out << "Continue [Y/n]? ";
out.flush();
if(!autoConfirm && !readAnswer('y'))
{
out << "Aborting.\n";
return EXIT_SUCCESS;
}
}
// Check the output directory
if (!QDir(outDir).exists())
{
if (!autoConfirm)
{
out << "Directory '" << outDir << "' does not exist. Create it [Y/n]? ";
out.flush();
}
if (autoConfirm || readAnswer('y'))
{
if (!QDir().mkpath(outDir))
{
qCritical() << "Could not create directory:" << outDir;
return EXIT_FAILURE;
}
}
else
{
out << "Aborting.\n";
return EXIT_SUCCESS;
}
}
if (!QDir(outDir).entryList(QDir::AllEntries | QDir::NoDotAndDotDot).isEmpty())
{
if (!autoConfirm)
{
out << "Directory '" << outDir << "' is not empty. Continue [y/N]? ";
out.flush();
}
if (!autoConfirm && !readAnswer('n'))
{
out << "Aborting.\n";
return EXIT_SUCCESS;
}
}
// Extract the license text
QFile licenseFile(licensePath);
if (!licenseFile.open(QIODevice::ReadOnly))
{
qCritical() << "Cannot open file" << licenseFile.fileName();
return EXIT_FAILURE;
}
QString licenseText = licenseFile.readAll();
licenseFile.close();
QHash<QString,QString> parameters;
if (createProject)
{
// Extract the copyright
QFile copyrightFile(copyrightPath);
if (!copyrightFile.open(QIODevice::ReadOnly))
{
qCritical() << "Cannot open file" << copyrightFile.fileName();
return EXIT_FAILURE;
}
QString copyrighText = copyrightFile.readAll();
copyrightFile.close();
parameters["$(copyright)"] = copyrighText;
parameters["$(project-name)"] = projectName;
parameters["$(project-app-name)"] = projectAppName;
parameters["$(project-plugins)"] = QString("Plugins/") + pluginSymbolicName + ":ON";
QStringList toks = pluginTarget.split("_");
QString projectPluginBase = toks[0] + "_" + toks[1];
parameters["$(project-plugin-base)"] = projectPluginBase;
}
parameters["$(license)"] = licenseText;
parameters["$(plugin-name)"] = pluginName;
parameters["$(plugin-symbolic-name)"] = pluginSymbolicName;
parameters["$(vendor)"] = vendor;
parameters["$(plugin-target)"] = pluginTarget;
parameters["$(plugin-export-directive)"] = pluginExportDirective;
parameters["$(view-id)"] = viewId;
parameters["$(view-name)"] = viewName;
parameters["$(view-file-name)"] = viewClass;
parameters["$(view-class-name)"] = viewClass;
if (createProject)
{
QHash<QString,QString> projectFileNameMapping;
projectFileNameMapping["TemplateApp"] = projectAppName;
QHash<QString,QString> filePathMapping = createTemplateFileMapping(":/ProjectTemplate", outDir, projectFileNameMapping);
generateFiles(parameters, filePathMapping);
}
QHash<QString,QString> pluginFileNameMapping;
pluginFileNameMapping["QmitkTemplateView"] = viewClass;
if (createProject)
{
if (!outDir.endsWith('/'))
outDir += '/';
outDir += "Plugins/" + pluginSymbolicName;
}
QHash<QString,QString> filePathMapping = createTemplateFileMapping(":/PluginTemplate", outDir, pluginFileNameMapping);
generateFiles(parameters, filePathMapping);
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>// The I/O APIC manages hardware interrupts for an SMP system.
// http://www.intel.com/design/chipsets/datashts/29056601.pdf
// See also picirq.c.
#include "types.h"
#include "traps.h"
#include "kernel.hh"
#include "apic.hh"
#include "irq.hh"
#include "cpu.hh"
#include "pci.hh"
#include "kstream.hh"
#include "iommu.hh"
#include "bitset.hh"
static console_stream verbose(true);
#define REG_ID 0x00 // Register index: ID
#define REG_VER 0x01 // Register index: version
#define REG_TABLE 0x10 // Redirection table base
// The redirection table starts at REG_TABLE and uses
// two registers to configure each interrupt.
// The first (low) register in a pair contains configuration bits.
// The second (high) register contains a bitmask telling which
// CPUs can serve that interrupt.
#define INT_DISABLED 0x00010000 // Interrupt disabled
#define INT_LEVEL 0x00008000 // Level-triggered (vs edge-)
#define INT_IRR 0x00004000 // Remote IRR (RO)
#define INT_ACTIVELOW 0x00002000 // Active low (vs high)
#define INT_DELIVS 0x00001000 // Delivery status (RO)
#define INT_LOGICAL 0x00000800 // Destination is CPU id (vs APIC ID)
#define INT_REMAPPABLE (1ull<<48) // IOMMU remappable
#define MAX_IOAPICS 8
// IO APIC MMIO structure: write reg, then read or write data.
struct ioapic_mmio {
u32 reg;
u32 pad[3];
u32 data;
u32 read(int reg) volatile;
void write(int reg, u32 data) volatile;
};
class ioapic_82093 : public ioapic
{
// The n'th IOAPIC services IRQs [ioapic_base[n], ioapic_lim[n]).
volatile ioapic_mmio *ioapics[MAX_IOAPICS];
int ioapic_base[MAX_IOAPICS];
int ioapic_lim[MAX_IOAPICS];
int nioapics;
// Map from ISA IRQs to IOAPIC pins. Identity mapped by default,
// but can be overridden by the BIOS.
irq isa_irqs[16];
volatile ioapic_mmio *map_gsi(int gsi, int *pin_out);
public:
ioapic_82093();
void register_base(int irq_base, paddr address);
void register_isa_irq_override(int isa_irq, irq override);
void register_nmi(irq nmi);
irq map_isa_irq(int isa_irq);
irq map_pci_irq(struct pci_func *f);
void dump();
protected:
void enable_irq(const struct irq &, bool enable);
void eoi_irq(const struct irq &);
};
u32
ioapic_mmio::read(int reg) volatile
{
this->reg = reg;
return this->data;
}
void
ioapic_mmio::write(int reg, u32 data) volatile
{
this->reg = reg;
this->data = data;
}
volatile ioapic_mmio *
ioapic_82093::map_gsi(int gsi, int *pin_out)
{
for (int i = 0; i < nioapics; ++i)
if (ioapic_base[i] <= gsi && gsi < ioapic_lim[i]) {
*pin_out = gsi - ioapic_base[i];
return ioapics[i];
}
return nullptr;
}
ioapic_82093::ioapic_82093()
{
// Initialize ISA IRQ overrides to the default identity mapping.
for (int i = 0; i < 16; ++i) {
isa_irqs[i] = irq::default_isa();
isa_irqs[i].vector = T_IRQ0 + i;
isa_irqs[i].gsi = i;
}
}
void
ioapic_82093::register_base(int irq_base, paddr address)
{
if (nioapics == MAX_IOAPICS)
panic("ioapic: Too many IOAPICs. Increase MAX_IOAPICS");
// [IOAPIC 3.2.2]
auto ioapic = (volatile struct ioapic_mmio*)p2v(address);
ioapics[nioapics] = ioapic;
int maxintr = (ioapic->read(REG_VER) >> 16) & 0xFF;
ioapic_base[nioapics] = irq_base;
ioapic_lim[nioapics] = irq_base + maxintr + 1;
verbose.println("ioapic: IOAPIC for IRQs ", irq_base, "..",
irq_base + maxintr, " at ", shex(address));
// Mark all interrupts edge-triggered, active high, disabled,
// and not routed to any CPUs.
for(int i = 0; i <= maxintr; i++) {
ioapic->write(REG_TABLE+2*i, INT_DISABLED | (T_IRQ0 + i));
ioapic->write(REG_TABLE+2*i+1, 0);
}
++nioapics;
}
void
ioapic_82093::register_isa_irq_override(int isa_irq, irq override)
{
if (isa_irq >= 16) {
swarn.println("ioapic: Cannot override non-legacy IRQ ", isa_irq);
return;
}
override.vector = T_IRQ0 + override.gsi;
isa_irqs[isa_irq] = override;
}
void
ioapic_82093::register_nmi(irq nmi)
{
swarn.println("ioapic: register_nmi not implemented");
}
irq
ioapic_82093::map_isa_irq(int isa_irq)
{
assert(isa_irq < 16);
return isa_irqs[isa_irq];
}
irq
ioapic_82093::map_pci_irq(struct pci_func *f)
{
irq res = acpi_pci_resolve_irq(f);
if (res.valid())
res.vector = T_IRQ0 + res.gsi;
return res;
}
void
ioapic_82093::enable_irq(const struct irq &irq, bool enable)
{
assert(irq.valid());
assert(irq.vector >= 32 && irq.vector < 256);
assert(irq.vector != T_TLBFLUSH && irq.vector != T_SAMPCONF);
int pin;
auto ioapic = map_gsi(irq.gsi, &pin);
if (!ioapic)
panic("ioapic: Cannot enable IRQ %d, no IOAPIC for that IRQ", irq.gsi);
// Route interrupts to CPU 0
struct cpu *dest = &cpus[0];
// If we're using an IOMMU, allocate an interrupt redirection entry
uint64_t iommu_index = 0;
if (iommu)
iommu_index = iommu->allocate_int(irq, dest);
if (enable)
verbose.println("ioapic: Routing ", irq, " to APICID ", dest->hwid.num);
else
verbose.println("ioapic: Masking ", irq);
// [IOAPIC 3.2.4] Fixed delivery mode, physical destination mode,
// routed to APIC ID dest.
uint64_t reg = irq.vector;
if (irq.active_low)
reg |= INT_ACTIVELOW;
if (irq.level_triggered)
reg |= INT_LEVEL;
if (!enable)
reg |= INT_DISABLED;
if (!iommu)
reg |= ((uint64_t)dest->hwid.num << 56);
else
reg |= INT_REMAPPABLE |
((iommu_index & 0x7fff) << 49) | ((iommu_index >> 15) << 11);
ioapic->write(REG_TABLE+2*pin, reg & 0xFFFFFFFF);
ioapic->write(REG_TABLE+2*pin+1, (reg >> 32) & 0xFFFFFFFF);
}
void
ioapic_82093::eoi_irq(const struct irq &irq)
{
assert(irq.valid());
// Assume the LAPIC is in broadcast EOI mode
lapic->eoi();
}
void
ioapic_82093::dump()
{
bitset<256> irr, delivs;
scoped_cli cli();
for (int i = 0; i < nioapics; ++i) {
for (int gsi = ioapic_base[i]; gsi < ioapic_lim[i]; ++gsi) {
int pin = gsi - ioapic_base[i];
uint32_t reg = ioapics[i]->read(REG_TABLE+2*pin);
if ((reg & INT_LEVEL) && (reg & INT_IRR))
irr.set(gsi);
if (reg & INT_DELIVS)
delivs.set(gsi);
}
}
if (irr.any() || delivs.any())
// GSIs that are awaiting EOI (IRR) and that are pending delivery
// to the LAPIC (DELIVS)
console.println("IOAPIC GSI IRR ", irr, " DELIVS ", delivs);
}
bool
initextpic_ioapic(void)
{
static ioapic_82093 ioapic;
if (!acpi_setup_ioapic(&ioapic))
return false;
extpic = &ioapic;
return true;
}
<commit_msg>ioapic: Get and check version<commit_after>// The I/O APIC manages hardware interrupts for an SMP system.
// http://www.intel.com/design/chipsets/datashts/29056601.pdf
// See also picirq.c.
#include "types.h"
#include "traps.h"
#include "kernel.hh"
#include "apic.hh"
#include "irq.hh"
#include "cpu.hh"
#include "pci.hh"
#include "kstream.hh"
#include "iommu.hh"
#include "bitset.hh"
static console_stream verbose(true);
#define REG_ID 0x00 // Register index: ID
#define REG_VER 0x01 // Register index: version
#define REG_TABLE 0x10 // Redirection table base
// The redirection table starts at REG_TABLE and uses
// two registers to configure each interrupt.
// The first (low) register in a pair contains configuration bits.
// The second (high) register contains a bitmask telling which
// CPUs can serve that interrupt.
#define INT_DISABLED 0x00010000 // Interrupt disabled
#define INT_LEVEL 0x00008000 // Level-triggered (vs edge-)
#define INT_IRR 0x00004000 // Remote IRR (RO)
#define INT_ACTIVELOW 0x00002000 // Active low (vs high)
#define INT_DELIVS 0x00001000 // Delivery status (RO)
#define INT_LOGICAL 0x00000800 // Destination is CPU id (vs APIC ID)
#define INT_REMAPPABLE (1ull<<48) // IOMMU remappable
#define MAX_IOAPICS 8
// IO APIC MMIO structure: write reg, then read or write data.
struct ioapic_mmio {
u32 reg;
u32 pad[3];
u32 data;
u32 read(int reg) volatile;
void write(int reg, u32 data) volatile;
};
class ioapic_82093 : public ioapic
{
// The n'th IOAPIC services IRQs [ioapic_base[n], ioapic_lim[n]).
volatile ioapic_mmio *ioapics[MAX_IOAPICS];
int ioapic_base[MAX_IOAPICS];
int ioapic_lim[MAX_IOAPICS];
int nioapics;
// Map from ISA IRQs to IOAPIC pins. Identity mapped by default,
// but can be overridden by the BIOS.
irq isa_irqs[16];
volatile ioapic_mmio *map_gsi(int gsi, int *pin_out);
public:
ioapic_82093();
void register_base(int irq_base, paddr address);
void register_isa_irq_override(int isa_irq, irq override);
void register_nmi(irq nmi);
irq map_isa_irq(int isa_irq);
irq map_pci_irq(struct pci_func *f);
void dump();
protected:
void enable_irq(const struct irq &, bool enable);
void eoi_irq(const struct irq &);
};
u32
ioapic_mmio::read(int reg) volatile
{
this->reg = reg;
return this->data;
}
void
ioapic_mmio::write(int reg, u32 data) volatile
{
this->reg = reg;
this->data = data;
}
volatile ioapic_mmio *
ioapic_82093::map_gsi(int gsi, int *pin_out)
{
for (int i = 0; i < nioapics; ++i)
if (ioapic_base[i] <= gsi && gsi < ioapic_lim[i]) {
*pin_out = gsi - ioapic_base[i];
return ioapics[i];
}
return nullptr;
}
ioapic_82093::ioapic_82093()
{
// Initialize ISA IRQ overrides to the default identity mapping.
for (int i = 0; i < 16; ++i) {
isa_irqs[i] = irq::default_isa();
isa_irqs[i].vector = T_IRQ0 + i;
isa_irqs[i].gsi = i;
}
}
void
ioapic_82093::register_base(int irq_base, paddr address)
{
if (nioapics == MAX_IOAPICS)
panic("ioapic: Too many IOAPICs. Increase MAX_IOAPICS");
// [IOAPIC 3.2.2]
auto ioapic = (volatile struct ioapic_mmio*)p2v(address);
ioapics[nioapics] = ioapic;
u32 verreg = ioapic->read(REG_VER);
int version = verreg & 0xFF;
int maxintr = (verreg >> 16) & 0xFF;
// Some ACPI tables (*cough* josmp) report IOAPICs that don't exist,
// so we sanity check it.
if (version < 0x10 || maxintr > 239) {
swarn.println("ioapic: Ignoring nonsensical IOAPIC at ", shex(address));
return;
}
ioapic_base[nioapics] = irq_base;
ioapic_lim[nioapics] = irq_base + maxintr + 1;
verbose.println("ioapic: IOAPIC version ", shex(version),
" for IRQs ", irq_base, "..",
irq_base + maxintr, " at ", shex(address));
// Mark all interrupts edge-triggered, active high, disabled,
// and not routed to any CPUs.
for(int i = 0; i <= maxintr; i++) {
ioapic->write(REG_TABLE+2*i, INT_DISABLED | (T_IRQ0 + i));
ioapic->write(REG_TABLE+2*i+1, 0);
}
++nioapics;
}
void
ioapic_82093::register_isa_irq_override(int isa_irq, irq override)
{
if (isa_irq >= 16) {
swarn.println("ioapic: Cannot override non-legacy IRQ ", isa_irq);
return;
}
override.vector = T_IRQ0 + override.gsi;
isa_irqs[isa_irq] = override;
}
void
ioapic_82093::register_nmi(irq nmi)
{
swarn.println("ioapic: register_nmi not implemented");
}
irq
ioapic_82093::map_isa_irq(int isa_irq)
{
assert(isa_irq < 16);
return isa_irqs[isa_irq];
}
irq
ioapic_82093::map_pci_irq(struct pci_func *f)
{
irq res = acpi_pci_resolve_irq(f);
if (res.valid())
res.vector = T_IRQ0 + res.gsi;
return res;
}
void
ioapic_82093::enable_irq(const struct irq &irq, bool enable)
{
assert(irq.valid());
assert(irq.vector >= 32 && irq.vector < 256);
assert(irq.vector != T_TLBFLUSH && irq.vector != T_SAMPCONF);
int pin;
auto ioapic = map_gsi(irq.gsi, &pin);
if (!ioapic)
panic("ioapic: Cannot enable IRQ %d, no IOAPIC for that IRQ", irq.gsi);
// Route interrupts to CPU 0
struct cpu *dest = &cpus[0];
// If we're using an IOMMU, allocate an interrupt redirection entry
uint64_t iommu_index = 0;
if (iommu)
iommu_index = iommu->allocate_int(irq, dest);
if (enable)
verbose.println("ioapic: Routing ", irq, " to APICID ", dest->hwid.num);
else
verbose.println("ioapic: Masking ", irq);
// [IOAPIC 3.2.4] Fixed delivery mode, physical destination mode,
// routed to APIC ID dest.
uint64_t reg = irq.vector;
if (irq.active_low)
reg |= INT_ACTIVELOW;
if (irq.level_triggered)
reg |= INT_LEVEL;
if (!enable)
reg |= INT_DISABLED;
if (!iommu)
reg |= ((uint64_t)dest->hwid.num << 56);
else
reg |= INT_REMAPPABLE |
((iommu_index & 0x7fff) << 49) | ((iommu_index >> 15) << 11);
ioapic->write(REG_TABLE+2*pin, reg & 0xFFFFFFFF);
ioapic->write(REG_TABLE+2*pin+1, (reg >> 32) & 0xFFFFFFFF);
}
void
ioapic_82093::eoi_irq(const struct irq &irq)
{
assert(irq.valid());
// Assume the LAPIC is in broadcast EOI mode
lapic->eoi();
}
void
ioapic_82093::dump()
{
bitset<256> irr, delivs;
scoped_cli cli();
for (int i = 0; i < nioapics; ++i) {
for (int gsi = ioapic_base[i]; gsi < ioapic_lim[i]; ++gsi) {
int pin = gsi - ioapic_base[i];
uint32_t reg = ioapics[i]->read(REG_TABLE+2*pin);
if ((reg & INT_LEVEL) && (reg & INT_IRR))
irr.set(gsi);
if (reg & INT_DELIVS)
delivs.set(gsi);
}
}
if (irr.any() || delivs.any())
// GSIs that are awaiting EOI (IRR) and that are pending delivery
// to the LAPIC (DELIVS)
console.println("IOAPIC GSI IRR ", irr, " DELIVS ", delivs);
}
bool
initextpic_ioapic(void)
{
static ioapic_82093 ioapic;
if (!acpi_setup_ioapic(&ioapic))
return false;
extpic = &ioapic;
return true;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "bench.h"
#include "chainparams.h"
#include "validation/validation.h"
namespace block_bench {
#include "bench/data/block413567.raw.h"
}
// These are the two major time-sinks which happen after we have fully received
// a block off the wire, but before we can relay the block on to peers using
// compact block relay.
static void DeserializeBlockTest(benchmark::State& state)
{
CDataStream stream((const char*)block_bench::block413567,
(const char*)&block_bench::block413567[sizeof(block_bench::block413567)],
SER_NETWORK, PROTOCOL_VERSION);
char a;
stream.write(&a, 1); // Prevent compaction
while (state.KeepRunning()) {
CBlock block;
stream >> block;
assert(stream.Rewind(sizeof(block_bench::block413567)));
}
}
static void DeserializeAndCheckBlockTest(benchmark::State& state)
{
CDataStream stream((const char*)block_bench::block413567,
(const char*)&block_bench::block413567[sizeof(block_bench::block413567)],
SER_NETWORK, PROTOCOL_VERSION);
char a;
stream.write(&a, 1); // Prevent compaction
SelectParams(CBaseChainParams::MAIN);
while (state.KeepRunning()) {
CBlock block; // Note that CBlock caches its checked state, so we need to recreate it here
stream >> block;
assert(stream.Rewind(sizeof(block_bench::block413567)));
CValidationState _state;
assert(CheckBlock(block, _state));
}
}
BENCHMARK(DeserializeBlockTest);
BENCHMARK(DeserializeAndCheckBlockTest);
<commit_msg>[bench] Avoid function call arguments which are pointers to uninitialized values<commit_after>// Copyright (c) 2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "bench.h"
#include "chainparams.h"
#include "validation/validation.h"
namespace block_bench {
#include "bench/data/block413567.raw.h"
}
// These are the two major time-sinks which happen after we have fully received
// a block off the wire, but before we can relay the block on to peers using
// compact block relay.
static void DeserializeBlockTest(benchmark::State& state)
{
CDataStream stream((const char*)block_bench::block413567,
(const char*)&block_bench::block413567[sizeof(block_bench::block413567)],
SER_NETWORK, PROTOCOL_VERSION);
char a = '\0';
stream.write(&a, 1); // Prevent compaction
while (state.KeepRunning()) {
CBlock block;
stream >> block;
assert(stream.Rewind(sizeof(block_bench::block413567)));
}
}
static void DeserializeAndCheckBlockTest(benchmark::State& state)
{
CDataStream stream((const char*)block_bench::block413567,
(const char*)&block_bench::block413567[sizeof(block_bench::block413567)],
SER_NETWORK, PROTOCOL_VERSION);
char a = '\0';
stream.write(&a, 1); // Prevent compaction
SelectParams(CBaseChainParams::MAIN);
while (state.KeepRunning()) {
CBlock block; // Note that CBlock caches its checked state, so we need to recreate it here
stream >> block;
assert(stream.Rewind(sizeof(block_bench::block413567)));
CValidationState _state;
assert(CheckBlock(block, _state));
}
}
BENCHMARK(DeserializeBlockTest);
BENCHMARK(DeserializeAndCheckBlockTest);
<|endoftext|> |
<commit_before>/*
* Copyright 2014 Open Connectome Project (http://openconnecto.me)
* Written by Da Zheng (zhengda1936@gmail.com)
*
* This file is part of FlashMatrix.
*
* 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 "matrix_store.h"
#include "local_matrix_store.h"
namespace fm
{
namespace detail
{
size_t matrix_store::get_num_portions() const
{
std::pair<size_t, size_t> chunk_size = get_portion_size();
if (is_wide()) {
assert(chunk_size.first == get_num_rows());
return ceil(((double) get_num_cols()) / chunk_size.second);
}
else {
assert(chunk_size.second == get_num_cols());
return ceil(((double) get_num_rows()) / chunk_size.first);
}
}
}
}
<commit_msg>[Matrix]: fix a bug in get_num_portions().<commit_after>/*
* Copyright 2014 Open Connectome Project (http://openconnecto.me)
* Written by Da Zheng (zhengda1936@gmail.com)
*
* This file is part of FlashMatrix.
*
* 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 "matrix_store.h"
#include "local_matrix_store.h"
namespace fm
{
namespace detail
{
size_t matrix_store::get_num_portions() const
{
std::pair<size_t, size_t> chunk_size = get_portion_size();
if (is_wide())
return ceil(((double) get_num_cols()) / chunk_size.second);
else
return ceil(((double) get_num_rows()) / chunk_size.first);
}
}
}
<|endoftext|> |
<commit_before>//..............................................................................
//
// This file is part of the Jancy toolkit.
//
// Jancy is distributed under the MIT license.
// For details see accompanying license.txt file,
// the public copy of which is also available at:
// http://tibbo.com/downloads/archive/jancy/license.txt
//
//..............................................................................
#include "pch.h"
#include "jnc_EditTheme.h"
namespace jnc {
//..............................................................................
void EditTheme::setDefaultLightTheme() {
m_colorTable[BaseBack] = 0xffffff;
m_colorTable[BaseText] = (QRgb)0x000000;
m_colorTable[LineMarginBack] = QColor::Invalid;
m_colorTable[LineMarginText] = 0x2b91af;
m_colorTable[ErrorBack] = 0xffc8c8;
m_colorTable[ErrorText] = QColor::Invalid;
m_colorTable[SelectionBack] = 0x99c9ef;
m_colorTable[SelectionText] = QColor::Invalid;
m_colorTable[SelectionBackInactive] = 0xe0e0e0;
m_colorTable[SelectionTextInactive] = QColor::Invalid;
m_colorTable[BraceMatchBack] = 0xfff080;
m_colorTable[BraceMatchText] = QColor::Invalid;
m_colorTable[CurrentLineBack] = 0xe8eff8;
m_colorTable[CompleterSynopsisColumn] = 0x808080;
m_colorTable[Keyword] = 0x0000ff;
m_colorTable[Constant] = 0xce7b00;
m_colorTable[Comment] = 0x969696;
invalidatePalette();
}
void EditTheme::setDefaultDarkTheme() {
// based on monokai
m_colorTable[BaseBack] = 0x2c292d;
m_colorTable[BaseText] = 0xd6d6d6;
m_colorTable[LineMarginBack] = 0x3c393d;
m_colorTable[LineMarginText] = 0x7d7d7d;
m_colorTable[ErrorBack] = 0x773f40;
m_colorTable[ErrorText] = QColor::Invalid;
m_colorTable[SelectionBack] = 0x405672;
m_colorTable[SelectionText] = QColor::Invalid;
m_colorTable[SelectionBackInactive] = 0x505050;
m_colorTable[SelectionTextInactive] = QColor::Invalid;
m_colorTable[BraceMatchBack] = 0x835c42;
m_colorTable[BraceMatchText] = QColor::Invalid;
m_colorTable[CurrentLineBack] = 0x3c393d;
m_colorTable[CompleterSynopsisColumn] = 0x7d7d7d;
m_colorTable[Keyword] = 0xf05279;
m_colorTable[Constant] = 0x77dce8;
m_colorTable[Comment] = 0x7d7d7d;
invalidatePalette();
}
const QPalette& EditTheme::createPalette() {
setPaletteColor(QPalette::Base, m_colorTable[BaseBack]);
setPaletteColor(QPalette::Window, m_colorTable[BaseBack]);
setPaletteColor(QPalette::Text, m_colorTable[BaseText]);
setPaletteColor(QPalette::WindowText, m_colorTable[BaseText]);
setPaletteColor(QPalette::Highlight, m_colorTable[SelectionBack]);
setPaletteColor(QPalette::HighlightedText, m_colorTable[SelectionText]);
setPaletteColor(QPalette::Inactive, QPalette::Base, m_colorTable[BaseBack]);
setPaletteColor(QPalette::Inactive, QPalette::Window, m_colorTable[BaseBack]);
setPaletteColor(QPalette::Inactive, QPalette::Text, m_colorTable[BaseText]);
setPaletteColor(QPalette::Inactive, QPalette::WindowText, m_colorTable[BaseText]);
setPaletteColor(QPalette::Inactive, QPalette::Highlight, m_colorTable[SelectionBackInactive]);
setPaletteColor(QPalette::Inactive, QPalette::HighlightedText, m_colorTable[SelectionTextInactive]);
return m_palette;
}
//..............................................................................
} // namespace jnc
<commit_msg>[jnc_edit] update the default dark theme colors<commit_after>//..............................................................................
//
// This file is part of the Jancy toolkit.
//
// Jancy is distributed under the MIT license.
// For details see accompanying license.txt file,
// the public copy of which is also available at:
// http://tibbo.com/downloads/archive/jancy/license.txt
//
//..............................................................................
#include "pch.h"
#include "jnc_EditTheme.h"
namespace jnc {
//..............................................................................
void EditTheme::setDefaultLightTheme() {
m_colorTable[BaseBack] = 0xffffff;
m_colorTable[BaseText] = (QRgb)0x000000;
m_colorTable[LineMarginBack] = QColor::Invalid;
m_colorTable[LineMarginText] = 0x2b91af;
m_colorTable[ErrorBack] = 0xffc8c8;
m_colorTable[ErrorText] = QColor::Invalid;
m_colorTable[SelectionBack] = 0x99c9ef;
m_colorTable[SelectionText] = QColor::Invalid;
m_colorTable[SelectionBackInactive] = 0xe0e0e0;
m_colorTable[SelectionTextInactive] = QColor::Invalid;
m_colorTable[BraceMatchBack] = 0xfff080;
m_colorTable[BraceMatchText] = QColor::Invalid;
m_colorTable[CurrentLineBack] = 0xe8eff8;
m_colorTable[CompleterSynopsisColumn] = 0x808080;
m_colorTable[Keyword] = 0x0000ff;
m_colorTable[Constant] = 0xce7b00;
m_colorTable[Comment] = 0x969696;
invalidatePalette();
}
void EditTheme::setDefaultDarkTheme() {
// based on monokai
m_colorTable[BaseBack] = 0x2e3841;
m_colorTable[BaseText] = 0xd7dee9;
m_colorTable[LineMarginBack] = 0x3e4851;
m_colorTable[LineMarginText] = 0x838b95;
m_colorTable[ErrorBack] = 0x773f40;
m_colorTable[ErrorText] = QColor::Invalid;
m_colorTable[SelectionBack] = 0x405672;
m_colorTable[SelectionText] = QColor::Invalid;
m_colorTable[SelectionBackInactive] = 0x505050;
m_colorTable[SelectionTextInactive] = QColor::Invalid;
m_colorTable[BraceMatchBack] = 0x835c42;
m_colorTable[BraceMatchText] = QColor::Invalid;
m_colorTable[CurrentLineBack] = 0x3e4851;
m_colorTable[CompleterSynopsisColumn] = 0x7d7d7d;
m_colorTable[Keyword] = 0xca95c5;
m_colorTable[Constant] = 0x94c796;
m_colorTable[Comment] = 0xa5acb8;
invalidatePalette();
}
const QPalette& EditTheme::createPalette() {
setPaletteColor(QPalette::Base, m_colorTable[BaseBack]);
setPaletteColor(QPalette::Window, m_colorTable[BaseBack]);
setPaletteColor(QPalette::Text, m_colorTable[BaseText]);
setPaletteColor(QPalette::WindowText, m_colorTable[BaseText]);
setPaletteColor(QPalette::Highlight, m_colorTable[SelectionBack]);
setPaletteColor(QPalette::HighlightedText, m_colorTable[SelectionText]);
setPaletteColor(QPalette::Inactive, QPalette::Base, m_colorTable[BaseBack]);
setPaletteColor(QPalette::Inactive, QPalette::Window, m_colorTable[BaseBack]);
setPaletteColor(QPalette::Inactive, QPalette::Text, m_colorTable[BaseText]);
setPaletteColor(QPalette::Inactive, QPalette::WindowText, m_colorTable[BaseText]);
setPaletteColor(QPalette::Inactive, QPalette::Highlight, m_colorTable[SelectionBackInactive]);
setPaletteColor(QPalette::Inactive, QPalette::HighlightedText, m_colorTable[SelectionTextInactive]);
return m_palette;
}
//..............................................................................
} // namespace jnc
<|endoftext|> |
<commit_before>#ifndef STAN_MATH_PRIM_MAT_PROB_ORDERED_PROBIT_LOG_HPP
#define STAN_MATH_PRIM_MAT_PROB_ORDERED_PROBIT_LOG_HPP
#include <stan/math/prim/mat/prob/ordered_probit_lpmf.hpp>
#include <stan/math/prim/scal/meta/return_type.hpp>
namespace stan {
namespace math {
/**
* Returns the (natural) log probability of the integer/s
* given the vector of continuous location/s and
* specified cutpoints in an ordered probit model.
*
* <p>Typically the continous location
* will be the dot product of a vector of regression coefficients
* and a vector of predictors for the outcome.
*
* @tparam propto True if calculating up to a proportion.
* @tparam T_y y variable type (int or array of integers).
* @tparam T_loc Location type (double or vector).
* @tparam T_cut Cut-point type (vector or array of vectors).
* @param y Integers
* @param lambda Continuous location variables.
* @param c Positive increasing cutpoints.
* @return Log probability of outcome given location and
* cutpoints.
* @throw std::domain_error If the outcome is not between 1 and
* the number of cutpoints plus 2; if the cutpoint vector is
* empty; if the cutpoint vector contains a non-positive,
* non-finite value; or if the cutpoint vector is not sorted in
* ascending order.
* @throw std::invalid_argument If array y and vector lambda
* are different lengths.
* @throw std::invalid_argument if array y and array of vectors
* c are different lengths.
*
* @deprecated use <code>ordered_probit_lpmf</code>
*/
template <bool propto, typename T_y, typename T_loc, typename T_cut>
typename return_type<T_loc, T_cut>::type
ordered_probit_log(const T_y& y, const T_loc& lambda, const T_cut& c) {
return ordered_probit_lpmf<propto>(y, lambda, c);
}
/**
* @deprecated use <code>ordered_probit_lpmf</code>
*/
template <typename T_y, typename T_loc, typename T_cut>
typename return_type<T_loc, T_cut>::type
ordered_probit_log(const T_y& y, const T_loc& lambda, const T_cut& c) {
return ordered_probit_lpmf(y, lambda, c);
}
}
}
#endif
<commit_msg>Whitespace fix<commit_after>#ifndef STAN_MATH_PRIM_MAT_PROB_ORDERED_PROBIT_LOG_HPP
#define STAN_MATH_PRIM_MAT_PROB_ORDERED_PROBIT_LOG_HPP
#include <stan/math/prim/mat/prob/ordered_probit_lpmf.hpp>
#include <stan/math/prim/scal/meta/return_type.hpp>
namespace stan {
namespace math {
/**
* Returns the (natural) log probability of the integer/s
* given the vector of continuous location/s and
* specified cutpoints in an ordered probit model.
*
* <p>Typically the continous location
* will be the dot product of a vector of regression coefficients
* and a vector of predictors for the outcome.
*
* @tparam propto True if calculating up to a proportion.
* @tparam T_y y variable type (int or array of integers).
* @tparam T_loc Location type (double or vector).
* @tparam T_cut Cut-point type (vector or array of vectors).
* @param y Integers
* @param lambda Continuous location variables.
* @param c Positive increasing cutpoints.
* @return Log probability of outcome given location and
* cutpoints.
* @throw std::domain_error If the outcome is not between 1 and
* the number of cutpoints plus 2; if the cutpoint vector is
* empty; if the cutpoint vector contains a non-positive,
* non-finite value; or if the cutpoint vector is not sorted in
* ascending order.
* @throw std::invalid_argument If array y and vector lambda
* are different lengths.
* @throw std::invalid_argument if array y and array of vectors
* c are different lengths.
*
* @deprecated use <code>ordered_probit_lpmf</code>
*/
template <bool propto, typename T_y, typename T_loc, typename T_cut>
typename return_type<T_loc, T_cut>::type
ordered_probit_log(const T_y& y, const T_loc& lambda, const T_cut& c) {
return ordered_probit_lpmf<propto>(y, lambda, c);
}
/**
* @deprecated use <code>ordered_probit_lpmf</code>
*/
template <typename T_y, typename T_loc, typename T_cut>
typename return_type<T_loc, T_cut>::type
ordered_probit_log(const T_y& y, const T_loc& lambda, const T_cut& c) {
return ordered_probit_lpmf(y, lambda, c);
}
}
}
#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 "chrome/browser/ui/views/keyboard_overlay_delegate.h"
#include "base/memory/scoped_ptr.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/chromeos/frame/bubble_window.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/views/html_dialog_view.h"
#include "chrome/browser/ui/webui/html_dialog_ui.h"
#include "chrome/common/url_constants.h"
#include "grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"
void KeyboardOverlayDelegate::ShowDialog(gfx::NativeWindow owning_window) {
Browser* browser = BrowserList::GetLastActive();
KeyboardOverlayDelegate* delegate = new KeyboardOverlayDelegate(
UTF16ToWide(l10n_util::GetStringUTF16(IDS_KEYBOARD_OVERLAY_TITLE)));
HtmlDialogView* html_view =
new HtmlDialogView(browser->profile(), delegate);
html_view->InitDialog();
chromeos::BubbleWindow::Create(owning_window,
gfx::Rect(),
chromeos::BubbleWindow::STYLE_XSHAPE,
html_view);
html_view->window()->Show();
}
KeyboardOverlayDelegate::KeyboardOverlayDelegate(
const std::wstring& title)
: title_(title) {
}
KeyboardOverlayDelegate::~KeyboardOverlayDelegate() {
}
bool KeyboardOverlayDelegate::IsDialogModal() const {
return true;
}
std::wstring KeyboardOverlayDelegate::GetDialogTitle() const {
return title_;
}
GURL KeyboardOverlayDelegate::GetDialogContentURL() const {
std::string url_string(chrome::kChromeUIKeyboardOverlayURL);
return GURL(url_string);
}
void KeyboardOverlayDelegate::GetWebUIMessageHandlers(
std::vector<WebUIMessageHandler*>* handlers) const {
}
void KeyboardOverlayDelegate::GetDialogSize(
gfx::Size* size) const {
size->SetSize(1280, 528);
}
std::string KeyboardOverlayDelegate::GetDialogArgs() const {
return "[]";
}
void KeyboardOverlayDelegate::OnDialogClosed(
const std::string& json_retval) {
delete this;
return;
}
void KeyboardOverlayDelegate::OnCloseContents(TabContents* source,
bool* out_close_dialog) {
}
bool KeyboardOverlayDelegate::ShouldShowDialogTitle() const {
return false;
}
<commit_msg>Fix the position of the keyboard overlay.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/views/keyboard_overlay_delegate.h"
#include "base/memory/scoped_ptr.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/chromeos/frame/bubble_window.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/views/html_dialog_view.h"
#include "chrome/browser/ui/webui/html_dialog_ui.h"
#include "chrome/common/url_constants.h"
#include "grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"
void KeyboardOverlayDelegate::ShowDialog(gfx::NativeWindow owning_window) {
Browser* browser = BrowserList::GetLastActive();
KeyboardOverlayDelegate* delegate = new KeyboardOverlayDelegate(
UTF16ToWide(l10n_util::GetStringUTF16(IDS_KEYBOARD_OVERLAY_TITLE)));
HtmlDialogView* html_view =
new HtmlDialogView(browser->profile(), delegate);
html_view->InitDialog();
chromeos::BubbleWindow::Create(owning_window,
gfx::Rect(),
chromeos::BubbleWindow::STYLE_XSHAPE,
html_view);
html_view->window()->Show();
}
KeyboardOverlayDelegate::KeyboardOverlayDelegate(
const std::wstring& title)
: title_(title) {
}
KeyboardOverlayDelegate::~KeyboardOverlayDelegate() {
}
bool KeyboardOverlayDelegate::IsDialogModal() const {
return true;
}
std::wstring KeyboardOverlayDelegate::GetDialogTitle() const {
return title_;
}
GURL KeyboardOverlayDelegate::GetDialogContentURL() const {
std::string url_string(chrome::kChromeUIKeyboardOverlayURL);
return GURL(url_string);
}
void KeyboardOverlayDelegate::GetWebUIMessageHandlers(
std::vector<WebUIMessageHandler*>* handlers) const {
}
void KeyboardOverlayDelegate::GetDialogSize(
gfx::Size* size) const {
size->SetSize(1252, 516);
}
std::string KeyboardOverlayDelegate::GetDialogArgs() const {
return "[]";
}
void KeyboardOverlayDelegate::OnDialogClosed(
const std::string& json_retval) {
delete this;
return;
}
void KeyboardOverlayDelegate::OnCloseContents(TabContents* source,
bool* out_close_dialog) {
}
bool KeyboardOverlayDelegate::ShouldShowDialogTitle() const {
return false;
}
<|endoftext|> |
<commit_before>// Test various levels of coverage
//
// FIXME: Port the environment variable logic below for the lit shell.
// REQUIRES: shell
//
// RUN: mkdir -p %T/coverage-levels
// RUN: %clangxx -fsanitize=shift -DGOOD_SHIFT=1 -O1 -fsanitize-coverage=func %s -o %t
// RUN: %env_ubsan_opts=coverage=1:verbosity=1:coverage_dir=%T/coverage-levels %run %t 2>&1 | FileCheck %s --check-prefix=CHECK1 --check-prefix=CHECK_NOWARN
// RUN: %clangxx -fsanitize=undefined -DGOOD_SHIFT=1 -O1 -fsanitize-coverage=func %s -o %t
// RUN: %env_ubsan_opts=coverage=1:verbosity=1:coverage_dir=%T/coverage-levels %run %t 2>&1 | FileCheck %s --check-prefix=CHECK1 --check-prefix=CHECK_NOWARN
// RUN: %clangxx -fsanitize=shift -O1 -fsanitize-coverage=func %s -o %t
// RUN: %env_ubsan_opts=coverage=1:verbosity=1:coverage_dir=%T/coverage-levels %run %t 2>&1 | FileCheck %s --check-prefix=CHECK1 --check-prefix=CHECK_WARN
// RUN: %clangxx -fsanitize=shift -O1 -fsanitize-coverage=bb %s -o %t
// RUN: %env_ubsan_opts=coverage=1:verbosity=1:coverage_dir=%T/coverage-levels %run %t 2>&1 | FileCheck %s --check-prefix=CHECK2 --check-prefix=CHECK_WARN
// RUN: %clangxx -fsanitize=shift -O1 -fsanitize-coverage=edge %s -o %t
// RUN: %env_ubsan_opts=coverage=1:verbosity=1:coverage_dir=%T/coverage-levels %run %t 2>&1 | FileCheck %s --check-prefix=CHECK3 --check-prefix=CHECK_WARN
// Coverage is not yet implemented in TSan.
// XFAIL: ubsan-tsan
volatile int sink;
int main(int argc, char **argv) {
int shift = argc * 32;
#if GOOD_SHIFT
shift = 3;
#endif
if ((argc << shift) == 16) // False.
return 1;
return 0;
}
// CHECK_WARN: shift exponent 32 is too large
// CHECK_NOWARN-NOT: ERROR
// FIXME: Currently, coverage instrumentation kicks in after ubsan, so we get
// more than the minimal number of instrumented blocks.
// FIXME: Currently, ubsan with -fno-sanitize-recover and w/o asan will fail
// to dump coverage.
// CHECK1: 1 PCs written
// CHECK2: 3 PCs written
// CHECK3: 3 PCs written
<commit_msg>[test/ubsan/coverage-levels] Fix file references in UBSAN_OPTIONS<commit_after>// Test various levels of coverage
//
// FIXME: Port the environment variable logic below for the lit shell.
// REQUIRES: shell
//
// RUN: mkdir -p %T/coverage-levels
// RUN: %clangxx -fsanitize=shift -DGOOD_SHIFT=1 -O1 -fsanitize-coverage=func %s -o %t
// RUN: %env_ubsan_opts=coverage=1:verbosity=1:coverage_dir='"%T/coverage-levels"' %run %t 2>&1 | FileCheck %s --check-prefix=CHECK1 --check-prefix=CHECK_NOWARN
// RUN: %clangxx -fsanitize=undefined -DGOOD_SHIFT=1 -O1 -fsanitize-coverage=func %s -o %t
// RUN: %env_ubsan_opts=coverage=1:verbosity=1:coverage_dir='"%T/coverage-levels"' %run %t 2>&1 | FileCheck %s --check-prefix=CHECK1 --check-prefix=CHECK_NOWARN
// RUN: %clangxx -fsanitize=shift -O1 -fsanitize-coverage=func %s -o %t
// RUN: %env_ubsan_opts=coverage=1:verbosity=1:coverage_dir='"%T/coverage-levels"' %run %t 2>&1 | FileCheck %s --check-prefix=CHECK1 --check-prefix=CHECK_WARN
// RUN: %clangxx -fsanitize=shift -O1 -fsanitize-coverage=bb %s -o %t
// RUN: %env_ubsan_opts=coverage=1:verbosity=1:coverage_dir='"%T/coverage-levels"' %run %t 2>&1 | FileCheck %s --check-prefix=CHECK2 --check-prefix=CHECK_WARN
// RUN: %clangxx -fsanitize=shift -O1 -fsanitize-coverage=edge %s -o %t
// RUN: %env_ubsan_opts=coverage=1:verbosity=1:coverage_dir='"%T/coverage-levels"' %run %t 2>&1 | FileCheck %s --check-prefix=CHECK3 --check-prefix=CHECK_WARN
// Coverage is not yet implemented in TSan.
// XFAIL: ubsan-tsan
volatile int sink;
int main(int argc, char **argv) {
int shift = argc * 32;
#if GOOD_SHIFT
shift = 3;
#endif
if ((argc << shift) == 16) // False.
return 1;
return 0;
}
// CHECK_WARN: shift exponent 32 is too large
// CHECK_NOWARN-NOT: ERROR
// FIXME: Currently, coverage instrumentation kicks in after ubsan, so we get
// more than the minimal number of instrumented blocks.
// FIXME: Currently, ubsan with -fno-sanitize-recover and w/o asan will fail
// to dump coverage.
// CHECK1: 1 PCs written
// CHECK2: 3 PCs written
// CHECK3: 3 PCs written
<|endoftext|> |
<commit_before>/*
Copyright (c) 2013-2016 Ubidots.
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.
Made by Mateo Velez - Metavix for Ubidots Inc
*/
#include "UbidotsYUN.h"
#include <Process.h>
/**
* Constructor.
*/
Ubidots::Ubidots(char* token) {
_token = token;
_dsName = "YUN";
_dsTag = "YUN";
val = (Value *)malloc(MAX_VALUES*sizeof(Value));
}
/**
* This function set a data source tag
* @arg tag the tag to set
*/
void Ubidots::setDataSourceTag(char *tag) {
_dsTag = tag;
}
/**
* This function set a data source name
* @arg name the name to set
*/
void Ubidots::setDataSourceName(char *name) {
_dsName = name;
}
/**
* This function start the YUN device
*/
void Ubidots::init() {
pinMode(13, OUTPUT);
digitalWrite(13, LOW);
Bridge.begin();
digitalWrite(13, HIGH);
}
/**
* This function is to get value from the Ubidots API
* @arg id the id where you will get the data
* @return num the data that you get from the Ubidots API
*/
float Ubidots::parseValue(char *body) {
String raw;
char *pch;
float num;
char reply[25];
uint8_t bodyPosinit = 0;
uint8_t bodyPosend = 0;
pch = strstr(body, "\"value\":");
raw = String(pch);
bodyPosinit = 9 + raw.indexOf("\"value\":");
bodyPosend = raw.indexOf(", \"timestamp\"");
raw.substring(bodyPosinit, bodyPosend).toCharArray(reply, 25);
Serial.println(reply);
num = atof(reply);
return num;
}
/**
* This function is to get value from the Ubidots API
* @arg id the id where you will get the data
* @return num the data that you get from the Ubidots API
*/
float Ubidots::getValue(String id) {
Process _client;
float num;
char c[400];
int i = 0;
int timeout = 0;
String TOKEN = _token;
String token;
String headers;
String url;
url = "http://things.ubidots.com/api/v1.6/variables/"+id;
url += "/values?page_size=1";
token = " \"X-Auth-Token: "+TOKEN;
token += "\" ";
headers = "curl --header \"Accept: application/json; indent=4\" --header" + token;
headers += "-X GET ";
/*Serial.println(token);
Serial.println(url);
Serial.println(all);*/
_client.runShellCommand(headers + url);
url = "";
while (!_client.available() && timeout < 10000) {
timeout++;
delay(1);
}
while (_client.available() && i < 400) {
c[i] = _client.read();
i++;
}
c[i] = '\0';
while (_client.available()) {
_client.read();
}
i = 0;
num = parseValue(c);
Serial.flush();
return num;
}
/**
* This function is to save data to the YUN cache
* @arg id the name of your variable
* @arg value the value to save
* @arg ctext the context to save
*/
void Ubidots::add(char *id, float value, char *ctext) {
(val+currentValue)->idName = id;
(val+currentValue)->idValue = value;
(val+currentValue)->context = ctext;
currentValue++;
if (currentValue > MAX_VALUES) {
currentValue = MAX_VALUES;
}
}
/**
* This function is to send all data saved in add function
*/
void Ubidots::sendAll() {
Process _client;
int i;
int timeout = 0;
String value;
char buffer[400];
snprintf(buffer, "(sleep 1\necho \"");
if (_dsName == "YUN") {
snprintf(buffer, "%s%s%s|POST|%s|%s=>", buffer, USER_AGENT, VERSION, _token, _dsTag);
} else {
snprintf(buffer, "%s%s%s|POST|%s|%s:%s=>", buffer, USER_AGENT, VERSION, _token, _dsTag, _dsName);
}
for (i = 0; i < currentValue; ) {
value = String((val + i)->idValue, 2);
snprintf(buffer, "%s%s:%s", buffer, (val + i)->idName, value.c_str());
if ((val + i)->context != NULL) {
snprintf(buffer, "%s\\$%s", buffer, (val + i)->context);
}
i++;
if (i < currentValue) {
snprintf(buffer, "%s,", buffer);
}
}
snprintf(buffer, "%s|end\") | telnet %s %s", buffer, SERVER, PORT);
SerialUSB.println(buffer);
_client.runShellCommand(buffer);
while (_client.running() && timeout < 10000) {
timeout++;
delay(1);
}
Serial.flush();
currentValue = 0;
}
// Old functions of the library
bool Ubidots::saveValue(String id, float value){
Process _client;
String TOKEN = _token;
String url;
String token;
String data;
String headers;
String all;
url = "http://things.ubidots.com/api/v1.6/variables/"+id;
url += "/values";
token = " \"X-Auth-Token: "+TOKEN;
token += "\" ";
data = "\'{\"value\":"+String(value,5);
data += "}\' ";
headers = "curl -i --header \"Accept: application/json; indent=4\" --header \"Content-Type: application/json\" --header"+token;
headers += "-X POST -d ";
all = headers + data;
all += url;
/*Serial.println(token);
Serial.println(url);
Serial.println(data);
Serial.println(all);*/
_client.runShellCommand(all);
while(!_client.available());
while (_client.available()) {
char c = _client.read();
}
Serial.flush();
}
<commit_msg>deleted infinite loops<commit_after>/*
Copyright (c) 2013-2016 Ubidots.
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.
Made by Mateo Velez - Metavix for Ubidots Inc
*/
#include "UbidotsYUN.h"
#include <Process.h>
/**
* Constructor.
*/
Ubidots::Ubidots(char* token) {
_token = token;
_dsName = "YUN";
_dsTag = "YUN";
val = (Value *)malloc(MAX_VALUES*sizeof(Value));
}
/**
* This function set a data source tag
* @arg tag the tag to set
*/
void Ubidots::setDataSourceTag(char *tag) {
_dsTag = tag;
}
/**
* This function set a data source name
* @arg name the name to set
*/
void Ubidots::setDataSourceName(char *name) {
_dsName = name;
}
/**
* This function start the YUN device
*/
void Ubidots::init() {
pinMode(13, OUTPUT);
digitalWrite(13, LOW);
Bridge.begin();
digitalWrite(13, HIGH);
}
/**
* This function is to get value from the Ubidots API
* @arg id the id where you will get the data
* @return num the data that you get from the Ubidots API
*/
float Ubidots::parseValue(char *body) {
String raw;
char *pch;
float num;
char reply[25];
uint8_t bodyPosinit = 0;
uint8_t bodyPosend = 0;
pch = strstr(body, "\"value\":");
raw = String(pch);
bodyPosinit = 9 + raw.indexOf("\"value\":");
bodyPosend = raw.indexOf(", \"timestamp\"");
raw.substring(bodyPosinit, bodyPosend).toCharArray(reply, 25);
Serial.println(reply);
num = atof(reply);
return num;
}
/**
* This function is to get value from the Ubidots API
* @arg id the id where you will get the data
* @return num the data that you get from the Ubidots API
*/
float Ubidots::getValue(String id) {
Process _client;
float num;
char c[400];
int i = 0;
int timeout = 0;
String TOKEN = _token;
String token;
String headers;
String url;
url = "http://things.ubidots.com/api/v1.6/variables/"+id;
url += "/values?page_size=1";
token = " \"X-Auth-Token: "+TOKEN;
token += "\" ";
headers = "curl --header \"Accept: application/json; indent=4\" --header" + token;
headers += "-X GET ";
/*Serial.println(token);
Serial.println(url);
Serial.println(all);*/
_client.runShellCommand(headers + url);
url = "";
while (!_client.available() && timeout < 10000) {
timeout++;
delay(1);
}
while (_client.available() && i < 400) {
c[i] = _client.read();
i++;
}
c[i] = '\0';
while (_client.available()) {
_client.read();
}
i = 0;
num = parseValue(c);
Serial.flush();
return num;
}
/**
* This function is to save data to the YUN cache
* @arg id the name of your variable
* @arg value the value to save
* @arg ctext the context to save
*/
void Ubidots::add(char *id, float value, char *ctext) {
(val+currentValue)->idName = id;
(val+currentValue)->idValue = value;
(val+currentValue)->context = ctext;
currentValue++;
if (currentValue > MAX_VALUES) {
currentValue = MAX_VALUES;
}
}
/**
* This function is to send all data saved in add function
*/
void Ubidots::sendAll() {
Process _client;
int i;
int timeout = 0;
String value;
char buffer[400];
snprintf(buffer, "(sleep 1\necho \"");
if (_dsName == "YUN") {
snprintf(buffer, "%s%s%s|POST|%s|%s=>", buffer, USER_AGENT, VERSION, _token, _dsTag);
} else {
snprintf(buffer, "%s%s%s|POST|%s|%s:%s=>", buffer, USER_AGENT, VERSION, _token, _dsTag, _dsName);
}
for (i = 0; i < currentValue; ) {
value = String((val + i)->idValue, 2);
snprintf(buffer, "%s%s:%s", buffer, (val + i)->idName, value.c_str());
if ((val + i)->context != NULL) {
snprintf(buffer, "%s\\$%s", buffer, (val + i)->context);
}
i++;
if (i < currentValue) {
snprintf(buffer, "%s,", buffer);
}
}
snprintf(buffer, "%s|end\") | telnet %s %s", buffer, SERVER, PORT);
SerialUSB.println(buffer);
_client.runShellCommand(buffer);
while (_client.running() && timeout < 10000) {
timeout++;
delay(1);
}
Serial.flush();
currentValue = 0;
}
// Old functions of the library
bool Ubidots::saveValue(String id, float value) {
Process _client;
int timeout = 0;
String TOKEN = _token;
String url;
String token;
String data;
String headers;
String all;
url = "http://things.ubidots.com/api/v1.6/variables/"+id;
url += "/values";
token = " \"X-Auth-Token: "+TOKEN;
token += "\" ";
data = "\'{\"value\":" + String(value, 5);
data += "}\' ";
headers = "curl -i --header \"Accept: application/json; indent=4\" --header \"Content-Type: application/json\" --header"+token;
headers += "-X POST -d ";
all = headers + data;
all += url;
/*Serial.println(token);
Serial.println(url);
Serial.println(data);
Serial.println(all);*/
_client.runShellCommand(all);
while (!_client.available() && timeout > 10000) {
timeout++;
delay(1);
}
while (_client.available()) {
char c = _client.read();
}
Serial.flush();
}
<|endoftext|> |
<commit_before>/* Copyright 2015 Google Inc. 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.
==============================================================================*/
#define EIGEN_USE_THREADS
#include <algorithm>
#include <numeric>
#include <unordered_map>
#include <utility>
#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_util.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/lib/gtl/inlined_vector.h"
#include "tensorflow/core/util/sparse/sparse_tensor.h"
namespace tensorflow {
template <typename T>
class SparseReorderOp : public OpKernel {
public:
explicit SparseReorderOp(OpKernelConstruction* context) : OpKernel(context) {}
void Compute(OpKernelContext* context) override {
const Tensor& input_ind = context->input(0);
OP_REQUIRES(context, TensorShapeUtils::IsMatrix(input_ind.shape()),
errors::InvalidArgument(
"Input indices should be a matrix but received shape",
input_ind.shape().DebugString()));
const Tensor& input_val = context->input(1);
OP_REQUIRES(context, TensorShapeUtils::IsVector(input_val.shape()),
errors::InvalidArgument(
"Input values should be a vector but received shape",
input_val.shape().DebugString()));
const Tensor& input_shape_in = context->input(2);
OP_REQUIRES(context, TensorShapeUtils::IsVector(input_shape_in.shape()),
errors::InvalidArgument(
"Input shape should be a vector but received shape",
input_shape_in.shape().DebugString()));
const TensorShape input_shape(input_shape_in.vec<int64>());
gtl::InlinedVector<int64, 8> std_order(input_shape.dims());
std::iota(std_order.begin(), std_order.end(), 0);
// Check if the sparse tensor is already ordered correctly
sparse::SparseTensor input_sp(input_ind, input_val, input_shape, std_order);
if (input_sp.IndicesValid().ok()) {
context->set_output(0, input_sp.indices());
context->set_output(1, input_sp.values());
} else {
// Deep-copy the input Tensors, then reorder in-place
sparse::SparseTensor reordered_sp(tensor::DeepCopy(input_ind),
tensor::DeepCopy(input_val),
input_shape);
reordered_sp.Reorder<T>(std_order);
context->set_output(0, reordered_sp.indices());
context->set_output(1, reordered_sp.values());
}
}
};
#define REGISTER_KERNELS(type) \
REGISTER_KERNEL_BUILDER( \
Name("SparseReorder").Device(DEVICE_CPU).TypeConstraint<type>("T"), \
SparseReorderOp<type>)
TF_CALL_ALL_TYPES(REGISTER_KERNELS);
#undef REGISTER_KERNELS
} // namespace tensorflow
<commit_msg>Fix missing spaces in SparseReorder's error messages Change: 116875393<commit_after>/* Copyright 2015 Google Inc. 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.
==============================================================================*/
#define EIGEN_USE_THREADS
#include <algorithm>
#include <numeric>
#include <unordered_map>
#include <utility>
#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_util.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/lib/gtl/inlined_vector.h"
#include "tensorflow/core/util/sparse/sparse_tensor.h"
namespace tensorflow {
template <typename T>
class SparseReorderOp : public OpKernel {
public:
explicit SparseReorderOp(OpKernelConstruction* context) : OpKernel(context) {}
void Compute(OpKernelContext* context) override {
const Tensor& input_ind = context->input(0);
OP_REQUIRES(context, TensorShapeUtils::IsMatrix(input_ind.shape()),
errors::InvalidArgument(
"Input indices should be a matrix but received shape ",
input_ind.shape().DebugString()));
const Tensor& input_val = context->input(1);
OP_REQUIRES(context, TensorShapeUtils::IsVector(input_val.shape()),
errors::InvalidArgument(
"Input values should be a vector but received shape ",
input_val.shape().DebugString()));
const Tensor& input_shape_in = context->input(2);
OP_REQUIRES(context, TensorShapeUtils::IsVector(input_shape_in.shape()),
errors::InvalidArgument(
"Input shape should be a vector but received shape ",
input_shape_in.shape().DebugString()));
const TensorShape input_shape(input_shape_in.vec<int64>());
gtl::InlinedVector<int64, 8> std_order(input_shape.dims());
std::iota(std_order.begin(), std_order.end(), 0);
// Check if the sparse tensor is already ordered correctly
sparse::SparseTensor input_sp(input_ind, input_val, input_shape, std_order);
if (input_sp.IndicesValid().ok()) {
context->set_output(0, input_sp.indices());
context->set_output(1, input_sp.values());
} else {
// Deep-copy the input Tensors, then reorder in-place
sparse::SparseTensor reordered_sp(tensor::DeepCopy(input_ind),
tensor::DeepCopy(input_val),
input_shape);
reordered_sp.Reorder<T>(std_order);
context->set_output(0, reordered_sp.indices());
context->set_output(1, reordered_sp.values());
}
}
};
#define REGISTER_KERNELS(type) \
REGISTER_KERNEL_BUILDER( \
Name("SparseReorder").Device(DEVICE_CPU).TypeConstraint<type>("T"), \
SparseReorderOp<type>)
TF_CALL_ALL_TYPES(REGISTER_KERNELS);
#undef REGISTER_KERNELS
} // namespace tensorflow
<|endoftext|> |
<commit_before>/* Copyright (c) 2017-2020 Hans-Kristian Arntzen
*
* 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.
*/
#pragma once
#include <stdint.h>
#include <functional>
#include <memory>
#include <limits>
#include "global_managers_interface.hpp"
namespace Granite
{
namespace Global
{
enum ManagerFeatureFlagBits
{
MANAGER_FEATURE_FILESYSTEM_BIT = 1 << 0,
MANAGER_FEATURE_EVENT_BIT = 1 << 1,
MANAGER_FEATURE_THREAD_GROUP_BIT = 1 << 2,
MANAGER_FEATURE_UI_MANAGER_BIT = 1 << 3,
MANAGER_FEATURE_AUDIO_BIT = 1 << 4,
MANAGER_FEATURE_COMMON_RENDERER_DATA_BIT = 1 << 5,
MANAGER_FEATURE_PHYSICS_BIT = 1 << 6,
MANAGER_FEATURE_LOGGING_BIT = 1 << 7,
MANAGER_FEATURE_DEFAULT_BITS = (MANAGER_FEATURE_FILESYSTEM_BIT |
MANAGER_FEATURE_EVENT_BIT |
MANAGER_FEATURE_THREAD_GROUP_BIT |
MANAGER_FEATURE_COMMON_RENDERER_DATA_BIT |
MANAGER_FEATURE_UI_MANAGER_BIT)
};
using ManagerFeatureFlags = uint32_t;
// Decouple creation from global TLS storage.
// This avoids some nasty cyclical dependencies.
class Factory
{
public:
virtual ~Factory() = default;
virtual FilesystemInterface *create_filesystem();
virtual EventManagerInterface *create_event_manager();
virtual ThreadGroupInterface *create_thread_group();
virtual CommonRendererDataInterface *create_common_renderer_data();
virtual PhysicsSystemInterface *create_physics_system();
virtual Audio::BackendInterface *create_audio_backend(Audio::MixerInterface *mixer,
float sample_rate,
unsigned channels);
virtual Audio::MixerInterface *create_audio_mixer();
virtual UI::UIManagerInterface *create_ui_manager();
virtual Util::MessageQueueInterface *create_message_queue();
};
void init(Factory &factory, ManagerFeatureFlags flags = MANAGER_FEATURE_DEFAULT_BITS,
unsigned max_threads = std::numeric_limits<unsigned>::max());
void deinit();
// Used if the application wants to use multiple instances of Granite in the same process.
// This allows each thread to be associated to a global context.
struct GlobalManagers;
struct GlobalManagerDeleter
{
void operator()(GlobalManagers *managers);
};
using GlobalManagersHandle = std::unique_ptr<GlobalManagers, GlobalManagerDeleter>;
GlobalManagersHandle create_thread_context();
void delete_thread_context(GlobalManagers *managers);
void set_thread_context(const GlobalManagers &managers);
void clear_thread_context();
void start_audio_system();
void stop_audio_system();
void install_audio_system(Audio::BackendInterface *backend, Audio::MixerInterface *mixer);
Util::MessageQueueInterface *message_queue();
FilesystemInterface *filesystem();
EventManagerInterface *event_manager();
ThreadGroupInterface *thread_group();
UI::UIManagerInterface *ui_manager();
CommonRendererDataInterface *common_renderer_data();
Audio::BackendInterface *audio_backend();
Audio::MixerInterface *audio_mixer();
PhysicsSystemInterface *physics();
}
}
#define GRANITE_MESSAGE_QUEUE() static_cast<::Util::MessageQueue *>(::Granite::Global::message_queue())
#define GRANITE_FILESYSTEM() static_cast<::Granite::Filesystem *>(::Granite::Global::filesystem())
#define GRANITE_EVENT_MANAGER() static_cast<::Granite::EventManager *>(::Granite::Global::event_manager())
#define GRANITE_THREAD_GROUP() static_cast<::Granite::ThreadGroup *>(::Granite::Global::thread_group())
#define GRANITE_UI_MANAGER() static_cast<::Granite::UI::UIManager *>(::Granite::Global::ui_manager())
#define GRANITE_COMMON_RENDERER_DATA() static_cast<::Granite::CommonRendererData *>(::Granite::Global::common_renderer_data())
#define GRANITE_AUDIO_BACKEND() static_cast<::Granite::Audio::Backend *>(::Granite::Global::audio_backend())
#define GRANITE_AUDIO_MIXER() static_cast<::Granite::Audio::Mixer *>(::Granite::Global::audio_mixer())
#define GRANITE_PHYSICS() static_cast<::Granite::PhysicsSystem *>(::Granite::Global::physics())
<commit_msg>Add audio to default init list.<commit_after>/* Copyright (c) 2017-2020 Hans-Kristian Arntzen
*
* 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.
*/
#pragma once
#include <stdint.h>
#include <functional>
#include <memory>
#include <limits>
#include "global_managers_interface.hpp"
namespace Granite
{
namespace Global
{
enum ManagerFeatureFlagBits
{
MANAGER_FEATURE_FILESYSTEM_BIT = 1 << 0,
MANAGER_FEATURE_EVENT_BIT = 1 << 1,
MANAGER_FEATURE_THREAD_GROUP_BIT = 1 << 2,
MANAGER_FEATURE_UI_MANAGER_BIT = 1 << 3,
MANAGER_FEATURE_AUDIO_BIT = 1 << 4,
MANAGER_FEATURE_COMMON_RENDERER_DATA_BIT = 1 << 5,
MANAGER_FEATURE_PHYSICS_BIT = 1 << 6,
MANAGER_FEATURE_LOGGING_BIT = 1 << 7,
MANAGER_FEATURE_DEFAULT_BITS = (MANAGER_FEATURE_FILESYSTEM_BIT |
MANAGER_FEATURE_EVENT_BIT |
MANAGER_FEATURE_THREAD_GROUP_BIT |
MANAGER_FEATURE_COMMON_RENDERER_DATA_BIT |
MANAGER_FEATURE_UI_MANAGER_BIT |
MANAGER_FEATURE_AUDIO_BIT)
};
using ManagerFeatureFlags = uint32_t;
// Decouple creation from global TLS storage.
// This avoids some nasty cyclical dependencies.
class Factory
{
public:
virtual ~Factory() = default;
virtual FilesystemInterface *create_filesystem();
virtual EventManagerInterface *create_event_manager();
virtual ThreadGroupInterface *create_thread_group();
virtual CommonRendererDataInterface *create_common_renderer_data();
virtual PhysicsSystemInterface *create_physics_system();
virtual Audio::BackendInterface *create_audio_backend(Audio::MixerInterface *mixer,
float sample_rate,
unsigned channels);
virtual Audio::MixerInterface *create_audio_mixer();
virtual UI::UIManagerInterface *create_ui_manager();
virtual Util::MessageQueueInterface *create_message_queue();
};
void init(Factory &factory, ManagerFeatureFlags flags = MANAGER_FEATURE_DEFAULT_BITS,
unsigned max_threads = std::numeric_limits<unsigned>::max());
void deinit();
// Used if the application wants to use multiple instances of Granite in the same process.
// This allows each thread to be associated to a global context.
struct GlobalManagers;
struct GlobalManagerDeleter
{
void operator()(GlobalManagers *managers);
};
using GlobalManagersHandle = std::unique_ptr<GlobalManagers, GlobalManagerDeleter>;
GlobalManagersHandle create_thread_context();
void delete_thread_context(GlobalManagers *managers);
void set_thread_context(const GlobalManagers &managers);
void clear_thread_context();
void start_audio_system();
void stop_audio_system();
void install_audio_system(Audio::BackendInterface *backend, Audio::MixerInterface *mixer);
Util::MessageQueueInterface *message_queue();
FilesystemInterface *filesystem();
EventManagerInterface *event_manager();
ThreadGroupInterface *thread_group();
UI::UIManagerInterface *ui_manager();
CommonRendererDataInterface *common_renderer_data();
Audio::BackendInterface *audio_backend();
Audio::MixerInterface *audio_mixer();
PhysicsSystemInterface *physics();
}
}
#define GRANITE_MESSAGE_QUEUE() static_cast<::Util::MessageQueue *>(::Granite::Global::message_queue())
#define GRANITE_FILESYSTEM() static_cast<::Granite::Filesystem *>(::Granite::Global::filesystem())
#define GRANITE_EVENT_MANAGER() static_cast<::Granite::EventManager *>(::Granite::Global::event_manager())
#define GRANITE_THREAD_GROUP() static_cast<::Granite::ThreadGroup *>(::Granite::Global::thread_group())
#define GRANITE_UI_MANAGER() static_cast<::Granite::UI::UIManager *>(::Granite::Global::ui_manager())
#define GRANITE_COMMON_RENDERER_DATA() static_cast<::Granite::CommonRendererData *>(::Granite::Global::common_renderer_data())
#define GRANITE_AUDIO_BACKEND() static_cast<::Granite::Audio::Backend *>(::Granite::Global::audio_backend())
#define GRANITE_AUDIO_MIXER() static_cast<::Granite::Audio::Mixer *>(::Granite::Global::audio_mixer())
#define GRANITE_PHYSICS() static_cast<::Granite::PhysicsSystem *>(::Granite::Global::physics())
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: corbaoptions.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2005-09-08 02:07:55 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _CORBAMAKER_CPPUOPTIONS_HXX_
#define _CORBAMAKER_CPPUOPTIONS_HXX_
#include <codemaker/options.hxx>
class CorbaOptions : public Options
{
public:
CorbaOptions()
: Options() {}
~CorbaOptions() {}
sal_Bool initOptions(int ac, char* av[], sal_Bool bCmdFile=sal_False)
throw( IllegalArgument );
::rtl::OString prepareHelp();
::rtl::OString prepareVersion();
protected:
};
#endif // _CORBAMAKER_CPPUOPTIONS_HXX_
<commit_msg>INTEGRATION: CWS changefileheader (1.2.80); FILE MERGED 2008/03/31 07:22:51 rt 1.2.80.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: corbaoptions.hxx,v $
* $Revision: 1.3 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _CORBAMAKER_CPPUOPTIONS_HXX_
#define _CORBAMAKER_CPPUOPTIONS_HXX_
#include <codemaker/options.hxx>
class CorbaOptions : public Options
{
public:
CorbaOptions()
: Options() {}
~CorbaOptions() {}
sal_Bool initOptions(int ac, char* av[], sal_Bool bCmdFile=sal_False)
throw( IllegalArgument );
::rtl::OString prepareHelp();
::rtl::OString prepareVersion();
protected:
};
#endif // _CORBAMAKER_CPPUOPTIONS_HXX_
<|endoftext|> |
<commit_before>/* BatchLearning.cpp
*
* Kubo Ryosuke
*/
#ifndef NLEARN
#include "BatchLearning.h"
#include "LearningConfig.h"
#include "LearningTemplates.h"
#include "config/Config.h"
#include "core/move/MoveGenerator.h"
#include "core/record/CsaReader.h"
#include "core/util/FileList.h"
#include <list>
#include <cstdlib>
#define TRAINING_DAT "training.dat"
#define SEARCH_WINDOW 256
#define NORM 1.0e-2f
namespace sunfish {
namespace {
inline float gain() {
return 7.0f / SEARCH_WINDOW;
}
inline float sigmoid(float x) {
return 1.0 / (1.0 + std::exp(x * -gain()));
}
inline float dsigmoid(float x) {
float s = sigmoid(x);
return (s - s * s) * gain();
}
inline float loss(float x) {
return sigmoid(x);
}
inline float gradient(float x) {
return dsigmoid(x);
}
inline float norm(float x) {
if (x > 0.0f) {
return -NORM;
} else if (x < 0.0f) {
return NORM;
} else {
return 0.0f;
}
}
} // namespace
bool BatchLearning::openTrainingData() {
trainingData_.reset(new std::ofstream);
trainingData_->open(TRAINING_DAT, std::ios::binary | std::ios::out);
if (!trainingData_) {
Loggers::error << "open error!! [" << TRAINING_DAT << "]";
return false;
}
return true;
}
void BatchLearning::closeTrainingData() {
trainingData_->close();
}
/**
* プログレスバーの表示を更新します。
*/
void BatchLearning::updateProgress() {
int cmax = 50;
std::cout << "\r";
for (int c = 0; c < cmax; c++) {
if (c * totalJobs_ <= cmax * completedJobs_) {
std::cout << '#';
} else {
std::cout << ' ';
}
}
float percentage = (float)completedJobs_ / totalJobs_ * 100.0f;
std::cout << " [" << percentage << "%]";
std::cout << std::flush;
}
/**
* プログレスバーの表示を終了します。
*/
void BatchLearning::closeProgress() {
std::cout << "\n";
std::cout << std::flush;
}
/**
* 訓練データを生成します。
*/
void BatchLearning::generateTraningData(int wn, Board board, Move move0) {
// 合法手生成
Moves moves;
MoveGenerator::generate(board, moves);
if (moves.size() < 2) {
return;
}
Value val0;
Move tmpMove;
std::list<PV> list;
// ヒストリのクリア
searchers_[wn]->clearHistory();
{
// 探索
board.makeMove(move0);
searchers_[wn]->idsearch(board, tmpMove);
board.unmakeMove(move0);
// PV と評価値
const auto& info = searchers_[wn]->getInfo();
const auto& pv = info.pv;
val0 = -info.eval;
// 詰みは除外
if (val0 <= -Value::Mate || val0 >= Value::Mate) {
return;
}
list.push_back({});
list.back().set(move0, 0, pv);
}
totalMoves_++;
// 棋譜の手の評価値から window を決定
Value alpha = val0 - SEARCH_WINDOW;
Value beta = val0 + SEARCH_WINDOW;
for (auto& move : moves) {
// 探索
bool valid = board.makeMove(move);
if (!valid) { continue; }
searchers_[wn]->idsearch(board, tmpMove, -beta, -alpha);
board.unmakeMove(move);
// PV と評価値
const auto& info = searchers_[wn]->getInfo();
const auto& pv = info.pv;
Value val = -info.eval;
if (val <= alpha) {
continue;
}
if (val >= beta) {
outOfWindLoss_++;
continue;
}
list.push_back({});
list.back().set(move, 0, pv);
}
// 書き出し
if (!list.empty()) {
std::lock_guard<std::mutex> lock(mutex_);
// ルート局面
CompactBoard cb = board.getCompactBoard();
trainingData_->write(reinterpret_cast<char*>(&cb), sizeof(cb));
for (const auto& pv : list) {
// 手順の長さ
uint8_t length = static_cast<uint8_t>(pv.size()) + 1;
trainingData_->write(reinterpret_cast<char*>(&length), sizeof(length));
// 手順
for (size_t i = 0; i < pv.size(); i++) {
uint16_t m = Move::serialize16(pv.get(i).move);
trainingData_->write(reinterpret_cast<char*>(&m), sizeof(m));
}
}
// 終端
uint8_t n = 0;
trainingData_->write(reinterpret_cast<char*>(&n), sizeof(n));
}
}
/**
* 訓練データを生成します。
*/
void BatchLearning::generateTraningData(int wn, const Job& job) {
Record record;
if (!CsaReader::read(job.path, record)) {
Loggers::error << "Could not read csa file. [" << job.path << "]";
exit(1);
}
// 棋譜の先頭へ
while (record.unmakeMove())
;
while (true) {
// 次の1手を取得
Move move = record.getNextMove();
if (move.isEmpty()) {
break;
}
generateTraningData(wn, record.getBoard(), move);
// 1手進める
if (!record.makeMove()) {
break;
}
}
}
/**
* ジョブを拾います。
*/
void BatchLearning::work(int wn) {
while (!shutdown_) {
std::this_thread::sleep_for(std::chrono::milliseconds(1));
Job job;
// dequeue
{
std::lock_guard<std::mutex> lock(mutex_);
if (jobQueue_.empty()) {
continue;
}
job = jobQueue_.front();
jobQueue_.pop();
activeCount_++;
}
generateTraningData(wn, job);
completedJobs_++;
activeCount_--;
{
std::lock_guard<std::mutex> lock(mutex_);
updateProgress();
}
}
}
/**
* ジョブを作成します。
*/
bool BatchLearning::generateJobs() {
FileList fileList;
std::string dir = config_.getString(LCONF_KIFU);
fileList.enumerate(dir.c_str(), "csa");
if (fileList.size() == 0) {
Loggers::error << "no files.";
return false;
}
completedJobs_ = 0;
totalJobs_ = fileList.size();
{
std::lock_guard<std::mutex> lock(mutex_);
for (const auto& path : fileList) {
jobQueue_.push({ path });
}
}
return true;
}
/**
* ワーカーがジョブを終えるまで待機します。
*/
void BatchLearning::waitForWorkers() {
while (true) {
{
std::lock_guard<std::mutex> lock(mutex_);
if (jobQueue_.empty() && activeCount_ == 0) {
return;
}
}
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
}
/**
* 勾配ベクトルを生成します。
*/
bool BatchLearning::generateGradient() {
std::ifstream trainingData;
trainingData.open(TRAINING_DAT);
if (!trainingData) {
Loggers::error << "open error!! [" << TRAINING_DAT << "]";
return false;
}
g_.init();
while (true) {
// ルート局面
CompactBoard cb;
trainingData.read(reinterpret_cast<char*>(&cb), sizeof(cb));
if (trainingData.eof()) {
break;
}
const Board root(cb);
const bool black = root.isBlack();
auto readPV = [&trainingData](Board& board) {
// 手順の長さ
uint8_t length;
trainingData.read(reinterpret_cast<char*>(&length), sizeof(length));
if (length == 0) {
return false;
}
length--;
// 手順
bool ok = true;
for (uint8_t i = 0; i < length; i++) {
uint16_t m;
trainingData.read(reinterpret_cast<char*>(&m), sizeof(m));
Move move = Move::deserialize16(m, board);
if (!ok || move.isEmpty() || !board.makeMove(move)) {
ok = false;
}
}
return true;
};
Board board0 = root;
readPV(board0);
Value val0 = eval_.evaluate(board0).value();
while (true) {
Board board = root;
if (!readPV(board)) {
break;
}
Value val = eval_.evaluate(board).value();
float diff = val.int32() - val0.int32();
diff = black ? diff : -diff;
loss_ += loss(diff);
float g = gradient(diff);
g = black ? g : -g;
g_.extract<float, true>(board0, g);
g_.extract<float, true>(board, -g);
}
}
trainingData.close();
return true;
}
/**
* パラメータを更新します。
*/
void BatchLearning::updateParameters() {
LearningTemplates::symmetrize(g_, [](float& a, float& b) {
a = b = a + b;
});
auto update = [this](FV::ValueType& g, Evaluator::ValueType& e,
Evaluator::ValueType& max, uint64_t& magnitude) {
g += norm(e);
if (g > 0.0f) {
e += rand_.getBit() + rand_.getBit();
} else if (g < 0.0f) {
e -= rand_.getBit() + rand_.getBit();
}
Evaluator::ValueType abs = std::abs(e);
max = std::max(max, abs);
magnitude = magnitude + abs;
};
max_ = 0;
magnitude_ = 0;
for (int i = 0; i < KPP_ALL; i++) {
update(((FV::ValueType*)g_.t_->kpp)[i],
((Evaluator::ValueType*)eval_.t_->kpp)[i],
max_, magnitude_);
}
for (int i = 0; i < KKP_ALL; i++) {
update(((FV::ValueType*)g_.t_->kkp)[i],
((Evaluator::ValueType*)eval_.t_->kkp)[i],
max_, magnitude_);
}
LearningTemplates::symmetrize(eval_, [](Evaluator::ValueType& a, Evaluator::ValueType& b) {
a = b;
});
// ハッシュ表を初期化
eval_.clearCache();
// transposition table は SearchConfig::learning で無効にしている
//for (uint32_t wn = 0; wn < nt_; wn++) {
// searchers_[wn]->clearTT();
//}
}
/**
* バッチ学習の反復処理を実行します。
*/
bool BatchLearning::iterate() {
const int iterateCount = config_.getInt(LCONF_ITERATION);
int updateCount = 256;
for (int i = 0; i < iterateCount; i++) {
if (!openTrainingData()) {
return false;
}
totalMoves_ = 0;
outOfWindLoss_ = 0;
if (!generateJobs()) {
return false;
}
waitForWorkers();
closeTrainingData();
closeProgress();
updateCount = std::max(updateCount / 2, 16);
for (int j = 0; j < updateCount; j++) {
loss_ = 0.0f;
if (!generateGradient()) {
return false;
}
updateParameters();
float elapsed = timer_.get();
float outOfWindLoss = (float)outOfWindLoss_ / totalMoves_;
float totalLoss = ((float)outOfWindLoss_ + loss_) / totalMoves_;
Loggers::message
<< "elapsed=" << elapsed
<< "\titeration=" << i << "," << j
<< "\tout_wind_loss=" << outOfWindLoss
<< "\tloss=" << totalLoss
<< "\tmax=" << max_
<< "\tmagnitude=" << magnitude_;
}
// 保存
eval_.writeFile();
// キャッシュクリア
eval_.clearCache();
}
return true;
}
/**
* 学習を実行します。
*/
bool BatchLearning::run() {
Loggers::message << "begin learning";
timer_.set();
// 初期化
eval_.init();
// 学習スレッド数
nt_ = config_.getInt(LCONF_THREADS);
// Searcher生成
searchers_.clear();
for (uint32_t wn = 0; wn < nt_; wn++) {
searchers_.emplace_back(new Searcher(eval_));
auto searchConfig = searchers_.back()->getConfig();
searchConfig.maxDepth = config_.getInt(LCONF_DEPTH);
searchConfig.workerSize = 1;
searchConfig.treeSize = Searcher::standardTreeSize(searchConfig.workerSize);
searchConfig.enableLimit = false;
searchConfig.enableTimeManagement = false;
searchConfig.ponder = false;
searchConfig.logging = false;
searchConfig.learning = true;
searchers_.back()->setConfig(searchConfig);
}
activeCount_ = 0;
// ワーカースレッド生成
shutdown_ = false;
threads_.clear();
for (uint32_t wn = 0; wn < nt_; wn++) {
threads_.emplace_back(std::bind(std::mem_fn(&BatchLearning::work), this, wn));
}
bool ok = iterate();
// ワーカースレッド停止
shutdown_ = true;
for (uint32_t wn = 0; wn < nt_; wn++) {
threads_[wn].join();
}
if (!ok) {
return false;
}
Loggers::message << "completed..";
float elapsed = timer_.get();
Loggers::message << "elapsed: " << elapsed;
Loggers::message << "end learning";
return true;
}
}
#endif // NLEARN
<commit_msg>Output tranining data size<commit_after>/* BatchLearning.cpp
*
* Kubo Ryosuke
*/
#ifndef NLEARN
#include "BatchLearning.h"
#include "LearningConfig.h"
#include "LearningTemplates.h"
#include "config/Config.h"
#include "core/move/MoveGenerator.h"
#include "core/record/CsaReader.h"
#include "core/util/FileList.h"
#include <list>
#include <cstdlib>
#define TRAINING_DAT "training.dat"
#define SEARCH_WINDOW 256
#define NORM 1.0e-2f
namespace sunfish {
namespace {
inline float gain() {
return 7.0f / SEARCH_WINDOW;
}
inline float sigmoid(float x) {
return 1.0 / (1.0 + std::exp(x * -gain()));
}
inline float dsigmoid(float x) {
float s = sigmoid(x);
return (s - s * s) * gain();
}
inline float loss(float x) {
return sigmoid(x);
}
inline float gradient(float x) {
return dsigmoid(x);
}
inline float norm(float x) {
if (x > 0.0f) {
return -NORM;
} else if (x < 0.0f) {
return NORM;
} else {
return 0.0f;
}
}
} // namespace
bool BatchLearning::openTrainingData() {
trainingData_.reset(new std::ofstream);
trainingData_->open(TRAINING_DAT, std::ios::binary | std::ios::out);
if (!trainingData_) {
Loggers::error << "open error!! [" << TRAINING_DAT << "]";
return false;
}
return true;
}
void BatchLearning::closeTrainingData() {
Loggers::message << "training_data_size=" << trainingData_->tellp();
trainingData_->close();
}
/**
* プログレスバーの表示を更新します。
*/
void BatchLearning::updateProgress() {
int cmax = 50;
std::cout << "\r";
for (int c = 0; c < cmax; c++) {
if (c * totalJobs_ <= cmax * completedJobs_) {
std::cout << '#';
} else {
std::cout << ' ';
}
}
float percentage = (float)completedJobs_ / totalJobs_ * 100.0f;
std::cout << " [" << percentage << "%]";
std::cout << std::flush;
}
/**
* プログレスバーの表示を終了します。
*/
void BatchLearning::closeProgress() {
std::cout << "\n";
std::cout << std::flush;
}
/**
* 訓練データを生成します。
*/
void BatchLearning::generateTraningData(int wn, Board board, Move move0) {
// 合法手生成
Moves moves;
MoveGenerator::generate(board, moves);
if (moves.size() < 2) {
return;
}
Value val0;
Move tmpMove;
std::list<PV> list;
// ヒストリのクリア
searchers_[wn]->clearHistory();
{
// 探索
board.makeMove(move0);
searchers_[wn]->idsearch(board, tmpMove);
board.unmakeMove(move0);
// PV と評価値
const auto& info = searchers_[wn]->getInfo();
const auto& pv = info.pv;
val0 = -info.eval;
// 詰みは除外
if (val0 <= -Value::Mate || val0 >= Value::Mate) {
return;
}
list.push_back({});
list.back().set(move0, 0, pv);
}
totalMoves_++;
// 棋譜の手の評価値から window を決定
Value alpha = val0 - SEARCH_WINDOW;
Value beta = val0 + SEARCH_WINDOW;
for (auto& move : moves) {
// 探索
bool valid = board.makeMove(move);
if (!valid) { continue; }
searchers_[wn]->idsearch(board, tmpMove, -beta, -alpha);
board.unmakeMove(move);
// PV と評価値
const auto& info = searchers_[wn]->getInfo();
const auto& pv = info.pv;
Value val = -info.eval;
if (val <= alpha) {
continue;
}
if (val >= beta) {
outOfWindLoss_++;
continue;
}
list.push_back({});
list.back().set(move, 0, pv);
}
// 書き出し
if (!list.empty()) {
std::lock_guard<std::mutex> lock(mutex_);
// ルート局面
CompactBoard cb = board.getCompactBoard();
trainingData_->write(reinterpret_cast<char*>(&cb), sizeof(cb));
for (const auto& pv : list) {
// 手順の長さ
uint8_t length = static_cast<uint8_t>(pv.size()) + 1;
trainingData_->write(reinterpret_cast<char*>(&length), sizeof(length));
// 手順
for (size_t i = 0; i < pv.size(); i++) {
uint16_t m = Move::serialize16(pv.get(i).move);
trainingData_->write(reinterpret_cast<char*>(&m), sizeof(m));
}
}
// 終端
uint8_t n = 0;
trainingData_->write(reinterpret_cast<char*>(&n), sizeof(n));
}
}
/**
* 訓練データを生成します。
*/
void BatchLearning::generateTraningData(int wn, const Job& job) {
Record record;
if (!CsaReader::read(job.path, record)) {
Loggers::error << "Could not read csa file. [" << job.path << "]";
exit(1);
}
// 棋譜の先頭へ
while (record.unmakeMove())
;
while (true) {
// 次の1手を取得
Move move = record.getNextMove();
if (move.isEmpty()) {
break;
}
generateTraningData(wn, record.getBoard(), move);
// 1手進める
if (!record.makeMove()) {
break;
}
}
}
/**
* ジョブを拾います。
*/
void BatchLearning::work(int wn) {
while (!shutdown_) {
std::this_thread::sleep_for(std::chrono::milliseconds(1));
Job job;
// dequeue
{
std::lock_guard<std::mutex> lock(mutex_);
if (jobQueue_.empty()) {
continue;
}
job = jobQueue_.front();
jobQueue_.pop();
activeCount_++;
}
generateTraningData(wn, job);
completedJobs_++;
activeCount_--;
{
std::lock_guard<std::mutex> lock(mutex_);
updateProgress();
}
}
}
/**
* ジョブを作成します。
*/
bool BatchLearning::generateJobs() {
FileList fileList;
std::string dir = config_.getString(LCONF_KIFU);
fileList.enumerate(dir.c_str(), "csa");
if (fileList.size() == 0) {
Loggers::error << "no files.";
return false;
}
completedJobs_ = 0;
totalJobs_ = fileList.size();
{
std::lock_guard<std::mutex> lock(mutex_);
for (const auto& path : fileList) {
jobQueue_.push({ path });
}
}
return true;
}
/**
* ワーカーがジョブを終えるまで待機します。
*/
void BatchLearning::waitForWorkers() {
while (true) {
{
std::lock_guard<std::mutex> lock(mutex_);
if (jobQueue_.empty() && activeCount_ == 0) {
return;
}
}
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
}
/**
* 勾配ベクトルを生成します。
*/
bool BatchLearning::generateGradient() {
std::ifstream trainingData;
trainingData.open(TRAINING_DAT);
if (!trainingData) {
Loggers::error << "open error!! [" << TRAINING_DAT << "]";
return false;
}
g_.init();
while (true) {
// ルート局面
CompactBoard cb;
trainingData.read(reinterpret_cast<char*>(&cb), sizeof(cb));
if (trainingData.eof()) {
break;
}
const Board root(cb);
const bool black = root.isBlack();
auto readPV = [&trainingData](Board& board) {
// 手順の長さ
uint8_t length;
trainingData.read(reinterpret_cast<char*>(&length), sizeof(length));
if (length == 0) {
return false;
}
length--;
// 手順
bool ok = true;
for (uint8_t i = 0; i < length; i++) {
uint16_t m;
trainingData.read(reinterpret_cast<char*>(&m), sizeof(m));
Move move = Move::deserialize16(m, board);
if (!ok || move.isEmpty() || !board.makeMove(move)) {
ok = false;
}
}
return true;
};
Board board0 = root;
readPV(board0);
Value val0 = eval_.evaluate(board0).value();
while (true) {
Board board = root;
if (!readPV(board)) {
break;
}
Value val = eval_.evaluate(board).value();
float diff = val.int32() - val0.int32();
diff = black ? diff : -diff;
loss_ += loss(diff);
float g = gradient(diff);
g = black ? g : -g;
g_.extract<float, true>(board0, g);
g_.extract<float, true>(board, -g);
}
}
trainingData.close();
return true;
}
/**
* パラメータを更新します。
*/
void BatchLearning::updateParameters() {
LearningTemplates::symmetrize(g_, [](float& a, float& b) {
a = b = a + b;
});
auto update = [this](FV::ValueType& g, Evaluator::ValueType& e,
Evaluator::ValueType& max, uint64_t& magnitude) {
g += norm(e);
if (g > 0.0f) {
e += rand_.getBit() + rand_.getBit();
} else if (g < 0.0f) {
e -= rand_.getBit() + rand_.getBit();
}
Evaluator::ValueType abs = std::abs(e);
max = std::max(max, abs);
magnitude = magnitude + abs;
};
max_ = 0;
magnitude_ = 0;
for (int i = 0; i < KPP_ALL; i++) {
update(((FV::ValueType*)g_.t_->kpp)[i],
((Evaluator::ValueType*)eval_.t_->kpp)[i],
max_, magnitude_);
}
for (int i = 0; i < KKP_ALL; i++) {
update(((FV::ValueType*)g_.t_->kkp)[i],
((Evaluator::ValueType*)eval_.t_->kkp)[i],
max_, magnitude_);
}
LearningTemplates::symmetrize(eval_, [](Evaluator::ValueType& a, Evaluator::ValueType& b) {
a = b;
});
// ハッシュ表を初期化
eval_.clearCache();
// transposition table は SearchConfig::learning で無効にしている
//for (uint32_t wn = 0; wn < nt_; wn++) {
// searchers_[wn]->clearTT();
//}
}
/**
* バッチ学習の反復処理を実行します。
*/
bool BatchLearning::iterate() {
const int iterateCount = config_.getInt(LCONF_ITERATION);
int updateCount = 256;
for (int i = 0; i < iterateCount; i++) {
if (!openTrainingData()) {
return false;
}
totalMoves_ = 0;
outOfWindLoss_ = 0;
if (!generateJobs()) {
return false;
}
waitForWorkers();
closeProgress();
closeTrainingData();
updateCount = std::max(updateCount / 2, 16);
for (int j = 0; j < updateCount; j++) {
loss_ = 0.0f;
if (!generateGradient()) {
return false;
}
updateParameters();
float elapsed = timer_.get();
float outOfWindLoss = (float)outOfWindLoss_ / totalMoves_;
float totalLoss = ((float)outOfWindLoss_ + loss_) / totalMoves_;
Loggers::message
<< "elapsed=" << elapsed
<< "\titeration=" << i << "," << j
<< "\tout_wind_loss=" << outOfWindLoss
<< "\tloss=" << totalLoss
<< "\tmax=" << max_
<< "\tmagnitude=" << magnitude_;
}
// 保存
eval_.writeFile();
// キャッシュクリア
eval_.clearCache();
}
return true;
}
/**
* 学習を実行します。
*/
bool BatchLearning::run() {
Loggers::message << "begin learning";
timer_.set();
// 初期化
eval_.init();
// 学習スレッド数
nt_ = config_.getInt(LCONF_THREADS);
// Searcher生成
searchers_.clear();
for (uint32_t wn = 0; wn < nt_; wn++) {
searchers_.emplace_back(new Searcher(eval_));
auto searchConfig = searchers_.back()->getConfig();
searchConfig.maxDepth = config_.getInt(LCONF_DEPTH);
searchConfig.workerSize = 1;
searchConfig.treeSize = Searcher::standardTreeSize(searchConfig.workerSize);
searchConfig.enableLimit = false;
searchConfig.enableTimeManagement = false;
searchConfig.ponder = false;
searchConfig.logging = false;
searchConfig.learning = true;
searchers_.back()->setConfig(searchConfig);
}
activeCount_ = 0;
// ワーカースレッド生成
shutdown_ = false;
threads_.clear();
for (uint32_t wn = 0; wn < nt_; wn++) {
threads_.emplace_back(std::bind(std::mem_fn(&BatchLearning::work), this, wn));
}
bool ok = iterate();
// ワーカースレッド停止
shutdown_ = true;
for (uint32_t wn = 0; wn < nt_; wn++) {
threads_[wn].join();
}
if (!ok) {
return false;
}
Loggers::message << "completed..";
float elapsed = timer_.get();
Loggers::message << "elapsed: " << elapsed;
Loggers::message << "end learning";
return true;
}
}
#endif // NLEARN
<|endoftext|> |
<commit_before>/*
* Copyright 2014 Cloudius Systems
*/
#ifndef SSTRING_HH_
#define SSTRING_HH_
#include <stdint.h>
#include <algorithm>
#include <string>
#include <cstring>
#include <stdexcept>
#include <initializer_list>
#include <iostream>
#include <functional>
#include <cstdio>
#include <experimental/string_view>
#include "core/temporary_buffer.hh"
template <typename char_type, typename Size, Size max_size>
class basic_sstring {
union contents {
struct external_type {
char_type* str;
Size size;
int8_t pad;
} external;
struct internal_type {
char_type str[max_size];
int8_t size;
} internal;
static_assert(sizeof(external_type) <= sizeof(internal_type), "max_size too small");
static_assert(max_size <= 127, "max_size too large");
} u;
bool is_internal() const noexcept {
return u.internal.size >= 0;
}
bool is_external() const noexcept {
return !is_internal();
}
const char_type* str() const {
return is_internal() ? u.internal.str : u.external.str;
}
char_type* str() {
return is_internal() ? u.internal.str : u.external.str;
}
public:
using value_type = char_type;
using traits_type = std::char_traits<char_type>;
using allocator_type = std::allocator<char_type>;
using reference = char_type&;
using const_reference = const char_type&;
using pointer = char_type*;
using const_pointer = const char_type*;
using iterator = char_type*;
using const_iterator = const char_type*;
// FIXME: add reverse_iterator and friend
using difference_type = ssize_t; // std::make_signed_t<Size> can be too small
using size_type = Size;
public:
struct initialized_later {};
basic_sstring() noexcept {
u.internal.size = 0;
u.internal.str[0] = '\0';
}
basic_sstring(const basic_sstring& x) {
if (x.is_internal()) {
u.internal = x.u.internal;
} else {
u.internal.size = -1;
u.external.str = reinterpret_cast<char_type*>(std::malloc(x.u.external.size + 1));
if (!u.external.str) {
throw std::bad_alloc();
}
std::copy(x.u.external.str, x.u.external.str + x.u.external.size + 1, u.external.str);
u.external.size = x.u.external.size;
}
}
basic_sstring(basic_sstring&& x) noexcept {
u = x.u;
x.u.internal.size = 0;
x.u.internal.str[0] = '\0';
}
basic_sstring(initialized_later, size_t size) {
if (size_type(size) != size) {
throw std::overflow_error("sstring overflow");
}
if (size + 1 <= sizeof(u.internal.str)) {
u.internal.str[size] = '\0';
u.internal.size = size;
} else {
u.internal.size = -1;
u.external.str = reinterpret_cast<char_type*>(std::malloc(size + 1));
if (!u.external.str) {
throw std::bad_alloc();
}
u.external.size = size;
u.external.str[size] = '\0';
}
}
basic_sstring(const char_type* x, size_t size) {
if (size_type(size) != size) {
throw std::overflow_error("sstring overflow");
}
if (size + 1 <= sizeof(u.internal.str)) {
std::copy(x, x + size, u.internal.str);
u.internal.str[size] = '\0';
u.internal.size = size;
} else {
u.internal.size = -1;
u.external.str = reinterpret_cast<char_type*>(std::malloc(size + 1));
if (!u.external.str) {
throw std::bad_alloc();
}
u.external.size = size;
std::copy(x, x + size, u.external.str);
u.external.str[size] = '\0';
}
}
basic_sstring(const char* x) : basic_sstring(reinterpret_cast<const char_type*>(x), std::strlen(x)) {}
basic_sstring(std::basic_string<char_type>& x) : basic_sstring(x.c_str(), x.size()) {}
basic_sstring(std::initializer_list<char_type> x) : basic_sstring(x.begin(), x.end() - x.begin()) {}
basic_sstring(const char_type* b, const char_type* e) : basic_sstring(b, e - b) {}
basic_sstring(const std::basic_string<char_type>& s)
: basic_sstring(s.data(), s.size()) {}
~basic_sstring() noexcept {
if (is_external()) {
std::free(u.external.str);
}
}
basic_sstring& operator=(const basic_sstring& x) {
basic_sstring tmp(x);
swap(tmp);
return *this;
}
basic_sstring& operator=(basic_sstring&& x) noexcept {
if (this != &x) {
swap(x);
x.reset();
}
return *this;
}
operator std::string() const {
return { str(), size() };
}
size_t size() const noexcept {
return is_internal() ? u.internal.size : u.external.size;
}
bool empty() const noexcept {
return u.internal.size == 0;
}
void reset() noexcept {
if (is_external()) {
std::free(u.external.str);
}
u.internal.size = 0;
u.internal.str[0] = '\0';
}
temporary_buffer<char_type> release() && {
if (is_external()) {
auto ptr = u.external.str;
auto size = u.external.size;
u.external.str = nullptr;
u.external.size = 0;
return temporary_buffer<char_type>(ptr, size, make_free_deleter(ptr));
} else {
auto buf = temporary_buffer<char_type>(u.internal.size);
std::copy(u.internal.str, u.internal.str + u.internal.size, buf.get_write());
u.internal.size = 0;
u.internal.str[0] = '\0';
return buf;
}
}
void swap(basic_sstring& x) noexcept {
contents tmp;
tmp = x.u;
x.u = u;
u = tmp;
}
const char_type* c_str() const {
return str();
}
const char_type* begin() const { return str(); }
const char_type* end() const { return str() + size(); }
char_type* begin() { return str(); }
char_type* end() { return str() + size(); }
bool operator==(const basic_sstring& x) const {
return size() == x.size() && std::equal(begin(), end(), x.begin());
}
bool operator!=(const basic_sstring& x) const {
return !operator==(x);
}
basic_sstring operator+(const basic_sstring& x) const {
basic_sstring ret(initialized_later(), size() + x.size());
std::copy(begin(), end(), ret.begin());
std::copy(x.begin(), x.end(), ret.begin() + size());
return ret;
}
basic_sstring& operator+=(const basic_sstring& x) {
return *this = *this + x;
}
char_type& operator[](size_type pos) {
return str()[pos];
}
const char_type& operator[](size_type pos) const {
return str()[pos];
}
operator std::experimental::string_view() const {
return std::experimental::string_view(str(), size());
}
};
template <typename char_type, typename size_type, size_type Max, size_type N>
inline
basic_sstring<char_type, size_type, Max>
operator+(const char(&s)[N], const basic_sstring<char_type, size_type, Max>& t) {
using sstring = basic_sstring<char_type, size_type, Max>;
// don't copy the terminating NUL character
sstring ret(typename sstring::initialized_later(), N-1 + t.size());
auto p = std::copy(std::begin(s), std::end(s)-1, ret.begin());
std::copy(t.begin(), t.end(), p);
return ret;
}
template <size_t N>
static inline
size_t str_len(const char(&s)[N]) { return N - 1; }
template <size_t N>
static inline
const char* str_begin(const char(&s)[N]) { return s; }
template <size_t N>
static inline
const char* str_end(const char(&s)[N]) { return str_begin(s) + str_len(s); }
template <typename char_type, typename size_type, size_type max_size>
static inline
const char_type* str_begin(const basic_sstring<char_type, size_type, max_size>& s) { return s.begin(); }
template <typename char_type, typename size_type, size_type max_size>
static inline
const char_type* str_end(const basic_sstring<char_type, size_type, max_size>& s) { return s.end(); }
template <typename char_type, typename size_type, size_type max_size>
static inline
size_type str_len(const basic_sstring<char_type, size_type, max_size>& s) { return s.size(); }
template <typename First, typename Second, typename... Tail>
static inline
const size_t str_len(const First& first, const Second& second, const Tail&... tail) {
return str_len(first) + str_len(second, tail...);
}
template <typename char_type, typename size_type, size_type max_size>
inline
void swap(basic_sstring<char_type, size_type, max_size>& x,
basic_sstring<char_type, size_type, max_size>& y) noexcept
{
return x.swap(y);
}
template <typename char_type, typename size_type, size_type max_size, typename char_traits>
inline
std::basic_ostream<char_type, char_traits>&
operator<<(std::basic_ostream<char_type, char_traits>& os,
const basic_sstring<char_type, size_type, max_size>& s) {
return os.write(s.begin(), s.size());
}
namespace std {
template <typename char_type, typename size_type, size_type max_size>
struct hash<basic_sstring<char_type, size_type, max_size>> {
size_t operator()(const basic_sstring<char_type, size_type, max_size>& s) const {
return std::hash<std::experimental::string_view>()(s);
}
};
}
using sstring = basic_sstring<char, uint32_t, 15>;
static inline
char* copy_str_to(char* dst) {
return dst;
}
template <typename Head, typename... Tail>
static inline
char* copy_str_to(char* dst, const Head& head, const Tail&... tail) {
return copy_str_to(std::copy(str_begin(head), str_end(head), dst), tail...);
}
template <typename String = sstring, typename... Args>
static String make_sstring(Args&&... args)
{
String ret(sstring::initialized_later(), str_len(args...));
copy_str_to(ret.begin(), args...);
return ret;
}
template <typename T, typename String = sstring, typename for_enable_if = void*>
String to_sstring(T value, for_enable_if);
template <typename T>
inline
sstring to_sstring_sprintf(T value, const char* fmt) {
char tmp[sizeof(value) * 3 + 3];
auto len = std::sprintf(tmp, fmt, value);
return sstring(tmp, len);
}
template <typename string_type = sstring>
inline
string_type to_sstring(int value, void* = nullptr) {
return to_sstring_sprintf(value, "%d");
}
template <typename string_type = sstring>
inline
string_type to_sstring(unsigned value, void* = nullptr) {
return to_sstring_sprintf(value, "%u");
}
template <typename string_type = sstring>
inline
string_type to_sstring(long value, void* = nullptr) {
return to_sstring_sprintf(value, "%ld");
}
template <typename string_type = sstring>
inline
string_type to_sstring(unsigned long value, void* = nullptr) {
return to_sstring_sprintf(value, "%lu");
}
template <typename string_type = sstring>
inline
string_type to_sstring(long long value, void* = nullptr) {
return to_sstring_sprintf(value, "%lld");
}
template <typename string_type = sstring>
inline
string_type to_sstring(unsigned long long value, void* = nullptr) {
return to_sstring_sprintf(value, "%llu");
}
template <typename string_type = sstring>
inline
string_type to_sstring(float value, void* = nullptr) {
return to_sstring_sprintf(value, "%f");
}
template <typename string_type = sstring>
inline
string_type to_sstring(double value, void* = nullptr) {
return to_sstring_sprintf(value, "%f");
}
template <typename string_type = sstring>
inline
string_type to_sstring(long double value, void* = nullptr) {
return to_sstring_sprintf(value, "%Lf");
}
template <typename string_type = sstring>
inline
string_type to_sstring(const char* value, void* = nullptr) {
return string_type(value);
}
template <typename string_type = sstring>
inline
string_type to_sstring(sstring value, void* = nullptr) {
return value;
}
template <typename string_type = sstring>
static string_type to_sstring(const temporary_buffer<char>& buf) {
return string_type(buf.get(), buf.size());
}
template <typename T>
inline
std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) {
bool first = true;
os << "{";
for (auto&& elem : v) {
if (!first) {
os << ", ";
} else {
first = false;
}
os << elem;
}
os << "}";
return os;
}
#endif /* SSTRING_HH_ */
<commit_msg>basic_sstring: Add 'compare' and 'operator<'<commit_after>/*
* Copyright 2014 Cloudius Systems
*/
#ifndef SSTRING_HH_
#define SSTRING_HH_
#include <stdint.h>
#include <algorithm>
#include <string>
#include <cstring>
#include <stdexcept>
#include <initializer_list>
#include <iostream>
#include <functional>
#include <cstdio>
#include <experimental/string_view>
#include "core/temporary_buffer.hh"
template <typename char_type, typename Size, Size max_size>
class basic_sstring {
union contents {
struct external_type {
char_type* str;
Size size;
int8_t pad;
} external;
struct internal_type {
char_type str[max_size];
int8_t size;
} internal;
static_assert(sizeof(external_type) <= sizeof(internal_type), "max_size too small");
static_assert(max_size <= 127, "max_size too large");
} u;
bool is_internal() const noexcept {
return u.internal.size >= 0;
}
bool is_external() const noexcept {
return !is_internal();
}
const char_type* str() const {
return is_internal() ? u.internal.str : u.external.str;
}
char_type* str() {
return is_internal() ? u.internal.str : u.external.str;
}
public:
using value_type = char_type;
using traits_type = std::char_traits<char_type>;
using allocator_type = std::allocator<char_type>;
using reference = char_type&;
using const_reference = const char_type&;
using pointer = char_type*;
using const_pointer = const char_type*;
using iterator = char_type*;
using const_iterator = const char_type*;
// FIXME: add reverse_iterator and friend
using difference_type = ssize_t; // std::make_signed_t<Size> can be too small
using size_type = Size;
public:
struct initialized_later {};
basic_sstring() noexcept {
u.internal.size = 0;
u.internal.str[0] = '\0';
}
basic_sstring(const basic_sstring& x) {
if (x.is_internal()) {
u.internal = x.u.internal;
} else {
u.internal.size = -1;
u.external.str = reinterpret_cast<char_type*>(std::malloc(x.u.external.size + 1));
if (!u.external.str) {
throw std::bad_alloc();
}
std::copy(x.u.external.str, x.u.external.str + x.u.external.size + 1, u.external.str);
u.external.size = x.u.external.size;
}
}
basic_sstring(basic_sstring&& x) noexcept {
u = x.u;
x.u.internal.size = 0;
x.u.internal.str[0] = '\0';
}
basic_sstring(initialized_later, size_t size) {
if (size_type(size) != size) {
throw std::overflow_error("sstring overflow");
}
if (size + 1 <= sizeof(u.internal.str)) {
u.internal.str[size] = '\0';
u.internal.size = size;
} else {
u.internal.size = -1;
u.external.str = reinterpret_cast<char_type*>(std::malloc(size + 1));
if (!u.external.str) {
throw std::bad_alloc();
}
u.external.size = size;
u.external.str[size] = '\0';
}
}
basic_sstring(const char_type* x, size_t size) {
if (size_type(size) != size) {
throw std::overflow_error("sstring overflow");
}
if (size + 1 <= sizeof(u.internal.str)) {
std::copy(x, x + size, u.internal.str);
u.internal.str[size] = '\0';
u.internal.size = size;
} else {
u.internal.size = -1;
u.external.str = reinterpret_cast<char_type*>(std::malloc(size + 1));
if (!u.external.str) {
throw std::bad_alloc();
}
u.external.size = size;
std::copy(x, x + size, u.external.str);
u.external.str[size] = '\0';
}
}
basic_sstring(const char* x) : basic_sstring(reinterpret_cast<const char_type*>(x), std::strlen(x)) {}
basic_sstring(std::basic_string<char_type>& x) : basic_sstring(x.c_str(), x.size()) {}
basic_sstring(std::initializer_list<char_type> x) : basic_sstring(x.begin(), x.end() - x.begin()) {}
basic_sstring(const char_type* b, const char_type* e) : basic_sstring(b, e - b) {}
basic_sstring(const std::basic_string<char_type>& s)
: basic_sstring(s.data(), s.size()) {}
~basic_sstring() noexcept {
if (is_external()) {
std::free(u.external.str);
}
}
basic_sstring& operator=(const basic_sstring& x) {
basic_sstring tmp(x);
swap(tmp);
return *this;
}
basic_sstring& operator=(basic_sstring&& x) noexcept {
if (this != &x) {
swap(x);
x.reset();
}
return *this;
}
operator std::string() const {
return { str(), size() };
}
size_t size() const noexcept {
return is_internal() ? u.internal.size : u.external.size;
}
bool empty() const noexcept {
return u.internal.size == 0;
}
void reset() noexcept {
if (is_external()) {
std::free(u.external.str);
}
u.internal.size = 0;
u.internal.str[0] = '\0';
}
temporary_buffer<char_type> release() && {
if (is_external()) {
auto ptr = u.external.str;
auto size = u.external.size;
u.external.str = nullptr;
u.external.size = 0;
return temporary_buffer<char_type>(ptr, size, make_free_deleter(ptr));
} else {
auto buf = temporary_buffer<char_type>(u.internal.size);
std::copy(u.internal.str, u.internal.str + u.internal.size, buf.get_write());
u.internal.size = 0;
u.internal.str[0] = '\0';
return buf;
}
}
int compare(const basic_sstring& x) const noexcept {
auto n = traits_type::compare(begin(), x.begin(), std::min(size(), x.size()));
if (n != 0) {
return n;
}
return size() - x.size();
}
void swap(basic_sstring& x) noexcept {
contents tmp;
tmp = x.u;
x.u = u;
u = tmp;
}
const char_type* c_str() const {
return str();
}
const char_type* begin() const { return str(); }
const char_type* end() const { return str() + size(); }
char_type* begin() { return str(); }
char_type* end() { return str() + size(); }
bool operator==(const basic_sstring& x) const {
return size() == x.size() && std::equal(begin(), end(), x.begin());
}
bool operator!=(const basic_sstring& x) const {
return !operator==(x);
}
bool operator<(const basic_sstring& x) const {
return compare(x) < 0;
}
basic_sstring operator+(const basic_sstring& x) const {
basic_sstring ret(initialized_later(), size() + x.size());
std::copy(begin(), end(), ret.begin());
std::copy(x.begin(), x.end(), ret.begin() + size());
return ret;
}
basic_sstring& operator+=(const basic_sstring& x) {
return *this = *this + x;
}
char_type& operator[](size_type pos) {
return str()[pos];
}
const char_type& operator[](size_type pos) const {
return str()[pos];
}
operator std::experimental::string_view() const {
return std::experimental::string_view(str(), size());
}
};
template <typename char_type, typename size_type, size_type Max, size_type N>
inline
basic_sstring<char_type, size_type, Max>
operator+(const char(&s)[N], const basic_sstring<char_type, size_type, Max>& t) {
using sstring = basic_sstring<char_type, size_type, Max>;
// don't copy the terminating NUL character
sstring ret(typename sstring::initialized_later(), N-1 + t.size());
auto p = std::copy(std::begin(s), std::end(s)-1, ret.begin());
std::copy(t.begin(), t.end(), p);
return ret;
}
template <size_t N>
static inline
size_t str_len(const char(&s)[N]) { return N - 1; }
template <size_t N>
static inline
const char* str_begin(const char(&s)[N]) { return s; }
template <size_t N>
static inline
const char* str_end(const char(&s)[N]) { return str_begin(s) + str_len(s); }
template <typename char_type, typename size_type, size_type max_size>
static inline
const char_type* str_begin(const basic_sstring<char_type, size_type, max_size>& s) { return s.begin(); }
template <typename char_type, typename size_type, size_type max_size>
static inline
const char_type* str_end(const basic_sstring<char_type, size_type, max_size>& s) { return s.end(); }
template <typename char_type, typename size_type, size_type max_size>
static inline
size_type str_len(const basic_sstring<char_type, size_type, max_size>& s) { return s.size(); }
template <typename First, typename Second, typename... Tail>
static inline
const size_t str_len(const First& first, const Second& second, const Tail&... tail) {
return str_len(first) + str_len(second, tail...);
}
template <typename char_type, typename size_type, size_type max_size>
inline
void swap(basic_sstring<char_type, size_type, max_size>& x,
basic_sstring<char_type, size_type, max_size>& y) noexcept
{
return x.swap(y);
}
template <typename char_type, typename size_type, size_type max_size, typename char_traits>
inline
std::basic_ostream<char_type, char_traits>&
operator<<(std::basic_ostream<char_type, char_traits>& os,
const basic_sstring<char_type, size_type, max_size>& s) {
return os.write(s.begin(), s.size());
}
namespace std {
template <typename char_type, typename size_type, size_type max_size>
struct hash<basic_sstring<char_type, size_type, max_size>> {
size_t operator()(const basic_sstring<char_type, size_type, max_size>& s) const {
return std::hash<std::experimental::string_view>()(s);
}
};
}
using sstring = basic_sstring<char, uint32_t, 15>;
static inline
char* copy_str_to(char* dst) {
return dst;
}
template <typename Head, typename... Tail>
static inline
char* copy_str_to(char* dst, const Head& head, const Tail&... tail) {
return copy_str_to(std::copy(str_begin(head), str_end(head), dst), tail...);
}
template <typename String = sstring, typename... Args>
static String make_sstring(Args&&... args)
{
String ret(sstring::initialized_later(), str_len(args...));
copy_str_to(ret.begin(), args...);
return ret;
}
template <typename T, typename String = sstring, typename for_enable_if = void*>
String to_sstring(T value, for_enable_if);
template <typename T>
inline
sstring to_sstring_sprintf(T value, const char* fmt) {
char tmp[sizeof(value) * 3 + 3];
auto len = std::sprintf(tmp, fmt, value);
return sstring(tmp, len);
}
template <typename string_type = sstring>
inline
string_type to_sstring(int value, void* = nullptr) {
return to_sstring_sprintf(value, "%d");
}
template <typename string_type = sstring>
inline
string_type to_sstring(unsigned value, void* = nullptr) {
return to_sstring_sprintf(value, "%u");
}
template <typename string_type = sstring>
inline
string_type to_sstring(long value, void* = nullptr) {
return to_sstring_sprintf(value, "%ld");
}
template <typename string_type = sstring>
inline
string_type to_sstring(unsigned long value, void* = nullptr) {
return to_sstring_sprintf(value, "%lu");
}
template <typename string_type = sstring>
inline
string_type to_sstring(long long value, void* = nullptr) {
return to_sstring_sprintf(value, "%lld");
}
template <typename string_type = sstring>
inline
string_type to_sstring(unsigned long long value, void* = nullptr) {
return to_sstring_sprintf(value, "%llu");
}
template <typename string_type = sstring>
inline
string_type to_sstring(float value, void* = nullptr) {
return to_sstring_sprintf(value, "%f");
}
template <typename string_type = sstring>
inline
string_type to_sstring(double value, void* = nullptr) {
return to_sstring_sprintf(value, "%f");
}
template <typename string_type = sstring>
inline
string_type to_sstring(long double value, void* = nullptr) {
return to_sstring_sprintf(value, "%Lf");
}
template <typename string_type = sstring>
inline
string_type to_sstring(const char* value, void* = nullptr) {
return string_type(value);
}
template <typename string_type = sstring>
inline
string_type to_sstring(sstring value, void* = nullptr) {
return value;
}
template <typename string_type = sstring>
static string_type to_sstring(const temporary_buffer<char>& buf) {
return string_type(buf.get(), buf.size());
}
template <typename T>
inline
std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) {
bool first = true;
os << "{";
for (auto&& elem : v) {
if (!first) {
os << ", ";
} else {
first = false;
}
os << elem;
}
os << "}";
return os;
}
#endif /* SSTRING_HH_ */
<|endoftext|> |
<commit_before>// Copyright (c) 2010-2021, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
#ifndef MFEM_MESH_OPERATORS
#define MFEM_MESH_OPERATORS
#include "../config/config.hpp"
#include "../general/array.hpp"
#include "mesh.hpp"
#include "../fem/estimators.hpp"
#include <limits>
namespace mfem
{
/** @brief The MeshOperator class serves as base for mesh manipulation classes.
The purpose of the class is to provide a common abstraction for various
AMR mesh control schemes. The typical use in an AMR loop is illustrated
in examples 6/6p and 15/15p.
A more general loop that also supports sequences of mesh operators with
multiple updates looks like this:
\code
for (...)
{
// computations on the current mesh ...
while (mesh_operator->Apply(mesh))
{
// update FiniteElementSpaces and interpolate GridFunctions ...
if (mesh_operator->Continue()) { break; }
}
if (mesh_operator->Stop()) { break; }
}
\endcode
*/
class MeshOperator
{
private:
int mod;
protected:
friend class MeshOperatorSequence;
/** @brief Implementation of the mesh operation. Invoked by the Apply()
public method.
@return Combination of ActionInfo constants. */
virtual int ApplyImpl(Mesh &mesh) = 0;
/// Constructor to be used by derived classes.
MeshOperator() : mod(NONE) { }
public:
/** @brief Action and information constants and masks.
Combinations of constants are returned by the Apply() virtual method and
can be accessed directly with GetActionInfo() or indirectly with methods
like Stop(), Continue(), etc. The information bits (MASK_INFO) can be set
only when the update bit is set (see MASK_UPDATE). */
enum Action
{
NONE = 0, /**< continue with computations without updating spaces
or grid-functions, i.e. the mesh was not modified */
CONTINUE = 1, /**< update spaces and grid-functions and continue
computations with the new mesh */
STOP = 2, ///< a stopping criterion was satisfied
REPEAT = 3, /**< update spaces and grid-functions and call the
operator Apply() method again */
MASK_UPDATE = 1, ///< bit mask for the "update" bit
MASK_ACTION = 3 ///< bit mask for all "action" bits
};
enum Info
{
REFINED = 4*1, ///< the mesh was refined
DEREFINED = 4*2, ///< the mesh was de-refined
REBALANCED = 4*3, ///< the mesh was rebalanced
MASK_INFO = ~3 ///< bit mask for all "info" bits
};
/** @brief Perform the mesh operation.
@return true if FiniteElementSpaces and GridFunctions need to be updated.
*/
bool Apply(Mesh &mesh) { return ((mod = ApplyImpl(mesh)) & MASK_UPDATE); }
/** @brief Check if STOP action is requested, e.g. stopping criterion is
satisfied. */
bool Stop() const { return ((mod & MASK_ACTION) == STOP); }
/** @brief Check if REPEAT action is requested, i.e. FiniteElementSpaces and
GridFunctions need to be updated, and Apply() must be called again. */
bool Repeat() const { return ((mod & MASK_ACTION) == REPEAT); }
/** @brief Check if CONTINUE action is requested, i.e. FiniteElementSpaces
and GridFunctions need to be updated and computations should continue. */
bool Continue() const { return ((mod & MASK_ACTION) == CONTINUE); }
/// Check if the mesh was refined.
bool Refined() const { return ((mod & MASK_INFO) == REFINED); }
/// Check if the mesh was de-refined.
bool Derefined() const { return ((mod & MASK_INFO) == DEREFINED); }
/// Check if the mesh was rebalanced.
bool Rebalanced() const { return ((mod & MASK_INFO) == REBALANCED); }
/** @brief Get the full ActionInfo value generated by the last call to
Apply(). */
int GetActionInfo() const { return mod; }
/// Reset the MeshOperator.
virtual void Reset() = 0;
/// The destructor is virtual.
virtual ~MeshOperator() { }
};
/** Composition of MeshOperators into a sequence. Use the Append() method to
create the sequence. */
class MeshOperatorSequence : public MeshOperator
{
protected:
int step;
Array<MeshOperator*> sequence; ///< MeshOperators sequence, owned by us.
/// Do not allow copy construction, due to assumed ownership.
MeshOperatorSequence(const MeshOperatorSequence &) { }
/** @brief Apply the MeshOperatorSequence.
@return ActionInfo value corresponding to the last applied operator from
the sequence. */
virtual int ApplyImpl(Mesh &mesh);
public:
/// Constructor. Use the Append() method to create the sequence.
MeshOperatorSequence() : step(-1) { }
/// Delete all operators from the sequence.
virtual ~MeshOperatorSequence();
/** @brief Add an operator to the end of the sequence.
The MeshOperatorSequence assumes ownership of the operator. */
void Append(MeshOperator *mc) { sequence.Append(mc); }
/// Access the underlying sequence.
Array<MeshOperator*> &GetSequence() { return sequence; }
/// Reset all MeshOperators in the sequence.
virtual void Reset();
};
/** @brief Mesh refinement operator using an error threshold.
This class uses the given ErrorEstimator to estimate local element errors
and then marks for refinement all elements i such that loc_err_i > threshold.
The threshold is computed as
\code
threshold = max(total_err * total_fraction * pow(num_elements,-1.0/p),
local_err_goal);
\endcode
where p (=total_norm_p), total_fraction, and local_err_goal are settable
parameters, total_err = (sum_i local_err_i^p)^{1/p}, when p < inf,
or total_err = max_i local_err_i, when p = inf.
*/
class ThresholdRefiner : public MeshOperator
{
protected:
ErrorEstimator &estimator;
AnisotropicErrorEstimator *aniso_estimator;
double total_norm_p;
double total_err_goal;
double total_fraction;
double local_err_goal;
long max_elements;
double threshold;
long num_marked_elements;
Array<Refinement> marked_elements;
long current_sequence;
int non_conforming;
int nc_limit;
double GetNorm(const Vector &local_err, Mesh &mesh) const;
/** @brief Apply the operator to the mesh.
@return STOP if a stopping criterion is satisfied or no elements were
marked for refinement; REFINED + CONTINUE otherwise. */
virtual int ApplyImpl(Mesh &mesh);
public:
/// Construct a ThresholdRefiner using the given ErrorEstimator.
ThresholdRefiner(ErrorEstimator &est);
// default destructor (virtual)
/** @brief Set the exponent, p, of the discrete p-norm used to compute the
total error from the local element errors. */
void SetTotalErrorNormP(double norm_p = infinity())
{ total_norm_p = norm_p; }
/** @brief Set the total error stopping criterion: stop when
total_err <= total_err_goal. The default value is zero. */
void SetTotalErrorGoal(double err_goal) { total_err_goal = err_goal; }
/** @brief Set the total fraction used in the computation of the threshold.
The default value is 1/2.
@note If fraction == 0, total_err is essentially ignored in the threshold
computation, i.e. threshold = local error goal. */
void SetTotalErrorFraction(double fraction) { total_fraction = fraction; }
/** @brief Set the local stopping criterion: stop when
local_err_i <= local_err_goal. The default value is zero.
@note If local_err_goal == 0, it is essentially ignored in the threshold
computation. */
void SetLocalErrorGoal(double err_goal) { local_err_goal = err_goal; }
/** @brief Set the maximum number of elements stopping criterion: stop when
the input mesh has num_elements >= max_elem. The default value is
LONG_MAX. */
void SetMaxElements(long max_elem) { max_elements = max_elem; }
/// Use nonconforming refinement, if possible (triangles, quads, hexes).
void PreferNonconformingRefinement() { non_conforming = 1; }
/** @brief Use conforming refinement, if possible (triangles, tetrahedra)
-- this is the default. */
void PreferConformingRefinement() { non_conforming = -1; }
/** @brief Set the maximum ratio of refinement levels of adjacent elements
(0 = unlimited). */
void SetNCLimit(int nc_limit)
{
MFEM_ASSERT(nc_limit >= 0, "Invalid NC limit");
this->nc_limit = nc_limit;
}
/// Get the number of marked elements in the last Apply() call.
long GetNumMarkedElements() const { return num_marked_elements; }
/// Get the threshold used in the last Apply() call.
double GetThreshold() const { return threshold; }
/// Reset the associated estimator.
virtual void Reset();
};
// TODO: BulkRefiner to refine a portion of the global error
/** @brief De-refinement operator using an error threshold.
This de-refinement operator marks elements in the hierarchy whose children
are leaves and their combined error is below a given threshold. The
errors of the children are combined by one of the following operations:
- op = 0: minimum of the errors
- op = 1: sum of the errors (default)
- op = 2: maximum of the errors. */
class ThresholdDerefiner : public MeshOperator
{
protected:
ErrorEstimator &estimator;
double threshold;
int nc_limit, op;
/** @brief Apply the operator to the mesh.
@return DEREFINED + CONTINUE if some elements were de-refined; NONE
otherwise. */
virtual int ApplyImpl(Mesh &mesh);
public:
/// Construct a ThresholdDerefiner using the given ErrorEstimator.
ThresholdDerefiner(ErrorEstimator &est)
: estimator(est)
{
threshold = 0.0;
nc_limit = 0;
op = 1;
}
// default destructor (virtual)
/// Set the de-refinement threshold. The default value is zero.
void SetThreshold(double thresh) { threshold = thresh; }
void SetOp(int op) { this->op = op; }
/** @brief Set the maximum ratio of refinement levels of adjacent elements
(0 = unlimited). */
void SetNCLimit(int nc_limit)
{
MFEM_ASSERT(nc_limit >= 0, "Invalid NC limit");
this->nc_limit = nc_limit;
}
/// Reset the associated estimator.
virtual void Reset() { estimator.Reset(); }
};
/** @brief Refinement operator to control data oscillation.
This class computes osc_K(f) := || h ⋅ (I - Π) f ||_K at each element K.
Here, Π is the L2-projection and ||⋅||_K is the L2-norm, restricted to the
element K. All elements satisfying the inequality
\code
osc_K(f) > threshold ⋅ ||f|| / sqrt(n_el),
\endcode
are refined. Here, threshold is a postive parameter, ||⋅|| is the L2-norm
over the entire domain Ω, and n_el is the number of elements in the mesh.
Note that if osc(f) = threshold ⋅ ||f|| / sqrt(n_el) for each K, then
\code
osc(f) = sqrt( sum_K osc_K^2(f)) = threshold ⋅ ||f||.
\endcode
This is the reason for the 1/sqrt(n_el) factor. */
class CoefficientRefiner : public MeshOperator
{
protected:
int nc_limit = 1;
int nonconforming = -1;
int order;
long max_elements = std::numeric_limits<long>::max();
double threshold = 1.0e-2;
double global_osc = 0.0;
Array<int> mesh_refinements;
Vector element_oscs;
Coefficient *coeff = NULL;
GridFunction *gf;
const IntegrationRule *ir_default[Geometry::NumGeom];
const IntegrationRule **irs = NULL;
/** @brief Apply the operator to the mesh once.
@return STOP if a stopping criterion is satisfied or no elements were
marked for refinement; REFINED + CONTINUE otherwise. */
virtual int ApplyImpl(Mesh &mesh);
public:
/// Constructor
CoefficientRefiner(int order_) : order(order_) { }
/** @brief Apply the operator to the mesh max_it times or until tolerance
* achieved.
@return STOP if a stopping criterion is satisfied or no elements were
marked for refinement; REFINED + CONTINUE otherwise. */
virtual int PreprocessMesh(Mesh &mesh, int max_it);
int PreprocessMesh(Mesh &mesh)
{
int max_it = 10;
return PreprocessMesh(mesh, max_it);
}
/// Set the refinement threshold. The default value is 1.0e-2.
void SetThreshold(double threshold_) { threshold = threshold_; }
/** @brief Set the maximum number of elements stopping criterion: stop when
the input mesh has num_elements >= max_elem. The default value is
LONG_MAX. */
void SetMaxElements(long max_elements_) { max_elements = max_elements_; }
/// Set the function f
void SetCoefficient(Coefficient &coeff_)
{
element_oscs.Destroy();
global_osc = 0.0;
coeff = &coeff_;
}
/// Reset the oscillation order
void SetOrder(double order_) { order = order_; }
/** @brief Set the maximum ratio of refinement levels of adjacent elements
(0 = unlimited). The default value is 1, which helps ensure appropriate
refinements in pathological situations where the default quadrature
order is too low. */
void SetNCLimit(int nc_limit_)
{
MFEM_ASSERT(nc_limit_ >= 0, "Invalid NC limit");
nc_limit = nc_limit_;
}
// Set a custom integration rule
void SetIntRule(const IntegrationRule *irs_[]) { irs = irs_; }
// Return the value of the global relative data oscillation
const double GetOsc() { return global_osc; }
// Return the local relative data oscillation errors
Vector GetLocalOscs()
{
MFEM_ASSERT(element_oscs.Size() > 0,
"Local oscillations have not been computed yet")
return element_oscs;
}
/// Reset
virtual void Reset();
};
/** @brief ParMesh rebalancing operator.
If the mesh is a parallel mesh, perform rebalancing; otherwise, do nothing.
*/
class Rebalancer : public MeshOperator
{
protected:
/** @brief Rebalance a parallel mesh (only non-conforming parallel meshes are
supported).
@return CONTINUE + REBALANCE on success, NONE otherwise. */
virtual int ApplyImpl(Mesh &mesh);
public:
/// Empty.
virtual void Reset() { }
};
} // namespace mfem
#endif // MFEM_MESH_OPERATORS
<commit_msg>const Vector & GetLocalOscs() const<commit_after>// Copyright (c) 2010-2021, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
#ifndef MFEM_MESH_OPERATORS
#define MFEM_MESH_OPERATORS
#include "../config/config.hpp"
#include "../general/array.hpp"
#include "mesh.hpp"
#include "../fem/estimators.hpp"
#include <limits>
namespace mfem
{
/** @brief The MeshOperator class serves as base for mesh manipulation classes.
The purpose of the class is to provide a common abstraction for various
AMR mesh control schemes. The typical use in an AMR loop is illustrated
in examples 6/6p and 15/15p.
A more general loop that also supports sequences of mesh operators with
multiple updates looks like this:
\code
for (...)
{
// computations on the current mesh ...
while (mesh_operator->Apply(mesh))
{
// update FiniteElementSpaces and interpolate GridFunctions ...
if (mesh_operator->Continue()) { break; }
}
if (mesh_operator->Stop()) { break; }
}
\endcode
*/
class MeshOperator
{
private:
int mod;
protected:
friend class MeshOperatorSequence;
/** @brief Implementation of the mesh operation. Invoked by the Apply()
public method.
@return Combination of ActionInfo constants. */
virtual int ApplyImpl(Mesh &mesh) = 0;
/// Constructor to be used by derived classes.
MeshOperator() : mod(NONE) { }
public:
/** @brief Action and information constants and masks.
Combinations of constants are returned by the Apply() virtual method and
can be accessed directly with GetActionInfo() or indirectly with methods
like Stop(), Continue(), etc. The information bits (MASK_INFO) can be set
only when the update bit is set (see MASK_UPDATE). */
enum Action
{
NONE = 0, /**< continue with computations without updating spaces
or grid-functions, i.e. the mesh was not modified */
CONTINUE = 1, /**< update spaces and grid-functions and continue
computations with the new mesh */
STOP = 2, ///< a stopping criterion was satisfied
REPEAT = 3, /**< update spaces and grid-functions and call the
operator Apply() method again */
MASK_UPDATE = 1, ///< bit mask for the "update" bit
MASK_ACTION = 3 ///< bit mask for all "action" bits
};
enum Info
{
REFINED = 4*1, ///< the mesh was refined
DEREFINED = 4*2, ///< the mesh was de-refined
REBALANCED = 4*3, ///< the mesh was rebalanced
MASK_INFO = ~3 ///< bit mask for all "info" bits
};
/** @brief Perform the mesh operation.
@return true if FiniteElementSpaces and GridFunctions need to be updated.
*/
bool Apply(Mesh &mesh) { return ((mod = ApplyImpl(mesh)) & MASK_UPDATE); }
/** @brief Check if STOP action is requested, e.g. stopping criterion is
satisfied. */
bool Stop() const { return ((mod & MASK_ACTION) == STOP); }
/** @brief Check if REPEAT action is requested, i.e. FiniteElementSpaces and
GridFunctions need to be updated, and Apply() must be called again. */
bool Repeat() const { return ((mod & MASK_ACTION) == REPEAT); }
/** @brief Check if CONTINUE action is requested, i.e. FiniteElementSpaces
and GridFunctions need to be updated and computations should continue. */
bool Continue() const { return ((mod & MASK_ACTION) == CONTINUE); }
/// Check if the mesh was refined.
bool Refined() const { return ((mod & MASK_INFO) == REFINED); }
/// Check if the mesh was de-refined.
bool Derefined() const { return ((mod & MASK_INFO) == DEREFINED); }
/// Check if the mesh was rebalanced.
bool Rebalanced() const { return ((mod & MASK_INFO) == REBALANCED); }
/** @brief Get the full ActionInfo value generated by the last call to
Apply(). */
int GetActionInfo() const { return mod; }
/// Reset the MeshOperator.
virtual void Reset() = 0;
/// The destructor is virtual.
virtual ~MeshOperator() { }
};
/** Composition of MeshOperators into a sequence. Use the Append() method to
create the sequence. */
class MeshOperatorSequence : public MeshOperator
{
protected:
int step;
Array<MeshOperator*> sequence; ///< MeshOperators sequence, owned by us.
/// Do not allow copy construction, due to assumed ownership.
MeshOperatorSequence(const MeshOperatorSequence &) { }
/** @brief Apply the MeshOperatorSequence.
@return ActionInfo value corresponding to the last applied operator from
the sequence. */
virtual int ApplyImpl(Mesh &mesh);
public:
/// Constructor. Use the Append() method to create the sequence.
MeshOperatorSequence() : step(-1) { }
/// Delete all operators from the sequence.
virtual ~MeshOperatorSequence();
/** @brief Add an operator to the end of the sequence.
The MeshOperatorSequence assumes ownership of the operator. */
void Append(MeshOperator *mc) { sequence.Append(mc); }
/// Access the underlying sequence.
Array<MeshOperator*> &GetSequence() { return sequence; }
/// Reset all MeshOperators in the sequence.
virtual void Reset();
};
/** @brief Mesh refinement operator using an error threshold.
This class uses the given ErrorEstimator to estimate local element errors
and then marks for refinement all elements i such that loc_err_i > threshold.
The threshold is computed as
\code
threshold = max(total_err * total_fraction * pow(num_elements,-1.0/p),
local_err_goal);
\endcode
where p (=total_norm_p), total_fraction, and local_err_goal are settable
parameters, total_err = (sum_i local_err_i^p)^{1/p}, when p < inf,
or total_err = max_i local_err_i, when p = inf.
*/
class ThresholdRefiner : public MeshOperator
{
protected:
ErrorEstimator &estimator;
AnisotropicErrorEstimator *aniso_estimator;
double total_norm_p;
double total_err_goal;
double total_fraction;
double local_err_goal;
long max_elements;
double threshold;
long num_marked_elements;
Array<Refinement> marked_elements;
long current_sequence;
int non_conforming;
int nc_limit;
double GetNorm(const Vector &local_err, Mesh &mesh) const;
/** @brief Apply the operator to the mesh.
@return STOP if a stopping criterion is satisfied or no elements were
marked for refinement; REFINED + CONTINUE otherwise. */
virtual int ApplyImpl(Mesh &mesh);
public:
/// Construct a ThresholdRefiner using the given ErrorEstimator.
ThresholdRefiner(ErrorEstimator &est);
// default destructor (virtual)
/** @brief Set the exponent, p, of the discrete p-norm used to compute the
total error from the local element errors. */
void SetTotalErrorNormP(double norm_p = infinity())
{ total_norm_p = norm_p; }
/** @brief Set the total error stopping criterion: stop when
total_err <= total_err_goal. The default value is zero. */
void SetTotalErrorGoal(double err_goal) { total_err_goal = err_goal; }
/** @brief Set the total fraction used in the computation of the threshold.
The default value is 1/2.
@note If fraction == 0, total_err is essentially ignored in the threshold
computation, i.e. threshold = local error goal. */
void SetTotalErrorFraction(double fraction) { total_fraction = fraction; }
/** @brief Set the local stopping criterion: stop when
local_err_i <= local_err_goal. The default value is zero.
@note If local_err_goal == 0, it is essentially ignored in the threshold
computation. */
void SetLocalErrorGoal(double err_goal) { local_err_goal = err_goal; }
/** @brief Set the maximum number of elements stopping criterion: stop when
the input mesh has num_elements >= max_elem. The default value is
LONG_MAX. */
void SetMaxElements(long max_elem) { max_elements = max_elem; }
/// Use nonconforming refinement, if possible (triangles, quads, hexes).
void PreferNonconformingRefinement() { non_conforming = 1; }
/** @brief Use conforming refinement, if possible (triangles, tetrahedra)
-- this is the default. */
void PreferConformingRefinement() { non_conforming = -1; }
/** @brief Set the maximum ratio of refinement levels of adjacent elements
(0 = unlimited). */
void SetNCLimit(int nc_limit)
{
MFEM_ASSERT(nc_limit >= 0, "Invalid NC limit");
this->nc_limit = nc_limit;
}
/// Get the number of marked elements in the last Apply() call.
long GetNumMarkedElements() const { return num_marked_elements; }
/// Get the threshold used in the last Apply() call.
double GetThreshold() const { return threshold; }
/// Reset the associated estimator.
virtual void Reset();
};
// TODO: BulkRefiner to refine a portion of the global error
/** @brief De-refinement operator using an error threshold.
This de-refinement operator marks elements in the hierarchy whose children
are leaves and their combined error is below a given threshold. The
errors of the children are combined by one of the following operations:
- op = 0: minimum of the errors
- op = 1: sum of the errors (default)
- op = 2: maximum of the errors. */
class ThresholdDerefiner : public MeshOperator
{
protected:
ErrorEstimator &estimator;
double threshold;
int nc_limit, op;
/** @brief Apply the operator to the mesh.
@return DEREFINED + CONTINUE if some elements were de-refined; NONE
otherwise. */
virtual int ApplyImpl(Mesh &mesh);
public:
/// Construct a ThresholdDerefiner using the given ErrorEstimator.
ThresholdDerefiner(ErrorEstimator &est)
: estimator(est)
{
threshold = 0.0;
nc_limit = 0;
op = 1;
}
// default destructor (virtual)
/// Set the de-refinement threshold. The default value is zero.
void SetThreshold(double thresh) { threshold = thresh; }
void SetOp(int op) { this->op = op; }
/** @brief Set the maximum ratio of refinement levels of adjacent elements
(0 = unlimited). */
void SetNCLimit(int nc_limit)
{
MFEM_ASSERT(nc_limit >= 0, "Invalid NC limit");
this->nc_limit = nc_limit;
}
/// Reset the associated estimator.
virtual void Reset() { estimator.Reset(); }
};
/** @brief Refinement operator to control data oscillation.
This class computes osc_K(f) := || h ⋅ (I - Π) f ||_K at each element K.
Here, Π is the L2-projection and ||⋅||_K is the L2-norm, restricted to the
element K. All elements satisfying the inequality
\code
osc_K(f) > threshold ⋅ ||f|| / sqrt(n_el),
\endcode
are refined. Here, threshold is a postive parameter, ||⋅|| is the L2-norm
over the entire domain Ω, and n_el is the number of elements in the mesh.
Note that if osc(f) = threshold ⋅ ||f|| / sqrt(n_el) for each K, then
\code
osc(f) = sqrt( sum_K osc_K^2(f)) = threshold ⋅ ||f||.
\endcode
This is the reason for the 1/sqrt(n_el) factor. */
class CoefficientRefiner : public MeshOperator
{
protected:
int nc_limit = 1;
int nonconforming = -1;
int order;
long max_elements = std::numeric_limits<long>::max();
double threshold = 1.0e-2;
double global_osc = 0.0;
Array<int> mesh_refinements;
Vector element_oscs;
Coefficient *coeff = NULL;
GridFunction *gf;
const IntegrationRule *ir_default[Geometry::NumGeom];
const IntegrationRule **irs = NULL;
/** @brief Apply the operator to the mesh once.
@return STOP if a stopping criterion is satisfied or no elements were
marked for refinement; REFINED + CONTINUE otherwise. */
virtual int ApplyImpl(Mesh &mesh);
public:
/// Constructor
CoefficientRefiner(int order_) : order(order_) { }
/** @brief Apply the operator to the mesh max_it times or until tolerance
* achieved.
@return STOP if a stopping criterion is satisfied or no elements were
marked for refinement; REFINED + CONTINUE otherwise. */
virtual int PreprocessMesh(Mesh &mesh, int max_it);
int PreprocessMesh(Mesh &mesh)
{
int max_it = 10;
return PreprocessMesh(mesh, max_it);
}
/// Set the refinement threshold. The default value is 1.0e-2.
void SetThreshold(double threshold_) { threshold = threshold_; }
/** @brief Set the maximum number of elements stopping criterion: stop when
the input mesh has num_elements >= max_elem. The default value is
LONG_MAX. */
void SetMaxElements(long max_elements_) { max_elements = max_elements_; }
/// Set the function f
void SetCoefficient(Coefficient &coeff_)
{
element_oscs.Destroy();
global_osc = 0.0;
coeff = &coeff_;
}
/// Reset the oscillation order
void SetOrder(double order_) { order = order_; }
/** @brief Set the maximum ratio of refinement levels of adjacent elements
(0 = unlimited). The default value is 1, which helps ensure appropriate
refinements in pathological situations where the default quadrature
order is too low. */
void SetNCLimit(int nc_limit_)
{
MFEM_ASSERT(nc_limit_ >= 0, "Invalid NC limit");
nc_limit = nc_limit_;
}
// Set a custom integration rule
void SetIntRule(const IntegrationRule *irs_[]) { irs = irs_; }
// Return the value of the global relative data oscillation
const double GetOsc() { return global_osc; }
// Return the local relative data oscillation errors
const Vector & GetLocalOscs() const
{
MFEM_ASSERT(element_oscs.Size() > 0,
"Local oscillations have not been computed yet")
return element_oscs;
}
/// Reset
virtual void Reset();
};
/** @brief ParMesh rebalancing operator.
If the mesh is a parallel mesh, perform rebalancing; otherwise, do nothing.
*/
class Rebalancer : public MeshOperator
{
protected:
/** @brief Rebalance a parallel mesh (only non-conforming parallel meshes are
supported).
@return CONTINUE + REBALANCE on success, NONE otherwise. */
virtual int ApplyImpl(Mesh &mesh);
public:
/// Empty.
virtual void Reset() { }
};
} // namespace mfem
#endif // MFEM_MESH_OPERATORS
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: textconversionImpl.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: vg $ $Date: 2003-04-17 17:53:51 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include <assert.h>
#include <textconversionImpl.hxx>
using namespace com::sun::star::lang;
using namespace com::sun::star::uno;
using namespace rtl;
namespace com { namespace sun { namespace star { namespace i18n {
TextConversionResult SAL_CALL
TextConversionImpl::getConversions( const OUString& aText, sal_Int32 nStartPos, sal_Int32 nLength,
const Locale& aLocale, sal_Int16 nConversionType, sal_Int32 nConversionOptions)
throw( RuntimeException, IllegalArgumentException, NoSupportException )
{
getLocaleSpecificTextConversion(aLocale);
return xTC->getConversions(aText, nStartPos, nLength, aLocale, nConversionType, nConversionOptions);
}
OUString SAL_CALL
TextConversionImpl::getConversion( const OUString& aText, sal_Int32 nStartPos, sal_Int32 nLength,
const Locale& aLocale, sal_Int16 nConversionType, sal_Int32 nConversionOptions)
throw( RuntimeException, IllegalArgumentException, NoSupportException )
{
getLocaleSpecificTextConversion(aLocale);
return xTC->getConversion(aText, nStartPos, nLength, aLocale, nConversionType, nConversionOptions);
}
sal_Bool SAL_CALL
TextConversionImpl::interactiveConversion( const Locale& aLocale, sal_Int16 nTextConversionType, sal_Int32 nTextConversionOptions )
throw( RuntimeException, IllegalArgumentException, NoSupportException )
{
getLocaleSpecificTextConversion(aLocale);
return xTC->interactiveConversion(aLocale, nTextConversionType, nTextConversionOptions);
}
static inline sal_Bool operator != (const Locale& l1, const Locale& l2) {
return l1.Language != l2.Language || l1.Country != l2.Country || l1.Variant != l2.Variant;
}
void SAL_CALL
TextConversionImpl::getLocaleSpecificTextConversion(const Locale& rLocale) throw( NoSupportException )
{
if (xMSF.is() && rLocale != aLocale) {
aLocale = rLocale;
Reference < XInterface > xI;
xI = xMSF->createInstance(
OUString::createFromAscii("com.sun.star.i18n.TextConversion_") + aLocale.Language);
if ( ! xI.is() )
xI = xMSF->createInstance(
OUString::createFromAscii("com.sun.star.i18n.TextConversion_") + aLocale.Language +
OUString::createFromAscii("_") + aLocale.Country);
if ( ! xI.is() )
xI = xMSF->createInstance(
OUString::createFromAscii("com.sun.star.i18n.TextConversion_") + aLocale.Language +
OUString::createFromAscii("_") + aLocale.Country +
OUString::createFromAscii("_") + aLocale.Variant);
if (xI.is())
xI->queryInterface( getCppuType((const Reference< XTextConversion>*)0) ) >>= xTC;
else if (xTC.is())
xTC.clear();
}
if (! xTC.is())
throw NoSupportException(); // aLocale is not supported
}
const sal_Char cTextConversion[] = "com.sun.star.i18n.TextConversion";
OUString SAL_CALL
TextConversionImpl::getImplementationName() throw( RuntimeException )
{
return OUString::createFromAscii(cTextConversion);
}
sal_Bool SAL_CALL
TextConversionImpl::supportsService(const OUString& rServiceName)
throw( RuntimeException )
{
return rServiceName.equalsAscii(cTextConversion);
}
Sequence< OUString > SAL_CALL
TextConversionImpl::getSupportedServiceNames() throw( RuntimeException )
{
Sequence< OUString > aRet(1);
aRet[0] = OUString::createFromAscii(cTextConversion);
return aRet;
}
} } } }
<commit_msg>INTEGRATION: CWS os34 (1.2.116); FILE MERGED 2004/07/23 06:57:26 khong 1.2.116.3: #i29300# check string length 2004/07/23 06:52:48 khong 1.2.116.2: #i29300# check string length 2004/07/23 06:43:22 khong 1.2.116.1: #i29300# check string length<commit_after>/*************************************************************************
*
* $RCSfile: textconversionImpl.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2004-09-17 13:57:21 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include <assert.h>
#include <textconversionImpl.hxx>
using namespace com::sun::star::lang;
using namespace com::sun::star::uno;
using namespace rtl;
namespace com { namespace sun { namespace star { namespace i18n {
TextConversionResult SAL_CALL
TextConversionImpl::getConversions( const OUString& aText, sal_Int32 nStartPos, sal_Int32 nLength,
const Locale& rLocale, sal_Int16 nConversionType, sal_Int32 nConversionOptions)
throw( RuntimeException, IllegalArgumentException, NoSupportException )
{
getLocaleSpecificTextConversion(rLocale);
sal_Int32 len = aText.getLength() - nStartPos;
if (nLength > len)
nLength = len > 0 ? len : 0;
return xTC->getConversions(aText, nStartPos, nLength, rLocale, nConversionType, nConversionOptions);
}
OUString SAL_CALL
TextConversionImpl::getConversion( const OUString& aText, sal_Int32 nStartPos, sal_Int32 nLength,
const Locale& rLocale, sal_Int16 nConversionType, sal_Int32 nConversionOptions)
throw( RuntimeException, IllegalArgumentException, NoSupportException )
{
getLocaleSpecificTextConversion(rLocale);
sal_Int32 len = aText.getLength() - nStartPos;
if (nLength > len)
nLength = len > 0 ? len : 0;
return xTC->getConversion(aText, nStartPos, nLength, rLocale, nConversionType, nConversionOptions);
}
sal_Bool SAL_CALL
TextConversionImpl::interactiveConversion( const Locale& rLocale, sal_Int16 nTextConversionType, sal_Int32 nTextConversionOptions )
throw( RuntimeException, IllegalArgumentException, NoSupportException )
{
getLocaleSpecificTextConversion(rLocale);
return xTC->interactiveConversion(rLocale, nTextConversionType, nTextConversionOptions);
}
static inline sal_Bool operator != (const Locale& l1, const Locale& l2) {
return l1.Language != l2.Language || l1.Country != l2.Country || l1.Variant != l2.Variant;
}
void SAL_CALL
TextConversionImpl::getLocaleSpecificTextConversion(const Locale& rLocale) throw( NoSupportException )
{
if (xMSF.is() && rLocale != aLocale) {
aLocale = rLocale;
Reference < XInterface > xI;
xI = xMSF->createInstance(
OUString::createFromAscii("com.sun.star.i18n.TextConversion_") + aLocale.Language);
if ( ! xI.is() )
xI = xMSF->createInstance(
OUString::createFromAscii("com.sun.star.i18n.TextConversion_") + aLocale.Language +
OUString::createFromAscii("_") + aLocale.Country);
if ( ! xI.is() )
xI = xMSF->createInstance(
OUString::createFromAscii("com.sun.star.i18n.TextConversion_") + aLocale.Language +
OUString::createFromAscii("_") + aLocale.Country +
OUString::createFromAscii("_") + aLocale.Variant);
if (xI.is())
xI->queryInterface( getCppuType((const Reference< XTextConversion>*)0) ) >>= xTC;
else if (xTC.is())
xTC.clear();
}
if (! xTC.is())
throw NoSupportException(); // aLocale is not supported
}
const sal_Char cTextConversion[] = "com.sun.star.i18n.TextConversion";
OUString SAL_CALL
TextConversionImpl::getImplementationName() throw( RuntimeException )
{
return OUString::createFromAscii(cTextConversion);
}
sal_Bool SAL_CALL
TextConversionImpl::supportsService(const OUString& rServiceName)
throw( RuntimeException )
{
return rServiceName.equalsAscii(cTextConversion);
}
Sequence< OUString > SAL_CALL
TextConversionImpl::getSupportedServiceNames() throw( RuntimeException )
{
Sequence< OUString > aRet(1);
aRet[0] = OUString::createFromAscii(cTextConversion);
return aRet;
}
} } } }
<|endoftext|> |
<commit_before>/*
Copyright (c) 2022 Advanced Micro Devices, Inc. All rights reserved.
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 WARRANNTY OF ANY KIND, EXPRESS OR
IMPLIED, INNCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANNY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER INN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR INN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/*
1)Testcase verifies the hipIpcMemAccess APIs by creating memory handle
in parent process and access it in child process.
2)Test case performs Parameter validation of hipIpcMemAccess APIs.
*/
#include <hip_test_common.hh>
#include <hip_test_checkers.hh>
#ifdef __linux__
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <semaphore.h>
#include <unistd.h>
#define NUM_ELMTS 1024
#define NUM_THREADS 10
typedef struct mem_handle {
int device;
hipIpcMemHandle_t memHandle;
bool IfTestPassed;
} hip_ipc_t;
// This testcase verifies the hipIpcMemAccess APIs as follows
// The following program spawns a child process and does the following
// Parent iterate through each device, create memory -- create hipIpcMemhandle
// stores the mem handle in mmaped memory, release the child using sem_post()
// and wait for child to release itself(parent process)
// child process:
// Child process get the ipc mem handle using hipIpcOpenMemHandle
// Iterate through all the available gpus and do Device to Device copies
// and check for data consistencies and close the hipIpcCloseMemHandle
// release the parent and wait for parent to release itself(child)
TEST_CASE("Unit_hipIpcMemAccess_Semaphores") {
hip_ipc_t *shrd_mem = NULL;
pid_t pid;
size_t N = 1024;
size_t Nbytes = N * sizeof(int);
int *A_d{nullptr}, *B_d{nullptr}, *C_d{nullptr};
int *A_h{nullptr}, *C_h{nullptr};
sem_t *sem_ob1{nullptr}, *sem_ob2{nullptr};
int Num_devices = 0, CanAccessPeer = 0;
std::string cmd_line = "rm -rf /dev/shm/sem.my-sem-object*";
int res = system(cmd_line.c_str());
REQUIRE(res != -1);
sem_ob1 = sem_open("/my-sem-object1", O_CREAT|O_EXCL, 0660, 0);
sem_ob2 = sem_open("/my-sem-object2", O_CREAT|O_EXCL, 0660, 0);
REQUIRE(sem_ob1 != SEM_FAILED);
REQUIRE(sem_ob2 != SEM_FAILED);
shrd_mem = reinterpret_cast<hip_ipc_t *>(mmap(NULL, sizeof(hip_ipc_t),
PROT_READ | PROT_WRITE,
MAP_SHARED | MAP_ANONYMOUS,
0, 0));
REQUIRE(shrd_mem != NULL);
shrd_mem->IfTestPassed = true;
HipTest::initArrays<int>(nullptr, nullptr, nullptr,
&A_h, nullptr, &C_h, N, false);
pid = fork();
if (pid != 0) {
// Parent process
HIP_CHECK(hipGetDeviceCount(&Num_devices));
for (int i = 0; i < Num_devices; ++i) {
if (shrd_mem->IfTestPassed == true) {
HIP_CHECK(hipSetDevice(i));
HIP_CHECK(hipMalloc(&A_d, Nbytes));
HIP_CHECK(hipIpcGetMemHandle(reinterpret_cast<hipIpcMemHandle_t *>
(&shrd_mem->memHandle),
A_d));
HIP_CHECK(hipMemcpy(A_d, A_h, Nbytes, hipMemcpyHostToDevice));
shrd_mem->device = i;
if ((sem_post(sem_ob1)) == -1) {
// Need to use inline function to release resources.
shrd_mem->IfTestPassed = false;
WARN("sem_post() call failed in parent process.");
}
if ((sem_wait(sem_ob2)) == -1) {
shrd_mem->IfTestPassed = false;
WARN("sem_wait() call failed in parent process.");
}
HIP_CHECK(hipFree(A_d));
}
}
} else {
// Child process
HIP_CHECK(hipGetDeviceCount(&Num_devices));
for (int j = 0; j < Num_devices; ++j) {
HIP_CHECK(hipSetDevice(j));
if ((sem_wait(sem_ob1)) == -1) {
shrd_mem->IfTestPassed = false;
WARN("sem_wait() call failed in child process.");
if ((sem_post(sem_ob2)) == -1) {
shrd_mem->IfTestPassed = false;
WARN("sem_post() call on sem_ob2 failed");
exit(1);
}
}
for (int i = 0; i < Num_devices; ++i) {
HIP_CHECK(hipSetDevice(i));
HIP_CHECK(hipDeviceCanAccessPeer(&CanAccessPeer, i, shrd_mem->device));
if (CanAccessPeer == 1) {
HIP_CHECK(hipMalloc(&C_d, Nbytes));
HIP_CHECK(hipIpcOpenMemHandle(reinterpret_cast<void **>(&B_d),
shrd_mem->memHandle,
hipIpcMemLazyEnablePeerAccess));
HIP_CHECK(hipMemcpy(C_d, B_d, Nbytes, hipMemcpyDeviceToDevice));
HIP_CHECK(hipMemcpy(C_h, C_d, Nbytes, hipMemcpyDeviceToHost));
HipTest::checkTest<int>(A_h, C_h, N);
memset(reinterpret_cast<void*>(C_h), 0, Nbytes);
// Checking if the data obtained from Ipc shared memory is consistent
HIP_CHECK(hipMemcpy(C_h, B_d, Nbytes, hipMemcpyDeviceToHost));
HipTest::checkTest<int>(A_h, C_h, N);
HIP_CHECK(hipIpcCloseMemHandle(reinterpret_cast<void*>(B_d)));
HIP_CHECK(hipFree(C_d));
}
}
if ((sem_post(sem_ob2)) == -1) {
shrd_mem->IfTestPassed = false;
WARN("sem_post() call on sem_ob2 failed");
exit(1);
}
}
exit(0);
}
if ((sem_unlink("/my-sem-object1")) == -1) {
WARN("sem_unlink() call on /my-sem-object1 failed");
}
if ((sem_unlink("/my-sem-object2")) == -1) {
WARN("sem_unlink() call on /my-sem-object2 failed");
}
int rFlag = 0;
waitpid(pid, &rFlag, 0);
REQUIRE(shrd_mem->IfTestPassed == true);
}
TEST_CASE("Unit_hipIpcMemAccess_ParameterValidation") {
hipIpcMemHandle_t MemHandle;
hipIpcMemHandle_t MemHandleUninit;
void *Ad{}, *Ad2{};
hipError_t ret;
HIP_CHECK(hipMalloc(&Ad, 1024));
#if HT_AMD
// Test is disabled for nvidia as api resulting in seg fault.
SECTION("Get mem handle with handle as nullptr") {
ret = hipIpcGetMemHandle(nullptr, Ad);
REQUIRE(ret == hipErrorInvalidValue);
}
#endif
SECTION("Get mem handle with devptr as nullptr") {
ret = hipIpcGetMemHandle(&MemHandle, nullptr);
REQUIRE(ret == hipErrorInvalidValue);
}
SECTION("Get mem handle with handle/devptr as nullptr") {
ret = hipIpcGetMemHandle(nullptr, nullptr);
REQUIRE(ret == hipErrorInvalidValue);
}
SECTION("Get mem handle with valid devptr") {
ret = hipIpcGetMemHandle(&MemHandle, Ad);
REQUIRE(ret == hipSuccess);
}
SECTION("Open mem handle with devptr as nullptr") {
ret = hipIpcOpenMemHandle(nullptr, MemHandle,
hipIpcMemLazyEnablePeerAccess);
REQUIRE(ret == hipErrorInvalidValue);
}
SECTION("Open mem handle with handle as un-initialized") {
ret = hipIpcOpenMemHandle(&Ad2, MemHandleUninit,
hipIpcMemLazyEnablePeerAccess);
REQUIRE(ret == hipErrorInvalidValue);
}
#if HT_AMD
// Test is disabled for nvidia as api not returning expected value.
SECTION("Open mem handle with flags as random value") {
constexpr unsigned int flags = 123;
HIP_CHECK(hipIpcGetMemHandle(&MemHandle, Ad));
ret = hipIpcOpenMemHandle(&Ad2, MemHandle, flags);
REQUIRE(ret == hipErrorInvalidValue);
}
#endif
SECTION("Close mem handle with devptr(nullptr)") {
ret = hipIpcCloseMemHandle(nullptr);
REQUIRE(ret == hipErrorInvalidValue);
}
HIP_CHECK(hipFree(Ad));
}
#endif
<commit_msg>SWDEV-341744 - Accept error code hipErrorInvalidDevicePointer in hipTest (#2950)<commit_after>/*
Copyright (c) 2022 Advanced Micro Devices, Inc. All rights reserved.
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 WARRANNTY OF ANY KIND, EXPRESS OR
IMPLIED, INNCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANNY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER INN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR INN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/*
1)Testcase verifies the hipIpcMemAccess APIs by creating memory handle
in parent process and access it in child process.
2)Test case performs Parameter validation of hipIpcMemAccess APIs.
*/
#include <hip_test_common.hh>
#include <hip_test_checkers.hh>
#ifdef __linux__
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <semaphore.h>
#include <unistd.h>
#define NUM_ELMTS 1024
#define NUM_THREADS 10
typedef struct mem_handle {
int device;
hipIpcMemHandle_t memHandle;
bool IfTestPassed;
} hip_ipc_t;
// This testcase verifies the hipIpcMemAccess APIs as follows
// The following program spawns a child process and does the following
// Parent iterate through each device, create memory -- create hipIpcMemhandle
// stores the mem handle in mmaped memory, release the child using sem_post()
// and wait for child to release itself(parent process)
// child process:
// Child process get the ipc mem handle using hipIpcOpenMemHandle
// Iterate through all the available gpus and do Device to Device copies
// and check for data consistencies and close the hipIpcCloseMemHandle
// release the parent and wait for parent to release itself(child)
TEST_CASE("Unit_hipIpcMemAccess_Semaphores") {
hip_ipc_t *shrd_mem = NULL;
pid_t pid;
size_t N = 1024;
size_t Nbytes = N * sizeof(int);
int *A_d{nullptr}, *B_d{nullptr}, *C_d{nullptr};
int *A_h{nullptr}, *C_h{nullptr};
sem_t *sem_ob1{nullptr}, *sem_ob2{nullptr};
int Num_devices = 0, CanAccessPeer = 0;
std::string cmd_line = "rm -rf /dev/shm/sem.my-sem-object*";
int res = system(cmd_line.c_str());
REQUIRE(res != -1);
sem_ob1 = sem_open("/my-sem-object1", O_CREAT|O_EXCL, 0660, 0);
sem_ob2 = sem_open("/my-sem-object2", O_CREAT|O_EXCL, 0660, 0);
REQUIRE(sem_ob1 != SEM_FAILED);
REQUIRE(sem_ob2 != SEM_FAILED);
shrd_mem = reinterpret_cast<hip_ipc_t *>(mmap(NULL, sizeof(hip_ipc_t),
PROT_READ | PROT_WRITE,
MAP_SHARED | MAP_ANONYMOUS,
0, 0));
REQUIRE(shrd_mem != NULL);
shrd_mem->IfTestPassed = true;
HipTest::initArrays<int>(nullptr, nullptr, nullptr,
&A_h, nullptr, &C_h, N, false);
pid = fork();
if (pid != 0) {
// Parent process
HIP_CHECK(hipGetDeviceCount(&Num_devices));
for (int i = 0; i < Num_devices; ++i) {
if (shrd_mem->IfTestPassed == true) {
HIP_CHECK(hipSetDevice(i));
HIP_CHECK(hipMalloc(&A_d, Nbytes));
HIP_CHECK(hipIpcGetMemHandle(reinterpret_cast<hipIpcMemHandle_t *>
(&shrd_mem->memHandle),
A_d));
HIP_CHECK(hipMemcpy(A_d, A_h, Nbytes, hipMemcpyHostToDevice));
shrd_mem->device = i;
if ((sem_post(sem_ob1)) == -1) {
// Need to use inline function to release resources.
shrd_mem->IfTestPassed = false;
WARN("sem_post() call failed in parent process.");
}
if ((sem_wait(sem_ob2)) == -1) {
shrd_mem->IfTestPassed = false;
WARN("sem_wait() call failed in parent process.");
}
HIP_CHECK(hipFree(A_d));
}
}
} else {
// Child process
HIP_CHECK(hipGetDeviceCount(&Num_devices));
for (int j = 0; j < Num_devices; ++j) {
HIP_CHECK(hipSetDevice(j));
if ((sem_wait(sem_ob1)) == -1) {
shrd_mem->IfTestPassed = false;
WARN("sem_wait() call failed in child process.");
if ((sem_post(sem_ob2)) == -1) {
shrd_mem->IfTestPassed = false;
WARN("sem_post() call on sem_ob2 failed");
exit(1);
}
}
for (int i = 0; i < Num_devices; ++i) {
HIP_CHECK(hipSetDevice(i));
HIP_CHECK(hipDeviceCanAccessPeer(&CanAccessPeer, i, shrd_mem->device));
if (CanAccessPeer == 1) {
HIP_CHECK(hipMalloc(&C_d, Nbytes));
HIP_CHECK(hipIpcOpenMemHandle(reinterpret_cast<void **>(&B_d),
shrd_mem->memHandle,
hipIpcMemLazyEnablePeerAccess));
HIP_CHECK(hipMemcpy(C_d, B_d, Nbytes, hipMemcpyDeviceToDevice));
HIP_CHECK(hipMemcpy(C_h, C_d, Nbytes, hipMemcpyDeviceToHost));
HipTest::checkTest<int>(A_h, C_h, N);
memset(reinterpret_cast<void*>(C_h), 0, Nbytes);
// Checking if the data obtained from Ipc shared memory is consistent
HIP_CHECK(hipMemcpy(C_h, B_d, Nbytes, hipMemcpyDeviceToHost));
HipTest::checkTest<int>(A_h, C_h, N);
HIP_CHECK(hipIpcCloseMemHandle(reinterpret_cast<void*>(B_d)));
HIP_CHECK(hipFree(C_d));
}
}
if ((sem_post(sem_ob2)) == -1) {
shrd_mem->IfTestPassed = false;
WARN("sem_post() call on sem_ob2 failed");
exit(1);
}
}
exit(0);
}
if ((sem_unlink("/my-sem-object1")) == -1) {
WARN("sem_unlink() call on /my-sem-object1 failed");
}
if ((sem_unlink("/my-sem-object2")) == -1) {
WARN("sem_unlink() call on /my-sem-object2 failed");
}
int rFlag = 0;
waitpid(pid, &rFlag, 0);
REQUIRE(shrd_mem->IfTestPassed == true);
}
TEST_CASE("Unit_hipIpcMemAccess_ParameterValidation") {
hipIpcMemHandle_t MemHandle;
hipIpcMemHandle_t MemHandleUninit;
void *Ad{}, *Ad2{};
hipError_t ret;
HIP_CHECK(hipMalloc(&Ad, 1024));
#if HT_AMD
// Test is disabled for nvidia as api resulting in seg fault.
SECTION("Get mem handle with handle as nullptr") {
ret = hipIpcGetMemHandle(nullptr, Ad);
REQUIRE(ret == hipErrorInvalidValue);
}
#endif
SECTION("Get mem handle with devptr as nullptr") {
ret = hipIpcGetMemHandle(&MemHandle, nullptr);
REQUIRE(ret == hipErrorInvalidValue);
}
SECTION("Get mem handle with handle/devptr as nullptr") {
ret = hipIpcGetMemHandle(nullptr, nullptr);
REQUIRE(ret == hipErrorInvalidValue);
}
SECTION("Get mem handle with valid devptr") {
ret = hipIpcGetMemHandle(&MemHandle, Ad);
REQUIRE(ret == hipSuccess);
}
SECTION("Open mem handle with devptr as nullptr") {
ret = hipIpcOpenMemHandle(nullptr, MemHandle,
hipIpcMemLazyEnablePeerAccess);
REQUIRE(ret == hipErrorInvalidValue);
}
SECTION("Open mem handle with handle as un-initialized") {
ret = hipIpcOpenMemHandle(&Ad2, MemHandleUninit,
hipIpcMemLazyEnablePeerAccess);
REQUIRE((ret == hipErrorInvalidValue || ret == hipErrorInvalidDevicePointer));
}
#if HT_AMD
// Test is disabled for nvidia as api not returning expected value.
SECTION("Open mem handle with flags as random value") {
constexpr unsigned int flags = 123;
HIP_CHECK(hipIpcGetMemHandle(&MemHandle, Ad));
ret = hipIpcOpenMemHandle(&Ad2, MemHandle, flags);
REQUIRE(ret == hipErrorInvalidValue);
}
#endif
SECTION("Close mem handle with devptr(nullptr)") {
ret = hipIpcCloseMemHandle(nullptr);
REQUIRE(ret == hipErrorInvalidValue);
}
HIP_CHECK(hipFree(Ad));
}
#endif
<|endoftext|> |
<commit_before>// -*- Mode:C++ -*-
/**************************************************************************************************/
/* */
/* Copyright (C) 2016 University of Hull */
/* */
/**************************************************************************************************/
/* */
/* module : hugh/support/test/trace.cpp */
/* project : */
/* description: */
/* */
/**************************************************************************************************/
// includes, system
// #include <>
// includes, project
// #include <>
#define HUGH_USE_TRACE
// #undef HUGH_USE_TRACE
#include <hugh/support/trace.hpp>
// internal unnamed namespace
namespace {
// types, internal (class, enum, struct, union, typedef)
struct init_test_base {
virtual ~init_test_base()
{
TRACE("<unnamed>::init_test_base::~init_test_base");
}
virtual void method()
{
TRACE("<unnamed>::init_test_base::method");
}
protected:
explicit init_test_base()
{
TRACE("<unnamed>::init_test_base::init_test_base");
}
};
struct static_init_test : public init_test_base {
static_init_test()
: init_test_base()
{
TRACE("<unnamed>::static_init_test::static_init_test");
}
virtual ~static_init_test()
{
TRACE("<unnamed>::static_init_test::~static_init_test");
}
} static_init_test_default_instance;
struct dynamic_init_test : public init_test_base {
dynamic_init_test()
: init_test_base()
{
TRACE("<unnamed>::dynamic_init_test::dynamic_init_test");
}
virtual ~dynamic_init_test()
{
TRACE("<unnamed>::dynamic_init_test::~dynamic_init_test");
}
virtual void method()
{
TRACE("<unnamed>::dynamic_init_test::method");
init_test_base::method();
}
};
// variables, internal
// functions, internal
void
test_func()
{
TRACE("<unnamed>::test_func");
{
TRACE("<unnamed>::test_func: scope");
static_init_test static_init_test_instance;
dynamic_init_test dynamic_init_test_instance;
}
}
} // namespace {
// functions, exported
#define BOOST_TEST_MAIN
#include <boost/test/unit_test.hpp>
BOOST_AUTO_TEST_CASE(test_hugh_support_trace)
{
TRACE_FUNC;
dynamic_init_test dynamic_init_test_instance;
test_func();
dynamic_init_test_instance.method();
BOOST_CHECK(true);
}
<commit_msg>added: support::trace::prefix test<commit_after>// -*- Mode:C++ -*-
/**************************************************************************************************/
/* */
/* Copyright (C) 2016 University of Hull */
/* */
/**************************************************************************************************/
/* */
/* module : hugh/support/test/trace.cpp */
/* project : */
/* description: */
/* */
/**************************************************************************************************/
// includes, system
#include <sstream> // std::ostringstream
// includes, project
// #include <>
#define HUGH_USE_TRACE
// #undef HUGH_USE_TRACE
#include <hugh/support/trace.hpp>
// internal unnamed namespace
namespace {
// types, internal (class, enum, struct, union, typedef)
struct init_test_base {
virtual ~init_test_base()
{
TRACE("<unnamed>::init_test_base::~init_test_base");
}
virtual void method()
{
TRACE("<unnamed>::init_test_base::method");
}
protected:
explicit init_test_base()
{
TRACE("<unnamed>::init_test_base::init_test_base");
}
};
struct static_init_test : public init_test_base {
static_init_test()
: init_test_base()
{
TRACE("<unnamed>::static_init_test::static_init_test");
}
virtual ~static_init_test()
{
TRACE("<unnamed>::static_init_test::~static_init_test");
}
} static_init_test_default_instance;
struct dynamic_init_test : public init_test_base {
dynamic_init_test()
: init_test_base()
{
TRACE("<unnamed>::dynamic_init_test::dynamic_init_test");
}
virtual ~dynamic_init_test()
{
TRACE("<unnamed>::dynamic_init_test::~dynamic_init_test");
}
virtual void method()
{
TRACE("<unnamed>::dynamic_init_test::method");
init_test_base::method();
}
};
// variables, internal
// functions, internal
void
test_func()
{
TRACE("<unnamed>::test_func");
{
TRACE("<unnamed>::test_func: scope");
static_init_test static_init_test_instance;
dynamic_init_test dynamic_init_test_instance;
}
}
} // namespace {
// functions, exported
#define BOOST_TEST_MAIN
#include <boost/test/unit_test.hpp>
BOOST_AUTO_TEST_CASE(test_hugh_support_trace)
{
TRACE_FUNC;
dynamic_init_test dynamic_init_test_instance;
test_func();
dynamic_init_test_instance.method();
BOOST_CHECK(true);
}
BOOST_AUTO_TEST_CASE(test_hugh_support_trace_prefix)
{
TRACE_FUNC;
std::string const pfx1(hugh::support::trace::prefix());
std::string const pfx2(hugh::support::trace::prefix());
BOOST_CHECK(pfx1 != pfx2);
std::ostringstream ostr;
ostr << pfx1 << ".\n" << pfx2 << '.';
BOOST_TEST_MESSAGE(ostr.str());
}
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <opencv2/calib3d/claib3d.hpp>
#include <iostream>
#include <vector>
#include <string>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/nonfree/features2d.hpp>
using namespace std;
using namespace cv;
int main(int argc,char **argv)
{
Mat image1;
Mat image2;
image1=cv::imread(argv[1],1); //read the input images
image2=cv::imread(argv[2],1);
vector<cv::KeyPoint> kp1;
vector<cv::KeyPoint> kp2;
std::vector<Point2f> obj_corners(4);
///////////get the obj_scene corners////////
obj_corners[0]=(cvPoint(0,0));
obj_corners[1]=(cvPoint(image1.cols,0));
obj_corners[2]=(cvPoint(image1.cols,image1.rows));
obj_corners[3]=(cvPoint(0,image1.rows));
Mat des1, des2;
FastFeatureDetector detector(500); //get the keypoints
detector.detect(image1,kp1);
detector.detect(image2,kp2);
SurfDescriptorExtractor extractor; //get the descriptors
extractor.compute(image1,kp1,des1);
extractor.compute(image2,kp2,des2);
Ptr<DescriptorMatcher> matcher = DescriptorMatcher::create("BruteForce"); //define matcher object
std::vector< std::vector< DMatch > > matches; //define DMatch object to store matches
std::vector< std::vector< DMatch > > matches1; //define DMatch object to store matches
matcher->knnMatch(des1,des2, matches,2);
matcher->knnMatch(des2,des1, matches1,2);
std::vector<DMatch> goodMatches;
std::vector<DMatch> goodMatches1;
for(int i=0;i<des1.rows;i++) //ratio test to remove poor matches
{
const DMatch &m = matches[i][0];
const DMatch &n = matches[i][1];
if(m.distance<0.75*n.distance)
goodMatches.push_back(m);
else if(n.distance<0.75*m.distance)
goodMatches.push_back(n);
}
for(int i=0;i<des2.rows;i++) //ratio test to remove poor matches
{
const DMatch &m = matches1[i][0];
const DMatch &n = matches1[i][1];
if(m.distance<0.75*n.distance)
goodMatches1.push_back(m);
else if(n.distance<0.75*m.distance)
goodMatches1.push_back(n);
}
//std::vector<cv::DMatch> symMatches;
/* for (vector<DMatch>::const_iterator matchIterator1= goodMatches.begin();matchIterator1!= goodMatches.end(); ++matchIterator1)
{
for (vector<DMatch>::const_iterator matchIterator2= goodMatches1.begin();matchIterator2!= goodMatches1.end();++matchIterator2)
{
if ((*matchIterator1).queryIdx ==(*matchIterator2).trainIdx &&(*matchIterator2).queryIdx ==(*matchIterator1).trainIdx)
{
symMatches.push_back(DMatch((*matchIterator1).queryIdx,(*matchIterator1).trainIdx,(*matchIterator1).distance));
break;
}
}
}*/
Mat image3;
std::vector<Point2f> obj;
std::vector<Point2f> scene;
std::vector<Point2f> scene_corners(4);
//drawMatches(image1,kp1,image2,kp2,goodMatches,image3,2);
if(goodMatches.size()>=4)
{
for(int i=0;i<goodMatches.size();i++)
{
obj.push_back(kp1[good_matches[i].queryIdx].pt);
scene.push_back(kp2[good_matches[i].trainIdx].pt);
}
H=findHomography(obj,scene,CV_RANSAC);
perspectiveTransform(obj_corners,scene_corners,H)
line(image2,scene_corners[0],scene_corners[1],Scalar(0,255,0),4);
line(image2,scene_corners[1],scene_corners[2],Scalar(0,255,0),4);
line(image2,scene_corners[2],scene_corners[3],Scalar(0,255,0),4);
line(image2,scene_corners[3],scene_corners[0],Scalar(0,255,0),4);
}
cv::namedWindow("image",CV_WINDOW_NORMAL);
cv::imshow("image",image2);
cv::waitKey(0);
return 0;
}
<commit_msg>changed parameters<commit_after>#include <stdio.h>
#include <opencv2/calib3d/claib3d.hpp>
#include <iostream>
#include <vector>
#include <string>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/nonfree/features2d.hpp>
using namespace std;
using namespace cv;
int main(int argc,char **argv)
{
Mat image1;
Mat image2;
image1=cv::imread(argv[1],1); //read the input images
image2=cv::imread(argv[2],1);
vector<cv::KeyPoint> kp1;
vector<cv::KeyPoint> kp2;
std::vector<Point2f> obj_corners(4);
///////////get the obj_scene corners////////
obj_corners[0]=(cvPoint(0,0));
obj_corners[1]=(cvPoint(image1.cols,0));
obj_corners[2]=(cvPoint(image1.cols,image1.rows));
obj_corners[3]=(cvPoint(0,image1.rows));
Mat des1, des2;
FastFeatureDetector detector(130; //get the keypoints
detector.detect(image1,kp1);
detector.detect(image2,kp2);
SurfDescriptorExtractor extractor; //get the descriptors
extractor.compute(image1,kp1,des1);
extractor.compute(image2,kp2,des2);
Ptr<DescriptorMatcher> matcher = DescriptorMatcher::create("BruteForce"); //define matcher object
std::vector< std::vector< DMatch > > matches; //define DMatch object to store matches
std::vector< std::vector< DMatch > > matches1; //define DMatch object to store matches
matcher->knnMatch(des1,des2, matches,2);
matcher->knnMatch(des2,des1, matches1,2);
std::vector<DMatch> goodMatches;
std::vector<DMatch> goodMatches1;
for(int i=0;i<des1.rows;i++) //ratio test to remove poor matches
{
const DMatch &m = matches[i][0];
const DMatch &n = matches[i][1];
if(m.distance<0.75*n.distance)
goodMatches.push_back(m);
else if(n.distance<0.75*m.distance)
goodMatches.push_back(n);
}
for(int i=0;i<des2.rows;i++) //ratio test to remove poor matches
{
const DMatch &m = matches1[i][0];
const DMatch &n = matches1[i][1];
if(m.distance<0.75*n.distance)
goodMatches1.push_back(m);
else if(n.distance<0.75*m.distance)
goodMatches1.push_back(n);
}
//std::vector<cv::DMatch> symMatches;
/* for (vector<DMatch>::const_iterator matchIterator1= goodMatches.begin();matchIterator1!= goodMatches.end(); ++matchIterator1)
{
for (vector<DMatch>::const_iterator matchIterator2= goodMatches1.begin();matchIterator2!= goodMatches1.end();++matchIterator2)
{
if ((*matchIterator1).queryIdx ==(*matchIterator2).trainIdx &&(*matchIterator2).queryIdx ==(*matchIterator1).trainIdx)
{
symMatches.push_back(DMatch((*matchIterator1).queryIdx,(*matchIterator1).trainIdx,(*matchIterator1).distance));
break;
}
}
}*/
Mat image3;
std::vector<Point2f> obj;
std::vector<Point2f> scene;
std::vector<Point2f> scene_corners(4);
//drawMatches(image1,kp1,image2,kp2,goodMatches,image3,2);
if(goodMatches.size()>=4)
{
for(int i=0;i<goodMatches.size();i++)
{
obj.push_back(kp1[good_matches[i].queryIdx].pt);
scene.push_back(kp2[good_matches[i].trainIdx].pt);
}
H=findHomography(obj,scene,CV_RANSAC);
perspectiveTransform(obj_corners,scene_corners,H)
line(image2,scene_corners[0],scene_corners[1],Scalar(0,255,0),4);
line(image2,scene_corners[1],scene_corners[2],Scalar(0,255,0),4);
line(image2,scene_corners[2],scene_corners[3],Scalar(0,255,0),4);
line(image2,scene_corners[3],scene_corners[0],Scalar(0,255,0),4);
}
cv::namedWindow("image",CV_WINDOW_NORMAL);
cv::imshow("image",image2);
cv::waitKey(0);
return 0;
}
<|endoftext|> |
<commit_before>//============================================================================
// Name : Application.cpp
// Author : Rian van Gijlswijk
// Description : Main application file.
//============================================================================
#include "Application.h"
#include <string>
#include <regex>
#include <boost/log/core.hpp>
#include <boost/log/trivial.hpp>
#include <boost/log/expressions.hpp>
#include <boost/log/utility/setup/file.hpp>
#include "Timer.cpp"
#include "CommandLine.h"
#include "../math/Matrix3d.h"
#include "../exporter/JsonExporter.h"
#include "../exporter/MatlabExporter.h"
#include "../radio/AntennaFactory.h"
namespace raytracer {
namespace core {
using namespace std;
using namespace tracer;
using namespace exporter;
using namespace math;
using namespace threading;
using namespace radio;
boost::mutex datasetMutex;
boost::mutex tracingIncMutex;
boost::threadpool::pool tp;
void Application::init(int argc, char * argv[]) {
BOOST_LOG_TRIVIAL(debug) << "Init application";
AntennaFactory::printMappedTypes();
parseCommandLineArgs(argc, argv);
start();
run();
}
void Application::parseCommandLineArgs(int argc, char * argv[]) {
BOOST_LOG_TRIVIAL(debug) << "parseCommandLineArgs";
for (int i = 0; i < argc; i++) {
if (strcmp(argv[i], "-h") == 0) {
std::cout << "Ionospheric Ray Tracer\n\n"
<< "Synopsis:\n"
<< "\tirt [-opts] scenarioConfig\n\n"
<< "Description: \n"
<< "\tPerform ionospheric ray tracing on a celestial object described by the _celestialConfig json file. "
<< "If no config file is supplied, use a default scenario.\n\n"
<< "Options:\n"
<< "\t-c | --config\t Application config file\n"
<< "\t-i | --iterations\t The number of consecutive times every ray option should be run.\n"
<< "\t-h | --help\t This help.\n"
<< "\t-o | --output\t Path where output file should be stored.\n"
<< "\t-p | --parallelism\t Multithreading indicator.\n"
<< "\t-v | --verbose\t Verbose, display log output\n"
<< "\t-vv \t\t Very verbose, display log and debug output\n";
std::exit(0);
} else if (strcmp(argv[i], "-s") == 0 || strcmp(argv[i], "--scenario") == 0) {
_celestialConfigFile = argv[i+1];
} else if (strcmp(argv[i], "-c") == 0 || strcmp(argv[i], "--config") == 0) {
_applicationConfigFile = argv[i+1];
} else if (strcmp(argv[i], "-p") == 0 || strcmp(argv[i], "--parallelism") == 0) {
_parallelism = atoi(argv[i+1]);
} else if (strcmp(argv[i], "-o") == 0 || strcmp(argv[i], "--output") == 0) {
_outputFile = argv[i+1];
} else if (strcmp(argv[i], "-i") == 0 || strcmp(argv[i], "--iterations") == 0) {
_iterations = atoi(argv[i+1]);
} else if (strcmp(argv[i], "-v") == 0 || strcmp(argv[i], "--verbose") == 0) {
_verbosity = boost::log::trivial::info;
} else if (strcmp(argv[i], "-vv") == 0) {
_verbosity = boost::log::trivial::debug;
} else if (strcmp(argv[i], "-fmin") == 0) {
_fmin = atoi(argv[i+1]);
} else if (strcmp(argv[i], "-fstep") == 0) {
_fstep = atoi(argv[i+1]);
} else if (strcmp(argv[i], "-fmax") == 0) {
_fmax = atoi(argv[i+1]);
}
}
// load scenario config file. Must be given.
if (!std::regex_match (argv[argc-1], std::regex("[A-Za-z0-9_/]+\.json") )) {
BOOST_LOG_TRIVIAL(fatal) << "No scenario file given! Exiting.";
std::exit(0);
}
_celestialConfigFile = argv[argc-1];
}
void Application::start() {
BOOST_LOG_TRIVIAL(debug) << "Start application";
_isRunning = true;
_applicationConfig = Config(_applicationConfigFile);
_celestialConfig = Config(_celestialConfigFile);
if (_parallelism < 1) {
_parallelism = _applicationConfig.getInt("parallelism");
}
if (_iterations < 1) {
_iterations = _applicationConfig.getInt("iterations");
}
if (_fmin < 1) {
_fmin = _applicationConfig.getObject("frequencies")["min"].asInt();
}
if (_fstep < 1) {
_fstep = _applicationConfig.getObject("frequencies")["step"].asInt();
}
if (_fmax < 1) {
_fmax = _applicationConfig.getObject("frequencies")["max"].asInt();
}
// boost::log::add_file_log("log/sample.log");
boost::log::core::get()->set_filter(
boost::log::trivial::severity >= _verbosity);
tp = boost::threadpool::pool(_parallelism);
BOOST_LOG_TRIVIAL(debug) << "applicationConfig: " << _applicationConfigFile << endl
<< _applicationConfig << endl
<< "celestialConfig:" << _celestialConfigFile << endl
<< _celestialConfig;
_me = new MatlabExporter(_outputFile);
}
void Application::run() {
BOOST_LOG_TRIVIAL(debug) << "Run application";
Timer tmr;
int radius = _celestialConfig.getInt("radius");
BOOST_LOG_TRIVIAL(info) << "Parallelism is " << _applicationConfig.getInt("parallelism");
if (_verbosity > boost::log::trivial::info) {
std::ostringstream stringStream;
stringStream << "Parallelism is " << _applicationConfig.getInt("parallelism");
CommandLine::getInstance().addToHeader(stringStream.str().c_str());
}
BOOST_LOG_TRIVIAL(info) << _applicationConfig.getInt("iterations") << " iterations";
// load config values
double SZAmin = _applicationConfig.getObject("SZA")["min"].asDouble();
double SZAstep = _applicationConfig.getObject("SZA")["step"].asDouble();
double SZAmax = _applicationConfig.getObject("SZA")["max"].asDouble();
double azimuthMin = _applicationConfig.getObject("azimuth")["min"].asDouble();
double azimuthStep = _applicationConfig.getObject("azimuth")["step"].asDouble();
double azimuthMax = _applicationConfig.getObject("azimuth")["max"].asDouble();
const Json::Value beacons = _applicationConfig.getArray("beacons");
// trace a ray
int rayCounter = 0;
for (int iteration = 0; iteration < _applicationConfig.getInt("iterations"); iteration++) {
BOOST_LOG_TRIVIAL(info) << "Iteration " << (iteration+1) << " of " << _applicationConfig.getInt("iterations");
createScene();
BOOST_LOG_TRIVIAL(info) << "Simulating " << beacons.size() << " beacons";
BOOST_LOG_TRIVIAL(info) << "Scanning frequencies " << _fmin << " Hz to " << _fmax << "Hz with steps of " << _fstep << "Hz";
BOOST_LOG_TRIVIAL(info) << "Scanning SZA " << SZAmin << " deg to " << SZAmax << " deg with steps of " << SZAstep << " deg";
BOOST_LOG_TRIVIAL(info) << "Scanning azimuth " << azimuthMin << " deg to " << azimuthMax << " deg with steps of " << azimuthStep << " deg";
if (_verbosity > boost::log::trivial::info) {
std::ostringstream stringStream;
stringStream << "Simulating " << beacons.size() << " beacons\n" << "Scanning frequencies " << _fmin << " Hz to " << _fmax
<< "Hz with steps of " << _fstep << "Hz\n" << "Scanning SZA " << SZAmin << " deg to "
<< SZAmax << " deg with steps of " << SZAstep << " deg\n"
<< "Scanning azimuth " << azimuthMin << " deg to " << azimuthMax << " deg with steps of " << azimuthStep << " deg";
CommandLine::getInstance().addToHeader(stringStream.str().c_str());
}
for(int b = 0; b < beacons.size(); b++) {
double latitudeOffset = beacons[b].get("latitudeOffset", "").asDouble() * Constants::PI / 180.0;
double longitudeOffset = beacons[b].get("longitudeOffset", "").asDouble() * Constants::PI / 180.0;
const Json::Value antenna = beacons[b].get("antenna", "");
IAntenna* ant = AntennaFactory::createInstance(antenna.get("type", "").asString());
ant->setConfig(antenna);
Matrix3d latitude = Matrix3d::createRotationMatrix(latitudeOffset, Matrix3d::ROTATION_X);
Matrix3d longitude = Matrix3d::createRotationMatrix(longitudeOffset, Matrix3d::ROTATION_Z);
Matrix3d rotationMatrix = latitude * longitude;
Vector3d startPosition = rotationMatrix * Vector3d(0, (radius+2), 0);
BOOST_LOG_TRIVIAL(debug) << startPosition;
for(double azimuth = azimuthMin; azimuth <= azimuthMax; azimuth += azimuthStep) {
Matrix3d azimuthRotation = Matrix3d::createRotationMatrix(azimuth * Constants::PI / 180, Matrix3d::ROTATION_Y);
for (int freq = _fmin; freq <= _fmax; freq += _fstep) {
for (double elevation = SZAmin; elevation <= SZAmax; elevation += SZAstep) {
Ray r;
r.rayNumber = ++rayCounter;
r.frequency = (double)freq;
r.signalPower = ant->getSignalPowerAt(azimuth, elevation);
r.o = startPosition;
r.originalAngle = elevation * Constants::PI / 180.0;
r.originBeaconId = b+1;
r.originalAzimuth = azimuth * Constants::PI / 180.0;
Vector3d direction = Vector3d(cos(Constants::PI/2.0 - r.originalAngle),
sin(Constants::PI/2.0 - r.originalAngle),
0).norm();
r.d = azimuthRotation * direction;
Worker w;
w.schedule(&tp, r);
numWorkers++;
}
}
}
}
BOOST_LOG_TRIVIAL(info) << numWorkers << " workers queued";
if (_verbosity > boost::log::trivial::info) {
std::ostringstream stringStream;
stringStream << numWorkers << " workers queued";
CommandLine::getInstance().addToHeader(stringStream.str().c_str());
}
tp.wait();
flushScene();
}
stop();
double t = tmr.elapsed();
double tracingsPerSec = _numTracings / t;
char buffer[80];
CommandLine::getInstance().updateBody("\n");
sprintf(buffer, "Elapsed: %5.2f sec. %d tracings done. %5.2f tracings/sec",
t, _numTracings, tracingsPerSec);
BOOST_LOG_TRIVIAL(warning) << buffer;
//CsvExporter ce;
//ce.dump("Debug/data.csv", dataSet);
_me->dump(_outputFile, dataSet);
BOOST_LOG_TRIVIAL(warning) << "Results stored at: " << _outputFile;
}
void Application::stop() {
_isRunning = false;
}
/**
* Add geometries to the scenemanager
*/
void Application::createScene() {
_scm = SceneManager();
_scm.loadStaticEnvironment();
int numSceneObjectsCreated = 0;
double R = _celestialConfig.getInt("radius");
double angularStepSize = _applicationConfig.getDouble("angularStepSize");
for (double latitude = 0 * Constants::PI; latitude <= 0.3 * Constants::PI; latitude += angularStepSize) {
for (double longitude = 0 * Constants::PI; longitude <= 2 * Constants::PI; longitude += angularStepSize) {
Matrix3d latitudeM = Matrix3d::createRotationMatrix(latitude, Matrix3d::ROTATION_X);
Matrix3d longitudeM = Matrix3d::createRotationMatrix(longitude, Matrix3d::ROTATION_Z);
Matrix3d rotationMatrix = latitudeM * longitudeM;
Vector3d startPosition = rotationMatrix * Vector3d(0, R, 0);
Plane3d mesh = Plane3d(startPosition.norm(), startPosition);
mesh.size = angularStepSize * R;
Terrain* tr = new Terrain(mesh);
numSceneObjectsCreated++;
_scm.addToScene(tr);
}
}
if (numSceneObjectsCreated > 1e9)
BOOST_LOG_TRIVIAL(info) << setprecision(3) << numSceneObjectsCreated/1.0e9 << "G scene objects created";
else if (numSceneObjectsCreated > 1e6)
BOOST_LOG_TRIVIAL(info) << setprecision(3) << numSceneObjectsCreated/1.0e6 << "M scene objects created";
else if (numSceneObjectsCreated > 1e3)
BOOST_LOG_TRIVIAL(info) << setprecision(3) << numSceneObjectsCreated/1.0e3 << "K scene objects created";
else
BOOST_LOG_TRIVIAL(info) << setprecision(3) << numSceneObjectsCreated << " scene objects created";
}
/**
* Flush the scene by clearing the list of scene objects
*/
void Application::flushScene() {
_scm.removeAllFromScene();
}
void Application::addToDataset(Data dat) {
datasetMutex.lock();
dataSet.push_back(dat);
if (dataSet.size() > Data::MAX_DATASET_SIZE) {
_me->dump(_outputFile, dataSet);
dataSet.clear();
}
datasetMutex.unlock();
}
void Application::incrementTracing() {
tracingIncMutex.lock();
_numTracings++;
tracingIncMutex.unlock();
}
SceneManager Application::getSceneManager() {
return _scm;
}
Config Application::getApplicationConfig() {
return _applicationConfig;
}
Config Application::getCelestialConfig() {
return _celestialConfig;
}
void Application::setCelestialConfig(Config conf) {
_celestialConfig = conf;
}
void Application::setApplicationConfig(Config conf) {
_applicationConfig = conf;
}
int Application::getVerbosity() {
return _verbosity;
}
} /* namespace core */
} /* namespace raytracer */
<commit_msg>Temporarily disabled automatic antenna loading to solve issues with manual compilation<commit_after>//============================================================================
// Name : Application.cpp
// Author : Rian van Gijlswijk
// Description : Main application file.
//============================================================================
#include "Application.h"
#include <string>
#include <regex>
#include <boost/log/core.hpp>
#include <boost/log/trivial.hpp>
#include <boost/log/expressions.hpp>
#include <boost/log/utility/setup/file.hpp>
#include "Timer.cpp"
#include "CommandLine.h"
#include "../math/Matrix3d.h"
#include "../exporter/JsonExporter.h"
#include "../exporter/MatlabExporter.h"
#include "../radio/AntennaFactory.h"
#include "../radio/IsotropicAntenna.h"
namespace raytracer {
namespace core {
using namespace std;
using namespace tracer;
using namespace exporter;
using namespace math;
using namespace threading;
using namespace radio;
boost::mutex datasetMutex;
boost::mutex tracingIncMutex;
boost::threadpool::pool tp;
void Application::init(int argc, char * argv[]) {
BOOST_LOG_TRIVIAL(debug) << "Init application";
AntennaFactory::printMappedTypes();
parseCommandLineArgs(argc, argv);
start();
run();
}
void Application::parseCommandLineArgs(int argc, char * argv[]) {
BOOST_LOG_TRIVIAL(debug) << "parseCommandLineArgs";
for (int i = 0; i < argc; i++) {
if (strcmp(argv[i], "-h") == 0) {
std::cout << "Ionospheric Ray Tracer\n\n"
<< "Synopsis:\n"
<< "\tirt [-opts] scenarioConfig\n\n"
<< "Description: \n"
<< "\tPerform ionospheric ray tracing on a celestial object described by the _celestialConfig json file. "
<< "If no config file is supplied, use a default scenario.\n\n"
<< "Options:\n"
<< "\t-c | --config\t Application config file\n"
<< "\t-i | --iterations\t The number of consecutive times every ray option should be run.\n"
<< "\t-h | --help\t This help.\n"
<< "\t-o | --output\t Path where output file should be stored.\n"
<< "\t-p | --parallelism\t Multithreading indicator.\n"
<< "\t-v | --verbose\t Verbose, display log output\n"
<< "\t-vv \t\t Very verbose, display log and debug output\n";
std::exit(0);
} else if (strcmp(argv[i], "-s") == 0 || strcmp(argv[i], "--scenario") == 0) {
_celestialConfigFile = argv[i+1];
} else if (strcmp(argv[i], "-c") == 0 || strcmp(argv[i], "--config") == 0) {
_applicationConfigFile = argv[i+1];
} else if (strcmp(argv[i], "-p") == 0 || strcmp(argv[i], "--parallelism") == 0) {
_parallelism = atoi(argv[i+1]);
} else if (strcmp(argv[i], "-o") == 0 || strcmp(argv[i], "--output") == 0) {
_outputFile = argv[i+1];
} else if (strcmp(argv[i], "-i") == 0 || strcmp(argv[i], "--iterations") == 0) {
_iterations = atoi(argv[i+1]);
} else if (strcmp(argv[i], "-v") == 0 || strcmp(argv[i], "--verbose") == 0) {
_verbosity = boost::log::trivial::info;
} else if (strcmp(argv[i], "-vv") == 0) {
_verbosity = boost::log::trivial::debug;
} else if (strcmp(argv[i], "-fmin") == 0) {
_fmin = atoi(argv[i+1]);
} else if (strcmp(argv[i], "-fstep") == 0) {
_fstep = atoi(argv[i+1]);
} else if (strcmp(argv[i], "-fmax") == 0) {
_fmax = atoi(argv[i+1]);
}
}
// load scenario config file. Must be given.
if (!std::regex_match (argv[argc-1], std::regex("[A-Za-z0-9_/]+\.json") )) {
BOOST_LOG_TRIVIAL(fatal) << "No scenario file given! Exiting.";
std::exit(0);
}
_celestialConfigFile = argv[argc-1];
}
void Application::start() {
BOOST_LOG_TRIVIAL(debug) << "Start application";
_isRunning = true;
_applicationConfig = Config(_applicationConfigFile);
_celestialConfig = Config(_celestialConfigFile);
if (_parallelism < 1) {
_parallelism = _applicationConfig.getInt("parallelism");
}
if (_iterations < 1) {
_iterations = _applicationConfig.getInt("iterations");
}
if (_fmin < 1) {
_fmin = _applicationConfig.getObject("frequencies")["min"].asInt();
}
if (_fstep < 1) {
_fstep = _applicationConfig.getObject("frequencies")["step"].asInt();
}
if (_fmax < 1) {
_fmax = _applicationConfig.getObject("frequencies")["max"].asInt();
}
// boost::log::add_file_log("log/sample.log");
boost::log::core::get()->set_filter(
boost::log::trivial::severity >= _verbosity);
tp = boost::threadpool::pool(_parallelism);
BOOST_LOG_TRIVIAL(debug) << "applicationConfig: " << _applicationConfigFile << endl
<< _applicationConfig << endl
<< "celestialConfig:" << _celestialConfigFile << endl
<< _celestialConfig;
_me = new MatlabExporter(_outputFile);
}
void Application::run() {
BOOST_LOG_TRIVIAL(debug) << "Run application";
Timer tmr;
int radius = _celestialConfig.getInt("radius");
BOOST_LOG_TRIVIAL(info) << "Parallelism is " << _applicationConfig.getInt("parallelism");
if (_verbosity > boost::log::trivial::info) {
std::ostringstream stringStream;
stringStream << "Parallelism is " << _applicationConfig.getInt("parallelism");
CommandLine::getInstance().addToHeader(stringStream.str().c_str());
}
BOOST_LOG_TRIVIAL(info) << _applicationConfig.getInt("iterations") << " iterations";
// load config values
double SZAmin = _applicationConfig.getObject("SZA")["min"].asDouble();
double SZAstep = _applicationConfig.getObject("SZA")["step"].asDouble();
double SZAmax = _applicationConfig.getObject("SZA")["max"].asDouble();
double azimuthMin = _applicationConfig.getObject("azimuth")["min"].asDouble();
double azimuthStep = _applicationConfig.getObject("azimuth")["step"].asDouble();
double azimuthMax = _applicationConfig.getObject("azimuth")["max"].asDouble();
const Json::Value beacons = _applicationConfig.getArray("beacons");
// trace a ray
int rayCounter = 0;
for (int iteration = 0; iteration < _applicationConfig.getInt("iterations"); iteration++) {
BOOST_LOG_TRIVIAL(info) << "Iteration " << (iteration+1) << " of " << _applicationConfig.getInt("iterations");
createScene();
BOOST_LOG_TRIVIAL(info) << "Simulating " << beacons.size() << " beacons";
BOOST_LOG_TRIVIAL(info) << "Scanning frequencies " << _fmin << " Hz to " << _fmax << "Hz with steps of " << _fstep << "Hz";
BOOST_LOG_TRIVIAL(info) << "Scanning SZA " << SZAmin << " deg to " << SZAmax << " deg with steps of " << SZAstep << " deg";
BOOST_LOG_TRIVIAL(info) << "Scanning azimuth " << azimuthMin << " deg to " << azimuthMax << " deg with steps of " << azimuthStep << " deg";
if (_verbosity > boost::log::trivial::info) {
std::ostringstream stringStream;
stringStream << "Simulating " << beacons.size() << " beacons\n" << "Scanning frequencies " << _fmin << " Hz to " << _fmax
<< "Hz with steps of " << _fstep << "Hz\n" << "Scanning SZA " << SZAmin << " deg to "
<< SZAmax << " deg with steps of " << SZAstep << " deg\n"
<< "Scanning azimuth " << azimuthMin << " deg to " << azimuthMax << " deg with steps of " << azimuthStep << " deg";
CommandLine::getInstance().addToHeader(stringStream.str().c_str());
}
for(int b = 0; b < beacons.size(); b++) {
double latitudeOffset = beacons[b].get("latitudeOffset", "").asDouble() * Constants::PI / 180.0;
double longitudeOffset = beacons[b].get("longitudeOffset", "").asDouble() * Constants::PI / 180.0;
const Json::Value antenna = beacons[b].get("antenna", "");
//IAntenna* ant = AntennaFactory::createInstance(antenna.get("type", "").asString());
IAntenna* ant = new IsotropicAntenna();
ant->setConfig(antenna);
Matrix3d latitude = Matrix3d::createRotationMatrix(latitudeOffset, Matrix3d::ROTATION_X);
Matrix3d longitude = Matrix3d::createRotationMatrix(longitudeOffset, Matrix3d::ROTATION_Z);
Matrix3d rotationMatrix = latitude * longitude;
Vector3d startPosition = rotationMatrix * Vector3d(0, (radius+2), 0);
BOOST_LOG_TRIVIAL(debug) << startPosition;
for(double azimuth = azimuthMin; azimuth <= azimuthMax; azimuth += azimuthStep) {
Matrix3d azimuthRotation = Matrix3d::createRotationMatrix(azimuth * Constants::PI / 180, Matrix3d::ROTATION_Y);
for (int freq = _fmin; freq <= _fmax; freq += _fstep) {
for (double elevation = SZAmin; elevation <= SZAmax; elevation += SZAstep) {
Ray r;
r.rayNumber = ++rayCounter;
r.frequency = (double)freq;
r.signalPower = ant->getSignalPowerAt(azimuth, elevation);
r.o = startPosition;
r.originalAngle = elevation * Constants::PI / 180.0;
r.originBeaconId = b+1;
r.originalAzimuth = azimuth * Constants::PI / 180.0;
Vector3d direction = Vector3d(cos(Constants::PI/2.0 - r.originalAngle),
sin(Constants::PI/2.0 - r.originalAngle),
0).norm();
r.d = azimuthRotation * direction;
Worker w;
w.schedule(&tp, r);
numWorkers++;
}
}
}
}
BOOST_LOG_TRIVIAL(info) << numWorkers << " workers queued";
if (_verbosity > boost::log::trivial::info) {
std::ostringstream stringStream;
stringStream << numWorkers << " workers queued";
CommandLine::getInstance().addToHeader(stringStream.str().c_str());
}
tp.wait();
flushScene();
}
stop();
double t = tmr.elapsed();
double tracingsPerSec = _numTracings / t;
char buffer[80];
CommandLine::getInstance().updateBody("\n");
sprintf(buffer, "Elapsed: %5.2f sec. %d tracings done. %5.2f tracings/sec",
t, _numTracings, tracingsPerSec);
BOOST_LOG_TRIVIAL(warning) << buffer;
//CsvExporter ce;
//ce.dump("Debug/data.csv", dataSet);
_me->dump(_outputFile, dataSet);
BOOST_LOG_TRIVIAL(warning) << "Results stored at: " << _outputFile;
}
void Application::stop() {
_isRunning = false;
}
/**
* Add geometries to the scenemanager
*/
void Application::createScene() {
_scm = SceneManager();
_scm.loadStaticEnvironment();
int numSceneObjectsCreated = 0;
double R = _celestialConfig.getInt("radius");
double angularStepSize = _applicationConfig.getDouble("angularStepSize");
for (double latitude = 0 * Constants::PI; latitude <= 0.3 * Constants::PI; latitude += angularStepSize) {
for (double longitude = 0 * Constants::PI; longitude <= 2 * Constants::PI; longitude += angularStepSize) {
Matrix3d latitudeM = Matrix3d::createRotationMatrix(latitude, Matrix3d::ROTATION_X);
Matrix3d longitudeM = Matrix3d::createRotationMatrix(longitude, Matrix3d::ROTATION_Z);
Matrix3d rotationMatrix = latitudeM * longitudeM;
Vector3d startPosition = rotationMatrix * Vector3d(0, R, 0);
Plane3d mesh = Plane3d(startPosition.norm(), startPosition);
mesh.size = angularStepSize * R;
Terrain* tr = new Terrain(mesh);
numSceneObjectsCreated++;
_scm.addToScene(tr);
}
}
if (numSceneObjectsCreated > 1e9)
BOOST_LOG_TRIVIAL(info) << setprecision(3) << numSceneObjectsCreated/1.0e9 << "G scene objects created";
else if (numSceneObjectsCreated > 1e6)
BOOST_LOG_TRIVIAL(info) << setprecision(3) << numSceneObjectsCreated/1.0e6 << "M scene objects created";
else if (numSceneObjectsCreated > 1e3)
BOOST_LOG_TRIVIAL(info) << setprecision(3) << numSceneObjectsCreated/1.0e3 << "K scene objects created";
else
BOOST_LOG_TRIVIAL(info) << setprecision(3) << numSceneObjectsCreated << " scene objects created";
}
/**
* Flush the scene by clearing the list of scene objects
*/
void Application::flushScene() {
_scm.removeAllFromScene();
}
void Application::addToDataset(Data dat) {
datasetMutex.lock();
dataSet.push_back(dat);
if (dataSet.size() > Data::MAX_DATASET_SIZE) {
_me->dump(_outputFile, dataSet);
dataSet.clear();
}
datasetMutex.unlock();
}
void Application::incrementTracing() {
tracingIncMutex.lock();
_numTracings++;
tracingIncMutex.unlock();
}
SceneManager Application::getSceneManager() {
return _scm;
}
Config Application::getApplicationConfig() {
return _applicationConfig;
}
Config Application::getCelestialConfig() {
return _celestialConfig;
}
void Application::setCelestialConfig(Config conf) {
_celestialConfig = conf;
}
void Application::setApplicationConfig(Config conf) {
_applicationConfig = conf;
}
int Application::getVerbosity() {
return _verbosity;
}
} /* namespace core */
} /* namespace raytracer */
<|endoftext|> |
<commit_before>// The libMesh Finite Element Library.
// Copyright (C) 2002-2016 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#include "libmesh/fe_compute_data.h"
#include "libmesh/equation_systems.h"
namespace libMesh
{
void FEComputeData::clear ()
{
this->shape.clear();
#if defined(LIBMESH_ENABLE_INFINITE_ELEMENTS) && !defined(LIBMESH_USE_COMPLEX_NUMBERS)
this->phase = 0.;
this->speed = 1.;
#endif
#if defined (LIBMESH_ENABLE_INFINITE_ELEMENTS) && defined(LIBMESH_USE_COMPLEX_NUMBERS)
//lets default speed and frequency to 1; 0 leads to troubles with the wavenumber.
this->speed = 1.;
this->frequency = 1.;
#endif
}
void FEComputeData::init ()
{
if (!(this->shape.empty()))
std::fill (this->shape.begin(), this->shape.end(), 0.);
#if defined(LIBMESH_ENABLE_INFINITE_ELEMENTS) && !defined(LIBMESH_USE_COMPLEX_NUMBERS)
this->phase = 0.;
if (equation_systems.parameters.have_parameter<Real>("speed"))
this->speed = this->equation_systems.parameters.get<Real>("speed");
#endif
#if defined (LIBMESH_ENABLE_INFINITE_ELEMENTS) && defined(LIBMESH_USE_COMPLEX_NUMBERS)
if (equation_systems.parameters.have_parameter<Real>("speed"))
this->speed = this->equation_systems.parameters.get<Real>("speed");
if (equation_systems.parameters.have_parameter<Real>("current frequency"))
this->frequency = this->equation_systems.parameters.get<Real>("current frequency");
#endif
// ensure that the wavenumber k=2. * libMesh::pi * this->frequency / this->speed
// in src/fe/inf_fe_static.C: 310
// is well-defined. 0 as well as NaN will lead to problems here.
libmesh_assert_not_equal_to(this->frequency,0);
libmesh_assert_not_equal_to(this->speed,0 );
}
} // namespace libMesh
<commit_msg>added check to have infinite elements.<commit_after>// The libMesh Finite Element Library.
// Copyright (C) 2002-2016 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#include "libmesh/fe_compute_data.h"
#include "libmesh/equation_systems.h"
namespace libMesh
{
void FEComputeData::clear ()
{
this->shape.clear();
#if defined(LIBMESH_ENABLE_INFINITE_ELEMENTS) && !defined(LIBMESH_USE_COMPLEX_NUMBERS)
this->phase = 0.;
this->speed = 1.;
#endif
#if defined (LIBMESH_ENABLE_INFINITE_ELEMENTS) && defined(LIBMESH_USE_COMPLEX_NUMBERS)
//lets default speed and frequency to 1; 0 leads to troubles with the wavenumber.
this->speed = 1.;
this->frequency = 1.;
#endif
}
void FEComputeData::init ()
{
if (!(this->shape.empty()))
std::fill (this->shape.begin(), this->shape.end(), 0.);
#if defined(LIBMESH_ENABLE_INFINITE_ELEMENTS) && !defined(LIBMESH_USE_COMPLEX_NUMBERS)
this->phase = 0.;
if (equation_systems.parameters.have_parameter<Real>("speed"))
this->speed = this->equation_systems.parameters.get<Real>("speed");
#endif
#if defined (LIBMESH_ENABLE_INFINITE_ELEMENTS) && defined(LIBMESH_USE_COMPLEX_NUMBERS)
if (equation_systems.parameters.have_parameter<Real>("speed"))
this->speed = this->equation_systems.parameters.get<Real>("speed");
if (equation_systems.parameters.have_parameter<Real>("current frequency"))
this->frequency = this->equation_systems.parameters.get<Real>("current frequency");
#endif
// ensure that the wavenumber k=2. * libMesh::pi * this->frequency / this->speed
// in src/fe/inf_fe_static.C: 310
// is well-defined. 0 as well as NaN will lead to problems here.
#if defined (LIBMESH_ENABLE_INFINITE_ELEMENTS)
libmesh_assert_not_equal_to(this->frequency,0);
libmesh_assert_not_equal_to(this->speed,0 );
#endif
}
} // namespace libMesh
<|endoftext|> |
<commit_before>#include <cstdint>
#include "clockUtils/errors.h"
#include "clockUtils/argparser/ArgumentParser.h"
#include "gtest/gtest.h"
TEST(ArgumentParser, parseBool) {
REGISTER_VARIABLE(bool, b, false, "A test boolean");
REGISTER_VARIABLE(bool, d, false, "A test boolean");
REGISTER_VARIABLE(bool, foo, false, "A test boolean");
REGISTER_VARIABLE(bool, bar, false, "A test boolean");
char * buffer1[] = { "-c", "-e", "3" };
int length1 = sizeof(buffer1) / sizeof(char *);
char * buffer2[] = { "-b" };
int length2 = sizeof(buffer2) / sizeof(char *);
char * buffer3[] = { "-b", "-d", "-foo", "-bar" };
int length3 = sizeof(buffer3) / sizeof(char *);
std::stringstream buffer;
std::streambuf * sbuf = std::cerr.rdbuf();
std::cerr.rdbuf(buffer.rdbuf());
EXPECT_EQ(false, b);
EXPECT_EQ(clockUtils::ClockError::INVALID_ARGUMENT, PARSE_ARGUMENTS(buffer1, length1));
EXPECT_FALSE(buffer.str().empty());
EXPECT_EQ("argument -c not registered!\nargument -e not registered!\n", buffer.str());
EXPECT_EQ(false, b);
buffer.str("");
EXPECT_EQ(clockUtils::ClockError::SUCCESS, PARSE_ARGUMENTS(buffer2, length2));
EXPECT_TRUE(buffer.str().empty());
buffer.str("");
EXPECT_EQ(true, b);
b = false;
EXPECT_EQ(clockUtils::ClockError::SUCCESS, PARSE_ARGUMENTS(buffer3, length3));
EXPECT_TRUE(buffer.str().empty());
buffer.str("");
EXPECT_EQ(true, b);
EXPECT_EQ(true, d);
EXPECT_EQ(true, foo);
EXPECT_EQ(true, bar);
std::cerr.rdbuf(sbuf);
}
TEST(ArgumentParser, parseString) {
REGISTER_VARIABLE(std::string, s, "test", "A test string");
char * buffer1[] = { "-c", "-e", "3" };
int length1 = sizeof(buffer1) / sizeof(char *);
char * buffer2[] = { "-s" };
int length2 = sizeof(buffer2) / sizeof(char *);
char * buffer3[] = { "-s", "blafoo" };
int length3 = sizeof(buffer3) / sizeof(char *);
char * buffer4[] = { "-sblafoo" };
int length4 = sizeof(buffer4) / sizeof(char *);
char * buffer5[] = { "-s=blafoo" };
int length5 = sizeof(buffer5) / sizeof(char *);
std::stringstream buffer;
std::streambuf * sbuf = std::cerr.rdbuf();
std::cerr.rdbuf(buffer.rdbuf());
EXPECT_EQ("test", s);
EXPECT_EQ(clockUtils::ClockError::INVALID_ARGUMENT, PARSE_ARGUMENTS(buffer1, length1));
EXPECT_FALSE(buffer.str().empty());
EXPECT_EQ("argument -c not registered!\nargument -e not registered!\n", buffer.str());
buffer.str("");
EXPECT_EQ("test", s);
EXPECT_EQ(clockUtils::ClockError::INVALID_USAGE, PARSE_ARGUMENTS(buffer2, length2));
EXPECT_FALSE(buffer.str().empty());
EXPECT_EQ("test", s);
EXPECT_EQ("s requires a value: -s <value> or -s<value> or -s=<value>\n", buffer.str());
buffer.str("");
s = "";
EXPECT_EQ(clockUtils::ClockError::SUCCESS, PARSE_ARGUMENTS(buffer3, length3));
EXPECT_TRUE(buffer.str().empty());
EXPECT_EQ("blafoo", s);
s = "";
EXPECT_EQ(clockUtils::ClockError::SUCCESS, PARSE_ARGUMENTS(buffer4, length4));
EXPECT_TRUE(buffer.str().empty());
EXPECT_EQ("blafoo", s);
s = "";
EXPECT_EQ(clockUtils::ClockError::SUCCESS, PARSE_ARGUMENTS(buffer5, length5));
EXPECT_TRUE(buffer.str().empty());
EXPECT_EQ("blafoo", s);
std::cerr.rdbuf(sbuf);
}
TEST(ArgumentParser, parseInt) {
REGISTER_VARIABLE(int32_t, i, -1, "A test integer");
char * buffer1[] = { "-c", "-e", "3" };
int length1 = sizeof(buffer1) / sizeof(char *);
char * buffer2[] = { "-i" };
int length2 = sizeof(buffer2) / sizeof(char *);
char * buffer3[] = { "-i", "blafoo" };
int length3 = sizeof(buffer3) / sizeof(char *);
char * buffer4[] = { "-i", "10" };
int length4 = sizeof(buffer4) / sizeof(char *);
char * buffer5[] = { "-i11" };
int length5 = sizeof(buffer5) / sizeof(char *);
char * buffer6[] = { "-i=12" };
int length6 = sizeof(buffer6) / sizeof(char *);
std::stringstream buffer;
std::streambuf * sbuf = std::cerr.rdbuf();
std::cerr.rdbuf(buffer.rdbuf());
EXPECT_EQ(-1, i);
EXPECT_EQ(clockUtils::ClockError::INVALID_ARGUMENT, PARSE_ARGUMENTS(buffer1, length1));
EXPECT_FALSE(buffer.str().empty());
EXPECT_EQ("argument -c not registered!\nargument -e not registered!\n", buffer.str());
buffer.str("");
EXPECT_EQ(-1, i);
EXPECT_EQ(clockUtils::ClockError::INVALID_USAGE, PARSE_ARGUMENTS(buffer2, length2));
EXPECT_FALSE(buffer.str().empty());
EXPECT_EQ("i requires a value: -i <value> or -i<value> or -i=<value>\n", buffer.str());
buffer.str("");
EXPECT_EQ(-1, i);
EXPECT_EQ(clockUtils::ClockError::INVALID_USAGE, PARSE_ARGUMENTS(buffer3, length3));
EXPECT_FALSE(buffer.str().empty());
EXPECT_EQ("blafoo is not a valid value for variable i\n", buffer.str());
buffer.str("");
i = -1;
EXPECT_EQ(clockUtils::ClockError::SUCCESS, PARSE_ARGUMENTS(buffer4, length4));
EXPECT_TRUE(buffer.str().empty());
buffer.str("");
EXPECT_EQ(10, i);
i = -1;
EXPECT_EQ(clockUtils::ClockError::SUCCESS, PARSE_ARGUMENTS(buffer5, length5));
EXPECT_TRUE(buffer.str().empty());
buffer.str("");
EXPECT_EQ(11, i);
i = -1;
EXPECT_EQ(clockUtils::ClockError::SUCCESS, PARSE_ARGUMENTS(buffer6, length6));
EXPECT_TRUE(buffer.str().empty());
buffer.str("");
EXPECT_EQ(12, i);
std::cerr.rdbuf(sbuf);
}
<commit_msg>CU-14 (argparser) wrote another test for argparser to check multiple different parameters at once<commit_after>#include <cstdint>
#include "clockUtils/errors.h"
#include "clockUtils/argparser/ArgumentParser.h"
#include "gtest/gtest.h"
TEST(ArgumentParser, parseBool) {
REGISTER_VARIABLE(bool, b, false, "A test boolean");
REGISTER_VARIABLE(bool, d, false, "A test boolean");
REGISTER_VARIABLE(bool, foo, false, "A test boolean");
REGISTER_VARIABLE(bool, bar, false, "A test boolean");
char * buffer1[] = { "-c", "-e", "3" };
int length1 = sizeof(buffer1) / sizeof(char *);
char * buffer2[] = { "-b" };
int length2 = sizeof(buffer2) / sizeof(char *);
char * buffer3[] = { "-b", "-d", "-foo", "-bar" };
int length3 = sizeof(buffer3) / sizeof(char *);
std::stringstream buffer;
std::streambuf * sbuf = std::cerr.rdbuf();
std::cerr.rdbuf(buffer.rdbuf());
EXPECT_EQ(false, b);
EXPECT_EQ(clockUtils::ClockError::INVALID_ARGUMENT, PARSE_ARGUMENTS(buffer1, length1));
EXPECT_FALSE(buffer.str().empty());
EXPECT_EQ("argument -c not registered!\nargument -e not registered!\n", buffer.str());
EXPECT_EQ(false, b);
buffer.str("");
EXPECT_EQ(clockUtils::ClockError::SUCCESS, PARSE_ARGUMENTS(buffer2, length2));
EXPECT_TRUE(buffer.str().empty());
buffer.str("");
EXPECT_EQ(true, b);
b = false;
EXPECT_EQ(clockUtils::ClockError::SUCCESS, PARSE_ARGUMENTS(buffer3, length3));
EXPECT_TRUE(buffer.str().empty());
buffer.str("");
EXPECT_EQ(true, b);
EXPECT_EQ(true, d);
EXPECT_EQ(true, foo);
EXPECT_EQ(true, bar);
std::cerr.rdbuf(sbuf);
}
TEST(ArgumentParser, parseString) {
REGISTER_VARIABLE(std::string, s, "test", "A test string");
char * buffer1[] = { "-c", "-e", "3" };
int length1 = sizeof(buffer1) / sizeof(char *);
char * buffer2[] = { "-s" };
int length2 = sizeof(buffer2) / sizeof(char *);
char * buffer3[] = { "-s", "blafoo" };
int length3 = sizeof(buffer3) / sizeof(char *);
char * buffer4[] = { "-sblafoo" };
int length4 = sizeof(buffer4) / sizeof(char *);
char * buffer5[] = { "-s=blafoo" };
int length5 = sizeof(buffer5) / sizeof(char *);
std::stringstream buffer;
std::streambuf * sbuf = std::cerr.rdbuf();
std::cerr.rdbuf(buffer.rdbuf());
EXPECT_EQ("test", s);
EXPECT_EQ(clockUtils::ClockError::INVALID_ARGUMENT, PARSE_ARGUMENTS(buffer1, length1));
EXPECT_FALSE(buffer.str().empty());
EXPECT_EQ("argument -c not registered!\nargument -e not registered!\n", buffer.str());
buffer.str("");
EXPECT_EQ("test", s);
EXPECT_EQ(clockUtils::ClockError::INVALID_USAGE, PARSE_ARGUMENTS(buffer2, length2));
EXPECT_FALSE(buffer.str().empty());
EXPECT_EQ("test", s);
EXPECT_EQ("s requires a value: -s <value> or -s<value> or -s=<value>\n", buffer.str());
buffer.str("");
s = "";
EXPECT_EQ(clockUtils::ClockError::SUCCESS, PARSE_ARGUMENTS(buffer3, length3));
EXPECT_TRUE(buffer.str().empty());
EXPECT_EQ("blafoo", s);
s = "";
EXPECT_EQ(clockUtils::ClockError::SUCCESS, PARSE_ARGUMENTS(buffer4, length4));
EXPECT_TRUE(buffer.str().empty());
EXPECT_EQ("blafoo", s);
s = "";
EXPECT_EQ(clockUtils::ClockError::SUCCESS, PARSE_ARGUMENTS(buffer5, length5));
EXPECT_TRUE(buffer.str().empty());
EXPECT_EQ("blafoo", s);
std::cerr.rdbuf(sbuf);
}
TEST(ArgumentParser, parseInt) {
REGISTER_VARIABLE(int32_t, i, -1, "A test integer");
char * buffer1[] = { "-c", "-e", "3" };
int length1 = sizeof(buffer1) / sizeof(char *);
char * buffer2[] = { "-i" };
int length2 = sizeof(buffer2) / sizeof(char *);
char * buffer3[] = { "-i", "blafoo" };
int length3 = sizeof(buffer3) / sizeof(char *);
char * buffer4[] = { "-i", "10" };
int length4 = sizeof(buffer4) / sizeof(char *);
char * buffer5[] = { "-i11" };
int length5 = sizeof(buffer5) / sizeof(char *);
char * buffer6[] = { "-i=12" };
int length6 = sizeof(buffer6) / sizeof(char *);
std::stringstream buffer;
std::streambuf * sbuf = std::cerr.rdbuf();
std::cerr.rdbuf(buffer.rdbuf());
EXPECT_EQ(-1, i);
EXPECT_EQ(clockUtils::ClockError::INVALID_ARGUMENT, PARSE_ARGUMENTS(buffer1, length1));
EXPECT_FALSE(buffer.str().empty());
EXPECT_EQ("argument -c not registered!\nargument -e not registered!\n", buffer.str());
buffer.str("");
EXPECT_EQ(-1, i);
EXPECT_EQ(clockUtils::ClockError::INVALID_USAGE, PARSE_ARGUMENTS(buffer2, length2));
EXPECT_FALSE(buffer.str().empty());
EXPECT_EQ("i requires a value: -i <value> or -i<value> or -i=<value>\n", buffer.str());
buffer.str("");
EXPECT_EQ(-1, i);
EXPECT_EQ(clockUtils::ClockError::INVALID_USAGE, PARSE_ARGUMENTS(buffer3, length3));
EXPECT_FALSE(buffer.str().empty());
EXPECT_EQ("blafoo is not a valid value for variable i\n", buffer.str());
buffer.str("");
i = -1;
EXPECT_EQ(clockUtils::ClockError::SUCCESS, PARSE_ARGUMENTS(buffer4, length4));
EXPECT_TRUE(buffer.str().empty());
buffer.str("");
EXPECT_EQ(10, i);
i = -1;
EXPECT_EQ(clockUtils::ClockError::SUCCESS, PARSE_ARGUMENTS(buffer5, length5));
EXPECT_TRUE(buffer.str().empty());
buffer.str("");
EXPECT_EQ(11, i);
i = -1;
EXPECT_EQ(clockUtils::ClockError::SUCCESS, PARSE_ARGUMENTS(buffer6, length6));
EXPECT_TRUE(buffer.str().empty());
buffer.str("");
EXPECT_EQ(12, i);
std::cerr.rdbuf(sbuf);
}
TEST(ArgumentParser, parseMultiple) {
REGISTER_VARIABLE(int32_t, i, -1, "A test integer");
REGISTER_VARIABLE(std::string, s, "empty", "A test string");
REGISTER_VARIABLE(bool, b, false, "A test bool");
REGISTER_VARIABLE(double, d, 1.23, "A test double");
char * buffer1[] = { "-i", "1234", "-s", "readString", "-b", "-d=3.14" };
int length1 = sizeof(buffer1) / sizeof(char *);
std::stringstream buffer;
std::streambuf * sbuf = std::cerr.rdbuf();
std::cerr.rdbuf(buffer.rdbuf());
EXPECT_EQ(clockUtils::ClockError::SUCCESS, PARSE_ARGUMENTS(buffer1, length1));
EXPECT_TRUE(buffer.str().empty());
buffer.str("");
EXPECT_EQ(1234, i);
EXPECT_EQ("readString", s);
EXPECT_EQ(true, b);
EXPECT_DOUBLE_EQ(3.14, d);
std::cerr.rdbuf(sbuf);
}
<|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.
// Most of this code is copied from various classes in
// src/chrome/browser/policy. In particular, look at
//
// configuration_policy_provider_delegate_win.{h,cc}
// configuration_policy_loader_win.{h,cc}
//
// This is a reduction of the functionality in those classes.
#include "remoting/host/policy_hack/policy_watcher.h"
#include <userenv.h>
#include "base/compiler_specific.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop_proxy.h"
#include "base/string16.h"
#include "base/synchronization/waitable_event.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "base/win/object_watcher.h"
#include "base/win/registry.h"
// userenv.dll is required for RegisterGPNotification().
#pragma comment(lib, "userenv.lib")
using base::win::RegKey;
namespace remoting {
namespace policy_hack {
namespace {
const wchar_t kRegistrySubKey[] = L"SOFTWARE\\Policies\\Google\\Chrome";
} // namespace
class PolicyWatcherWin :
public PolicyWatcher,
public base::win::ObjectWatcher::Delegate {
public:
explicit PolicyWatcherWin(
scoped_refptr<base::SingleThreadTaskRunner> task_runner)
: PolicyWatcher(task_runner),
user_policy_changed_event_(false, false),
machine_policy_changed_event_(false, false),
user_policy_watcher_failed_(false),
machine_policy_watcher_failed_(false) {
}
virtual ~PolicyWatcherWin() {
}
virtual void StartWatchingInternal() OVERRIDE {
DCHECK(OnPolicyWatcherThread());
if (!RegisterGPNotification(user_policy_changed_event_.handle(), false)) {
PLOG(WARNING) << "Failed to register user group policy notification";
user_policy_watcher_failed_ = true;
}
if (!RegisterGPNotification(machine_policy_changed_event_.handle(), true)) {
PLOG(WARNING) << "Failed to register machine group policy notification.";
machine_policy_watcher_failed_ = true;
}
Reload();
}
virtual void StopWatchingInternal() OVERRIDE {
DCHECK(OnPolicyWatcherThread());
if (!UnregisterGPNotification(user_policy_changed_event_.handle())) {
PLOG(WARNING) << "Failed to unregister user group policy notification";
}
if (!UnregisterGPNotification(machine_policy_changed_event_.handle())) {
PLOG(WARNING) <<
"Failed to unregister machine group policy notification.";
}
user_policy_watcher_.StopWatching();
machine_policy_watcher_.StopWatching();
}
private:
// Updates the watchers and schedules the reload task if appropriate.
void SetupWatches() {
DCHECK(OnPolicyWatcherThread());
if (!user_policy_watcher_failed_ &&
!user_policy_watcher_.GetWatchedObject() &&
!user_policy_watcher_.StartWatching(
user_policy_changed_event_.handle(), this)) {
LOG(WARNING) << "Failed to start watch for user policy change event";
user_policy_watcher_failed_ = true;
}
if (!machine_policy_watcher_failed_ &&
!machine_policy_watcher_.GetWatchedObject() &&
!machine_policy_watcher_.StartWatching(
machine_policy_changed_event_.handle(), this)) {
LOG(WARNING) << "Failed to start watch for machine policy change event";
machine_policy_watcher_failed_ = true;
}
if (user_policy_watcher_failed_ || machine_policy_watcher_failed_) {
ScheduleFallbackReloadTask();
}
}
bool GetRegistryPolicyInteger(const string16& value_name,
uint32* result) const {
DWORD value = 0;
RegKey policy_key(HKEY_LOCAL_MACHINE, kRegistrySubKey, KEY_READ);
if (policy_key.ReadValueDW(value_name.c_str(), &value) == ERROR_SUCCESS) {
*result = value;
return true;
}
if (policy_key.Open(HKEY_CURRENT_USER, kRegistrySubKey, KEY_READ) ==
ERROR_SUCCESS) {
if (policy_key.ReadValueDW(value_name.c_str(), &value) == ERROR_SUCCESS) {
*result = value;
return true;
}
}
return false;
}
bool GetRegistryPolicyBoolean(const string16& value_name,
bool* result) const {
uint32 local_result = 0;
bool ret = GetRegistryPolicyInteger(value_name, &local_result);
if (ret)
*result = local_result != 0;
return ret;
}
base::DictionaryValue* Load() {
base::DictionaryValue* policy = new base::DictionaryValue();
for (int i = 0; i < kBooleanPolicyNamesNum; ++i) {
const char* policy_name = kBooleanPolicyNames[i];
bool bool_value;
const string16 name(ASCIIToUTF16(policy_name));
if (GetRegistryPolicyBoolean(name, &bool_value)) {
policy->SetBoolean(policy_name, bool_value);
}
}
// TODO(simonmorris): Read policies whose names are in kStringPolicyNames.
return policy;
}
// Post a reload notification and update the watch machinery.
void Reload() {
DCHECK(OnPolicyWatcherThread());
SetupWatches();
scoped_ptr<DictionaryValue> new_policy(Load());
UpdatePolicies(new_policy.get());
}
// ObjectWatcher::Delegate overrides:
virtual void OnObjectSignaled(HANDLE object) {
DCHECK(OnPolicyWatcherThread());
DCHECK(object == user_policy_changed_event_.handle() ||
object == machine_policy_changed_event_.handle())
<< "unexpected object signaled policy reload, obj = "
<< std::showbase << std::hex << object;
Reload();
}
base::WaitableEvent user_policy_changed_event_;
base::WaitableEvent machine_policy_changed_event_;
base::win::ObjectWatcher user_policy_watcher_;
base::win::ObjectWatcher machine_policy_watcher_;
bool user_policy_watcher_failed_;
bool machine_policy_watcher_failed_;
};
PolicyWatcher* PolicyWatcher::Create(
scoped_refptr<base::SingleThreadTaskRunner> task_runner) {
return new PolicyWatcherWin(task_runner);
}
} // namespace policy_hack
} // namespace remoting
<commit_msg>[Chromoting] Let the Windows host policy watcher read string-valued policies.<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.
// Most of this code is copied from various classes in
// src/chrome/browser/policy. In particular, look at
//
// configuration_policy_provider_delegate_win.{h,cc}
// configuration_policy_loader_win.{h,cc}
//
// This is a reduction of the functionality in those classes.
#include "remoting/host/policy_hack/policy_watcher.h"
#include <userenv.h>
#include "base/compiler_specific.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop_proxy.h"
#include "base/string16.h"
#include "base/synchronization/waitable_event.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "base/win/object_watcher.h"
#include "base/win/registry.h"
// userenv.dll is required for RegisterGPNotification().
#pragma comment(lib, "userenv.lib")
using base::win::RegKey;
namespace remoting {
namespace policy_hack {
namespace {
const wchar_t kRegistrySubKey[] = L"SOFTWARE\\Policies\\Google\\Chrome";
} // namespace
class PolicyWatcherWin :
public PolicyWatcher,
public base::win::ObjectWatcher::Delegate {
public:
explicit PolicyWatcherWin(
scoped_refptr<base::SingleThreadTaskRunner> task_runner)
: PolicyWatcher(task_runner),
user_policy_changed_event_(false, false),
machine_policy_changed_event_(false, false),
user_policy_watcher_failed_(false),
machine_policy_watcher_failed_(false) {
}
virtual ~PolicyWatcherWin() {
}
virtual void StartWatchingInternal() OVERRIDE {
DCHECK(OnPolicyWatcherThread());
if (!RegisterGPNotification(user_policy_changed_event_.handle(), false)) {
PLOG(WARNING) << "Failed to register user group policy notification";
user_policy_watcher_failed_ = true;
}
if (!RegisterGPNotification(machine_policy_changed_event_.handle(), true)) {
PLOG(WARNING) << "Failed to register machine group policy notification.";
machine_policy_watcher_failed_ = true;
}
Reload();
}
virtual void StopWatchingInternal() OVERRIDE {
DCHECK(OnPolicyWatcherThread());
if (!UnregisterGPNotification(user_policy_changed_event_.handle())) {
PLOG(WARNING) << "Failed to unregister user group policy notification";
}
if (!UnregisterGPNotification(machine_policy_changed_event_.handle())) {
PLOG(WARNING) <<
"Failed to unregister machine group policy notification.";
}
user_policy_watcher_.StopWatching();
machine_policy_watcher_.StopWatching();
}
private:
// Updates the watchers and schedules the reload task if appropriate.
void SetupWatches() {
DCHECK(OnPolicyWatcherThread());
if (!user_policy_watcher_failed_ &&
!user_policy_watcher_.GetWatchedObject() &&
!user_policy_watcher_.StartWatching(
user_policy_changed_event_.handle(), this)) {
LOG(WARNING) << "Failed to start watch for user policy change event";
user_policy_watcher_failed_ = true;
}
if (!machine_policy_watcher_failed_ &&
!machine_policy_watcher_.GetWatchedObject() &&
!machine_policy_watcher_.StartWatching(
machine_policy_changed_event_.handle(), this)) {
LOG(WARNING) << "Failed to start watch for machine policy change event";
machine_policy_watcher_failed_ = true;
}
if (user_policy_watcher_failed_ || machine_policy_watcher_failed_) {
ScheduleFallbackReloadTask();
}
}
bool GetRegistryPolicyString(const std::string& value_name,
std::string* result) const {
std::wstring value_name_wide = UTF8ToWide(value_name);
std::wstring value;
RegKey policy_key(HKEY_LOCAL_MACHINE, kRegistrySubKey, KEY_READ);
if (policy_key.ReadValue(value_name_wide.c_str(), &value) ==
ERROR_SUCCESS) {
*result = WideToUTF8(value);
return true;
}
if (policy_key.Open(HKEY_CURRENT_USER, kRegistrySubKey, KEY_READ) ==
ERROR_SUCCESS) {
if (policy_key.ReadValue(value_name_wide.c_str(), &value) ==
ERROR_SUCCESS) {
*result = WideToUTF8(value);
return true;
}
}
return false;
}
bool GetRegistryPolicyInteger(const std::string& value_name,
uint32* result) const {
std::wstring value_name_wide = UTF8ToWide(value_name);
DWORD value = 0;
RegKey policy_key(HKEY_LOCAL_MACHINE, kRegistrySubKey, KEY_READ);
if (policy_key.ReadValueDW(value_name_wide.c_str(), &value) ==
ERROR_SUCCESS) {
*result = value;
return true;
}
if (policy_key.Open(HKEY_CURRENT_USER, kRegistrySubKey, KEY_READ) ==
ERROR_SUCCESS) {
if (policy_key.ReadValueDW(value_name_wide.c_str(), &value) ==
ERROR_SUCCESS) {
*result = value;
return true;
}
}
return false;
}
bool GetRegistryPolicyBoolean(const std::string& value_name,
bool* result) const {
uint32 local_result = 0;
bool ret = GetRegistryPolicyInteger(value_name, &local_result);
if (ret)
*result = local_result != 0;
return ret;
}
base::DictionaryValue* Load() {
base::DictionaryValue* policy = new base::DictionaryValue();
for (int i = 0; i < kBooleanPolicyNamesNum; ++i) {
const char* policy_name = kBooleanPolicyNames[i];
bool bool_value;
if (GetRegistryPolicyBoolean(policy_name, &bool_value)) {
policy->SetBoolean(policy_name, bool_value);
}
}
for (int i = 0; i < kStringPolicyNamesNum; ++i) {
const char* policy_name = kStringPolicyNames[i];
std::string string_value;
if (GetRegistryPolicyString(policy_name, &string_value)) {
policy->SetString(policy_name, string_value);
}
}
return policy;
}
// Post a reload notification and update the watch machinery.
void Reload() {
DCHECK(OnPolicyWatcherThread());
SetupWatches();
scoped_ptr<DictionaryValue> new_policy(Load());
UpdatePolicies(new_policy.get());
}
// ObjectWatcher::Delegate overrides:
virtual void OnObjectSignaled(HANDLE object) {
DCHECK(OnPolicyWatcherThread());
DCHECK(object == user_policy_changed_event_.handle() ||
object == machine_policy_changed_event_.handle())
<< "unexpected object signaled policy reload, obj = "
<< std::showbase << std::hex << object;
Reload();
}
base::WaitableEvent user_policy_changed_event_;
base::WaitableEvent machine_policy_changed_event_;
base::win::ObjectWatcher user_policy_watcher_;
base::win::ObjectWatcher machine_policy_watcher_;
bool user_policy_watcher_failed_;
bool machine_policy_watcher_failed_;
};
PolicyWatcher* PolicyWatcher::Create(
scoped_refptr<base::SingleThreadTaskRunner> task_runner) {
return new PolicyWatcherWin(task_runner);
}
} // namespace policy_hack
} // namespace remoting
<|endoftext|> |
<commit_before>#ifndef VEXCL_DEVLIST_HPP
#define VEXCL_DEVLIST_HPP
/*
The MIT License
Copyright (c) 2012 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 devlist.hpp
* \author Denis Demidov <ddemidov@ksu.ru>
* \brief OpenCL device enumeration.
*/
#ifdef WIN32
# pragma warning(disable : 4290 4715)
# define NOMINMAX
#endif
#define __CL_ENABLE_EXCEPTIONS
#include <vector>
#include <string>
#include <cstdlib>
#include <CL/cl.hpp>
/// OpenCL convenience utilities.
namespace vex {
/// Device filters.
namespace Filter {
/// Selects any device.
struct All {
bool operator()(const cl::Device &d) const {
return true;
}
};
/// Selects devices whose vendor name match given value.
struct Vendor {
Vendor(const std::string &name) : vendor(name) {}
bool operator()(const cl::Device &d) const {
return d.getInfo<CL_DEVICE_VENDOR>().find(vendor) != std::string::npos;
}
private:
const std::string &vendor;
};
/// Selects devices whose platform name match given value.
struct Platform {
Platform(const std::string &name) : platform(name) {}
bool operator()(const cl::Device &d) const {
return cl::Platform(d.getInfo<CL_DEVICE_PLATFORM>()).getInfo<CL_PLATFORM_NAME>().find(platform) != std::string::npos;
}
private:
const std::string &platform;
};
/// Selects devices whose names match given value.
struct Name {
Name(const std::string &name) : devname(name) {}
bool operator()(const cl::Device &d) const {
return d.getInfo<CL_DEVICE_NAME>().find(devname) != std::string::npos;
}
private:
const std::string &devname;
};
/// Selects devices by type.
struct Type {
Type(cl_device_type t) : type(t) {}
bool operator()(const cl::Device &d) const {
return d.getInfo<CL_DEVICE_TYPE>() == type;
}
private:
cl_device_type type;
};
/// Selects devices supporting double precision.
struct DoublePrecision {
bool operator()(const cl::Device &d) const {
if (d.getInfo<CL_DEVICE_TYPE>() == CL_DEVICE_TYPE_CPU)
return true;
std::string ext = d.getInfo<CL_DEVICE_EXTENSIONS>();
return (
ext.find("cl_khr_fp64") != std::string::npos ||
ext.find("cl_amd_fp64") != std::string::npos
);
}
};
/// Selects no more than given number of devices.
/**
* \note This filter should be the last in filter expression. In this case,
* it will be applied only to devices which passed all other filters.
* Otherwise, you could get less devices than planned (every time this
* filter is applied, internal counter is decremented).
*/
struct Count {
Count(int c) : count(c) {}
bool operator()(const cl::Device &d) const {
return --count >= 0;
}
private:
mutable int count;
};
/// Environment filter
/**
* Selects devices with respect to environment variables. Recognized
* variables are:
*
* \li OCL_PLATFORM -- platform name;
* \li OCL_VENDOR -- device vendor;
* \li OCL_DEVICE -- device name;
* \li OCL_MAX_DEVICES -- maximum number of devices to use.
*
* \note Since this filter possibly counts passed devices, it should be the
* last in filter expression. Same reasoning applies as in case of
* Filter::Count.
*/
struct Env {
Env()
: platform(getenv("OCL_PLATFORM")),
vendor (getenv("OCL_VENDOR")),
name (getenv("OCL_DEVICE")),
maxdev (getenv("OCL_MAX_DEVICES")),
count(maxdev ? atoi(maxdev) : std::numeric_limits<int>::max())
{}
bool operator()(const cl::Device &d) const {
if (platform &&
cl::Platform(
d.getInfo<CL_DEVICE_PLATFORM>()
).getInfo<CL_PLATFORM_NAME>().find(platform) == std::string::npos
) return false;
if (vendor &&
d.getInfo<CL_DEVICE_VENDOR>().find(vendor) == std::string::npos
) return false;
if (name &&
d.getInfo<CL_DEVICE_NAME>().find(name) == std::string::npos
) return false;
if (maxdev) return --count >= 0;
return true;
}
private:
const char *platform;
const char *vendor;
const char *name;
const char *maxdev;
mutable int count;
};
/// \internal Filter join operators.
enum FilterOp {
FilterAnd, FilterOr
};
/// \internal Filter join expression template.
template <class LeftFilter, class RightFilter, FilterOp op>
struct FilterBinaryOp {
FilterBinaryOp(const LeftFilter &l, const RightFilter &r)
: left(l), right(r) {}
bool operator()(const cl::Device &d) const {
switch (op) {
case FilterAnd:
return left(d) && right(d);
case FilterOr:
return left(d) || right(d);
}
}
private:
const LeftFilter &left;
const RightFilter &right;
};
/// Join two filters with AND operator.
template <class LeftFilter, class RightFilter>
FilterBinaryOp<LeftFilter, RightFilter, FilterAnd> operator&&(
const LeftFilter &left, const RightFilter &right)
{
return FilterBinaryOp<LeftFilter, RightFilter, FilterAnd>(left, right);
}
/// Join two filters with OR operator.
template <class LeftFilter, class RightFilter>
FilterBinaryOp<LeftFilter, RightFilter, FilterOr> operator||(
const LeftFilter &left, const RightFilter &right)
{
return FilterBinaryOp<LeftFilter, RightFilter, FilterOr>(left, right);
}
/// \internal Negation of a filter.
template <class Flt>
struct NegateFilter {
NegateFilter(const Flt &flt) : flt(flt) {}
bool operator()(const cl::Device &d) const {
return !flt(d);
}
private:
const Flt &flt;
};
/// Negate a filter.
template <class Flt>
NegateFilter<Flt> operator!(const Flt &flt) {
return NegateFilter<Flt>(flt);
}
} // namespace Filter
/// Select devices by given criteria.
/**
* \param filter Device filter functor. Functors may be combined with logical
* operators.
* \returns list of devices satisfying the provided filter.
*
* This example selects any GPU which supports double precision arithmetic:
* \code
* auto devices = device_list(
* Filter::Type(CL_DEVICE_TYPE_GPU) && Filter::DoublePrecision()
* );
* \endcode
*/
template<class DevFilter
#ifndef WIN32
= Filter::All
#endif
>
std::vector<cl::Device> device_list(DevFilter filter = Filter::All())
{
std::vector<cl::Device> device;
std::vector<cl::Platform> platforms;
cl::Platform::get(&platforms);
for(auto p = platforms.begin(); p != platforms.end(); p++) {
std::vector<cl::Device> dev_list;
p->getDevices(CL_DEVICE_TYPE_ALL, &dev_list);
for(auto d = dev_list.begin(); d != dev_list.end(); d++) {
if (!d->getInfo<CL_DEVICE_AVAILABLE>()) continue;
if (!filter(*d)) continue;
device.push_back(*d);
}
}
return device;
}
/// Create command queues on devices by given criteria.
/**
* \param filter Device filter functor. Functors may be combined with logical
* operators.
* \returns list of queues accociated with selected devices.
* \see device_list
*/
template<class DevFilter
#ifndef WIN32
= Filter::All
#endif
>
std::pair<std::vector<cl::Context>, std::vector<cl::CommandQueue>>
queue_list(
DevFilter filter = Filter::All(),
cl_command_queue_properties properties = 0
)
{
std::vector<cl::Context> context;
std::vector<cl::CommandQueue> queue;
std::vector<cl::Platform> platforms;
cl::Platform::get(&platforms);
for(auto p = platforms.begin(); p != platforms.end(); p++) {
std::vector<cl::Device> device;
std::vector<cl::Device> dev_list;
p->getDevices(CL_DEVICE_TYPE_ALL, &dev_list);
for(auto d = dev_list.begin(); d != dev_list.end(); d++) {
if (!d->getInfo<CL_DEVICE_AVAILABLE>()) continue;
if (!filter(*d)) continue;
device.push_back(*d);
}
if (device.empty()) continue;
context.push_back(cl::Context(device));
for(auto d = device.begin(); d != device.end(); d++)
queue.push_back(cl::CommandQueue(context.back(), *d, properties));
}
return std::make_pair(context, queue);
}
std::ostream& operator<<(std::ostream &os, const std::vector<cl::Device> &device) {
uint p = 1;
for(auto d = device.begin(); d != device.end(); d++)
os << p++ << ". " << d->getInfo<CL_DEVICE_NAME>() << std::endl;
return os;
}
std::ostream& operator<<(std::ostream &os, const std::vector<cl::CommandQueue> &queue) {
uint p = 1;
for(auto q = queue.begin(); q != queue.end(); q++)
os << p++ << ". "
<< q->getInfo<CL_QUEUE_DEVICE>().getInfo<CL_DEVICE_NAME>()
<< std::endl;
return os;
}
} // namespace vex
#endif
<commit_msg>Switched to one context per device.<commit_after>#ifndef VEXCL_DEVLIST_HPP
#define VEXCL_DEVLIST_HPP
/*
The MIT License
Copyright (c) 2012 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 devlist.hpp
* \author Denis Demidov <ddemidov@ksu.ru>
* \brief OpenCL device enumeration.
*/
#ifdef WIN32
# pragma warning(disable : 4290 4715)
# define NOMINMAX
#endif
#define __CL_ENABLE_EXCEPTIONS
#include <vector>
#include <string>
#include <cstdlib>
#include <CL/cl.hpp>
/// OpenCL convenience utilities.
namespace vex {
/// Device filters.
namespace Filter {
/// Selects any device.
struct All {
bool operator()(const cl::Device &d) const {
return true;
}
};
/// Selects devices whose vendor name match given value.
struct Vendor {
Vendor(const std::string &name) : vendor(name) {}
bool operator()(const cl::Device &d) const {
return d.getInfo<CL_DEVICE_VENDOR>().find(vendor) != std::string::npos;
}
private:
const std::string &vendor;
};
/// Selects devices whose platform name match given value.
struct Platform {
Platform(const std::string &name) : platform(name) {}
bool operator()(const cl::Device &d) const {
return cl::Platform(d.getInfo<CL_DEVICE_PLATFORM>()).getInfo<CL_PLATFORM_NAME>().find(platform) != std::string::npos;
}
private:
const std::string &platform;
};
/// Selects devices whose names match given value.
struct Name {
Name(const std::string &name) : devname(name) {}
bool operator()(const cl::Device &d) const {
return d.getInfo<CL_DEVICE_NAME>().find(devname) != std::string::npos;
}
private:
const std::string &devname;
};
/// Selects devices by type.
struct Type {
Type(cl_device_type t) : type(t) {}
bool operator()(const cl::Device &d) const {
return d.getInfo<CL_DEVICE_TYPE>() == type;
}
private:
cl_device_type type;
};
/// Selects devices supporting double precision.
struct DoublePrecision {
bool operator()(const cl::Device &d) const {
if (d.getInfo<CL_DEVICE_TYPE>() == CL_DEVICE_TYPE_CPU)
return true;
std::string ext = d.getInfo<CL_DEVICE_EXTENSIONS>();
return (
ext.find("cl_khr_fp64") != std::string::npos ||
ext.find("cl_amd_fp64") != std::string::npos
);
}
};
/// Selects no more than given number of devices.
/**
* \note This filter should be the last in filter expression. In this case,
* it will be applied only to devices which passed all other filters.
* Otherwise, you could get less devices than planned (every time this
* filter is applied, internal counter is decremented).
*/
struct Count {
Count(int c) : count(c) {}
bool operator()(const cl::Device &d) const {
return --count >= 0;
}
private:
mutable int count;
};
/// Environment filter
/**
* Selects devices with respect to environment variables. Recognized
* variables are:
*
* \li OCL_PLATFORM -- platform name;
* \li OCL_VENDOR -- device vendor;
* \li OCL_DEVICE -- device name;
* \li OCL_MAX_DEVICES -- maximum number of devices to use.
*
* \note Since this filter possibly counts passed devices, it should be the
* last in filter expression. Same reasoning applies as in case of
* Filter::Count.
*/
struct Env {
Env()
: platform(getenv("OCL_PLATFORM")),
vendor (getenv("OCL_VENDOR")),
name (getenv("OCL_DEVICE")),
maxdev (getenv("OCL_MAX_DEVICES")),
count(maxdev ? atoi(maxdev) : std::numeric_limits<int>::max())
{}
bool operator()(const cl::Device &d) const {
if (platform &&
cl::Platform(
d.getInfo<CL_DEVICE_PLATFORM>()
).getInfo<CL_PLATFORM_NAME>().find(platform) == std::string::npos
) return false;
if (vendor &&
d.getInfo<CL_DEVICE_VENDOR>().find(vendor) == std::string::npos
) return false;
if (name &&
d.getInfo<CL_DEVICE_NAME>().find(name) == std::string::npos
) return false;
if (maxdev) return --count >= 0;
return true;
}
private:
const char *platform;
const char *vendor;
const char *name;
const char *maxdev;
mutable int count;
};
/// \internal Filter join operators.
enum FilterOp {
FilterAnd, FilterOr
};
/// \internal Filter join expression template.
template <class LeftFilter, class RightFilter, FilterOp op>
struct FilterBinaryOp {
FilterBinaryOp(const LeftFilter &l, const RightFilter &r)
: left(l), right(r) {}
bool operator()(const cl::Device &d) const {
switch (op) {
case FilterAnd:
return left(d) && right(d);
case FilterOr:
return left(d) || right(d);
}
}
private:
const LeftFilter &left;
const RightFilter &right;
};
/// Join two filters with AND operator.
template <class LeftFilter, class RightFilter>
FilterBinaryOp<LeftFilter, RightFilter, FilterAnd> operator&&(
const LeftFilter &left, const RightFilter &right)
{
return FilterBinaryOp<LeftFilter, RightFilter, FilterAnd>(left, right);
}
/// Join two filters with OR operator.
template <class LeftFilter, class RightFilter>
FilterBinaryOp<LeftFilter, RightFilter, FilterOr> operator||(
const LeftFilter &left, const RightFilter &right)
{
return FilterBinaryOp<LeftFilter, RightFilter, FilterOr>(left, right);
}
/// \internal Negation of a filter.
template <class Flt>
struct NegateFilter {
NegateFilter(const Flt &flt) : flt(flt) {}
bool operator()(const cl::Device &d) const {
return !flt(d);
}
private:
const Flt &flt;
};
/// Negate a filter.
template <class Flt>
NegateFilter<Flt> operator!(const Flt &flt) {
return NegateFilter<Flt>(flt);
}
} // namespace Filter
/// Select devices by given criteria.
/**
* \param filter Device filter functor. Functors may be combined with logical
* operators.
* \returns list of devices satisfying the provided filter.
*
* This example selects any GPU which supports double precision arithmetic:
* \code
* auto devices = device_list(
* Filter::Type(CL_DEVICE_TYPE_GPU) && Filter::DoublePrecision()
* );
* \endcode
*/
template<class DevFilter
#ifndef WIN32
= Filter::All
#endif
>
std::vector<cl::Device> device_list(DevFilter filter = Filter::All())
{
std::vector<cl::Device> device;
std::vector<cl::Platform> platforms;
cl::Platform::get(&platforms);
for(auto p = platforms.begin(); p != platforms.end(); p++) {
std::vector<cl::Device> dev_list;
p->getDevices(CL_DEVICE_TYPE_ALL, &dev_list);
for(auto d = dev_list.begin(); d != dev_list.end(); d++) {
if (!d->getInfo<CL_DEVICE_AVAILABLE>()) continue;
if (!filter(*d)) continue;
device.push_back(*d);
}
}
return device;
}
/// Create command queues on devices by given criteria.
/**
* \param filter Device filter functor. Functors may be combined with logical
* operators.
* \returns list of queues accociated with selected devices.
* \see device_list
*/
template<class DevFilter
#ifndef WIN32
= Filter::All
#endif
>
std::pair<std::vector<cl::Context>, std::vector<cl::CommandQueue>>
queue_list(
DevFilter filter = Filter::All(),
cl_command_queue_properties properties = 0
)
{
std::vector<cl::Context> context;
std::vector<cl::CommandQueue> queue;
std::vector<cl::Platform> platforms;
cl::Platform::get(&platforms);
for(auto p = platforms.begin(); p != platforms.end(); p++) {
std::vector<cl::Device> device;
std::vector<cl::Device> dev_list;
p->getDevices(CL_DEVICE_TYPE_ALL, &dev_list);
for(auto d = dev_list.begin(); d != dev_list.end(); d++) {
if (!d->getInfo<CL_DEVICE_AVAILABLE>()) continue;
if (!filter(*d)) continue;
device.push_back(*d);
}
if (device.empty()) continue;
for(auto d = device.begin(); d != device.end(); d++)
try {
context.push_back(cl::Context(std::vector<cl::Device>(1, *d)));
queue.push_back(cl::CommandQueue(context.back(), *d, properties));
} catch(const cl::Error&) {
// Something bad happened. Better skip this device.
}
}
return std::make_pair(context, queue);
}
std::ostream& operator<<(std::ostream &os, const std::vector<cl::Device> &device) {
uint p = 1;
for(auto d = device.begin(); d != device.end(); d++)
os << p++ << ". " << d->getInfo<CL_DEVICE_NAME>() << std::endl;
return os;
}
std::ostream& operator<<(std::ostream &os, const std::vector<cl::CommandQueue> &queue) {
uint p = 1;
for(auto q = queue.begin(); q != queue.end(); q++)
os << p++ << ". "
<< q->getInfo<CL_QUEUE_DEVICE>().getInfo<CL_DEVICE_NAME>()
<< std::endl;
return os;
}
} // namespace vex
#endif
<|endoftext|> |
<commit_before>#include "geometry/triangular_mesh.h"
#include "geometry/triangle3.h"
#include "geometry/bounding_box3.h"
#include "math/vector3.h"
#include "math/matrix3.h"
#include <memory>
#include <set>
#include <gtest/gtest.h>
using namespace hd;
using namespace std;
class TriangularMeshTest : public ::testing::Test {
protected:
// A tetrahedral pyramid with top point at origin, and three base points
// at (1, 0, 0), (0, 1, 0), (0, 0, 1). Using flat face normal and averaged
// vertex normal.
unique_ptr<TriangularMesh> tetra1;
// The same tetrahedron as tetra1, but with averaged vertex normal and phong
// interpolated face normal.
unique_ptr<TriangularMesh> tetra2;
// A plane made of 2 triangles. Using flat face normal and user specified
// vertex normal.
unique_ptr<TriangularMesh> plane1;
// The same plane as plane2 but with user specified face and vertex normal.
unique_ptr<TriangularMesh> plane2;
virtual void SetUp() {
tetra1 = TriangularMesh::newBuilder(
TriangularMesh::VertexNormalMode::AVERAGED,
TriangularMesh::FaceNormalMode::FLAT)
.addVertex(Vector3(0, 0, 0))
.addVertex(Vector3(1, 0, 0))
.addVertex(Vector3(0, 1, 0))
.addVertex(Vector3(0, 0, 1))
.addFace({1, 0, 2})
.addFace({1, 3, 0})
.addFace({0, 3, 2})
.addFace({1, 2, 3})
.build();
tetra2 = TriangularMesh::newBuilder(
TriangularMesh::VertexNormalMode::AVERAGED,
TriangularMesh::FaceNormalMode::PHONG).build();
plane1 = TriangularMesh::newBuilder(
TriangularMesh::VertexNormalMode::USER_SPECIFIED,
TriangularMesh::FaceNormalMode::FLAT).build();
plane2 = TriangularMesh::newBuilder(
TriangularMesh::VertexNormalMode::USER_SPECIFIED,
TriangularMesh::FaceNormalMode::USER_SPECIFIED).build();
}
virtual void TearDown() {}
};
TEST_F(TriangularMeshTest, TestGeometryStructureAccess) {
EXPECT_EQ(tetra1->vertexNum(), 4);
EXPECT_EQ(tetra1->edgeNum(), 12);
EXPECT_EQ(tetra1->faceNum(), 4);
// Pick a random node, verify its position and degrees.
unsigned int vertexId = 1;
EXPECT_EQ(tetra1->v(vertexId).pos, Vector3(1.0, 0.0, 0.0));
EXPECT_EQ(tetra1->v(vertexId).edges.size(), 3);
// Pick a random edge starting that, and start traversing.
unsigned int edgeIndex = 2;
unsigned int eid = tetra1->v(vertexId).edges[edgeIndex];
EXPECT_EQ(tetra1->e(eid).startVertex, vertexId);
unsigned int endVertex = tetra1->e(eid).endVertex;
// Verify twin edge.
unsigned int twinEid = tetra1->e(eid).twinEdge;
EXPECT_EQ(tetra1->e(twinEid).startVertex, endVertex);
EXPECT_EQ(tetra1->e(twinEid).endVertex, vertexId);
// Verify next and prev edges.
unsigned int nextEid = tetra1->e(eid).nextEdge;
unsigned int prevEid = tetra1->e(eid).prevEdge;
EXPECT_EQ(tetra1->e(nextEid).startVertex, endVertex);
EXPECT_EQ(tetra1->e(nextEid).endVertex, tetra1->e(prevEid).startVertex);
EXPECT_EQ(tetra1->e(prevEid).endVertex, vertexId);
// Verify face info.
unsigned int fid = tetra1->e(eid).face;
TriangularMesh::Face face = tetra1->f(fid);
auto vertices = set<unsigned int>(face.vertices.cbegin(), face.vertices.cend());
EXPECT_EQ(vertices,
set<unsigned int>({vertexId, endVertex, tetra1->e(nextEid).endVertex}));
auto edges = set<unsigned int>(face.edges.cbegin(), face.edges.cend());
EXPECT_EQ(edges, set<unsigned int>({eid, nextEid, prevEid}));
}
TEST_F(TriangularMeshTest, TestGetTriangles) {
}
TEST_F(TriangularMeshTest, TestBoundingBox) {
}
TEST_F(TriangularMeshTest, TestNormalInterpolation) {
}
<commit_msg>Add a few more test cases for TriangularMesh<commit_after>#include "geometry/triangular_mesh.h"
#include "geometry/triangle3.h"
#include "geometry/bounding_box3.h"
#include "math/vector3.h"
#include "math/matrix3.h"
#include "const.h"
#include <memory>
#include <set>
#include <gtest/gtest.h>
using namespace hd;
using namespace std;
class TriangularMeshTest : public ::testing::Test {
protected:
// A tetrahedral pyramid with top point at origin, and three base points
// at (1, 0, 0), (0, 1, 0), (0, 0, 1). Using flat face normal and averaged
// vertex normal.
unique_ptr<TriangularMesh> tetra1;
// The same tetrahedron as tetra1, but with averaged vertex normal and phong
// interpolated face normal.
unique_ptr<TriangularMesh> tetra2;
// A plane made of 2 triangles. Using flat face normal and user specified
// vertex normal.
unique_ptr<TriangularMesh> plane1;
// The same plane as plane2 but with user specified face and vertex normal.
unique_ptr<TriangularMesh> plane2;
virtual void SetUp() {
tetra1 = TriangularMesh::newBuilder(
TriangularMesh::VertexNormalMode::AVERAGED,
TriangularMesh::FaceNormalMode::FLAT)
.addVertex(Vector3(0, 0, 0))
.addVertex(Vector3(1, 0, 0))
.addVertex(Vector3(0, 1, 0))
.addVertex(Vector3(0, 0, 1))
.addFace({1, 0, 2})
.addFace({1, 3, 0})
.addFace({0, 3, 2})
.addFace({1, 2, 3})
.build();
tetra2 = TriangularMesh::newBuilder(
TriangularMesh::VertexNormalMode::AVERAGED,
TriangularMesh::FaceNormalMode::PHONG)
.addVertex(Vector3(0, 0, 0))
.addVertex(Vector3(1, 0, 0))
.addVertex(Vector3(0, 1, 0))
.addVertex(Vector3(0, 0, 1))
.addFace({1, 0, 2})
.addFace({1, 3, 0})
.addFace({0, 3, 2})
.addFace({1, 2, 3})
.build();
// 0---1---2
// | /| /|
// | / | / |
// |/ |/ |
// 3---4---5
// | /| /|
// | / | / |
// |/ |/ |
// 6---7---8
plane1 = TriangularMesh::newBuilder(
TriangularMesh::VertexNormalMode::USER_SPECIFIED,
TriangularMesh::FaceNormalMode::FLAT)
.addVertex(Vector3(0.0, 0.0, 0.0), Vector3(0.0, 0.0, 1.0))
.addVertex(Vector3(1.0, 0.0, 0.0), Vector3(0.0, 0.0, 1.0))
.addVertex(Vector3(2.0, 0.0, 0.0), Vector3(0.0, 0.0, 1.0))
.addVertex(Vector3(0.0, 1.0, 0.0), Vector3(0.0, 0.0, 1.0))
.addVertex(Vector3(1.0, 1.0, 0.0), Vector3(0.0, 0.0, 1.0))
.addVertex(Vector3(2.0, 1.0, 0.0), Vector3(0.0, 0.0, 1.0))
.addVertex(Vector3(0.0, 2.0, 0.0), Vector3(0.0, 0.0, 1.0))
.addVertex(Vector3(1.0, 2.0, 0.0), Vector3(0.0, 0.0, 1.0))
.addVertex(Vector3(2.0, 2.0, 0.0), Vector3(0.0, 0.0, 1.0))
.addFace({0, 3, 1})
.addFace({1, 4, 2})
.addFace({1, 3, 4})
.addFace({2, 4, 5})
.addFace({3, 6, 4})
.addFace({4, 7, 5})
.addFace({4, 6, 7})
.addFace({5, 7, 8})
.build();
plane2 = TriangularMesh::newBuilder(
TriangularMesh::VertexNormalMode::USER_SPECIFIED,
TriangularMesh::FaceNormalMode::USER_SPECIFIED)
.addVertex(Vector3(0.0, 0.0, 0.0), Vector3(0.0, 0.0, 1.0))
.addVertex(Vector3(1.0, 0.0, 0.0), Vector3(0.0, 0.0, 1.0))
.addVertex(Vector3(2.0, 0.0, 0.0), Vector3(0.0, 0.0, 1.0))
.addVertex(Vector3(0.0, 1.0, 0.0), Vector3(0.0, 0.0, 1.0))
.addVertex(Vector3(1.0, 1.0, 0.0), Vector3(0.0, 0.0, 1.0))
.addVertex(Vector3(2.0, 1.0, 0.0), Vector3(0.0, 0.0, 1.0))
.addVertex(Vector3(0.0, 2.0, 0.0), Vector3(0.0, 0.0, 1.0))
.addVertex(Vector3(1.0, 2.0, 0.0), Vector3(0.0, 0.0, 1.0))
.addVertex(Vector3(2.0, 2.0, 0.0), Vector3(0.0, 0.0, 1.0))
.addFace({0, 3, 1}, Vector3(0.0, 0.0, 1.0))
.addFace({1, 4, 2}, Vector3(0.0, 0.0, 1.0))
.addFace({1, 3, 4}, Vector3(0.0, 0.0, 1.0))
.addFace({2, 4, 5}, Vector3(0.0, 0.0, 1.0))
.addFace({3, 6, 4}, Vector3(0.0, 0.0, 1.0))
.addFace({4, 7, 5}, Vector3(0.0, 0.0, 1.0))
.addFace({4, 6, 7}, Vector3(0.0, 0.0, 1.0))
.addFace({5, 7, 8}, Vector3(0.0, 0.0, 1.0))
.build();
}
virtual void TearDown() {}
protected:
// Attempt to traverse through vertices, edges and faces to verify the structure
// of a given mesh, by specifying a vertex id to start with, and an edge index indicating
// which edge to start with from the given vertex's outgoing edge list.
void verifyTraversal(const unique_ptr<TriangularMesh>& mesh,
unsigned int vertexId,
const Vector3& expectedPos,
unsigned int expectedDegree,
unsigned int edgeIndexFromVertex,
bool expectedHasTwinEdge) {
// Pick the vertex and verify its position and degrees.
EXPECT_EQ(mesh->v(vertexId).pos, expectedPos);
EXPECT_EQ(mesh->v(vertexId).edges.size(), expectedDegree);
// Pick the edge from selected vertex and start traversing.
unsigned int eid = mesh->v(vertexId).edges[edgeIndexFromVertex];
EXPECT_EQ(mesh->e(eid).startVertex, vertexId);
unsigned int endVertex = mesh->e(eid).endVertex;
// Verify twin edge and its start/end vertices being reverse of the original edge.
unsigned int twinEid = mesh->e(eid).twinEdge;
if (expectedHasTwinEdge) {
EXPECT_EQ(mesh->e(twinEid).startVertex, endVertex);
EXPECT_EQ(mesh->e(twinEid).endVertex, vertexId);
} else {
EXPECT_EQ(twinEid, HD_INVALID_ID);
}
// Verify next and prev edges.
unsigned int nextEid = mesh->e(eid).nextEdge;
unsigned int prevEid = mesh->e(eid).prevEdge;
EXPECT_EQ(mesh->e(nextEid).startVertex, endVertex);
EXPECT_EQ(mesh->e(nextEid).endVertex, mesh->e(prevEid).startVertex);
EXPECT_EQ(mesh->e(prevEid).endVertex, vertexId);
// Verify face info.
unsigned int fid = mesh->e(eid).face;
TriangularMesh::Face face = mesh->f(fid);
// Verify the vertices of the face is exactly the same set of vertices traversed
// previously with next and prev edges. Same for edges.
auto vertices = set<unsigned int>(face.vertices.cbegin(), face.vertices.cend());
EXPECT_EQ(vertices,
set<unsigned int>({vertexId, endVertex, mesh->e(nextEid).endVertex}));
auto edges = set<unsigned int>(face.edges.cbegin(), face.edges.cend());
EXPECT_EQ(edges, set<unsigned int>({eid, nextEid, prevEid}));
}
};
TEST_F(TriangularMeshTest, TestGeometryStructureTraversal_tetra1) {
EXPECT_EQ(tetra1->vertexNum(), 4);
EXPECT_EQ(tetra1->edgeNum(), 12);
EXPECT_EQ(tetra1->faceNum(), 4);
verifyTraversal(tetra1, 1, /* vertex id */
Vector3(1.0, 0.0, 0.0), /* expected pos */
3, /* expected degree */
2, /* edge index from picked vertex */
true /* should have a twin edge */);
}
TEST_F(TriangularMeshTest, TestGeometryStructureTraversal_plane1) {
EXPECT_EQ(plane1->vertexNum(), 9);
EXPECT_EQ(plane1->edgeNum(), 24);
EXPECT_EQ(plane1->faceNum(), 8);
verifyTraversal(plane1, 4, /* vertex id */
Vector3(1.0, 1.0, 0.0), /* expected pos */
6, /* expected degree */
3, /* edge index from picked vertex */
true /* should have a twin edge */);
verifyTraversal(plane1, 8, /* vertex id */
Vector3(2.0, 2.0, 0.0), /* expected pos */
1, /* expected degree */
0, /* edge index from picked vertex */
false /* should not have a twin edge */);
}
TEST_F(TriangularMeshTest, TestGetTriangles) {
Triangle3 tri1 = Triangle3(Vector3(1, 0, 0), Vector3(0, 0, 0), Vector3(0, 1, 0));
EXPECT_EQ(tetra1->triangle(0), tri1);
Triangle3 tri2 = Triangle3(Vector3(1, 0, 0), Vector3(0, 1, 0), Vector3(0, 0, 1));
EXPECT_EQ(tetra2->triangle(3), tri2);
Triangle3 tri3 = Triangle3(Vector3(2, 0, 0), Vector3(1, 1, 0), Vector3(2, 1, 0));
EXPECT_EQ(plane1->triangle(3), tri3);
EXPECT_EQ(plane2->triangle(3), tri3);
}
TEST_F(TriangularMeshTest, TestBoundingBox) {
BoundingBox3 box1 = BoundingBox3(Vector3(0, 0, 0), Vector3(1, 1, 1));
EXPECT_EQ(tetra1->boundingBox3(), box1);
EXPECT_EQ(tetra2->boundingBox3(), box1);
BoundingBox3 box2 = BoundingBox3(Vector3(0, 0, 0), Vector3(2, 2, 0));
EXPECT_EQ(plane1->boundingBox3(), box2);
EXPECT_EQ(plane2->boundingBox3(), box2);
}
TEST_F(TriangularMeshTest, TestNormalInterpolation) {
}
<|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: fgerlits $
Version : $Revision: 1.2 $
Location : $Source: /home/paul/cvs2svn-livesupport/newcvsrepo/livesupport/modules/widgets/src/ZebraCellRenderer.cxx,v $
------------------------------------------------------------------------------*/
/* ============================================================ include files */
#ifdef HAVE_CONFIG_H
#include "configure.h"
#endif
#include <iostream>
#include "LiveSupport/Widgets/ZebraCellRenderer.h"
using namespace LiveSupport::Widgets;
/* =================================================== local data structures */
/* ================================================ local constants & macros */
/* =============================================== local function prototypes */
/* ============================================================= module code */
/*------------------------------------------------------------------------------
* Constructor.
*----------------------------------------------------------------------------*/
ZebraCellRenderer::ZebraCellRenderer() throw ()
:
Glib::ObjectBase (typeid(ZebraCellRenderer)),
Gtk::CellRendererText ()
{
// std::cerr << "### constructor\n";
}
/*------------------------------------------------------------------------------
* Destructor.
*----------------------------------------------------------------------------*/
ZebraCellRenderer::~ZebraCellRenderer() throw ()
{
// std::cerr << "### destructor\n";
}
/*------------------------------------------------------------------------------
* Calculate the size of the cell.
*----------------------------------------------------------------------------*/
void
ZebraCellRenderer::get_size_vfunc(Gtk::Widget& widget,
const Gdk::Rectangle* cell_area,
int* x_offset, int* y_offset,
int* width, int* height) const
throw ()
{
/*
std::cerr << "### get_size_vfunc():"
<< (cell_area ? cell_area->get_x() : -1) << ", "
<< (cell_area ? cell_area->get_y() : -1) << "; "
<< (cell_area ? cell_area->get_width() : -1) << ", "
<< (cell_area ? cell_area->get_height() : -1) << "; "
<< (x_offset ? *x_offset : -1) << ", "
<< (y_offset ? *y_offset : -1) << " --- "
<< (width ? *width : -1) << ", "
<< (height ? *height : -1) << "\n";
*/
// call the parent method
Gtk::CellRendererText::get_size_vfunc(widget, cell_area,
x_offset, y_offset,
width, height);
/*
std::cerr << "... done: "
<< (cell_area ? cell_area->get_x() : -1) << ", "
<< (cell_area ? cell_area->get_y() : -1) << "; "
<< (cell_area ? cell_area->get_width() : -1) << ", "
<< (cell_area ? cell_area->get_height() : -1) << "; "
<< (x_offset ? *x_offset : -1) << ", "
<< (y_offset ? *y_offset : -1) << " --- "
<< (width ? *width : -1) << ", "
<< (height ? *height : -1) << "\n";
*/
/*
enum { TOGGLE_WIDTH = 12 };
const int calc_width = property_xpad() * 2 + TOGGLE_WIDTH;
const int calc_height = property_ypad() * 2 + TOGGLE_WIDTH;
if(width)
*width = calc_width;
if(height)
*height = calc_height;
if(cell_area)
{
if(x_offset)
{
*x_offset = int(property_xalign() * (cell_area->get_width() - calc_width));
*x_offset = std::max(0, *x_offset);
}
if(y_offset)
{
*y_offset = int(property_yalign() * (cell_area->get_height() - calc_height));
*y_offset = std::max(0, *y_offset);
}
}
*/
}
/*------------------------------------------------------------------------------
* Draw the cell.
*----------------------------------------------------------------------------*/
void
ZebraCellRenderer::render_vfunc(const Glib::RefPtr<Gdk::Drawable>& window,
Gtk::Widget& widget,
const Gdk::Rectangle& background_area,
const Gdk::Rectangle& cell_area,
const Gdk::Rectangle& expose_area,
Gtk::CellRendererState flags)
throw ()
{
/*
std::cerr << "### render_vfunc(): "
<< widget.get_name() << " --- "
<< background_area.get_x() << ", "
<< background_area.get_y() << "; "
<< background_area.get_width() << ", "
<< background_area.get_height() << " -- "
<< cell_area.get_x() << ", "
<< cell_area.get_y() << "; "
<< cell_area.get_width() << ", "
<< cell_area.get_height() << "; "
<< expose_area.get_x() << " -- "
<< expose_area.get_y() << "; "
<< expose_area.get_width() << ", "
<< expose_area.get_height() << " -- "
<< flags << "\n";
*/
// call the parent function
Gtk::CellRendererText::render_vfunc(window, widget, background_area,
cell_area, expose_area, flags);
/*
const unsigned int cell_xpad = property_xpad();
const unsigned int cell_ypad = property_ypad();
int x_offset = 0, y_offset = 0, width = 0, height = 0;
get_size(widget, cell_area, x_offset, y_offset, width, height);
width -= cell_xpad * 2;
height -= cell_ypad * 2;
if(width <= 0 || height <= 0)
return;
Gtk::StateType state = Gtk::STATE_INSENSITIVE;
if(property_activatable_)
state = Gtk::STATE_NORMAL;
if((flags & Gtk::CELL_RENDERER_SELECTED) != 0)
state = (widget.has_focus()) ? Gtk::STATE_SELECTED : Gtk::STATE_ACTIVE;
const Gtk::ShadowType shadow = (property_active_) ? Gtk::SHADOW_IN : Gtk::SHADOW_OUT;
//Cast the drawable to a Window. TODO: Maybe paint_option() should take a Drawable? murrayc.
Glib::RefPtr<Gdk::Window> window_casted = Glib::RefPtr<Gdk::Window>::cast_dynamic<>(window);
if(window_casted)
{
if(property_radio_)
{
widget.get_style()->paint_option(
window_casted, state, shadow,
cell_area, widget, "cellradio",
cell_area.get_x() + x_offset + cell_xpad,
cell_area.get_y() + y_offset + cell_ypad,
width - 1, height - 1);
}
else
{
widget.get_style()->paint_check(
window_casted, state, shadow,
cell_area, widget, "cellcheck",
cell_area.get_x() + x_offset + cell_xpad,
cell_area.get_y() + y_offset + cell_ypad,
width - 1, height - 1);
}
}
*/
}
/*------------------------------------------------------------------------------
* The user clicked on the cell.
*----------------------------------------------------------------------------*/
bool ZebraCellRenderer::activate_vfunc(GdkEvent* event,
Gtk::Widget& widget,
const Glib::ustring& path,
const Gdk::Rectangle& background_area,
const Gdk::Rectangle& cell_area,
Gtk::CellRendererState flags)
throw ()
{
/*
std::cerr << "### activate_vfunc(): "
<< widget.get_name() << ", "
<< path << ", "
// << background_area << ", "
// << cell_area << ", "
<< flags << "\n";
// call the parent function
Gtk::CellRendererText::activate_vfunc(event, widget, path,
background_area, cell_area, flags);
std::cerr << "... done.\n";
*/
/*
if(property_activatable_)
{
signal_toggled_(path);
return true;
}
return false;
*/
}
<commit_msg>fixed bug #825<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: fgerlits $
Version : $Revision: 1.3 $
Location : $Source: /home/paul/cvs2svn-livesupport/newcvsrepo/livesupport/modules/widgets/src/ZebraCellRenderer.cxx,v $
------------------------------------------------------------------------------*/
/* ============================================================ include files */
#ifdef HAVE_CONFIG_H
#include "configure.h"
#endif
#include <iostream>
#include "LiveSupport/Widgets/ZebraCellRenderer.h"
using namespace LiveSupport::Widgets;
/* =================================================== local data structures */
/* ================================================ local constants & macros */
/* =============================================== local function prototypes */
/* ============================================================= module code */
/*------------------------------------------------------------------------------
* Constructor.
*----------------------------------------------------------------------------*/
ZebraCellRenderer::ZebraCellRenderer() throw ()
:
Glib::ObjectBase (typeid(ZebraCellRenderer)),
Gtk::CellRendererText ()
{
// std::cerr << "### constructor\n";
}
/*------------------------------------------------------------------------------
* Destructor.
*----------------------------------------------------------------------------*/
ZebraCellRenderer::~ZebraCellRenderer() throw ()
{
// std::cerr << "### destructor\n";
}
/*------------------------------------------------------------------------------
* Calculate the size of the cell.
*----------------------------------------------------------------------------*/
void
ZebraCellRenderer::get_size_vfunc(Gtk::Widget& widget,
const Gdk::Rectangle* cell_area,
int* x_offset, int* y_offset,
int* width, int* height) const
throw ()
{
/*
std::cerr << "### get_size_vfunc():"
<< (cell_area ? cell_area->get_x() : -1) << ", "
<< (cell_area ? cell_area->get_y() : -1) << "; "
<< (cell_area ? cell_area->get_width() : -1) << ", "
<< (cell_area ? cell_area->get_height() : -1) << "; "
<< (x_offset ? *x_offset : -1) << ", "
<< (y_offset ? *y_offset : -1) << " --- "
<< (width ? *width : -1) << ", "
<< (height ? *height : -1) << "\n";
*/
// call the parent method
Gtk::CellRendererText::get_size_vfunc(widget, cell_area,
x_offset, y_offset,
width, height);
/*
std::cerr << "... done: "
<< (cell_area ? cell_area->get_x() : -1) << ", "
<< (cell_area ? cell_area->get_y() : -1) << "; "
<< (cell_area ? cell_area->get_width() : -1) << ", "
<< (cell_area ? cell_area->get_height() : -1) << "; "
<< (x_offset ? *x_offset : -1) << ", "
<< (y_offset ? *y_offset : -1) << " --- "
<< (width ? *width : -1) << ", "
<< (height ? *height : -1) << "\n";
*/
/*
enum { TOGGLE_WIDTH = 12 };
const int calc_width = property_xpad() * 2 + TOGGLE_WIDTH;
const int calc_height = property_ypad() * 2 + TOGGLE_WIDTH;
if(width)
*width = calc_width;
if(height)
*height = calc_height;
if(cell_area)
{
if(x_offset)
{
*x_offset = int(property_xalign() * (cell_area->get_width() - calc_width));
*x_offset = std::max(0, *x_offset);
}
if(y_offset)
{
*y_offset = int(property_yalign() * (cell_area->get_height() - calc_height));
*y_offset = std::max(0, *y_offset);
}
}
*/
}
/*------------------------------------------------------------------------------
* Draw the cell.
*----------------------------------------------------------------------------*/
void
ZebraCellRenderer::render_vfunc(const Glib::RefPtr<Gdk::Drawable>& window,
Gtk::Widget& widget,
const Gdk::Rectangle& background_area,
const Gdk::Rectangle& cell_area,
const Gdk::Rectangle& expose_area,
Gtk::CellRendererState flags)
throw ()
{
/*
std::cerr << "### render_vfunc(): "
<< widget.get_name() << " --- "
<< background_area.get_x() << ", "
<< background_area.get_y() << "; "
<< background_area.get_width() << ", "
<< background_area.get_height() << " -- "
<< cell_area.get_x() << ", "
<< cell_area.get_y() << "; "
<< cell_area.get_width() << ", "
<< cell_area.get_height() << "; "
<< expose_area.get_x() << " -- "
<< expose_area.get_y() << "; "
<< expose_area.get_width() << ", "
<< expose_area.get_height() << " -- "
<< flags << "\n";
*/
// call the parent function
Gtk::CellRendererText::render_vfunc(window, widget, background_area,
cell_area, expose_area, flags);
/*
const unsigned int cell_xpad = property_xpad();
const unsigned int cell_ypad = property_ypad();
int x_offset = 0, y_offset = 0, width = 0, height = 0;
get_size(widget, cell_area, x_offset, y_offset, width, height);
width -= cell_xpad * 2;
height -= cell_ypad * 2;
if(width <= 0 || height <= 0)
return;
Gtk::StateType state = Gtk::STATE_INSENSITIVE;
if(property_activatable_)
state = Gtk::STATE_NORMAL;
if((flags & Gtk::CELL_RENDERER_SELECTED) != 0)
state = (widget.has_focus()) ? Gtk::STATE_SELECTED : Gtk::STATE_ACTIVE;
const Gtk::ShadowType shadow = (property_active_) ? Gtk::SHADOW_IN : Gtk::SHADOW_OUT;
//Cast the drawable to a Window. TODO: Maybe paint_option() should take a Drawable? murrayc.
Glib::RefPtr<Gdk::Window> window_casted = Glib::RefPtr<Gdk::Window>::cast_dynamic<>(window);
if(window_casted)
{
if(property_radio_)
{
widget.get_style()->paint_option(
window_casted, state, shadow,
cell_area, widget, "cellradio",
cell_area.get_x() + x_offset + cell_xpad,
cell_area.get_y() + y_offset + cell_ypad,
width - 1, height - 1);
}
else
{
widget.get_style()->paint_check(
window_casted, state, shadow,
cell_area, widget, "cellcheck",
cell_area.get_x() + x_offset + cell_xpad,
cell_area.get_y() + y_offset + cell_ypad,
width - 1, height - 1);
}
}
*/
}
/*------------------------------------------------------------------------------
* The user clicked on the cell.
*----------------------------------------------------------------------------*/
bool
ZebraCellRenderer::activate_vfunc(GdkEvent* event,
Gtk::Widget& widget,
const Glib::ustring& path,
const Gdk::Rectangle& background_area,
const Gdk::Rectangle& cell_area,
Gtk::CellRendererState flags)
throw ()
{
/*
std::cerr << "### activate_vfunc(): "
<< widget.get_name() << ", "
<< path << ", "
// << background_area << ", "
// << cell_area << ", "
<< flags << "\n";
*/
// call the parent function
return Gtk::CellRendererText::activate_vfunc(event, widget, path,
background_area, cell_area, flags);
/*
std::cerr << "... done.\n";
*/
/*
if(property_activatable_)
{
signal_toggled_(path);
return true;
}
return false;
*/
}
<|endoftext|> |
<commit_before>// illarionserver - server for the game Illarion
// Copyright 2011 Illarion e.V.
//
// This file is part of illarionserver.
//
// illarionserver 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.
//
// illarionserver 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 illarionserver. If not, see <http://www.gnu.org/licenses/>.
#include "Item.hpp"
#include "data/CommonObjectTable.hpp"
#include "data/ContainerObjectTable.hpp"
#include <sstream>
extern CommonObjectTable *CommonItems;
extern ContainerObjectTable *ContainerItems;
Item::Item(id_type id, number_type number, wear_type wear, quality_type quality, const luabind::object &datamap):
id(id), number(number), wear(wear), quality(quality), datamap(1) {
setData(datamap);
}
void Item::setMinQuality(const Item &item) {
quality_type minQuality = (quality < item.quality) ? quality : item.quality;
minQuality /= 100;
quality_type minDurability = (getDurability() < item.getDurability()) ? getDurability() : item.getDurability();
quality = minQuality * 100 + minDurability;
}
Item::data_type Item::getData() const {
LuaScript::writeDeprecatedMsg("Item.data");
return data;
}
void Item::setData(data_type data) {
LuaScript::writeDeprecatedMsg("Item.data");
this->data = data;
}
Item::data_type Item::getOldData() const {
return getData();
}
void Item::setOldData(data_type data) {
setData(data);
}
void Item::setData(const luabind::object &datamap) {
using namespace luabind;
auto mapType = type(datamap);
if (mapType == LUA_TTABLE) {
for (iterator it(datamap), end; it != end; ++it) {
std::string key;
try {
key = object_cast<std::string>(it.key());
} catch (cast_failed &e) {
throw std::logic_error("Usage of invalid data map key. Data map keys must be numbers or strings.");
}
std::string value;
try {
value = object_cast<std::string>(*it);
} catch (cast_failed &e) {
throw std::logic_error("Usage of invalid data map value. Data map values must be numbers or strings.");
}
setData(key, value);
}
} else if (mapType == LUA_TNUMBER) {
setOldData(object_cast<uint32_t>(datamap));
} else if (mapType != LUA_TNIL) {
throw std::logic_error("Usage of invalid data map type. Data maps must be tables or nil.");
}
}
bool Item::hasData(const luabind::object &datamap) {
using namespace luabind;
auto mapType = type(datamap);
if (mapType == LUA_TTABLE) {
bool isSameData = true;
for (iterator it(datamap), end; it != end && isSameData; ++it) {
std::string key;
try {
key = object_cast<std::string>(it.key());
} catch (cast_failed &e) {
throw std::logic_error("Usage of invalid data map key. Data map keys must be numbers or strings.");
}
std::string value;
try {
value = object_cast<std::string>(*it);
} catch (cast_failed &e) {
throw std::logic_error("Usage of invalid data map value. Data map values must be numbers or strings.");
}
isSameData = (getData(key) == value);
}
return isSameData;
} else if (mapType == LUA_TNUMBER) {
return getOldData() == object_cast<uint32_t>(datamap);
} else if (mapType != LUA_TNIL) {
throw std::logic_error("Usage of invalid data map type. Data maps must be tables or nil.");
}
return true;
}
std::string Item::getData(std::string key) {
return datamap[key];
}
void Item::setData(std::string key, std::string value) {
datamap[key] = value;
}
void Item::setData(std::string key, int32_t value) {
std::stringstream ss;
ss << value;
setData(key, ss.str());
}
void Item::reset() {
id = 0;
number = 0;
wear = 0;
quality = 333;
data = 0;
datamap.clear();
}
void Item::resetWear() {
CommonStruct common;
if (CommonItems->find(id, common)) {
if (!common.rotsInInventory && common.AgingSpeed > wear) {
wear = common.AgingSpeed;
}
}
}
void Item::save(std::ostream *obj) const {
obj->write((char *) &id, sizeof(id_type));
obj->write((char *) &number, sizeof(number_type));
obj->write((char *) &wear, sizeof(wear_type));
obj->write((char *) &quality, sizeof(quality_type));
obj->write((char *) &data, sizeof(data_type));
uint8_t mapsize = static_cast<uint8_t>(datamap.size());
obj->write((char *) &mapsize, sizeof(uint8_t));
for (auto it = datamap.begin(); it != datamap.end(); ++it) {
uint8_t sz1 = static_cast<uint8_t>(it->first.size());
uint8_t sz2 = static_cast<uint8_t>(it->second.size());
obj->write((char *) &sz1 , sizeof(uint8_t));
obj->write((char *) &sz2 , sizeof(uint8_t));
obj->write((char *) it->first.data() , sz1);
obj->write((char *) it->second.data() , sz2);
}
}
void Item::load(std::istream *obj) {
obj->read((char *) &id, sizeof(id_type));
obj->read((char *) &number, sizeof(number_type));
obj->read((char *) &wear, sizeof(wear_type));
obj->read((char *) &quality, sizeof(quality_type));
obj->read((char *) &data, sizeof(data_type));
uint8_t tempsize;
obj->read((char *) &tempsize, sizeof(uint8_t));
char readStr[255];
for (int i = 0; i < tempsize; ++i) {
uint8_t sz1 = 0;
uint8_t sz2 = 0;
obj->read((char *) &sz1, sizeof(uint8_t));
obj->read((char *) &sz2, sizeof(uint8_t));
obj->read((char *) readStr, sz1);
std::string key(readStr,sz1);
obj->read((char *) readStr, sz2);
std::string value(readStr,sz2);
datamap[key] = value;
}
}
bool Item::survivesAging() {
if (wear != 255 && wear != 0) {
--wear;
}
return wear > 0;
}
bool Item::isContainer() const {
return ContainerItems->find(id);
}
TYPE_OF_WEIGHT Item::getWeight() const {
CommonStruct common;
if (CommonItems->find(id, common)) {
return common.Weight;
}
return 0;
}
TYPE_OF_WORTH Item::getWorth() const {
CommonStruct common;
if (CommonItems->find(id, common)) {
return common.Worth;
}
return 0;
}
bool Item::isComplete() const {
return quality >= 100;
}
bool Item::isPermanent() const {
return wear == PERMANENT_WEAR;
}
void Item::makePermanent() {
wear = PERMANENT_WEAR;
}
<commit_msg>Add integer support for data values<commit_after>// illarionserver - server for the game Illarion
// Copyright 2011 Illarion e.V.
//
// This file is part of illarionserver.
//
// illarionserver 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.
//
// illarionserver 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 illarionserver. If not, see <http://www.gnu.org/licenses/>.
#include "Item.hpp"
#include "data/CommonObjectTable.hpp"
#include "data/ContainerObjectTable.hpp"
#include <sstream>
extern CommonObjectTable *CommonItems;
extern ContainerObjectTable *ContainerItems;
Item::Item(id_type id, number_type number, wear_type wear, quality_type quality, const luabind::object &datamap):
id(id), number(number), wear(wear), quality(quality), datamap(1) {
setData(datamap);
}
void Item::setMinQuality(const Item &item) {
quality_type minQuality = (quality < item.quality) ? quality : item.quality;
minQuality /= 100;
quality_type minDurability = (getDurability() < item.getDurability()) ? getDurability() : item.getDurability();
quality = minQuality * 100 + minDurability;
}
Item::data_type Item::getData() const {
LuaScript::writeDeprecatedMsg("Item.data");
return data;
}
void Item::setData(data_type data) {
LuaScript::writeDeprecatedMsg("Item.data");
this->data = data;
}
Item::data_type Item::getOldData() const {
return getData();
}
void Item::setOldData(data_type data) {
setData(data);
}
void Item::setData(const luabind::object &datamap) {
using namespace luabind;
auto mapType = type(datamap);
if (mapType == LUA_TTABLE) {
for (iterator it(datamap), end; it != end; ++it) {
std::string key;
try {
key = object_cast<std::string>(it.key());
} catch (cast_failed &e) {
throw std::logic_error("Usage of invalid data map key. Data map keys must be strings.");
}
try {
std::string value = object_cast<std::string>(*it);
setData(key, value);
} catch (cast_failed &e) {
try {
int32_t intValue = object_cast<int32_t>(*it);
setData(key, intValue);
} catch (cast_failed &e) {
throw std::logic_error("Usage of invalid data map value. Data map values must be numbers or strings.");
}
}
}
} else if (mapType == LUA_TNUMBER) {
setOldData(object_cast<uint32_t>(datamap));
} else if (mapType != LUA_TNIL) {
throw std::logic_error("Usage of invalid data map type. Data maps must be tables or nil.");
}
}
bool Item::hasData(const luabind::object &datamap) {
using namespace luabind;
auto mapType = type(datamap);
if (mapType == LUA_TTABLE) {
bool isSameData = true;
for (iterator it(datamap), end; it != end && isSameData; ++it) {
std::string key;
try {
key = object_cast<std::string>(it.key());
} catch (cast_failed &e) {
throw std::logic_error("Usage of invalid data map key. Data map keys must be strings.");
}
std::string value;
try {
value = object_cast<std::string>(*it);
} catch (cast_failed &e) {
try {
int32_t intValue = object_cast<int32_t>(*it);
std::stringstream ss;
ss << intValue;
value = ss.str();
} catch (cast_failed &e) {
throw std::logic_error("Usage of invalid data map value. Data map values must be numbers or strings.");
}
}
isSameData = (getData(key) == value);
}
return isSameData;
} else if (mapType == LUA_TNUMBER) {
return getOldData() == object_cast<uint32_t>(datamap);
} else if (mapType != LUA_TNIL) {
throw std::logic_error("Usage of invalid data map type. Data maps must be tables or nil.");
}
return true;
}
std::string Item::getData(std::string key) {
return datamap[key];
}
void Item::setData(std::string key, std::string value) {
datamap[key] = value;
}
void Item::setData(std::string key, int32_t value) {
std::stringstream ss;
ss << value;
setData(key, ss.str());
}
void Item::reset() {
id = 0;
number = 0;
wear = 0;
quality = 333;
data = 0;
datamap.clear();
}
void Item::resetWear() {
CommonStruct common;
if (CommonItems->find(id, common)) {
if (!common.rotsInInventory && common.AgingSpeed > wear) {
wear = common.AgingSpeed;
}
}
}
void Item::save(std::ostream *obj) const {
obj->write((char *) &id, sizeof(id_type));
obj->write((char *) &number, sizeof(number_type));
obj->write((char *) &wear, sizeof(wear_type));
obj->write((char *) &quality, sizeof(quality_type));
obj->write((char *) &data, sizeof(data_type));
uint8_t mapsize = static_cast<uint8_t>(datamap.size());
obj->write((char *) &mapsize, sizeof(uint8_t));
for (auto it = datamap.begin(); it != datamap.end(); ++it) {
uint8_t sz1 = static_cast<uint8_t>(it->first.size());
uint8_t sz2 = static_cast<uint8_t>(it->second.size());
obj->write((char *) &sz1 , sizeof(uint8_t));
obj->write((char *) &sz2 , sizeof(uint8_t));
obj->write((char *) it->first.data() , sz1);
obj->write((char *) it->second.data() , sz2);
}
}
void Item::load(std::istream *obj) {
obj->read((char *) &id, sizeof(id_type));
obj->read((char *) &number, sizeof(number_type));
obj->read((char *) &wear, sizeof(wear_type));
obj->read((char *) &quality, sizeof(quality_type));
obj->read((char *) &data, sizeof(data_type));
uint8_t tempsize;
obj->read((char *) &tempsize, sizeof(uint8_t));
char readStr[255];
for (int i = 0; i < tempsize; ++i) {
uint8_t sz1 = 0;
uint8_t sz2 = 0;
obj->read((char *) &sz1, sizeof(uint8_t));
obj->read((char *) &sz2, sizeof(uint8_t));
obj->read((char *) readStr, sz1);
std::string key(readStr,sz1);
obj->read((char *) readStr, sz2);
std::string value(readStr,sz2);
datamap[key] = value;
}
}
bool Item::survivesAging() {
if (wear != 255 && wear != 0) {
--wear;
}
return wear > 0;
}
bool Item::isContainer() const {
return ContainerItems->find(id);
}
TYPE_OF_WEIGHT Item::getWeight() const {
CommonStruct common;
if (CommonItems->find(id, common)) {
return common.Weight;
}
return 0;
}
TYPE_OF_WORTH Item::getWorth() const {
CommonStruct common;
if (CommonItems->find(id, common)) {
return common.Worth;
}
return 0;
}
bool Item::isComplete() const {
return quality >= 100;
}
bool Item::isPermanent() const {
return wear == PERMANENT_WEAR;
}
void Item::makePermanent() {
wear = PERMANENT_WEAR;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
#include "mfem.hpp"
#include "unit_tests.hpp"
using namespace mfem;
#ifdef MFEM_USE_MPI
class IdentitySolver : public Solver
{
public:
IdentitySolver(int n) : Solver(n) { }
void Mult(const Vector& x, Vector& y) const { y = x; }
void SetOperator(const Operator& op) { }
};
class SimpleSaddle
{
public:
SimpleSaddle(double alpha, double beta);
~SimpleSaddle();
void Schur(Vector& serr, Vector& lerr);
void Penalty(double pen, Vector& serr, Vector& lerr);
void Elimination(Vector &serr, Vector& lerr);
void SetDualRHS(Vector &dualrhs_);
private:
SparseMatrix A, B;
HypreParMatrix * hA;
Vector rhs, sol, dualrhs, lambda;
double truex, truey, truelambda;
};
SimpleSaddle::SimpleSaddle(double alpha, double beta)
:
A(2, 2), B(1, 2), rhs(2), sol(2), dualrhs(1), lambda(1)
{
truex = 0.5 * alpha - 0.5 * beta;
truey = -0.5 * alpha + 0.5 * beta;
truelambda = 0.5 * (alpha + beta);
A.Add(0, 0, 1.0);
A.Add(1, 1, 1.0);
A.Finalize();
B.Add(0, 0, 1.0);
B.Add(0, 1, 1.0);
B.Finalize();
int row_starts[2] = {0, 2};
hA = new HypreParMatrix(MPI_COMM_WORLD, 2, row_starts, &A);
hA->CopyRowStarts();
rhs(0) = alpha;
rhs(1) = beta;
dualrhs = 0.0;
}
SimpleSaddle::~SimpleSaddle()
{
delete hA;
}
void SimpleSaddle::SetDualRHS(Vector& dualrhs_)
{
dualrhs = dualrhs_;
truelambda = truelambda - 0.5 * dualrhs(0);
truex = truex + 0.5 * dualrhs(0);
truey = truey + 0.5 * dualrhs(0);
}
void SimpleSaddle::Schur(Vector& serr, Vector& lerr)
{
ConstrainedSolver solver(*hA, B);
IdentitySolver prec(2);
solver.SetSchur(prec);
solver.SetDualRHS(dualrhs);
solver.SetRelTol(1.e-14);
solver.Mult(rhs, sol);
solver.GetDualSolution(lambda);
serr(0) = truex - sol(0);
serr(1) = truey - sol(1);
lerr(0) = truelambda - lambda(0);
}
void SimpleSaddle::Elimination(Vector& serr, Vector& lerr)
{
ConstrainedSolver solver(*hA, B);
Array<int> primary(1);
primary[0] = 0;
Array<int> secondary(1);
secondary[0] = 1;
solver.SetElimination(primary, secondary);
solver.SetDualRHS(dualrhs);
solver.Mult(rhs, sol);
solver.GetDualSolution(lambda);
serr(0) = truex - sol(0);
serr(1) = truey - sol(1);
lerr(0) = truelambda - lambda(0);
}
void SimpleSaddle::Penalty(double pen, Vector& serr, Vector& lerr)
{
ConstrainedSolver solver(*hA, B);
solver.SetPenalty(pen);
solver.SetDualRHS(dualrhs);
solver.Mult(rhs, sol);
solver.GetDualSolution(lambda);
serr(0) = truex - sol(0);
serr(1) = truey - sol(1);
lerr(0) = truelambda - lambda(0);
}
// TODO: test actual parallel problem, ...
TEST_CASE("ConstrainedSolver", "[Parallel], [ConstrainedSolver]")
{
int comm_size;
MPI_Comm_size(MPI_COMM_WORLD, &comm_size);
if (comm_size == 1)
{
Vector serr(2);
Vector lerr(1);
SimpleSaddle problem(4.0, -2.0);
problem.Schur(serr, lerr);
REQUIRE(serr(0) == MFEM_Approx(0.0));
REQUIRE(serr(1) == MFEM_Approx(0.0));
REQUIRE(lerr(0) == MFEM_Approx(0.0));
problem.Elimination(serr, lerr);
REQUIRE(serr(0) == MFEM_Approx(0.0));
REQUIRE(serr(1) == MFEM_Approx(0.0));
REQUIRE(lerr(0) == MFEM_Approx(0.0));
for (auto pen : {1.e+3, 1.e+4, 1.e+6})
{
problem.Penalty(pen, serr, lerr);
REQUIRE(std::abs(serr(0)) < pen);
REQUIRE(std::abs(serr(1)) < pen);
REQUIRE(std::abs(lerr(0)) < pen);
}
Vector dualrhs(1);
dualrhs(0) = 1.0;
problem.SetDualRHS(dualrhs);
problem.Schur(serr, lerr);
REQUIRE(serr(0) == MFEM_Approx(0.0));
REQUIRE(serr(1) == MFEM_Approx(0.0));
REQUIRE(lerr(0) == MFEM_Approx(0.0));
problem.Elimination(serr, lerr);
REQUIRE(serr(0) == MFEM_Approx(0.0));
REQUIRE(serr(1) == MFEM_Approx(0.0));
REQUIRE(lerr(0) == MFEM_Approx(0.0));
for (auto pen : {1.e+3, 1.e+4, 1.e+6})
{
problem.Penalty(pen, serr, lerr);
REQUIRE(std::abs(serr(0)) < pen);
REQUIRE(std::abs(serr(1)) < pen);
REQUIRE(std::abs(lerr(0)) < pen);
}
}
}
class ParallelTestProblem
{
public:
ParallelTestProblem();
~ParallelTestProblem();
private:
HypreParMatrix * amat;
HypreParMatrix * bmat;
};
ParallelTestProblem::ParallelTestProblem()
{
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
/// probably need localI to stick around...
SparseMatrix localI(2);
localI.Add(0, 0, 1.0);
localI.Add(1, 1, 1.0);
localI.Finalize();
int row_starts_a[2] = {2 * rank, 2 * (rank + 1)};
amat = new HypreParMatrix(MPI_COMM_WORLD, 8, row_starts_a, &localI);
amat->CopyRowStarts();
amat->Print("amat.hyprematrix");
SparseMatrix Blocal(1, 8);
if (rank == 3)
{
Blocal.Add(0, 0, 1.0);
Blocal.Add(0, 7, 1.0);
}
else
{
Blocal.Add(0, 2*rank + 1, 1.0);
Blocal.Add(0, 2*rank + 2, 1.0);
}
Blocal.Finalize();
int row_starts_c[2] = { rank, rank + 1 };
int col_starts[2] = { 2*rank, 2 * (rank + 1) };
bmat = new HypreParMatrix(MPI_COMM_WORLD, 1, 4, 8, Blocal.GetI(),
Blocal.GetJ(), Blocal.GetData(), row_starts_c,
col_starts);
bmat->Print("bmat.hyprematrix");
}
ParallelTestProblem::~ParallelTestProblem()
{
delete amat;
delete bmat;
}
/// *actual* parallel constrained solver
TEST_CASE("ParallelConstrainedSolver", "[Parallel], [ConstrainedSolver]")
{
int comm_size;
MPI_Comm_size(MPI_COMM_WORLD, &comm_size);
if (comm_size == 4)
{
ParallelTestProblem problem;
}
}
#endif
<commit_msg>Very basic unit test for ConstrainedSolver Schur version works.<commit_after>// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
#include "mfem.hpp"
#include "unit_tests.hpp"
using namespace mfem;
#ifdef MFEM_USE_MPI
class IdentitySolver : public Solver
{
public:
IdentitySolver(int n) : Solver(n) { }
void Mult(const Vector& x, Vector& y) const { y = x; }
void SetOperator(const Operator& op) { }
};
class SimpleSaddle
{
public:
SimpleSaddle(double alpha, double beta);
~SimpleSaddle();
void Schur(Vector& serr, Vector& lerr);
void Penalty(double pen, Vector& serr, Vector& lerr);
void Elimination(Vector &serr, Vector& lerr);
void SetDualRHS(Vector &dualrhs_);
private:
SparseMatrix A, B;
HypreParMatrix * hA;
Vector rhs, sol, dualrhs, lambda;
double truex, truey, truelambda;
};
SimpleSaddle::SimpleSaddle(double alpha, double beta)
:
A(2, 2), B(1, 2), rhs(2), sol(2), dualrhs(1), lambda(1)
{
truex = 0.5 * alpha - 0.5 * beta;
truey = -0.5 * alpha + 0.5 * beta;
truelambda = 0.5 * (alpha + beta);
A.Add(0, 0, 1.0);
A.Add(1, 1, 1.0);
A.Finalize();
B.Add(0, 0, 1.0);
B.Add(0, 1, 1.0);
B.Finalize();
int row_starts[2] = {0, 2};
hA = new HypreParMatrix(MPI_COMM_WORLD, 2, row_starts, &A);
hA->CopyRowStarts();
rhs(0) = alpha;
rhs(1) = beta;
dualrhs = 0.0;
}
SimpleSaddle::~SimpleSaddle()
{
delete hA;
}
void SimpleSaddle::SetDualRHS(Vector& dualrhs_)
{
dualrhs = dualrhs_;
truelambda = truelambda - 0.5 * dualrhs(0);
truex = truex + 0.5 * dualrhs(0);
truey = truey + 0.5 * dualrhs(0);
}
void SimpleSaddle::Schur(Vector& serr, Vector& lerr)
{
ConstrainedSolver solver(*hA, B);
IdentitySolver prec(2);
solver.SetSchur(prec);
solver.SetDualRHS(dualrhs);
solver.SetRelTol(1.e-14);
solver.Mult(rhs, sol);
solver.GetDualSolution(lambda);
serr(0) = truex - sol(0);
serr(1) = truey - sol(1);
lerr(0) = truelambda - lambda(0);
}
void SimpleSaddle::Elimination(Vector& serr, Vector& lerr)
{
ConstrainedSolver solver(*hA, B);
Array<int> primary(1);
primary[0] = 0;
Array<int> secondary(1);
secondary[0] = 1;
solver.SetElimination(primary, secondary);
solver.SetDualRHS(dualrhs);
solver.Mult(rhs, sol);
solver.GetDualSolution(lambda);
serr(0) = truex - sol(0);
serr(1) = truey - sol(1);
lerr(0) = truelambda - lambda(0);
}
void SimpleSaddle::Penalty(double pen, Vector& serr, Vector& lerr)
{
ConstrainedSolver solver(*hA, B);
solver.SetPenalty(pen);
solver.SetDualRHS(dualrhs);
solver.Mult(rhs, sol);
solver.GetDualSolution(lambda);
serr(0) = truex - sol(0);
serr(1) = truey - sol(1);
lerr(0) = truelambda - lambda(0);
}
// TODO: test actual parallel problem, ...
TEST_CASE("ConstrainedSolver", "[Parallel], [ConstrainedSolver]")
{
int comm_size;
MPI_Comm_size(MPI_COMM_WORLD, &comm_size);
if (comm_size == 1)
{
Vector serr(2);
Vector lerr(1);
SimpleSaddle problem(4.0, -2.0);
problem.Schur(serr, lerr);
REQUIRE(serr(0) == MFEM_Approx(0.0));
REQUIRE(serr(1) == MFEM_Approx(0.0));
REQUIRE(lerr(0) == MFEM_Approx(0.0));
problem.Elimination(serr, lerr);
REQUIRE(serr(0) == MFEM_Approx(0.0));
REQUIRE(serr(1) == MFEM_Approx(0.0));
REQUIRE(lerr(0) == MFEM_Approx(0.0));
for (auto pen : {1.e+3, 1.e+4, 1.e+6})
{
problem.Penalty(pen, serr, lerr);
REQUIRE(std::abs(serr(0)) < pen);
REQUIRE(std::abs(serr(1)) < pen);
REQUIRE(std::abs(lerr(0)) < pen);
}
Vector dualrhs(1);
dualrhs(0) = 1.0;
problem.SetDualRHS(dualrhs);
problem.Schur(serr, lerr);
REQUIRE(serr(0) == MFEM_Approx(0.0));
REQUIRE(serr(1) == MFEM_Approx(0.0));
REQUIRE(lerr(0) == MFEM_Approx(0.0));
problem.Elimination(serr, lerr);
REQUIRE(serr(0) == MFEM_Approx(0.0));
REQUIRE(serr(1) == MFEM_Approx(0.0));
REQUIRE(lerr(0) == MFEM_Approx(0.0));
for (auto pen : {1.e+3, 1.e+4, 1.e+6})
{
problem.Penalty(pen, serr, lerr);
REQUIRE(std::abs(serr(0)) < pen);
REQUIRE(std::abs(serr(1)) < pen);
REQUIRE(std::abs(lerr(0)) < pen);
}
}
}
class ParallelTestProblem
{
public:
ParallelTestProblem();
~ParallelTestProblem();
void Schur(Vector& serr, Vector& lerr);
void Penalty(double pen, Vector& serr, Vector& lerr);
private:
SparseMatrix Alocal;
Vector rhs, sol, truesol, lambda, truelambda;
HypreParMatrix * amat;
HypreParMatrix * bmat;
};
ParallelTestProblem::ParallelTestProblem()
:
Alocal(2), rhs(2), sol(2), truesol(2), lambda(1), truelambda(1)
{
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
Alocal.Add(0, 0, 1.0);
Alocal.Add(1, 1, 1.0);
Alocal.Finalize();
int row_starts_a[2] = {2 * rank, 2 * (rank + 1)};
amat = new HypreParMatrix(MPI_COMM_WORLD, 8, row_starts_a, &Alocal);
amat->CopyRowStarts();
SparseMatrix Blocal(1, 8);
if (rank == 3)
{
Blocal.Add(0, 0, 1.0);
Blocal.Add(0, 7, 1.0);
}
else
{
Blocal.Add(0, 2*rank + 1, 1.0);
Blocal.Add(0, 2*rank + 2, 1.0);
}
Blocal.Finalize();
int row_starts_c[2] = { rank, rank + 1 };
int col_starts[2] = { 2*rank, 2 * (rank + 1) };
bmat = new HypreParMatrix(MPI_COMM_WORLD, 1, 4, 8, Blocal.GetI(),
Blocal.GetJ(), Blocal.GetData(), row_starts_c,
col_starts);
// rhs // [ 1.1 -2. 3. -1.4 2.1 -3.2 -1.1 2.2 0. 0. 0. 0. ]
// truesol // [-0.55 -2.5 2.5 -1.75 1.75 -1.05 1.05 0.55 0.5 0.35 -2.15 1.65]
rhs = 0.0;
if (rank == 0)
{
rhs(0) = 1.1;
truesol(0) = -0.55;
rhs(1) = -2.0;
truesol(1) = -2.5;
truelambda(0) = 0.5;
}
else if (rank == 1)
{
rhs(0) = 3.0;
truesol(0) = 2.5;
rhs(1) = -1.4;
truesol(1) = -1.75;
truelambda(0) = 0.3500000000000001;
}
else if (rank == 2)
{
rhs(0) = 2.1;
truesol(0) = 1.75;
rhs(1) = -3.2;
truesol(1) = -1.0499999999999998;
truelambda(0) = -2.1500000000000004;
}
else if (rank == 3)
{
rhs(0) = -1.1;
truesol(0) = 1.0500000000000003;
rhs(1) = 2.2;
truesol(1) = 0.55;
truelambda(0) = 1.6500000000000001;
}
else
{
mfem_error("Test only works on 4 ranks!");
}
}
ParallelTestProblem::~ParallelTestProblem()
{
delete amat;
delete bmat;
}
void ParallelTestProblem::Schur(Vector& serr, Vector& lerr)
{
ConstrainedSolver solver(*amat, *bmat);
IdentitySolver prec(2);
solver.SetSchur(prec);
// solver.SetRelTol(1.e-14);
solver.Mult(rhs, sol);
solver.GetDualSolution(lambda);
for (int i = 0; i < 2; ++i)
{
serr(i) = truesol(i) - sol(i);
}
for (int i = 0; i < 1; ++i)
{
lerr(i) = truelambda(i) - lambda(i);
}
}
void ParallelTestProblem::Penalty(double pen, Vector& serr, Vector& lerr)
{
}
/// *actual* parallel constrained solver
TEST_CASE("ParallelConstrainedSolver", "[Parallel], [ConstrainedSolver]")
{
int comm_size;
MPI_Comm_size(MPI_COMM_WORLD, &comm_size);
if (comm_size == 4)
{
Vector serr(2), lerr(1);
ParallelTestProblem problem;
problem.Schur(serr, lerr);
double serrnorm = serr.Norml2();
REQUIRE(serrnorm == MFEM_Approx(0.0));
REQUIRE(lerr(0) == MFEM_Approx(0.0));
}
}
#endif
<|endoftext|> |
<commit_before>#include "Command.h"
#include <iostream>
#include <boost/tokenizer.hpp>
#include <sys/types.h>
#include <sys/wait.h>
using namespace std;
using namespace boost;
Command::Command()
{
commandString = "";
///pass = false;
}
Command::Command(string c)
{
commandString = c;
}
string Command::getString()
{
return this->commandString;
}
void Command::print()
{
//cout << this->commandString;
}
void Command::execute()
{
string command = this->getString();
typedef tokenizer<char_separator<char> > tokenizer;
char_separator<char> sep(" ",";||&&", drop_empty_tokens);
tokenizer tok(command, sep);
vector<char*> vec;
for(tokenizer::iterator itr = tok.begin(); itr != tok.end(); itr++)
{
string temp = static_cast<string>(*itr);
vec.push_back((char*)temp.c_str());
}
vec.push_back(NULL);
char** commands = &vec[0];
//cout << "command: " << vec.at(0) << endl;
this->success = true;
pid_t pid = fork();
int status;
if(pid < 0)
{
//cout << "error" << endl;
//cout << "EXITING" << endl;
exit(1);
}
else if (pid == 0)
{
int result = execvp(commands[0], commands);
if(result == -1)
{
//cout << "INPUTTED COMMAND IS FALSE " << endl;
this->success = false;
//cout << "after " << endl;
}
else
{
this->success = true;
//cout << "after << endl";
}
//cout << "after 1 " << endl;
}
else
{
//cout << "after 3" << endl;
while(waitpid(pid, &status, 0) != pid);
//cout << "after 4" << endl;
}
//cout << "after 5" << endl;
// return;
//cout << "agfter6 " << this->success << endl;
}
void Command::connector()
{
}
// void Command::setString()
// {
// this->commandString = "";
// }
// bool Command::isSuccess()
// {
// if(this->pass)
// {
// return true;
// }
// return false;
// }
// void Command::setBool(bool b)
// {
// this->pass = b;
// }<commit_msg>Delete Command.cpp<commit_after><|endoftext|> |
<commit_before>#include "viewer.hpp"
#include "trac0r/utils.hpp"
#include <SDL_ttf.h>
#include <SDL_image.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/intersect.hpp>
#include <glm/gtc/random.hpp>
#include <glm/gtx/string_cast.hpp>
#include <glm/gtx/rotate_vector.hpp>
#include <algorithm>
#include <iostream>
Viewer::~Viewer() {
TTF_CloseFont(m_font);
TTF_Quit();
SDL_DestroyTexture(m_render_tex);
SDL_DestroyRenderer(m_render);
SDL_DestroyWindow(m_window);
IMG_Quit();
SDL_Quit();
}
int Viewer::init() {
std::cout << "Start init" << std::endl;
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) != 0) {
std::cerr << "SDL_Init error: " << SDL_GetError() << std::endl;
return 1;
}
int screen_width = 600;
int screen_height = 400;
m_window = SDL_CreateWindow("trac0r", 100, 100, screen_width, screen_height, SDL_WINDOW_SHOWN);
if (m_window == nullptr) {
std::cerr << "SDL_CreateWindow error: " << SDL_GetError() << std::endl;
SDL_Quit();
return 1;
}
// m_render = SDL_CreateRenderer(m_window, -1, SDL_RENDERER_ACCELERATED |
// SDL_RENDERER_PRESENTVSYNC);
m_render = SDL_CreateRenderer(m_window, -1, SDL_RENDERER_ACCELERATED);
m_render_tex = SDL_CreateTexture(m_render, SDL_PIXELFORMAT_ARGB8888,
SDL_TEXTUREACCESS_STREAMING, screen_width, screen_height);
m_pixels.resize(screen_width * screen_height, 0);
if (m_render == nullptr) {
SDL_DestroyWindow(m_window);
std::cerr << "SDL_CreateRenderer error: " << SDL_GetError() << std::endl;
SDL_Quit();
return 1;
}
if (TTF_Init() != 0) {
std::cerr << "SDL_ttf could not initialize! SDL_ttf error: " << SDL_GetError() << std::endl;
return 1;
}
auto font_path = "res/DejaVuSansMono-Bold.ttf";
m_font = TTF_OpenFont(font_path, 14);
if (m_font == nullptr) {
std::cerr << "SDL_ttf could not open '" << font_path << "'" << std::endl;
return 1;
}
// Setup scene
setup_scene(screen_width, screen_height);
std::cout << "Finish init" << std::endl;
return 0;
}
void Viewer::setup_scene(int screen_width, int screen_height) {
auto triangle1 = std::make_unique<Triangle>(
glm::vec3{0.f, 0.f, -0.89f}, glm::vec3{0.07f, 0.f, -0.89f}, glm::vec3{0.07f, -0.04f, -0.89f},
glm::vec3{0.3, 0.3, 0.3}, glm::vec3{0.2, 0.2, 0.2});
auto triangle2 = std::make_unique<Triangle>(
glm::vec3{-0.05f, 0.f, -0.6f}, glm::vec3{-0.005f, 0.f, -0.6f}, glm::vec3{-0.05f, -0.04f, -0.6f},
glm::vec3{0.9, 0.3, 0.3}, glm::vec3{0.2, 0.2, 0.4});
m_scene.push_back(std::move(triangle1));
m_scene.push_back(std::move(triangle2));
// for (auto i = 0; i < 2; i++) {
// auto triangle =
// std::make_unique<Triangle>(glm::ballRand(5.f), glm::ballRand(5.f),
// glm::ballRand(5.f),
// glm::vec3{0.8, 0.3, 0.3}, glm::vec3{0.5, 0.5, 0.5});
// m_scene.push_back(std::move(triangle));
// }
glm::vec3 cam_pos = {0, 0, -1};
glm::vec3 cam_dir = {0, 0, 1};
glm::vec3 cam_up = {0, 1, 0};
m_camera = Camera(cam_pos, cam_dir, cam_up, 90.f, 0.1, 100.f, screen_width, screen_height);
}
glm::vec3 Viewer::intersect_scene(glm::vec3 &ray_pos, glm::vec3 &ray_dir, int depth) {
const auto MAX_DEPTH = 5;
if (depth == MAX_DEPTH)
return {0, 0, 0};
// check all triangles for collision
bool collided = false;
glm::vec3 ret_color;
for (const auto &tri : m_scene) {
glm::vec3 bary_pos;
collided =
glm::intersectRayTriangle(ray_pos, ray_dir, tri->m_v1, tri->m_v2, tri->m_v3, bary_pos);
if (collided) {
glm::vec3 new_ray_pos = ray_pos + ray_dir * bary_pos.z;
auto new_ray_dir = tri->m_normal;
new_ray_dir = glm::rotateX(tri->m_normal, glm::linearRand(-90.f, 90.f));
new_ray_dir = glm::rotateY(tri->m_normal, glm::linearRand(-90.f, 90.f));
float cos_theta = glm::dot(new_ray_dir, tri->m_normal);
glm::vec3 brdf = 2.f * tri->m_reflectance * cos_theta;
glm::vec3 reflected = intersect_scene(new_ray_pos, new_ray_dir, depth + 1);
ret_color = tri->m_emittance + (brdf * reflected);
break;
}
}
if (collided) {
return ret_color;
} else {
return {0, 0, 0};
}
}
void Viewer::mainloop() {
int current_time = SDL_GetTicks();
double dt = (current_time - m_last_frame_time) / 1000.0;
m_last_frame_time = current_time;
// Input
SDL_Event e;
while (SDL_PollEvent(&e)) {
if (e.type == SDL_QUIT) {
shutdown();
}
if (e.type == SDL_KEYDOWN) {
if (e.key.keysym.sym == SDLK_ESCAPE) {
shutdown();
}
}
if (e.type == SDL_MOUSEBUTTONDOWN) {
if (e.button.button == SDL_BUTTON_RIGHT) {
if (m_look_mode) {
m_look_mode = false;
SDL_SetRelativeMouseMode(SDL_FALSE);
} else if (!m_look_mode) {
m_look_mode = true;
SDL_SetRelativeMouseMode(SDL_TRUE);
}
}
}
}
glm::vec3 cam_velocity{0};
const uint8_t *keystates = SDL_GetKeyboardState(0);
if (keystates[SDL_SCANCODE_A])
cam_velocity.x += -0.01f;
else if (keystates[SDL_SCANCODE_D])
cam_velocity.x += 0.01f;
if (keystates[SDL_SCANCODE_W])
cam_velocity.z += 0.01f;
else if (keystates[SDL_SCANCODE_S])
cam_velocity.z += -0.01f;
m_camera.set_pos(m_camera.pos() += cam_velocity);
// Rendering here
int width;
int height;
SDL_GetWindowSize(m_window, &width, &height);
glm::ivec2 mouse_pos;
if (m_look_mode) {
SDL_GetRelativeMouseState(&(mouse_pos.x), &(mouse_pos.y));
m_camera.set_dir(glm::rotateX(m_camera.dir(), mouse_pos.y * 0.001f));
m_camera.set_dir(glm::rotateY(m_camera.dir(), mouse_pos.x * 0.001f));
} else if (!m_look_mode) {
SDL_GetMouseState(&(mouse_pos.x), &(mouse_pos.y));
}
// Lots of debug info
glm::vec2 mouse_rel_pos = m_camera.screenspace_to_camspace(mouse_pos.x, mouse_pos.y);
glm::vec3 mouse_canvas_pos = m_camera.camspace_to_worldspace(mouse_rel_pos);
auto fps_debug_info = "FPS: " + std::to_string(int(1. / dt));
auto cam_look_debug_info = "Cam Look Mode: " + std::to_string(m_look_mode);
auto cam_pos_debug_info = "Cam Pos: " + glm::to_string(m_camera.pos());
auto cam_dir_debug_info = "Cam Dir: " + glm::to_string(m_camera.dir());
auto cam_fov_debug_info =
"Cam FOV (H/V): " + std::to_string(int(glm::degrees(m_camera.horizontal_fov()))) + "/";
cam_fov_debug_info += std::to_string(int(glm::degrees(m_camera.vertical_fov())));
auto cam_canvas_center_pos_info =
"Cam Canvas Center: " + glm::to_string(m_camera.canvas_center_pos());
auto mouse_pos_screen_info = "Mouse Pos Screen Space: " + glm::to_string(mouse_pos);
auto mouse_pos_relative_info = "Mouse Pos Cam Space: " + glm::to_string(mouse_rel_pos);
auto mouse_pos_canvas_info =
"Mouse Pos Canvas World Space: " + glm::to_string(mouse_canvas_pos);
auto cam_look_debug_tex =
trac0r::make_text(m_render, m_font, cam_look_debug_info, {200, 100, 100, 200});
auto cam_pos_debug_tex =
trac0r::make_text(m_render, m_font, cam_pos_debug_info, {200, 100, 100, 200});
auto cam_dir_debug_tex =
trac0r::make_text(m_render, m_font, cam_dir_debug_info, {200, 100, 100, 200});
auto cam_fov_debug_tex =
trac0r::make_text(m_render, m_font, cam_fov_debug_info, {200, 100, 100, 200});
auto fps_debug_tex = trac0r::make_text(m_render, m_font, fps_debug_info, {200, 100, 100, 200});
auto cam_canvas_center_pos_tex =
trac0r::make_text(m_render, m_font, cam_canvas_center_pos_info, {200, 100, 100, 200});
auto mouse_pos_screen_tex =
trac0r::make_text(m_render, m_font, mouse_pos_screen_info, {200, 100, 100, 200});
auto mouse_pos_relative_tex =
trac0r::make_text(m_render, m_font, mouse_pos_relative_info, {200, 100, 100, 200});
auto mouse_pos_canvas_tex =
trac0r::make_text(m_render, m_font, mouse_pos_canvas_info, {200, 100, 100, 200});
// Sort by distance to camera
std::sort(m_scene.begin(), m_scene.end(), [this](const auto &tri1, const auto &tri2) {
return glm::distance(m_camera.pos(), tri1->m_centroid) <
glm::distance(m_camera.pos(), tri2->m_centroid);
});
for (auto sample_cnt = 0; sample_cnt < 2; sample_cnt++) {
for (auto x = 0; x < width; x++) {
for (auto y = 0; y < height; y++) {
glm::vec2 rel_pos = m_camera.screenspace_to_camspace(x, y);
glm::vec3 world_pos = m_camera.camspace_to_worldspace(rel_pos);
glm::vec3 ray_dir = world_pos - m_camera.pos();
glm::vec3 color = intersect_scene(world_pos, ray_dir, 0);
m_pixels[y * width + x] = 0xff << 24 | int(color.r * 255) << 16 |
int(color.g * 255) << 8 | int(color.b * 255);
}
}
}
SDL_RenderClear(m_render);
SDL_UpdateTexture(m_render_tex, 0, m_pixels.data(), width * sizeof(uint32_t));
SDL_RenderCopy(m_render, m_render_tex, 0, 0);
trac0r::render_text(m_render, fps_debug_tex, 10, 10);
trac0r::render_text(m_render, cam_look_debug_tex, 10, 25);
trac0r::render_text(m_render, cam_pos_debug_tex, 10, 40);
trac0r::render_text(m_render, cam_dir_debug_tex, 10, 55);
trac0r::render_text(m_render, cam_fov_debug_tex, 10, 70);
trac0r::render_text(m_render, cam_canvas_center_pos_tex, 10, 85);
trac0r::render_text(m_render, mouse_pos_screen_tex, 10, 100);
trac0r::render_text(m_render, mouse_pos_relative_tex, 10, 115);
trac0r::render_text(m_render, mouse_pos_canvas_tex, 10, 130);
SDL_RenderPresent(m_render);
SDL_DestroyTexture(fps_debug_tex);
SDL_DestroyTexture(cam_look_debug_tex);
SDL_DestroyTexture(cam_pos_debug_tex);
SDL_DestroyTexture(cam_dir_debug_tex);
SDL_DestroyTexture(cam_fov_debug_tex);
SDL_DestroyTexture(cam_canvas_center_pos_tex);
SDL_DestroyTexture(mouse_pos_screen_tex);
SDL_DestroyTexture(mouse_pos_relative_tex);
SDL_DestroyTexture(mouse_pos_canvas_tex);
}
SDL_Renderer *Viewer::renderer() {
return m_render;
}
SDL_Window *Viewer::window() {
return m_window;
}
bool Viewer::is_running() {
return m_running;
}
void Viewer::shutdown() {
m_running = false;
}
<commit_msg>Set better cam parameters<commit_after>#include "viewer.hpp"
#include "trac0r/utils.hpp"
#include <SDL_ttf.h>
#include <SDL_image.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/intersect.hpp>
#include <glm/gtc/random.hpp>
#include <glm/gtx/string_cast.hpp>
#include <glm/gtx/rotate_vector.hpp>
#include <algorithm>
#include <iostream>
Viewer::~Viewer() {
TTF_CloseFont(m_font);
TTF_Quit();
SDL_DestroyTexture(m_render_tex);
SDL_DestroyRenderer(m_render);
SDL_DestroyWindow(m_window);
IMG_Quit();
SDL_Quit();
}
int Viewer::init() {
std::cout << "Start init" << std::endl;
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) != 0) {
std::cerr << "SDL_Init error: " << SDL_GetError() << std::endl;
return 1;
}
int screen_width = 600;
int screen_height = 400;
m_window = SDL_CreateWindow("trac0r", 100, 100, screen_width, screen_height, SDL_WINDOW_SHOWN);
if (m_window == nullptr) {
std::cerr << "SDL_CreateWindow error: " << SDL_GetError() << std::endl;
SDL_Quit();
return 1;
}
// m_render = SDL_CreateRenderer(m_window, -1, SDL_RENDERER_ACCELERATED |
// SDL_RENDERER_PRESENTVSYNC);
m_render = SDL_CreateRenderer(m_window, -1, SDL_RENDERER_ACCELERATED);
m_render_tex = SDL_CreateTexture(m_render, SDL_PIXELFORMAT_ARGB8888,
SDL_TEXTUREACCESS_STREAMING, screen_width, screen_height);
m_pixels.resize(screen_width * screen_height, 0);
if (m_render == nullptr) {
SDL_DestroyWindow(m_window);
std::cerr << "SDL_CreateRenderer error: " << SDL_GetError() << std::endl;
SDL_Quit();
return 1;
}
if (TTF_Init() != 0) {
std::cerr << "SDL_ttf could not initialize! SDL_ttf error: " << SDL_GetError() << std::endl;
return 1;
}
auto font_path = "res/DejaVuSansMono-Bold.ttf";
m_font = TTF_OpenFont(font_path, 14);
if (m_font == nullptr) {
std::cerr << "SDL_ttf could not open '" << font_path << "'" << std::endl;
return 1;
}
// Setup scene
setup_scene(screen_width, screen_height);
std::cout << "Finish init" << std::endl;
return 0;
}
void Viewer::setup_scene(int screen_width, int screen_height) {
auto triangle1 = std::make_unique<Triangle>(
glm::vec3{0.f, 0.f, -0.89f}, glm::vec3{0.07f, 0.f, -0.89f}, glm::vec3{0.07f, -0.04f, -0.89f},
glm::vec3{0.3, 0.3, 0.3}, glm::vec3{0.2, 0.2, 0.2});
auto triangle2 = std::make_unique<Triangle>(
glm::vec3{-0.05f, 0.f, -0.6f}, glm::vec3{-0.005f, 0.f, -0.6f}, glm::vec3{-0.05f, -0.04f, -0.6f},
glm::vec3{0.9, 0.3, 0.3}, glm::vec3{0.2, 0.2, 0.4});
m_scene.push_back(std::move(triangle1));
m_scene.push_back(std::move(triangle2));
// for (auto i = 0; i < 2; i++) {
// auto triangle =
// std::make_unique<Triangle>(glm::ballRand(5.f), glm::ballRand(5.f),
// glm::ballRand(5.f),
// glm::vec3{0.8, 0.3, 0.3}, glm::vec3{0.5, 0.5, 0.5});
// m_scene.push_back(std::move(triangle));
// }
glm::vec3 cam_pos = {0, 0, -1};
glm::vec3 cam_dir = {0, 0, 1};
glm::vec3 cam_up = {0, 1, 0};
m_camera = Camera(cam_pos, cam_dir, cam_up, 45.f, 0.001, 100.f, screen_width, screen_height);
}
glm::vec3 Viewer::intersect_scene(glm::vec3 &ray_pos, glm::vec3 &ray_dir, int depth) {
const auto MAX_DEPTH = 5;
if (depth == MAX_DEPTH)
return {0, 0, 0};
// check all triangles for collision
bool collided = false;
glm::vec3 ret_color;
for (const auto &tri : m_scene) {
glm::vec3 bary_pos;
collided =
glm::intersectRayTriangle(ray_pos, ray_dir, tri->m_v1, tri->m_v2, tri->m_v3, bary_pos);
if (collided) {
glm::vec3 new_ray_pos = ray_pos + ray_dir * bary_pos.z;
auto new_ray_dir = tri->m_normal;
new_ray_dir = glm::rotateX(tri->m_normal, glm::linearRand(-90.f, 90.f));
new_ray_dir = glm::rotateY(tri->m_normal, glm::linearRand(-90.f, 90.f));
float cos_theta = glm::dot(new_ray_dir, tri->m_normal);
glm::vec3 brdf = 2.f * tri->m_reflectance * cos_theta;
glm::vec3 reflected = intersect_scene(new_ray_pos, new_ray_dir, depth + 1);
ret_color = tri->m_emittance + (brdf * reflected);
break;
}
}
if (collided) {
return ret_color;
} else {
return {0, 0, 0};
}
}
void Viewer::mainloop() {
int current_time = SDL_GetTicks();
double dt = (current_time - m_last_frame_time) / 1000.0;
m_last_frame_time = current_time;
// Input
SDL_Event e;
while (SDL_PollEvent(&e)) {
if (e.type == SDL_QUIT) {
shutdown();
}
if (e.type == SDL_KEYDOWN) {
if (e.key.keysym.sym == SDLK_ESCAPE) {
shutdown();
}
}
if (e.type == SDL_MOUSEBUTTONDOWN) {
if (e.button.button == SDL_BUTTON_RIGHT) {
if (m_look_mode) {
m_look_mode = false;
SDL_SetRelativeMouseMode(SDL_FALSE);
} else if (!m_look_mode) {
m_look_mode = true;
SDL_SetRelativeMouseMode(SDL_TRUE);
}
}
}
}
glm::vec3 cam_velocity{0};
const uint8_t *keystates = SDL_GetKeyboardState(0);
if (keystates[SDL_SCANCODE_A])
cam_velocity.x += -0.01f;
else if (keystates[SDL_SCANCODE_D])
cam_velocity.x += 0.01f;
if (keystates[SDL_SCANCODE_W])
cam_velocity.z += 0.01f;
else if (keystates[SDL_SCANCODE_S])
cam_velocity.z += -0.01f;
m_camera.set_pos(m_camera.pos() += cam_velocity);
// Rendering here
int width;
int height;
SDL_GetWindowSize(m_window, &width, &height);
glm::ivec2 mouse_pos;
if (m_look_mode) {
SDL_GetRelativeMouseState(&(mouse_pos.x), &(mouse_pos.y));
m_camera.set_dir(glm::rotateX(m_camera.dir(), mouse_pos.y * 0.001f));
m_camera.set_dir(glm::rotateY(m_camera.dir(), mouse_pos.x * 0.001f));
} else if (!m_look_mode) {
SDL_GetMouseState(&(mouse_pos.x), &(mouse_pos.y));
}
// Lots of debug info
glm::vec2 mouse_rel_pos = m_camera.screenspace_to_camspace(mouse_pos.x, mouse_pos.y);
glm::vec3 mouse_canvas_pos = m_camera.camspace_to_worldspace(mouse_rel_pos);
auto fps_debug_info = "FPS: " + std::to_string(int(1. / dt));
auto cam_look_debug_info = "Cam Look Mode: " + std::to_string(m_look_mode);
auto cam_pos_debug_info = "Cam Pos: " + glm::to_string(m_camera.pos());
auto cam_dir_debug_info = "Cam Dir: " + glm::to_string(m_camera.dir());
auto cam_fov_debug_info =
"Cam FOV (H/V): " + std::to_string(int(glm::degrees(m_camera.horizontal_fov()))) + "/";
cam_fov_debug_info += std::to_string(int(glm::degrees(m_camera.vertical_fov())));
auto cam_canvas_center_pos_info =
"Cam Canvas Center: " + glm::to_string(m_camera.canvas_center_pos());
auto mouse_pos_screen_info = "Mouse Pos Screen Space: " + glm::to_string(mouse_pos);
auto mouse_pos_relative_info = "Mouse Pos Cam Space: " + glm::to_string(mouse_rel_pos);
auto mouse_pos_canvas_info =
"Mouse Pos Canvas World Space: " + glm::to_string(mouse_canvas_pos);
auto cam_look_debug_tex =
trac0r::make_text(m_render, m_font, cam_look_debug_info, {200, 100, 100, 200});
auto cam_pos_debug_tex =
trac0r::make_text(m_render, m_font, cam_pos_debug_info, {200, 100, 100, 200});
auto cam_dir_debug_tex =
trac0r::make_text(m_render, m_font, cam_dir_debug_info, {200, 100, 100, 200});
auto cam_fov_debug_tex =
trac0r::make_text(m_render, m_font, cam_fov_debug_info, {200, 100, 100, 200});
auto fps_debug_tex = trac0r::make_text(m_render, m_font, fps_debug_info, {200, 100, 100, 200});
auto cam_canvas_center_pos_tex =
trac0r::make_text(m_render, m_font, cam_canvas_center_pos_info, {200, 100, 100, 200});
auto mouse_pos_screen_tex =
trac0r::make_text(m_render, m_font, mouse_pos_screen_info, {200, 100, 100, 200});
auto mouse_pos_relative_tex =
trac0r::make_text(m_render, m_font, mouse_pos_relative_info, {200, 100, 100, 200});
auto mouse_pos_canvas_tex =
trac0r::make_text(m_render, m_font, mouse_pos_canvas_info, {200, 100, 100, 200});
// Sort by distance to camera
std::sort(m_scene.begin(), m_scene.end(), [this](const auto &tri1, const auto &tri2) {
return glm::distance(m_camera.pos(), tri1->m_centroid) <
glm::distance(m_camera.pos(), tri2->m_centroid);
});
for (auto sample_cnt = 0; sample_cnt < 2; sample_cnt++) {
for (auto x = 0; x < width; x++) {
for (auto y = 0; y < height; y++) {
glm::vec2 rel_pos = m_camera.screenspace_to_camspace(x, y);
glm::vec3 world_pos = m_camera.camspace_to_worldspace(rel_pos);
glm::vec3 ray_dir = world_pos - m_camera.pos();
glm::vec3 color = intersect_scene(world_pos, ray_dir, 0);
m_pixels[y * width + x] = 0xff << 24 | int(color.r * 255) << 16 |
int(color.g * 255) << 8 | int(color.b * 255);
}
}
}
SDL_RenderClear(m_render);
SDL_UpdateTexture(m_render_tex, 0, m_pixels.data(), width * sizeof(uint32_t));
SDL_RenderCopy(m_render, m_render_tex, 0, 0);
trac0r::render_text(m_render, fps_debug_tex, 10, 10);
trac0r::render_text(m_render, cam_look_debug_tex, 10, 25);
trac0r::render_text(m_render, cam_pos_debug_tex, 10, 40);
trac0r::render_text(m_render, cam_dir_debug_tex, 10, 55);
trac0r::render_text(m_render, cam_fov_debug_tex, 10, 70);
trac0r::render_text(m_render, cam_canvas_center_pos_tex, 10, 85);
trac0r::render_text(m_render, mouse_pos_screen_tex, 10, 100);
trac0r::render_text(m_render, mouse_pos_relative_tex, 10, 115);
trac0r::render_text(m_render, mouse_pos_canvas_tex, 10, 130);
SDL_RenderPresent(m_render);
SDL_DestroyTexture(fps_debug_tex);
SDL_DestroyTexture(cam_look_debug_tex);
SDL_DestroyTexture(cam_pos_debug_tex);
SDL_DestroyTexture(cam_dir_debug_tex);
SDL_DestroyTexture(cam_fov_debug_tex);
SDL_DestroyTexture(cam_canvas_center_pos_tex);
SDL_DestroyTexture(mouse_pos_screen_tex);
SDL_DestroyTexture(mouse_pos_relative_tex);
SDL_DestroyTexture(mouse_pos_canvas_tex);
}
SDL_Renderer *Viewer::renderer() {
return m_render;
}
SDL_Window *Viewer::window() {
return m_window;
}
bool Viewer::is_running() {
return m_running;
}
void Viewer::shutdown() {
m_running = false;
}
<|endoftext|> |
<commit_before>#include "Console.h"
#include <iostream>
#include <map>
#include <vector>
#include <sstream>
#include <llvm/ADT/OwningPtr.h>
#include <llvm/Support/MemoryBuffer.h>
#include <llvm/Linker.h>
#include <llvm/Module.h>
#include <llvm/ModuleProvider.h>
#include <llvm/DerivedTypes.h>
#include <llvm/ExecutionEngine/ExecutionEngine.h>
#include <llvm/ExecutionEngine/GenericValue.h>
#include <clang/AST/AST.h>
#include <clang/Basic/LangOptions.h>
#include <clang/Basic/SourceManager.h>
#include <clang/Basic/TargetInfo.h>
#include <clang/Basic/DiagnosticSema.h>
#include <clang/Driver/CompileOptions.h>
#include <clang/Driver/TextDiagnosticPrinter.h>
#include <clang/CodeGen/ModuleBuilder.h>
#include <clang/Lex/Preprocessor.h>
#include "Parser.h"
#include "SrcGen.h"
template<typename T>
inline std::string to_string(const T& t)
{
std::stringstream ss;
ss << t;
return ss.str();
}
using std::string;
namespace ccons {
class StmtFinder : public clang::StmtVisitor<StmtFinder> {
public:
explicit StmtFinder(unsigned pos, const clang::SourceManager& sm) :
_pos(pos), _sm(sm), _S(NULL) {}
~StmtFinder() {}
void VisitChildren(clang::Stmt *S) {
for (clang::Stmt::child_iterator I = S->child_begin(), E = S->child_end();
I != E; ++I) {
if (*I) {
Visit(*I);
}
}
}
void VisitStmt(clang::Stmt *S) {
clang::SourceLocation Loc = S->getLocStart();
if (_sm.getFileOffset(_sm.getInstantiationLoc(Loc)) == _pos) {
_S = S;
}
}
clang::Stmt * getStmt() { return _S; }
private:
unsigned _pos;
const clang::SourceManager& _sm;
clang::Stmt *_S;
};
class FunctionBodyConsumer : public clang::ASTConsumer {
public:
explicit FunctionBodyConsumer(StmtFinder *SF) : SF(SF) {}
~FunctionBodyConsumer() {}
void HandleTopLevelDecl(clang::Decl *D) {
if (clang::FunctionDecl *FD = dyn_cast<clang::FunctionDecl>(D)) {
if (clang::Stmt *S = FD->getBody()) {
SF->VisitChildren(S);
}
}
}
private:
StmtFinder *SF;
};
Console::Console() :
_prompt(">>> ")
{
_options.C99 = true;
}
Console::~Console()
{
if (_linker)
_linker->releaseModule();
}
int parensMatched(std::string buf)
{
int count = 0;
for (unsigned i = 0; i < buf.length(); i++) {
if (buf[i] == '{')
count++;
else if (buf[i] == '}')
count--;
}
return count;
}
const char * Console::prompt() const
{
return _prompt.c_str();
}
const char * Console::input() const
{
return _input.c_str();
}
class ProxyDiagnosticClient : public clang::DiagnosticClient {
public:
ProxyDiagnosticClient(clang::DiagnosticClient *DC) : _DC(DC) {}
void HandleDiagnostic(clang::Diagnostic::Level DiagLevel,
const clang::DiagnosticInfo &Info) {
if (!_DC) return;
if (Info.getID() != clang::diag::warn_unused_expr &&
Info.getID() != clang::diag::pp_macro_not_used)
_DC->HandleDiagnostic(DiagLevel, Info);
}
private:
clang::DiagnosticClient *_DC;
};
string Console::genSource(string appendix)
{
string src;
for (unsigned i = 0; i < _lines.size(); ++i) {
if (_lines[i].second == PrprLine) {
src += _lines[i].first;
src += "\n";
} else if (_lines[i].second == DeclLine) {
src += "extern ";
src += _lines[i].first;
src += "\n";
}
}
src += appendix;
return src;
}
clang::Stmt * Console::lineToStmt(std::string line,
clang::SourceManager *sm,
std::string *src)
{
*src += "void __ccons_temp() {\n";
const unsigned pos = src->length();
*src += line;
*src += "\n}\n";
clang::TextDiagnosticPrinter tdp(llvm::errs());
ProxyDiagnosticClient pdc(&tdp);
clang::Diagnostic diag(&pdc);
diag.setSuppressSystemWarnings(true);
StmtFinder finder(pos, *sm);
FunctionBodyConsumer consumer(&finder);
_parser.reset(new Parser(_options));
_parser->parse(*src, sm, &diag, &consumer);
return finder.getStmt();
}
void Console::printGV(const llvm::Function *F,
const llvm::GenericValue& GV,
const clang::QualType& QT)
{
string type = QT.getAsString();
const llvm::FunctionType *FTy = F->getFunctionType();
const llvm::Type *RetTy = FTy->getReturnType();
switch (RetTy->getTypeID()) {
case llvm::Type::IntegerTyID:
if (QT->isUnsignedIntegerType())
printf(("=> (" + type + ") %lu\n").c_str(), GV.IntVal.getZExtValue());
else
printf(("=> (" + type + ") %ld\n").c_str(), GV.IntVal.getZExtValue());
return;
case llvm::Type::FloatTyID:
printf(("=> (" + type + ") %f\n").c_str(), GV.FloatVal);
return;
case llvm::Type::DoubleTyID:
printf(("=> (" + type + ") %lf\n").c_str(), GV.DoubleVal);
return;
case llvm::Type::PointerTyID: {
void *p = GVTOP(GV);
// FIXME: this is a hack
if (p && !strncmp(type.c_str(), "char", 4))
printf(("=> (" + type + ") \"%s\"\n").c_str(), p);
else
printf(("=> (" + type + ") %p\n").c_str(), p);
return;
}
default:
break;
}
assert(0 && "Unknown return type!");
}
Console::SrcRange Console::getStmtRange(const clang::Stmt *S,
const clang::SourceManager& sm)
{
clang::SourceLocation SLoc = sm.getInstantiationLoc(S->getLocStart());
clang::SourceLocation ELoc = sm.getInstantiationLoc(S->getLocEnd());
unsigned start = sm.getFileOffset(SLoc);
unsigned end = sm.getFileOffset(ELoc);
end += clang::Lexer::MeasureTokenLength(ELoc, sm);
return SrcRange(start, end);
}
bool Console::handleDeclStmt(const clang::DeclStmt *DS,
const string& src,
string *appendix,
string *funcBody,
std::vector<CodeLine> *moreLines,
const clang::SourceManager& sm)
{
bool initializers = false;
for (clang::DeclStmt::const_decl_iterator D = DS->decl_begin(),
E = DS->decl_end(); D != E; ++D) {
if (const clang::VarDecl *VD = dyn_cast<clang::VarDecl>(*D)) {
if (VD->getInit()) {
initializers = true;
}
}
}
if (initializers) {
std::vector<string> decls;
std::vector<string> stmts;
for (clang::DeclStmt::const_decl_iterator D = DS->decl_begin(),
E = DS->decl_end(); D != E; ++D) {
if (const clang::VarDecl *VD = dyn_cast<clang::VarDecl>(*D)) {
decls.push_back(genVarDecl(VD->getType(), VD->getNameAsCString()) + ";");
if (const clang::Expr *I = VD->getInit()) {
SrcRange range = getStmtRange(I, sm);
std::stringstream stmt;
stmt << VD->getNameAsCString() << " = "
<< src.substr(range.first, range.second - range.first) << ";";
stmts.push_back(stmt.str());
}
}
}
for (unsigned i = 0; i < decls.size(); ++i) {
moreLines->push_back(CodeLine(decls[i], DeclLine));
*appendix += decls[i] + "\n";
}
for (unsigned i = 0; i < stmts.size(); ++i) {
moreLines->push_back(CodeLine(stmts[i], StmtLine));
*funcBody += stmts[i] + "\n";
}
return true;
}
return false;
}
string Console::genAppendix(const char *line, string *fName, clang::QualType& QT,
std::vector<CodeLine> *moreLines)
{
bool wasExpr = false;
string appendix;
string funcBody;
string src = genSource("");
clang::SourceManager sm;
while (isspace(*line)) line++;
if (*line == '#') {
moreLines->push_back(CodeLine(line, PrprLine));
} else if (const clang::Stmt *S = lineToStmt(line, &sm, &src)) {
if (const clang::Expr *E = dyn_cast<clang::Expr>(S)) {
QT = E->getType();
funcBody = line;
moreLines->push_back(CodeLine(line, StmtLine));
wasExpr = true;
} else if (const clang::DeclStmt *DS = dyn_cast<clang::DeclStmt>(S)) {
if (!handleDeclStmt(DS, src, &appendix, &funcBody, moreLines, sm)) {
moreLines->push_back(CodeLine(line, DeclLine));
appendix += line;
appendix += "\n";
}
}
}
if (!funcBody.empty()) {
int funcNo = 0;
for (unsigned i = 0; i < _lines.size(); ++i)
funcNo += (_lines[i].second == StmtLine);
*fName = "__ccons_anon" + to_string(funcNo);
appendix += genFunc(wasExpr ? &QT : NULL, *fName, funcBody);
}
return appendix;
}
void Console::process(const char *line)
{
string fName;
clang::QualType retType(0, 0);
std::vector<CodeLine> linesToAppend;
string appendix;
string src;
if (!_buffer.empty()) {
_buffer += line;
_buffer += "\n";
int indent = parensMatched(_buffer);
_input = string(indent * 2, ' ');
if (indent != 0)
return;
appendix = _buffer;
_buffer.clear();
_prompt = ">>> ";
_input = "";
// insert prototype to lines to append
} else {
if (*line && line[strlen(line)-2] == '{') {
_buffer = line;
_buffer += "\n";
_prompt = "... ";
_input = " ";
return;
}
appendix = genAppendix(line, &fName, retType, &linesToAppend);
}
src = genSource(appendix);
for (unsigned i = 0; i < linesToAppend.size(); ++i)
_lines.push_back(linesToAppend[i]);
clang::TextDiagnosticPrinter tdp(llvm::errs());
ProxyDiagnosticClient pdc(&tdp);
clang::Diagnostic diag(&pdc);
diag.setSuppressSystemWarnings(true);
llvm::OwningPtr<clang::CodeGenerator> codegen;
codegen.reset(CreateLLVMCodeGen(diag, _options, "-", false));
clang::SourceManager sm;
Parser p2(_options); // we keep the other parser around because of QT...
p2.parse(src, &sm, &diag, codegen.get());
llvm::Module *module = codegen->ReleaseModule();
if (module) {
if (!_linker)
_linker.reset(new llvm::Linker("ccons", "ccons"));
string err;
_linker->LinkInModule(module, &err);
std::cout << err;
// link it with the existing ones
if (!fName.empty()) {
module = _linker->getModule();
if (!_engine)
_engine.reset(llvm::ExecutionEngine::create(module));
llvm::Function *F = module->getFunction(fName.c_str());
assert(F && "Function was not found!");
std::vector<llvm::GenericValue> params;
llvm::GenericValue result = _engine->runFunction(F, params);
if (retType.getTypePtr())
printGV(F, result, retType);
}
}
_parser.reset();
}
} // namespace ccons
<commit_msg>warn about implicit function declarations and fix build<commit_after>#include "Console.h"
#include <iostream>
#include <map>
#include <vector>
#include <sstream>
#include <llvm/ADT/OwningPtr.h>
#include <llvm/Support/MemoryBuffer.h>
#include <llvm/Linker.h>
#include <llvm/Module.h>
#include <llvm/ModuleProvider.h>
#include <llvm/DerivedTypes.h>
#include <llvm/ExecutionEngine/ExecutionEngine.h>
#include <llvm/ExecutionEngine/GenericValue.h>
#include <clang/AST/AST.h>
#include <clang/Basic/LangOptions.h>
#include <clang/Basic/SourceManager.h>
#include <clang/Basic/TargetInfo.h>
#include <clang/Basic/Diagnostic.h>
#include <clang/Driver/CompileOptions.h>
#include <clang/Driver/TextDiagnosticPrinter.h>
#include <clang/CodeGen/ModuleBuilder.h>
#include <clang/Lex/Preprocessor.h>
#include <clang/Sema/SemaDiagnostic.h>
#include "Parser.h"
#include "SrcGen.h"
template<typename T>
inline std::string to_string(const T& t)
{
std::stringstream ss;
ss << t;
return ss.str();
}
using std::string;
namespace ccons {
class StmtFinder : public clang::StmtVisitor<StmtFinder> {
public:
explicit StmtFinder(unsigned pos, const clang::SourceManager& sm) :
_pos(pos), _sm(sm), _S(NULL) {}
~StmtFinder() {}
void VisitChildren(clang::Stmt *S) {
for (clang::Stmt::child_iterator I = S->child_begin(), E = S->child_end();
I != E; ++I) {
if (*I) {
Visit(*I);
}
}
}
void VisitStmt(clang::Stmt *S) {
clang::SourceLocation Loc = S->getLocStart();
if (_sm.getFileOffset(_sm.getInstantiationLoc(Loc)) == _pos) {
_S = S;
}
}
clang::Stmt * getStmt() { return _S; }
private:
unsigned _pos;
const clang::SourceManager& _sm;
clang::Stmt *_S;
};
class FunctionBodyConsumer : public clang::ASTConsumer {
public:
explicit FunctionBodyConsumer(StmtFinder *SF) : SF(SF) {}
~FunctionBodyConsumer() {}
void HandleTopLevelDecl(clang::Decl *D) {
if (clang::FunctionDecl *FD = dyn_cast<clang::FunctionDecl>(D)) {
if (clang::Stmt *S = FD->getBody()) {
SF->VisitChildren(S);
}
}
}
private:
StmtFinder *SF;
};
Console::Console() :
_prompt(">>> ")
{
_options.C99 = true;
}
Console::~Console()
{
if (_linker)
_linker->releaseModule();
}
int parensMatched(std::string buf)
{
int count = 0;
for (unsigned i = 0; i < buf.length(); i++) {
if (buf[i] == '{')
count++;
else if (buf[i] == '}')
count--;
}
return count;
}
const char * Console::prompt() const
{
return _prompt.c_str();
}
const char * Console::input() const
{
return _input.c_str();
}
class ProxyDiagnosticClient : public clang::DiagnosticClient {
public:
ProxyDiagnosticClient(clang::DiagnosticClient *DC) : _DC(DC) {}
void HandleDiagnostic(clang::Diagnostic::Level DiagLevel,
const clang::DiagnosticInfo &Info) {
if (!_DC) return;
if (Info.getID() != clang::diag::warn_unused_expr &&
Info.getID() != clang::diag::pp_macro_not_used)
_DC->HandleDiagnostic(DiagLevel, Info);
}
private:
clang::DiagnosticClient *_DC;
};
string Console::genSource(string appendix)
{
string src;
for (unsigned i = 0; i < _lines.size(); ++i) {
if (_lines[i].second == PrprLine) {
src += _lines[i].first;
src += "\n";
} else if (_lines[i].second == DeclLine) {
src += "extern ";
src += _lines[i].first;
src += "\n";
}
}
src += appendix;
return src;
}
clang::Stmt * Console::lineToStmt(std::string line,
clang::SourceManager *sm,
std::string *src)
{
*src += "void __ccons_temp() {\n";
const unsigned pos = src->length();
*src += line;
*src += "\n}\n";
clang::TextDiagnosticPrinter tdp(llvm::errs());
ProxyDiagnosticClient pdc(&tdp);
clang::Diagnostic diag(&pdc);
diag.setDiagnosticMapping(clang::diag::ext_implicit_function_decl,
clang::diag::MAP_WARNING);
diag.setSuppressSystemWarnings(true);
StmtFinder finder(pos, *sm);
FunctionBodyConsumer consumer(&finder);
_parser.reset(new Parser(_options));
_parser->parse(*src, sm, &diag, &consumer);
return finder.getStmt();
}
void Console::printGV(const llvm::Function *F,
const llvm::GenericValue& GV,
const clang::QualType& QT)
{
string type = QT.getAsString();
const llvm::FunctionType *FTy = F->getFunctionType();
const llvm::Type *RetTy = FTy->getReturnType();
switch (RetTy->getTypeID()) {
case llvm::Type::IntegerTyID:
if (QT->isUnsignedIntegerType())
printf(("=> (" + type + ") %lu\n").c_str(), GV.IntVal.getZExtValue());
else
printf(("=> (" + type + ") %ld\n").c_str(), GV.IntVal.getZExtValue());
return;
case llvm::Type::FloatTyID:
printf(("=> (" + type + ") %f\n").c_str(), GV.FloatVal);
return;
case llvm::Type::DoubleTyID:
printf(("=> (" + type + ") %lf\n").c_str(), GV.DoubleVal);
return;
case llvm::Type::PointerTyID: {
void *p = GVTOP(GV);
// FIXME: this is a hack
if (p && !strncmp(type.c_str(), "char", 4))
printf(("=> (" + type + ") \"%s\"\n").c_str(), p);
else
printf(("=> (" + type + ") %p\n").c_str(), p);
return;
}
default:
break;
}
assert(0 && "Unknown return type!");
}
Console::SrcRange Console::getStmtRange(const clang::Stmt *S,
const clang::SourceManager& sm)
{
clang::SourceLocation SLoc = sm.getInstantiationLoc(S->getLocStart());
clang::SourceLocation ELoc = sm.getInstantiationLoc(S->getLocEnd());
unsigned start = sm.getFileOffset(SLoc);
unsigned end = sm.getFileOffset(ELoc);
end += clang::Lexer::MeasureTokenLength(ELoc, sm);
return SrcRange(start, end);
}
bool Console::handleDeclStmt(const clang::DeclStmt *DS,
const string& src,
string *appendix,
string *funcBody,
std::vector<CodeLine> *moreLines,
const clang::SourceManager& sm)
{
bool initializers = false;
for (clang::DeclStmt::const_decl_iterator D = DS->decl_begin(),
E = DS->decl_end(); D != E; ++D) {
if (const clang::VarDecl *VD = dyn_cast<clang::VarDecl>(*D)) {
if (VD->getInit()) {
initializers = true;
}
}
}
if (initializers) {
std::vector<string> decls;
std::vector<string> stmts;
for (clang::DeclStmt::const_decl_iterator D = DS->decl_begin(),
E = DS->decl_end(); D != E; ++D) {
if (const clang::VarDecl *VD = dyn_cast<clang::VarDecl>(*D)) {
decls.push_back(genVarDecl(VD->getType(), VD->getNameAsCString()) + ";");
if (const clang::Expr *I = VD->getInit()) {
SrcRange range = getStmtRange(I, sm);
std::stringstream stmt;
stmt << VD->getNameAsCString() << " = "
<< src.substr(range.first, range.second - range.first) << ";";
stmts.push_back(stmt.str());
}
}
}
for (unsigned i = 0; i < decls.size(); ++i) {
moreLines->push_back(CodeLine(decls[i], DeclLine));
*appendix += decls[i] + "\n";
}
for (unsigned i = 0; i < stmts.size(); ++i) {
moreLines->push_back(CodeLine(stmts[i], StmtLine));
*funcBody += stmts[i] + "\n";
}
return true;
}
return false;
}
string Console::genAppendix(const char *line, string *fName, clang::QualType& QT,
std::vector<CodeLine> *moreLines)
{
bool wasExpr = false;
string appendix;
string funcBody;
string src = genSource("");
clang::SourceManager sm;
while (isspace(*line)) line++;
if (*line == '#') {
moreLines->push_back(CodeLine(line, PrprLine));
} else if (const clang::Stmt *S = lineToStmt(line, &sm, &src)) {
if (const clang::Expr *E = dyn_cast<clang::Expr>(S)) {
QT = E->getType();
funcBody = line;
moreLines->push_back(CodeLine(line, StmtLine));
wasExpr = true;
} else if (const clang::DeclStmt *DS = dyn_cast<clang::DeclStmt>(S)) {
if (!handleDeclStmt(DS, src, &appendix, &funcBody, moreLines, sm)) {
moreLines->push_back(CodeLine(line, DeclLine));
appendix += line;
appendix += "\n";
}
}
}
if (!funcBody.empty()) {
int funcNo = 0;
for (unsigned i = 0; i < _lines.size(); ++i)
funcNo += (_lines[i].second == StmtLine);
*fName = "__ccons_anon" + to_string(funcNo);
appendix += genFunc(wasExpr ? &QT : NULL, *fName, funcBody);
}
return appendix;
}
void Console::process(const char *line)
{
string fName;
clang::QualType retType(0, 0);
std::vector<CodeLine> linesToAppend;
string appendix;
string src;
if (!_buffer.empty()) {
_buffer += line;
_buffer += "\n";
int indent = parensMatched(_buffer);
_input = string(indent * 2, ' ');
if (indent != 0)
return;
appendix = _buffer;
_buffer.clear();
_prompt = ">>> ";
_input = "";
// insert prototype to lines to append
} else {
if (*line && line[strlen(line)-2] == '{') {
_buffer = line;
_buffer += "\n";
_prompt = "... ";
_input = " ";
return;
}
appendix = genAppendix(line, &fName, retType, &linesToAppend);
}
src = genSource(appendix);
for (unsigned i = 0; i < linesToAppend.size(); ++i)
_lines.push_back(linesToAppend[i]);
clang::TextDiagnosticPrinter tdp(llvm::errs());
ProxyDiagnosticClient pdc(&tdp);
clang::Diagnostic diag(&pdc);
diag.setDiagnosticMapping(clang::diag::ext_implicit_function_decl,
clang::diag::MAP_WARNING);
diag.setSuppressSystemWarnings(true);
llvm::OwningPtr<clang::CodeGenerator> codegen;
codegen.reset(CreateLLVMCodeGen(diag, _options, "-", false));
clang::SourceManager sm;
Parser p2(_options); // we keep the other parser around because of QT...
p2.parse(src, &sm, &diag, codegen.get());
llvm::Module *module = codegen->ReleaseModule();
if (module) {
if (!_linker)
_linker.reset(new llvm::Linker("ccons", "ccons"));
string err;
_linker->LinkInModule(module, &err);
std::cout << err;
// link it with the existing ones
if (!fName.empty()) {
module = _linker->getModule();
if (!_engine)
_engine.reset(llvm::ExecutionEngine::create(module));
llvm::Function *F = module->getFunction(fName.c_str());
assert(F && "Function was not found!");
std::vector<llvm::GenericValue> params;
llvm::GenericValue result = _engine->runFunction(F, params);
if (retType.getTypePtr())
printGV(F, result, retType);
}
}
_parser.reset();
}
} // namespace ccons
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: hfi_tag.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: rt $ $Date: 2005-09-07 17:47:56 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include <precomp.h>
#include "hfi_tag.hxx"
// NOT FULLY DEFINED SERVICES
#include <ary/idl/i_ce.hxx>
#include <ary/idl/i_module.hxx>
#include <ary_i/ci_text2.hxx>
#include <ary_i/d_token.hxx>
#include <toolkit/out_tree.hxx>
#include <adc_cl.hxx>
#include <adc_msg.hxx>
#include "hfi_typetext.hxx"
#include "hi_ary.hxx"
#include "hi_env.hxx"
#include "hi_linkhelper.hxx"
using ary::info::DocuTex2;
inline void
HF_IdlTag::Enter_TextOut( Xml::Element & o_rText ) const
{
aTextOut.Out().Enter(o_rText);
}
inline void
HF_IdlTag::Leave_TextOut() const
{
aTextOut.Out().Leave();
}
inline void
HF_IdlTag::PutText_Out( const ary::info::DocuTex2 & i_rText ) const
{
i_rText.DisplayAt( const_cast< HF_IdlDocuTextDisplay& >(aTextOut) );
}
HF_IdlTag::HF_IdlTag( Environment & io_rEnv,
const ary::idl::CodeEntity & i_rScopeGivingCe )
: HtmlFactory_Idl( io_rEnv, 0 ),
pTitleOut(0),
aTextOut(io_rEnv, 0, i_rScopeGivingCe)
{
}
HF_IdlTag::~HF_IdlTag()
{
}
void
HF_IdlTag::Produce_byData( Xml::Element & o_rTitle,
Xml::Element & o_rText,
const ary::info::AtTag2 & i_rTag ) const
{
pTitleOut = &o_rTitle;
Enter_TextOut(o_rText);
i_rTag.DisplayAt( const_cast< HF_IdlTag& >(*this) );
Leave_TextOut();
}
void
HF_IdlTag::Display_StdAtTag( const csi::dsapi::DT_StdAtTag & i_rTag )
{
if ( i_rTag.Text().IsEmpty() )
return;
csv_assert( pTitleOut != 0 );
*pTitleOut << i_rTag.Title();
PutText_Out( i_rTag.Text() );
}
void
HF_IdlTag::Display_SeeAlsoAtTag( const csi::dsapi::DT_SeeAlsoAtTag & i_rTag )
{
if ( i_rTag.Text().IsEmpty() )
return;
csv_assert( pTitleOut != 0 );
*pTitleOut << "See also";
HF_IdlTypeText aLinkText(Env(),aTextOut.CurOut(),true, &aTextOut.ScopeGivingCe());
aLinkText.Produce_byData( i_rTag.LinkText() );
aTextOut.CurOut() << new Html::LineBreak;
PutText_Out( i_rTag.Text() );
}
void
HF_IdlTag::Display_ParameterAtTag( const csi::dsapi::DT_ParameterAtTag & i_rTag )
{
csv_assert( pTitleOut != 0 );
*pTitleOut
<< ( StreamLock(100)() << "Parameter " << i_rTag.Title() << c_str );
PutText_Out( i_rTag.Text() );
}
void
HF_IdlTag::Display_SinceAtTag( const csi::dsapi::DT_SinceAtTag & i_rTag )
{
csv_assert(pTitleOut != 0);
if ( i_rTag.Text().IsEmpty() )
{
return;
}
// Transform the value of the @since tag into the text to be displayed.
String sDisplay =
autodoc::CommandLine::Get_().DisplayOf_SinceTagValue(
i_rTag.Text().TextOfFirstToken() );
if (sDisplay.empty())
return;
*pTitleOut << "Since ";
DocuTex2 aHelp;
aHelp.AddToken(* new csi::dsapi::DT_TextToken(sDisplay));
PutText_Out(aHelp);
}
//******************** HF_IdlShortDocu *********************/
HF_IdlShortDocu::HF_IdlShortDocu( Environment & io_rEnv,
Xml::Element & o_rOut )
: HtmlFactory_Idl( io_rEnv, &o_rOut )
{
}
HF_IdlShortDocu::~HF_IdlShortDocu()
{
}
void
HF_IdlShortDocu::Produce_byData( const ary::idl::CodeEntity & i_rCe )
{
if (i_rCe.Docu() == 0)
return;
const ce_info &
rDocu = *i_rCe.Docu();
if ( rDocu.IsDeprecated() )
{
CurOut()
>> *new Html::Bold
<< "[ DEPRECATED ]" << new Html::LineBreak;
}
if ( rDocu.IsOptional() )
{
CurOut()
>> *new Html::Bold
<< "[ OPTIONAL ]" << new Html::LineBreak;
}
HF_IdlDocuTextDisplay
aText( Env(), &CurOut(), i_rCe);
rDocu.Short().DisplayAt(aText);
}
//******************** HF_IdlDocuTextDisplay *********************/
HF_IdlDocuTextDisplay::HF_IdlDocuTextDisplay( Environment & io_rEnv,
Xml::Element * o_pOut,
const ary::idl::CodeEntity & i_rScopeGivingCe )
: HtmlFactory_Idl(io_rEnv, o_pOut),
sScope(),
sLinkToken(),
bGatherLink(false),
pScopeGivingCe(&i_rScopeGivingCe)
{
}
HF_IdlDocuTextDisplay::~HF_IdlDocuTextDisplay()
{
}
void
HF_IdlDocuTextDisplay::Display_TextToken( const csi::dsapi::DT_TextToken & i_rToken )
{
if (bGatherLink)
{
if (sLinkToken.length() == 0)
{
sLinkToken = i_rToken.GetText();
return;
}
else
{
if ( pScopeGivingCe == 0 )
{ // only in original file
TheMessages().Out_TypeVsMemberMisuse(sLinkToken, Env().CurPageCe_AsText(), 0);
}
// Would be duplicate, therefore we do nothing:
// else
// {
// Cerr() << "Error in documentation: Too many or too few tokens for a link in <member> or <type>." << Endl();
// Cerr() << " Link won't be created, but all tokens shown plain." << Endl();
// Cerr() << " \"" << sLinkToken << "\"";
// if ( pScopeGivingCe != 0 )
// Cerr() << " in " << pScopeGivingCe->LocalName();
// Cerr() << Endl();
// }
StopLinkGathering();
}
} // endif (bGatherLink)
CurOut() << new Xml::XmlCode( i_rToken.GetText() ) << " ";
}
void
HF_IdlDocuTextDisplay::Display_MupType( const csi::dsapi::DT_MupType & i_rToken )
{
if (i_rToken.IsBegin())
{
StartLinkGathering(i_rToken.Scope());
}
else
{
if (bGatherLink)
{
CreateTypeLink();
CurOut()
<< " ";
StopLinkGathering();
}
}
}
void
HF_IdlDocuTextDisplay::Display_MupMember( const csi::dsapi::DT_MupMember & i_rToken )
{
if (i_rToken.IsBegin())
{
StartLinkGathering(i_rToken.Scope());
}
else
{
if (bGatherLink)
{
CreateMemberLink();
CurOut()
<< " ";
StopLinkGathering();
}
}
}
void
HF_IdlDocuTextDisplay::Display_MupConst( const csi::dsapi::DT_MupConst & i_rToken )
{
CurOut()
>> *new Html::Bold
<< i_rToken.GetText();
CurOut()
<< " ";
}
void
HF_IdlDocuTextDisplay::Display_Style( const csi::dsapi::DT_Style & i_rToken )
{
CurOut() << new Xml::XmlCode( i_rToken.GetText() );
}
void
HF_IdlDocuTextDisplay::Display_EOL()
{
CurOut() << "\n";
}
void
HF_IdlDocuTextDisplay::CreateTypeLink()
{
if (strchr(sLinkToken,':') != 0)
{
TheMessages().Out_TypeVsMemberMisuse(sLinkToken, Env().CurPageCe_AsFile(".idl"), 0);
CurOut() << sLinkToken;
return;
}
HF_IdlTypeText aLink(Env(), CurOut(), true, &ScopeGivingCe());
aLink.Produce_LinkInDocu(sScope, sLinkToken, String::Null_());
}
void
HF_IdlDocuTextDisplay::CreateMemberLink()
{
HF_IdlTypeText aLink(Env(), CurOut(), true, &ScopeGivingCe());
const char *
sSplit = strchr(sLinkToken,':');
if (sSplit != 0)
{
String sCe(sLinkToken.c_str(), sSplit - sLinkToken.c_str());
String sMember(sSplit+2);
if (NOT sScope.empty() OR ScopeGivingCe().LocalName() != sCe )
aLink.Produce_LinkInDocu(sScope, sCe, sMember);
else
aLink.Produce_LocalLinkInDocu(sMember);
}
else
{
aLink.Produce_LocalLinkInDocu(sLinkToken);
}
}
<commit_msg>INTEGRATION: CWS adc14 (1.8.22); FILE MERGED 2006/04/27 09:43:30 np 1.8.22.1: #i62433#, Combine See Also tags, put deprecated and unpublished into title line.<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: hfi_tag.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: rt $ $Date: 2006-05-03 16:55:36 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include <precomp.h>
#include "hfi_tag.hxx"
// NOT FULLY DEFINED SERVICES
#include <ary/idl/i_ce.hxx>
#include <ary/idl/i_module.hxx>
#include <ary_i/ci_text2.hxx>
#include <ary_i/d_token.hxx>
#include <toolkit/out_tree.hxx>
#include <adc_cl.hxx>
#include <adc_msg.hxx>
#include "hfi_typetext.hxx"
#include "hi_ary.hxx"
#include "hi_env.hxx"
#include "hi_linkhelper.hxx"
using ary::info::DocuTex2;
inline void
HF_IdlTag::Enter_TextOut( Xml::Element & o_rText ) const
{
aTextOut.Out().Enter(o_rText);
}
inline void
HF_IdlTag::Leave_TextOut() const
{
aTextOut.Out().Leave();
}
inline void
HF_IdlTag::PutText_Out( const ary::info::DocuTex2 & i_rText ) const
{
i_rText.DisplayAt( const_cast< HF_IdlDocuTextDisplay& >(aTextOut) );
}
HF_IdlTag::HF_IdlTag( Environment & io_rEnv,
const ary::idl::CodeEntity & i_rScopeGivingCe )
: HtmlFactory_Idl( io_rEnv, 0 ),
pTitleOut(0),
aTextOut(io_rEnv, 0, i_rScopeGivingCe)
{
}
HF_IdlTag::~HF_IdlTag()
{
}
void
HF_IdlTag::Produce_byData( Xml::Element & o_rTitle,
Xml::Element & o_rText,
const ary::info::AtTag2 & i_rTag ) const
{
pTitleOut = &o_rTitle;
Enter_TextOut(o_rText);
i_rTag.DisplayAt( const_cast< HF_IdlTag& >(*this) );
Leave_TextOut();
}
void
HF_IdlTag::Produce_byData( Xml::Element & o_rTitle,
Xml::Element & o_rText,
const std::vector< csi::dsapi::DT_SeeAlsoAtTag* > &
i_seeAlsoVector ) const
{
o_rTitle << "See also";
for ( std::vector< csi::dsapi::DT_SeeAlsoAtTag* >::const_iterator
it = i_seeAlsoVector.begin();
it != i_seeAlsoVector.end();
++it )
{
if ( (*it)->Text().IsEmpty() )
continue;
if (it != i_seeAlsoVector.begin())
{
o_rText << ", ";
}
HF_IdlTypeText
aLinkText(Env(), o_rText, true, &aTextOut.ScopeGivingCe());
aLinkText.Produce_byData( (*it)->LinkText() );
}
}
void
HF_IdlTag::Display_StdAtTag( const csi::dsapi::DT_StdAtTag & i_rTag )
{
if ( i_rTag.Text().IsEmpty() )
return;
csv_assert( pTitleOut != 0 );
*pTitleOut << i_rTag.Title();
PutText_Out( i_rTag.Text() );
}
void
HF_IdlTag::Display_SeeAlsoAtTag( const csi::dsapi::DT_SeeAlsoAtTag & i_rTag )
{
if ( i_rTag.Text().IsEmpty() )
return;
csv_assert( pTitleOut != 0 );
*pTitleOut << "See also";
HF_IdlTypeText aLinkText(Env(),aTextOut.CurOut(),true, &aTextOut.ScopeGivingCe());
aLinkText.Produce_byData( i_rTag.LinkText() );
aTextOut.CurOut() << new Html::LineBreak;
PutText_Out( i_rTag.Text() );
}
void
HF_IdlTag::Display_ParameterAtTag( const csi::dsapi::DT_ParameterAtTag & i_rTag )
{
csv_assert( pTitleOut != 0 );
*pTitleOut
<< ( StreamLock(100)() << "Parameter " << i_rTag.Title() << c_str );
PutText_Out( i_rTag.Text() );
}
void
HF_IdlTag::Display_SinceAtTag( const csi::dsapi::DT_SinceAtTag & i_rTag )
{
csv_assert(pTitleOut != 0);
if ( i_rTag.Text().IsEmpty() )
{
return;
}
// Transform the value of the @since tag into the text to be displayed.
String sDisplay =
autodoc::CommandLine::Get_().DisplayOf_SinceTagValue(
i_rTag.Text().TextOfFirstToken() );
if (sDisplay.empty())
return;
*pTitleOut << "Since ";
DocuTex2 aHelp;
aHelp.AddToken(* new csi::dsapi::DT_TextToken(sDisplay));
PutText_Out(aHelp);
}
//******************** HF_IdlShortDocu *********************/
HF_IdlShortDocu::HF_IdlShortDocu( Environment & io_rEnv,
Xml::Element & o_rOut )
: HtmlFactory_Idl( io_rEnv, &o_rOut )
{
}
HF_IdlShortDocu::~HF_IdlShortDocu()
{
}
void
HF_IdlShortDocu::Produce_byData( const ary::idl::CodeEntity & i_rCe )
{
if (i_rCe.Docu() == 0)
return;
const ce_info &
rDocu = *i_rCe.Docu();
if ( rDocu.IsDeprecated() )
{
CurOut()
>> *new Html::Bold
<< "[ DEPRECATED ]" << new Html::LineBreak;
}
if ( rDocu.IsOptional() )
{
CurOut()
>> *new Html::Bold
<< "[ OPTIONAL ]" << new Html::LineBreak;
}
HF_IdlDocuTextDisplay
aText( Env(), &CurOut(), i_rCe);
rDocu.Short().DisplayAt(aText);
}
//******************** HF_IdlDocuTextDisplay *********************/
HF_IdlDocuTextDisplay::HF_IdlDocuTextDisplay( Environment & io_rEnv,
Xml::Element * o_pOut,
const ary::idl::CodeEntity & i_rScopeGivingCe )
: HtmlFactory_Idl(io_rEnv, o_pOut),
sScope(),
sLinkToken(),
bGatherLink(false),
pScopeGivingCe(&i_rScopeGivingCe)
{
}
HF_IdlDocuTextDisplay::~HF_IdlDocuTextDisplay()
{
}
void
HF_IdlDocuTextDisplay::Display_TextToken( const csi::dsapi::DT_TextToken & i_rToken )
{
if (bGatherLink)
{
if (sLinkToken.length() == 0)
{
sLinkToken = i_rToken.GetText();
return;
}
else
{
if ( pScopeGivingCe == 0 )
{ // only in original file
TheMessages().Out_TypeVsMemberMisuse(sLinkToken, Env().CurPageCe_AsText(), 0);
}
// Would be duplicate, therefore we do nothing:
// else
// {
// Cerr() << "Error in documentation: Too many or too few tokens for a link in <member> or <type>." << Endl();
// Cerr() << " Link won't be created, but all tokens shown plain." << Endl();
// Cerr() << " \"" << sLinkToken << "\"";
// if ( pScopeGivingCe != 0 )
// Cerr() << " in " << pScopeGivingCe->LocalName();
// Cerr() << Endl();
// }
StopLinkGathering();
}
} // endif (bGatherLink)
CurOut() << new Xml::XmlCode( i_rToken.GetText() ) << " ";
}
void
HF_IdlDocuTextDisplay::Display_MupType( const csi::dsapi::DT_MupType & i_rToken )
{
if (i_rToken.IsBegin())
{
StartLinkGathering(i_rToken.Scope());
}
else
{
if (bGatherLink)
{
CreateTypeLink();
CurOut()
<< " ";
StopLinkGathering();
}
}
}
void
HF_IdlDocuTextDisplay::Display_MupMember( const csi::dsapi::DT_MupMember & i_rToken )
{
if (i_rToken.IsBegin())
{
StartLinkGathering(i_rToken.Scope());
}
else
{
if (bGatherLink)
{
CreateMemberLink();
CurOut()
<< " ";
StopLinkGathering();
}
}
}
void
HF_IdlDocuTextDisplay::Display_MupConst( const csi::dsapi::DT_MupConst & i_rToken )
{
CurOut()
>> *new Html::Bold
<< i_rToken.GetText();
CurOut()
<< " ";
}
void
HF_IdlDocuTextDisplay::Display_Style( const csi::dsapi::DT_Style & i_rToken )
{
CurOut() << new Xml::XmlCode( i_rToken.GetText() );
}
void
HF_IdlDocuTextDisplay::Display_EOL()
{
CurOut() << "\n";
}
void
HF_IdlDocuTextDisplay::CreateTypeLink()
{
if (strchr(sLinkToken,':') != 0)
{
TheMessages().Out_TypeVsMemberMisuse(sLinkToken, Env().CurPageCe_AsFile(".idl"), 0);
CurOut() << sLinkToken;
return;
}
HF_IdlTypeText aLink(Env(), CurOut(), true, &ScopeGivingCe());
aLink.Produce_LinkInDocu(sScope, sLinkToken, String::Null_());
}
void
HF_IdlDocuTextDisplay::CreateMemberLink()
{
HF_IdlTypeText aLink(Env(), CurOut(), true, &ScopeGivingCe());
const char *
sSplit = strchr(sLinkToken,':');
if (sSplit != 0)
{
String sCe(sLinkToken.c_str(), sSplit - sLinkToken.c_str());
String sMember(sSplit+2);
if (NOT sScope.empty() OR ScopeGivingCe().LocalName() != sCe )
aLink.Produce_LinkInDocu(sScope, sCe, sMember);
else
aLink.Produce_LocalLinkInDocu(sMember);
}
else
{
aLink.Produce_LocalLinkInDocu(sLinkToken);
}
}
<|endoftext|> |
<commit_before>/*
*
* Copyright 2008-2012 NVIDIA Corporation
*
* 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 <thrust/random/normal_distribution.h>
#include <thrust/random/uniform_real_distribution.h>
#include <thrust/detail/cstdint.h>
#include <thrust/detail/integer_traits.h>
namespace thrust
{
namespace random
{
template<typename RealType>
normal_distribution<RealType>
::normal_distribution(RealType a, RealType b)
:super_t(),m_param(a,b)
{
} // end normal_distribution::normal_distribution()
template<typename RealType>
normal_distribution<RealType>
::normal_distribution(const param_type &parm)
:super_t(),m_param(parm)
{
} // end normal_distribution::normal_distribution()
template<typename RealType>
void normal_distribution<RealType>
::reset(void)
{
super_t::reset();
} // end normal_distribution::reset()
template<typename RealType>
template<typename UniformRandomNumberGenerator>
typename normal_distribution<RealType>::result_type
normal_distribution<RealType>
::operator()(UniformRandomNumberGenerator &urng)
{
return operator()(urng, m_param);
} // end normal_distribution::operator()()
template<typename RealType>
template<typename UniformRandomNumberGenerator>
typename normal_distribution<RealType>::result_type
normal_distribution<RealType>
::operator()(UniformRandomNumberGenerator &urng,
const param_type &parm)
{
return super_t::sample(urng, parm.first, parm.second);
} // end normal_distribution::operator()()
template<typename RealType>
typename normal_distribution<RealType>::param_type
normal_distribution<RealType>
::param(void) const
{
return m_param;
} // end normal_distribution::param()
template<typename RealType>
void normal_distribution<RealType>
::param(const param_type &parm)
{
m_param = parm;
} // end normal_distribution::param()
template<typename RealType>
typename normal_distribution<RealType>::result_type
normal_distribution<RealType>
::min THRUST_PREVENT_MACRO_SUBSTITUTION (void) const
{
// XXX this solution is pretty terrible
const thrust::detail::uint32_t inf_as_int = 0x7f800000u;
const float inf = *reinterpret_cast<const float*>(&inf_as_int);
return result_type(-inf);
} // end normal_distribution::min()
template<typename RealType>
typename normal_distribution<RealType>::result_type
normal_distribution<RealType>
::max THRUST_PREVENT_MACRO_SUBSTITUTION (void) const
{
// XXX this solution is pretty terrible
const thrust::detail::uint32_t inf_as_int = 0x7f800000u;
const float inf = *reinterpret_cast<const float*>(&inf_as_int);
return result_type(inf);
} // end normal_distribution::max()
template<typename RealType>
typename normal_distribution<RealType>::result_type
normal_distribution<RealType>
::mean(void) const
{
return m_param.first;
} // end normal_distribution::mean()
template<typename RealType>
typename normal_distribution<RealType>::result_type
normal_distribution<RealType>
::stddev(void) const
{
return m_param.second;
} // end normal_distribution::stddev()
template<typename RealType>
bool normal_distribution<RealType>
::equal(const normal_distribution &rhs) const
{
return m_param == rhs.param();
}
template<typename RealType>
template<typename CharT, typename Traits>
std::basic_ostream<CharT,Traits>&
normal_distribution<RealType>
::stream_out(std::basic_ostream<CharT,Traits> &os) const
{
typedef std::basic_ostream<CharT,Traits> ostream_type;
typedef typename ostream_type::ios_base ios_base;
// save old flags and fill character
const typename ios_base::fmtflags flags = os.flags();
const CharT fill = os.fill();
const CharT space = os.widen(' ');
os.flags(ios_base::dec | ios_base::fixed | ios_base::left);
os.fill(space);
os << mean() << space << stddev();
// restore old flags and fill character
os.flags(flags);
os.fill(fill);
return os;
}
template<typename RealType>
template<typename CharT, typename Traits>
std::basic_istream<CharT,Traits>&
normal_distribution<RealType>
::stream_in(std::basic_istream<CharT,Traits> &is)
{
typedef std::basic_istream<CharT,Traits> istream_type;
typedef typename istream_type::ios_base ios_base;
// save old flags
const typename ios_base::fmtflags flags = is.flags();
is.flags(ios_base::skipws);
is >> m_param.first >> m_param.second;
// restore old flags
is.flags(flags);
return is;
}
template<typename RealType>
bool operator==(const normal_distribution<RealType> &lhs,
const normal_distribution<RealType> &rhs)
{
return thrust::random::detail::random_core_access::equal(lhs,rhs);
}
template<typename RealType>
bool operator!=(const normal_distribution<RealType> &lhs,
const normal_distribution<RealType> &rhs)
{
return !(lhs == rhs);
}
template<typename RealType,
typename CharT, typename Traits>
std::basic_ostream<CharT,Traits>&
operator<<(std::basic_ostream<CharT,Traits> &os,
const normal_distribution<RealType> &d)
{
return thrust::random::detail::random_core_access::stream_out(os,d);
}
template<typename RealType,
typename CharT, typename Traits>
std::basic_istream<CharT,Traits>&
operator>>(std::basic_istream<CharT,Traits> &is,
normal_distribution<RealType> &d)
{
return thrust::random::detail::random_core_access::stream_in(is,d);
}
} // end random
} // end thrust
<commit_msg>Use INFINITY from <cmath> instead of reinterpret_cast tricks to get the fp inf value<commit_after>/*
*
* Copyright 2008-2012 NVIDIA Corporation
*
* 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 <thrust/random/normal_distribution.h>
#include <thrust/random/uniform_real_distribution.h>
#include <thrust/detail/cstdint.h>
#include <thrust/detail/integer_traits.h>
#include <cmath>
namespace thrust
{
namespace random
{
template<typename RealType>
normal_distribution<RealType>
::normal_distribution(RealType a, RealType b)
:super_t(),m_param(a,b)
{
} // end normal_distribution::normal_distribution()
template<typename RealType>
normal_distribution<RealType>
::normal_distribution(const param_type &parm)
:super_t(),m_param(parm)
{
} // end normal_distribution::normal_distribution()
template<typename RealType>
void normal_distribution<RealType>
::reset(void)
{
super_t::reset();
} // end normal_distribution::reset()
template<typename RealType>
template<typename UniformRandomNumberGenerator>
typename normal_distribution<RealType>::result_type
normal_distribution<RealType>
::operator()(UniformRandomNumberGenerator &urng)
{
return operator()(urng, m_param);
} // end normal_distribution::operator()()
template<typename RealType>
template<typename UniformRandomNumberGenerator>
typename normal_distribution<RealType>::result_type
normal_distribution<RealType>
::operator()(UniformRandomNumberGenerator &urng,
const param_type &parm)
{
return super_t::sample(urng, parm.first, parm.second);
} // end normal_distribution::operator()()
template<typename RealType>
typename normal_distribution<RealType>::param_type
normal_distribution<RealType>
::param(void) const
{
return m_param;
} // end normal_distribution::param()
template<typename RealType>
void normal_distribution<RealType>
::param(const param_type &parm)
{
m_param = parm;
} // end normal_distribution::param()
template<typename RealType>
typename normal_distribution<RealType>::result_type
normal_distribution<RealType>
::min THRUST_PREVENT_MACRO_SUBSTITUTION (void) const
{
// XXX we should use numeric_limits, but, CUDA
return -INFINITY;
} // end normal_distribution::min()
template<typename RealType>
typename normal_distribution<RealType>::result_type
normal_distribution<RealType>
::max THRUST_PREVENT_MACRO_SUBSTITUTION (void) const
{
// XXX we should use numeric_limits, but, CUDA
return INFINITY;
} // end normal_distribution::max()
template<typename RealType>
typename normal_distribution<RealType>::result_type
normal_distribution<RealType>
::mean(void) const
{
return m_param.first;
} // end normal_distribution::mean()
template<typename RealType>
typename normal_distribution<RealType>::result_type
normal_distribution<RealType>
::stddev(void) const
{
return m_param.second;
} // end normal_distribution::stddev()
template<typename RealType>
bool normal_distribution<RealType>
::equal(const normal_distribution &rhs) const
{
return m_param == rhs.param();
}
template<typename RealType>
template<typename CharT, typename Traits>
std::basic_ostream<CharT,Traits>&
normal_distribution<RealType>
::stream_out(std::basic_ostream<CharT,Traits> &os) const
{
typedef std::basic_ostream<CharT,Traits> ostream_type;
typedef typename ostream_type::ios_base ios_base;
// save old flags and fill character
const typename ios_base::fmtflags flags = os.flags();
const CharT fill = os.fill();
const CharT space = os.widen(' ');
os.flags(ios_base::dec | ios_base::fixed | ios_base::left);
os.fill(space);
os << mean() << space << stddev();
// restore old flags and fill character
os.flags(flags);
os.fill(fill);
return os;
}
template<typename RealType>
template<typename CharT, typename Traits>
std::basic_istream<CharT,Traits>&
normal_distribution<RealType>
::stream_in(std::basic_istream<CharT,Traits> &is)
{
typedef std::basic_istream<CharT,Traits> istream_type;
typedef typename istream_type::ios_base ios_base;
// save old flags
const typename ios_base::fmtflags flags = is.flags();
is.flags(ios_base::skipws);
is >> m_param.first >> m_param.second;
// restore old flags
is.flags(flags);
return is;
}
template<typename RealType>
bool operator==(const normal_distribution<RealType> &lhs,
const normal_distribution<RealType> &rhs)
{
return thrust::random::detail::random_core_access::equal(lhs,rhs);
}
template<typename RealType>
bool operator!=(const normal_distribution<RealType> &lhs,
const normal_distribution<RealType> &rhs)
{
return !(lhs == rhs);
}
template<typename RealType,
typename CharT, typename Traits>
std::basic_ostream<CharT,Traits>&
operator<<(std::basic_ostream<CharT,Traits> &os,
const normal_distribution<RealType> &d)
{
return thrust::random::detail::random_core_access::stream_out(os,d);
}
template<typename RealType,
typename CharT, typename Traits>
std::basic_istream<CharT,Traits>&
operator>>(std::basic_istream<CharT,Traits> &is,
normal_distribution<RealType> &d)
{
return thrust::random::detail::random_core_access::stream_in(is,d);
}
} // end random
} // end thrust
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: pe_param.cxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: hr $ $Date: 2007-11-02 16:56:30 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include <precomp.h>
#include "pe_param.hxx"
// NOT FULLY DEFINED SERVICES
#include <cosv/tpl/tpltools.hxx>
#include <ary/cpp/c_gate.hxx>
#include <ary/cpp/cp_type.hxx>
#include "pe_type.hxx"
#include "pe_vari.hxx"
namespace cpp {
//*********************** PE_Parameter ***********************//
PE_Parameter::PE_Parameter( Cpp_PE * i_pParent )
: Cpp_PE(i_pParent),
pStati( new PeStatusArray<PE_Parameter> )
// pSpType,
// pSpuType,
// pSpVariable,
// pSpuVariable,
// aResultParamInfo
{
Setup_StatusFunctions();
pSpType = new SP_Type(*this);
pSpuType = new SPU_Type(*pSpType, &PE_Parameter::SpInit_Type, &PE_Parameter::SpReturn_Type);
pSpVariable = new SP_Variable(*this);
pSpuVariable = new SPU_Variable(*pSpVariable, &PE_Parameter::SpInit_Variable, &PE_Parameter::SpReturn_Variable);
}
PE_Parameter::~PE_Parameter()
{
}
void
PE_Parameter::Call_Handler( const cpp::Token & i_rTok )
{
pStati->Cur().Call_Handler(i_rTok.TypeId(), i_rTok.Text());
}
void
PE_Parameter::Setup_StatusFunctions()
{
typedef CallFunction<PE_Parameter>::F_Tok F_Tok;
static F_Tok stateF_start[] = { &PE_Parameter::On_start_Type,
&PE_Parameter::On_start_Type,
&PE_Parameter::On_start_Type,
&PE_Parameter::On_start_Type,
&PE_Parameter::On_start_Type,
&PE_Parameter::On_start_Type,
&PE_Parameter::On_start_Type,
&PE_Parameter::On_start_Bracket_Right,
&PE_Parameter::On_start_Type,
&PE_Parameter::On_start_Ellipse,
&PE_Parameter::On_start_Type,
&PE_Parameter::On_start_Type,
&PE_Parameter::On_start_Type };
static INT16 stateT_start[] = { Tid_Identifier,
Tid_class,
Tid_struct,
Tid_union,
Tid_enum,
Tid_const,
Tid_volatile,
Tid_Bracket_Right,
Tid_DoubleColon,
Tid_Ellipse,
Tid_typename,
Tid_BuiltInType,
Tid_TypeSpecializer };
static F_Tok stateF_expectName[] = { &PE_Parameter::On_expectName_Identifier,
&PE_Parameter::On_expectName_ArrayBracket_Left,
&PE_Parameter::On_expectName_Bracket_Right,
&PE_Parameter::On_expectName_Comma,
&PE_Parameter::On_afterName_Assign };
static INT16 stateT_expectName[] = { Tid_Identifier,
Tid_ArrayBracket_Left,
Tid_Bracket_Right,
Tid_Comma,
Tid_Assign };
static F_Tok stateF_afterName[] = { &PE_Parameter::On_afterName_ArrayBracket_Left,
&PE_Parameter::On_afterName_Bracket_Right,
&PE_Parameter::On_afterName_Comma,
&PE_Parameter::On_afterName_Assign };
static INT16 stateT_afterName[] = { Tid_ArrayBracket_Left,
Tid_Bracket_Right,
Tid_Comma,
Tid_Assign };
static F_Tok stateF_finished[] = { &PE_Parameter::On_finished_Comma,
&PE_Parameter::On_finished_Bracket_Right };
static INT16 stateT_finished[] = { Tid_Bracket_Right,
Tid_Comma };
SEMPARSE_CREATE_STATUS(PE_Parameter, start, Hdl_SyntaxError);
SEMPARSE_CREATE_STATUS(PE_Parameter, expectName, Hdl_SyntaxError);
SEMPARSE_CREATE_STATUS(PE_Parameter, afterName, Hdl_SyntaxError);
SEMPARSE_CREATE_STATUS(PE_Parameter, finished, Hdl_SyntaxError);
}
void
PE_Parameter::InitData()
{
pStati->SetCur(start);
aResultParamInfo.Empty();
}
void
PE_Parameter::TransferData()
{
pStati->SetCur(size_of_states);
}
void
PE_Parameter::Hdl_SyntaxError( const char * i_sText)
{
StdHandlingOfSyntaxError(i_sText);
}
void
PE_Parameter::SpInit_Type()
{
// Does nothing.
}
void
PE_Parameter::SpInit_Variable()
{
// Does nothing.
}
void
PE_Parameter::SpReturn_Type()
{
aResultParamInfo.nType = pSpuType->Child().Result_Type().Id();
pStati->SetCur(expectName);
}
void
PE_Parameter::SpReturn_Variable()
{
if (pSpuVariable->Child().Result_Pattern() > 0)
{
aResultParamInfo.sSizeExpression = pSpuVariable->Child().Result_SizeExpression();
aResultParamInfo.sInitExpression = pSpuVariable->Child().Result_InitExpression();
}
}
void
PE_Parameter::On_start_Type(const char *)
{
pSpuType->Push(not_done);
}
void
PE_Parameter::On_start_Bracket_Right(const char *)
{
SetTokenResult(not_done, pop_success);
}
void
PE_Parameter::On_start_Ellipse(const char *)
{
SetTokenResult(done, pop_success);
aResultParamInfo.nType = Env().AryGate().Types().Tid_Ellipse();
}
void
PE_Parameter::On_expectName_Identifier(const char * i_sText)
{
SetTokenResult(done, stay);
pStati->SetCur(afterName);
aResultParamInfo.sName = i_sText;
}
void
PE_Parameter::On_expectName_ArrayBracket_Left(const char * i_sText)
{
On_afterName_ArrayBracket_Left(i_sText);
}
void
PE_Parameter::On_expectName_Bracket_Right(const char * i_sText)
{
On_afterName_Bracket_Right(i_sText);
}
void
PE_Parameter::On_expectName_Comma(const char * i_sText)
{
On_afterName_Comma(i_sText);
}
void
PE_Parameter::On_expectName_Assign(const char * i_sText)
{
On_afterName_Assign(i_sText);
}
void
PE_Parameter::On_afterName_ArrayBracket_Left(const char *)
{
pSpuVariable->Push(not_done);
}
void
PE_Parameter::On_afterName_Bracket_Right(const char *)
{
SetTokenResult(not_done, pop_success);
}
void
PE_Parameter::On_afterName_Comma(const char *)
{
SetTokenResult(not_done, pop_success);
}
void
PE_Parameter::On_afterName_Assign(const char *)
{
pSpuVariable->Push(not_done);
}
void
PE_Parameter::On_finished_Bracket_Right(const char *)
{
SetTokenResult(not_done, pop_success);
}
void
PE_Parameter::On_finished_Comma(const char *)
{
SetTokenResult(not_done, pop_success);
}
} // namespace cpp
<commit_msg>INTEGRATION: CWS changefileheader (1.10.22); FILE MERGED 2008/03/28 16:02:26 rt 1.10.22.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: pe_param.cxx,v $
* $Revision: 1.11 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#include <precomp.h>
#include "pe_param.hxx"
// NOT FULLY DEFINED SERVICES
#include <cosv/tpl/tpltools.hxx>
#include <ary/cpp/c_gate.hxx>
#include <ary/cpp/cp_type.hxx>
#include "pe_type.hxx"
#include "pe_vari.hxx"
namespace cpp {
//*********************** PE_Parameter ***********************//
PE_Parameter::PE_Parameter( Cpp_PE * i_pParent )
: Cpp_PE(i_pParent),
pStati( new PeStatusArray<PE_Parameter> )
// pSpType,
// pSpuType,
// pSpVariable,
// pSpuVariable,
// aResultParamInfo
{
Setup_StatusFunctions();
pSpType = new SP_Type(*this);
pSpuType = new SPU_Type(*pSpType, &PE_Parameter::SpInit_Type, &PE_Parameter::SpReturn_Type);
pSpVariable = new SP_Variable(*this);
pSpuVariable = new SPU_Variable(*pSpVariable, &PE_Parameter::SpInit_Variable, &PE_Parameter::SpReturn_Variable);
}
PE_Parameter::~PE_Parameter()
{
}
void
PE_Parameter::Call_Handler( const cpp::Token & i_rTok )
{
pStati->Cur().Call_Handler(i_rTok.TypeId(), i_rTok.Text());
}
void
PE_Parameter::Setup_StatusFunctions()
{
typedef CallFunction<PE_Parameter>::F_Tok F_Tok;
static F_Tok stateF_start[] = { &PE_Parameter::On_start_Type,
&PE_Parameter::On_start_Type,
&PE_Parameter::On_start_Type,
&PE_Parameter::On_start_Type,
&PE_Parameter::On_start_Type,
&PE_Parameter::On_start_Type,
&PE_Parameter::On_start_Type,
&PE_Parameter::On_start_Bracket_Right,
&PE_Parameter::On_start_Type,
&PE_Parameter::On_start_Ellipse,
&PE_Parameter::On_start_Type,
&PE_Parameter::On_start_Type,
&PE_Parameter::On_start_Type };
static INT16 stateT_start[] = { Tid_Identifier,
Tid_class,
Tid_struct,
Tid_union,
Tid_enum,
Tid_const,
Tid_volatile,
Tid_Bracket_Right,
Tid_DoubleColon,
Tid_Ellipse,
Tid_typename,
Tid_BuiltInType,
Tid_TypeSpecializer };
static F_Tok stateF_expectName[] = { &PE_Parameter::On_expectName_Identifier,
&PE_Parameter::On_expectName_ArrayBracket_Left,
&PE_Parameter::On_expectName_Bracket_Right,
&PE_Parameter::On_expectName_Comma,
&PE_Parameter::On_afterName_Assign };
static INT16 stateT_expectName[] = { Tid_Identifier,
Tid_ArrayBracket_Left,
Tid_Bracket_Right,
Tid_Comma,
Tid_Assign };
static F_Tok stateF_afterName[] = { &PE_Parameter::On_afterName_ArrayBracket_Left,
&PE_Parameter::On_afterName_Bracket_Right,
&PE_Parameter::On_afterName_Comma,
&PE_Parameter::On_afterName_Assign };
static INT16 stateT_afterName[] = { Tid_ArrayBracket_Left,
Tid_Bracket_Right,
Tid_Comma,
Tid_Assign };
static F_Tok stateF_finished[] = { &PE_Parameter::On_finished_Comma,
&PE_Parameter::On_finished_Bracket_Right };
static INT16 stateT_finished[] = { Tid_Bracket_Right,
Tid_Comma };
SEMPARSE_CREATE_STATUS(PE_Parameter, start, Hdl_SyntaxError);
SEMPARSE_CREATE_STATUS(PE_Parameter, expectName, Hdl_SyntaxError);
SEMPARSE_CREATE_STATUS(PE_Parameter, afterName, Hdl_SyntaxError);
SEMPARSE_CREATE_STATUS(PE_Parameter, finished, Hdl_SyntaxError);
}
void
PE_Parameter::InitData()
{
pStati->SetCur(start);
aResultParamInfo.Empty();
}
void
PE_Parameter::TransferData()
{
pStati->SetCur(size_of_states);
}
void
PE_Parameter::Hdl_SyntaxError( const char * i_sText)
{
StdHandlingOfSyntaxError(i_sText);
}
void
PE_Parameter::SpInit_Type()
{
// Does nothing.
}
void
PE_Parameter::SpInit_Variable()
{
// Does nothing.
}
void
PE_Parameter::SpReturn_Type()
{
aResultParamInfo.nType = pSpuType->Child().Result_Type().Id();
pStati->SetCur(expectName);
}
void
PE_Parameter::SpReturn_Variable()
{
if (pSpuVariable->Child().Result_Pattern() > 0)
{
aResultParamInfo.sSizeExpression = pSpuVariable->Child().Result_SizeExpression();
aResultParamInfo.sInitExpression = pSpuVariable->Child().Result_InitExpression();
}
}
void
PE_Parameter::On_start_Type(const char *)
{
pSpuType->Push(not_done);
}
void
PE_Parameter::On_start_Bracket_Right(const char *)
{
SetTokenResult(not_done, pop_success);
}
void
PE_Parameter::On_start_Ellipse(const char *)
{
SetTokenResult(done, pop_success);
aResultParamInfo.nType = Env().AryGate().Types().Tid_Ellipse();
}
void
PE_Parameter::On_expectName_Identifier(const char * i_sText)
{
SetTokenResult(done, stay);
pStati->SetCur(afterName);
aResultParamInfo.sName = i_sText;
}
void
PE_Parameter::On_expectName_ArrayBracket_Left(const char * i_sText)
{
On_afterName_ArrayBracket_Left(i_sText);
}
void
PE_Parameter::On_expectName_Bracket_Right(const char * i_sText)
{
On_afterName_Bracket_Right(i_sText);
}
void
PE_Parameter::On_expectName_Comma(const char * i_sText)
{
On_afterName_Comma(i_sText);
}
void
PE_Parameter::On_expectName_Assign(const char * i_sText)
{
On_afterName_Assign(i_sText);
}
void
PE_Parameter::On_afterName_ArrayBracket_Left(const char *)
{
pSpuVariable->Push(not_done);
}
void
PE_Parameter::On_afterName_Bracket_Right(const char *)
{
SetTokenResult(not_done, pop_success);
}
void
PE_Parameter::On_afterName_Comma(const char *)
{
SetTokenResult(not_done, pop_success);
}
void
PE_Parameter::On_afterName_Assign(const char *)
{
pSpuVariable->Push(not_done);
}
void
PE_Parameter::On_finished_Bracket_Right(const char *)
{
SetTokenResult(not_done, pop_success);
}
void
PE_Parameter::On_finished_Comma(const char *)
{
SetTokenResult(not_done, pop_success);
}
} // namespace cpp
<|endoftext|> |
<commit_before>#include "common/std_headers.h"
#include "nodebase/jswrapbase.h"
#include "build.src/vec_jsWrap.h"
#include "build.src/ivec_jsWrap.h"
#include "build.src/mat_jsWrap.h"
#include "build.src/mat44_jsWrap.h"
#include "./solid_geometry_jswrap.h"
using namespace arma;
/* ----------------------------------------------------------------------
StlSolid
*/
static void jsNew_StlSolid(FunctionCallbackInfo<Value> const &args) {
Isolate *isolate = args.GetIsolate();
HandleScope scope(isolate);
if (!(args.Holder()->InternalFieldCount() > 0)) {
return ThrowInvalidThis(isolate);
}
JsWrap_StlSolid* thisObj = new JsWrap_StlSolid(isolate);
jsConstructor_StlSolid(thisObj, args);
}
void jsConstructor_StlSolid(JsWrap_StlSolid *thisObj, FunctionCallbackInfo<Value> const &args) {
Isolate *isolate = args.GetIsolate();
HandleScope scope(isolate);
if (args.Length() == 0) {
thisObj->assignDefault();
}
else {
return ThrowInvalidArgs(isolate);
}
thisObj->Wrap2(args.This());
args.GetReturnValue().Set(args.This());
}
static void jsGet_StlSolid_bboxLo(Local<String> name, PropertyCallbackInfo<Value> const &args) {
Isolate *isolate = args.GetIsolate();
EscapableHandleScope scope(isolate);
JsWrap_StlSolid* thisObj = node::ObjectWrap::Unwrap<JsWrap_StlSolid>(args.This());
args.GetReturnValue().Set(JsWrap_vec::MemberInstance(isolate, thisObj->it, &(thisObj->it->bboxLo)));
}
static void jsGet_StlSolid_bboxHi(Local<String> name, PropertyCallbackInfo<Value> const &args) {
Isolate *isolate = args.GetIsolate();
HandleScope scope(isolate);
JsWrap_StlSolid* thisObj = node::ObjectWrap::Unwrap<JsWrap_StlSolid>(args.This());
args.GetReturnValue().Set(JsWrap_vec::MemberInstance(isolate, thisObj->it, &(thisObj->it->bboxHi)));
}
static void jsGet_StlSolid_numFaces(Local<String> name, PropertyCallbackInfo<Value> const &args) {
Isolate *isolate = args.GetIsolate();
HandleScope scope(isolate);
JsWrap_StlSolid* thisObj = node::ObjectWrap::Unwrap<JsWrap_StlSolid>(args.This());
args.GetReturnValue().Set(Number::New(isolate, thisObj->it->faces.size()));
}
static void jsWrap_StlSolid_toString(FunctionCallbackInfo<Value> const &args)
{
Isolate *isolate = args.GetIsolate();
HandleScope scope(isolate);
JsWrap_StlSolid* thisObj = node::ObjectWrap::Unwrap<JsWrap_StlSolid>(args.This());
ostringstream oss;
oss << *thisObj->it;
args.GetReturnValue().Set(convStringToJs(isolate, oss.str()));
}
static void jsWrap_StlSolid_inspect(FunctionCallbackInfo<Value> const &args)
{
Isolate *isolate = args.GetIsolate();
HandleScope scope(isolate);
JsWrap_StlSolid* thisObj = node::ObjectWrap::Unwrap<JsWrap_StlSolid>(args.This());
ostringstream oss;
oss << *thisObj->it;
args.GetReturnValue().Set(convStringToJs(isolate, oss.str()));
}
static void jsWrap_StlSolid_readBinaryFile(FunctionCallbackInfo<Value> const &args)
{
Isolate *isolate = args.GetIsolate();
HandleScope scope(isolate);
JsWrap_StlSolid* thisObj = node::ObjectWrap::Unwrap<JsWrap_StlSolid>(args.This());
if (args.Length() == 2 && canConvJsToString(isolate, args[0]) && args[1]->IsNumber()) {
string a0 = convJsToString(isolate, args[0]);
double a1 = args[1]->NumberValue();
FILE *fp = fopen(a0.c_str(), "rb");
if (!fp) {
return ThrowRuntimeError(isolate, stringprintf("Can't read %s", a0.c_str()).c_str());
}
thisObj->it->readBinaryFile(fp, a1);
fclose(fp);
}
else {
return ThrowInvalidArgs(isolate);
}
}
static void jsWrap_StlSolid_writeBinaryFile(FunctionCallbackInfo<Value> const &args)
{
Isolate *isolate = args.GetIsolate();
HandleScope scope(isolate);
JsWrap_StlSolid* thisObj = node::ObjectWrap::Unwrap<JsWrap_StlSolid>(args.This());
if (args.Length() == 2 && canConvJsToString(isolate, args[0]) && args[1]->IsNumber()) {
string a0 = convJsToString(isolate, args[0]);
double a1 = args[1]->NumberValue();
FILE *fp = fopen(a0.c_str(), "wb");
if (!fp) {
return ThrowRuntimeError(isolate, stringprintf("Can't write %s", a0.c_str()).c_str());
}
thisObj->it->writeBinaryFile(fp, a1);
fclose(fp);
}
else {
return ThrowInvalidArgs(isolate);
}
}
static void jsWrap_StlSolid_transform(FunctionCallbackInfo<Value> const &args)
{
Isolate *isolate = args.GetIsolate();
HandleScope scope(isolate);
JsWrap_StlSolid* thisObj = node::ObjectWrap::Unwrap<JsWrap_StlSolid>(args.This());
if (args.Length() == 1 && JsWrap_mat44::Extract(isolate, args[0]) != nullptr) {
arma::mat44 a0 = *JsWrap_mat44::Extract(isolate, args[0]);
thisObj->it->transform(a0);
}
else {
return ThrowInvalidArgs(isolate);
}
}
static void jsWrap_StlSolid_getStlMassProperties(FunctionCallbackInfo<Value> const &args)
{
Isolate *isolate = args.GetIsolate();
HandleScope scope(isolate);
JsWrap_StlSolid* thisObj = node::ObjectWrap::Unwrap<JsWrap_StlSolid>(args.This());
if (args.Length() == 1 && args[0]->IsNumber()) {
double a0 = args[0]->NumberValue();
StlMassProperties ret = thisObj->it->getStlMassProperties(a0);
args.GetReturnValue().Set(JsWrap_StlMassProperties::NewInstance(isolate, ret));
}
else {
return ThrowInvalidArgs(isolate);
}
}
static void jsWrap_StlSolid_getIntersections(FunctionCallbackInfo<Value> const &args)
{
Isolate *isolate = args.GetIsolate();
HandleScope scope(isolate);
JsWrap_StlSolid* thisObj = node::ObjectWrap::Unwrap<JsWrap_StlSolid>(args.This());
if (args.Length() == 2 &&
JsWrap_vec::Extract(isolate, args[0]) != NULL &&
JsWrap_vec::Extract(isolate, args[1]) != NULL) {
vec a0 = *JsWrap_vec::Extract(isolate, args[0]);
vec a1 = *JsWrap_vec::Extract(isolate, args[1]);
vector<StlIntersection> ret = thisObj->it->getIntersections(a0, a1);
Local<Array> retJs = Array::New(isolate, ret.size());
for (size_t ri = 0; ri < ret.size(); ri++) {
Local<Object> interJs = Object::New(isolate);
interJs->Set(String::NewFromUtf8(isolate, "t"), Number::New(isolate, ret[ri].t));
interJs->Set(String::NewFromUtf8(isolate, "face"), JsWrap_StlFace::NewInstance(isolate, ret[ri].face));
retJs->Set(ri, interJs);
}
args.GetReturnValue().Set(retJs);
}
else {
return ThrowInvalidArgs(isolate);
}
}
static void jsWrap_StlSolid_removeTinyFaces(FunctionCallbackInfo<Value> const &args)
{
Isolate *isolate = args.GetIsolate();
HandleScope scope(isolate);
JsWrap_StlSolid* thisObj = node::ObjectWrap::Unwrap<JsWrap_StlSolid>(args.This());
if (args.Length() == 1 && args[0]->IsNumber()) {
double a0 = args[0]->NumberValue();
thisObj->it->removeTinyFaces(a0);
}
else {
return ThrowInvalidArgs(isolate);
}
}
struct vecsortwrap {
};
static void jsWrap_StlSolid_exportWebglMesh(FunctionCallbackInfo<Value> const &args)
{
Isolate *isolate = args.GetIsolate();
HandleScope scope(isolate);
JsWrap_StlSolid* thisObj = node::ObjectWrap::Unwrap<JsWrap_StlSolid>(args.This());
if (args.Length() == 1 && args[0]->IsNumber()) {
double a0 = args[0]->NumberValue();
StlWebglMesh ret = thisObj->it->exportWebglMesh(a0);
Local<Object> retJs = Object::New(isolate);
retJs->Set(String::NewFromUtf8(isolate, "coords"), JsWrap_vec::NewInstance(isolate, ret.coords));
retJs->Set(String::NewFromUtf8(isolate, "normals"), JsWrap_vec::NewInstance(isolate, ret.normals));
retJs->Set(String::NewFromUtf8(isolate, "indexes"), JsWrap_ivec::NewInstance(isolate, ret.indexes));
args.GetReturnValue().Set(retJs);
}
else {
return ThrowInvalidArgs(isolate);
}
}
static void jsWrap_StlSolid_analyzeHole(FunctionCallbackInfo<Value> const &args)
{
Isolate *isolate = args.GetIsolate();
HandleScope scope(isolate);
JsWrap_StlSolid* thisObj = node::ObjectWrap::Unwrap<JsWrap_StlSolid>(args.This());
if (0) eprintf("StlSolid_analyzeHole thisObj=%p args.Length=%d a0.isNumber=%d\n", thisObj, (int)args.Length(), args[0]->IsNumber());
if (args.Length() == 1 && args[0]->IsNumber()) {
double a0 = args[0]->NumberValue();
arma::vec3 ret = thisObj->it->analyzeHole((int)a0);
args.GetReturnValue().Set(JsWrap_vec::NewInstance(isolate, ret));
}
else {
return ThrowInvalidArgs(isolate);
}
}
static void jsWrap_StlSolid_estimateVolume(FunctionCallbackInfo<Value> const &args)
{
Isolate *isolate = args.GetIsolate();
HandleScope scope(isolate);
JsWrap_StlSolid* thisObj = node::ObjectWrap::Unwrap<JsWrap_StlSolid>(args.This());
if (args.Length() == 0) {
auto ret = thisObj->it->estimateVolume();
Local<Object> retJs = Object::New(isolate);
retJs->Set(String::NewFromUtf8(isolate, "volume"), Number::New(isolate, ret.first));
retJs->Set(String::NewFromUtf8(isolate, "center"), JsWrap_vec::NewInstance(isolate, ret.second));
args.GetReturnValue().Set(retJs);
}
else {
return ThrowInvalidArgs(isolate);
}
}
void jsInit_StlSolid(Handle<Object> exports) {
Isolate *isolate = Isolate::GetCurrent();
Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, jsNew_StlSolid);
tpl->SetClassName(String::NewFromUtf8(isolate, "StlSolid"));
tpl->InstanceTemplate()->SetInternalFieldCount(1);
tpl->PrototypeTemplate()->SetAccessor(String::NewFromUtf8(isolate, "bboxLo"), &jsGet_StlSolid_bboxLo);
tpl->PrototypeTemplate()->SetAccessor(String::NewFromUtf8(isolate, "bboxHi"), &jsGet_StlSolid_bboxHi);
tpl->PrototypeTemplate()->SetAccessor(String::NewFromUtf8(isolate, "numFaces"), &jsGet_StlSolid_numFaces);
NODE_SET_PROTOTYPE_METHOD(tpl, "toString", &jsWrap_StlSolid_toString);
NODE_SET_PROTOTYPE_METHOD(tpl, "inspect", &jsWrap_StlSolid_inspect);
NODE_SET_PROTOTYPE_METHOD(tpl, "readBinaryFile", &jsWrap_StlSolid_readBinaryFile);
NODE_SET_PROTOTYPE_METHOD(tpl, "writeBinaryFile", &jsWrap_StlSolid_writeBinaryFile);
NODE_SET_PROTOTYPE_METHOD(tpl, "transform", &jsWrap_StlSolid_transform);
NODE_SET_PROTOTYPE_METHOD(tpl, "getStlMassProperties", &jsWrap_StlSolid_getStlMassProperties);
NODE_SET_PROTOTYPE_METHOD(tpl, "getIntersections", &jsWrap_StlSolid_getIntersections);
NODE_SET_PROTOTYPE_METHOD(tpl, "removeTinyFaces", &jsWrap_StlSolid_removeTinyFaces);
NODE_SET_PROTOTYPE_METHOD(tpl, "exportWebglMesh", &jsWrap_StlSolid_exportWebglMesh);
NODE_SET_PROTOTYPE_METHOD(tpl, "analyzeHole", &jsWrap_StlSolid_analyzeHole);
NODE_SET_PROTOTYPE_METHOD(tpl, "estimateVolume", &jsWrap_StlSolid_estimateVolume);
JsWrap_StlSolid::constructor.Reset(isolate, tpl->GetFunction());
exports->Set(String::NewFromUtf8(isolate, "StlSolid"), tpl->GetFunction());
}
/* ----------------------------------------------------------------------
StlFace
*/
static void jsNew_StlFace(FunctionCallbackInfo<Value> const &args) {
Isolate *isolate = args.GetIsolate();
HandleScope scope(isolate);
if (!(args.Holder()->InternalFieldCount() > 0)) return ThrowInvalidThis(isolate);
JsWrap_StlFace* thisObj = new JsWrap_StlFace(isolate);
jsConstructor_StlFace(thisObj, args);
}
void jsConstructor_StlFace(JsWrap_StlFace *thisObj, FunctionCallbackInfo<Value> const &args) {
Isolate *isolate = args.GetIsolate();
HandleScope scope(isolate);
if (args.Length() == 0) {
thisObj->assignDefault();
}
else if (args.Length() == 3 &&
JsWrap_vec::Extract(isolate, args[0]) != NULL &&
JsWrap_vec::Extract(isolate, args[1]) != NULL &&
JsWrap_vec::Extract(isolate, args[2]) != NULL) {
vec a0 = *JsWrap_vec::Extract(isolate, args[0]);
vec a1 = *JsWrap_vec::Extract(isolate, args[1]);
vec a2 = *JsWrap_vec::Extract(isolate, args[2]);
thisObj->assignConstruct(a0, a1, a2);
}
else {
return ThrowInvalidArgs(isolate);
}
thisObj->Wrap2(args.This());
args.GetReturnValue().Set(args.This());
}
static void jsWrap_StlFace_getArea(FunctionCallbackInfo<Value> const &args)
{
Isolate *isolate = args.GetIsolate();
HandleScope scope(isolate);
JsWrap_StlFace* thisObj = node::ObjectWrap::Unwrap<JsWrap_StlFace>(args.This());
if (args.Length() == 0) {
double ret = thisObj->it->getArea();
args.GetReturnValue().Set(Number::New(isolate, ret));
}
else {
return ThrowInvalidArgs(isolate);
}
}
static void jsWrap_StlFace_getE1(FunctionCallbackInfo<Value> const &args)
{
Isolate *isolate = args.GetIsolate();
HandleScope scope(isolate);
JsWrap_StlFace* thisObj = node::ObjectWrap::Unwrap<JsWrap_StlFace>(args.This());
if (args.Length() == 0) {
vec ret = thisObj->it->getE1();
args.GetReturnValue().Set(JsWrap_vec::NewInstance(isolate, ret));
}
else {
return ThrowInvalidArgs(isolate);
}
}
static void jsWrap_StlFace_getE2(FunctionCallbackInfo<Value> const &args)
{
Isolate *isolate = args.GetIsolate();
HandleScope scope(isolate);
JsWrap_StlFace* thisObj = node::ObjectWrap::Unwrap<JsWrap_StlFace>(args.This());
if (args.Length() == 0) {
vec ret = thisObj->it->getE2();
args.GetReturnValue().Set(JsWrap_vec::NewInstance(isolate, ret));
}
else {
return ThrowInvalidArgs(isolate);
}
}
static void jsWrap_StlFace_isDegenerate(FunctionCallbackInfo<Value> const &args)
{
Isolate *isolate = args.GetIsolate();
HandleScope scope(isolate);
JsWrap_StlFace* thisObj = node::ObjectWrap::Unwrap<JsWrap_StlFace>(args.This());
if (args.Length() == 0) {
bool ret = thisObj->it->isDegenerate();
args.GetReturnValue().Set(Boolean::New(isolate, ret));
}
else {
return ThrowInvalidArgs(isolate);
}
}
static void jsWrap_StlFace_getCentroid(FunctionCallbackInfo<Value> const &args)
{
Isolate *isolate = args.GetIsolate();
HandleScope scope(isolate);
JsWrap_StlFace* thisObj = node::ObjectWrap::Unwrap<JsWrap_StlFace>(args.This());
if (args.Length() == 0) {
vec ret = thisObj->it->getCentroid();
args.GetReturnValue().Set(JsWrap_vec::NewInstance(isolate, ret));
}
else {
return ThrowInvalidArgs(isolate);
}
}
void jsInit_StlFace(Handle<Object> exports) {
Isolate *isolate = Isolate::GetCurrent();
Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, jsNew_StlFace);
tpl->SetClassName(String::NewFromUtf8(isolate, "StlFace"));
tpl->InstanceTemplate()->SetInternalFieldCount(1);
NODE_SET_PROTOTYPE_METHOD(tpl, "getArea", &jsWrap_StlFace_getArea);
NODE_SET_PROTOTYPE_METHOD(tpl, "getE1", &jsWrap_StlFace_getE1);
NODE_SET_PROTOTYPE_METHOD(tpl, "getE2", &jsWrap_StlFace_getE2);
NODE_SET_PROTOTYPE_METHOD(tpl, "isDegenerate", &jsWrap_StlFace_isDegenerate);
NODE_SET_PROTOTYPE_METHOD(tpl, "getCentroid", &jsWrap_StlFace_getCentroid);
JsWrap_StlFace::constructor.Reset(isolate, tpl->GetFunction());
exports->Set(String::NewFromUtf8(isolate, "StlFace"), tpl->GetFunction());
}
/* ----------------------------------------------------------------------
StlMassProperties
*/
static void jsNew_StlMassProperties(FunctionCallbackInfo<Value> const &args) {
Isolate *isolate = args.GetIsolate();
HandleScope scope(isolate);
if (!(args.Holder()->InternalFieldCount() > 0)) return ThrowInvalidThis(isolate);
JsWrap_StlMassProperties* thisObj = new JsWrap_StlMassProperties(isolate);
jsConstructor_StlMassProperties(thisObj, args);
}
void jsConstructor_StlMassProperties(JsWrap_StlMassProperties *thisObj, FunctionCallbackInfo<Value> const &args) {
Isolate *isolate = args.GetIsolate();
HandleScope scope(isolate);
if (args.Length() == 0) {
thisObj->assignDefault();
}
else {
return ThrowInvalidArgs(isolate);
}
thisObj->Wrap2(args.This());
args.GetReturnValue().Set(args.This());
}
static void jsWrap_StlMassProperties_toString(FunctionCallbackInfo<Value> const &args)
{
Isolate *isolate = args.GetIsolate();
HandleScope scope(isolate);
JsWrap_StlMassProperties* thisObj = node::ObjectWrap::Unwrap<JsWrap_StlMassProperties>(args.This());
ostringstream oss;
oss << *thisObj->it;
args.GetReturnValue().Set(convStringToJs(isolate, oss.str()));
}
static void jsWrap_StlMassProperties_inspect(FunctionCallbackInfo<Value> const &args)
{
Isolate *isolate = args.GetIsolate();
HandleScope scope(isolate);
JsWrap_StlMassProperties* thisObj = node::ObjectWrap::Unwrap<JsWrap_StlMassProperties>(args.This());
ostringstream oss;
oss << *thisObj->it;
args.GetReturnValue().Set(convStringToJs(isolate, oss.str()));
}
static void jsGet_StlMassProperties_density(Local<String> name, PropertyCallbackInfo<Value> const &args) {
Isolate *isolate = args.GetIsolate();
HandleScope scope(isolate);
JsWrap_StlMassProperties* thisObj = node::ObjectWrap::Unwrap<JsWrap_StlMassProperties>(args.This());
args.GetReturnValue().Set(Number::New(isolate, thisObj->it->density));
}
static void jsGet_StlMassProperties_volume(Local<String> name, PropertyCallbackInfo<Value> const &args) {
Isolate *isolate = args.GetIsolate();
HandleScope scope(isolate);
JsWrap_StlMassProperties* thisObj = node::ObjectWrap::Unwrap<JsWrap_StlMassProperties>(args.This());
args.GetReturnValue().Set(Number::New(isolate, thisObj->it->volume));
}
static void jsGet_StlMassProperties_mass(Local<String> name, PropertyCallbackInfo<Value> const &args) {
Isolate *isolate = args.GetIsolate();
HandleScope scope(isolate);
JsWrap_StlMassProperties* thisObj = node::ObjectWrap::Unwrap<JsWrap_StlMassProperties>(args.This());
args.GetReturnValue().Set(Number::New(isolate, thisObj->it->mass));
}
static void jsGet_StlMassProperties_area(Local<String> name, PropertyCallbackInfo<Value> const &args) {
Isolate *isolate = args.GetIsolate();
HandleScope scope(isolate);
JsWrap_StlMassProperties* thisObj = node::ObjectWrap::Unwrap<JsWrap_StlMassProperties>(args.This());
args.GetReturnValue().Set(Number::New(isolate, thisObj->it->area));
}
static void jsGet_StlMassProperties_cm(Local<String> name, PropertyCallbackInfo<Value> const &args) {
Isolate *isolate = args.GetIsolate();
HandleScope scope(isolate);
JsWrap_StlMassProperties* thisObj = node::ObjectWrap::Unwrap<JsWrap_StlMassProperties>(args.This());
args.GetReturnValue().Set(JsWrap_vec::MemberInstance(isolate, thisObj->it, &(thisObj->it->cm)));
}
static void jsGet_StlMassProperties_inertiaOrigin(Local<String> name, PropertyCallbackInfo<Value> const &args) {
Isolate *isolate = args.GetIsolate();
HandleScope scope(isolate);
JsWrap_StlMassProperties* thisObj = node::ObjectWrap::Unwrap<JsWrap_StlMassProperties>(args.This());
args.GetReturnValue().Set(JsWrap_mat::MemberInstance(isolate, thisObj->it, &(thisObj->it->inertiaOrigin)));
}
static void jsGet_StlMassProperties_inertiaCm(Local<String> name, PropertyCallbackInfo<Value> const &args) {
Isolate *isolate = args.GetIsolate();
HandleScope scope(isolate);
JsWrap_StlMassProperties* thisObj = node::ObjectWrap::Unwrap<JsWrap_StlMassProperties>(args.This());
args.GetReturnValue().Set(JsWrap_mat::MemberInstance(isolate, thisObj->it, &(thisObj->it->inertiaCm)));
}
static void jsGet_StlMassProperties_rogOrigin(Local<String> name, PropertyCallbackInfo<Value> const &args) {
Isolate *isolate = args.GetIsolate();
HandleScope scope(isolate);
JsWrap_StlMassProperties* thisObj = node::ObjectWrap::Unwrap<JsWrap_StlMassProperties>(args.This());
args.GetReturnValue().Set(JsWrap_mat::MemberInstance(isolate, thisObj->it, &(thisObj->it->rogOrigin)));
}
static void jsGet_StlMassProperties_rogCm(Local<String> name, PropertyCallbackInfo<Value> const &args) {
Isolate *isolate = args.GetIsolate();
HandleScope scope(isolate);
JsWrap_StlMassProperties* thisObj = node::ObjectWrap::Unwrap<JsWrap_StlMassProperties>(args.This());
args.GetReturnValue().Set(JsWrap_mat::MemberInstance(isolate, thisObj->it, &(thisObj->it->rogCm)));
}
void jsInit_StlMassProperties(Handle<Object> exports) {
Isolate *isolate = Isolate::GetCurrent();
Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, jsNew_StlMassProperties);
tpl->SetClassName(String::NewFromUtf8(isolate, "StlMassProperties"));
tpl->InstanceTemplate()->SetInternalFieldCount(1);
NODE_SET_PROTOTYPE_METHOD(tpl, "toString", &jsWrap_StlMassProperties_toString);
NODE_SET_PROTOTYPE_METHOD(tpl, "inspect", &jsWrap_StlMassProperties_inspect);
tpl->PrototypeTemplate()->SetAccessor(String::NewFromUtf8(isolate, "density"), &jsGet_StlMassProperties_density);
tpl->PrototypeTemplate()->SetAccessor(String::NewFromUtf8(isolate, "volume"), &jsGet_StlMassProperties_volume);
tpl->PrototypeTemplate()->SetAccessor(String::NewFromUtf8(isolate, "mass"), &jsGet_StlMassProperties_mass);
tpl->PrototypeTemplate()->SetAccessor(String::NewFromUtf8(isolate, "area"), &jsGet_StlMassProperties_area);
tpl->PrototypeTemplate()->SetAccessor(String::NewFromUtf8(isolate, "cm"), &jsGet_StlMassProperties_cm);
tpl->PrototypeTemplate()->SetAccessor(String::NewFromUtf8(isolate, "inertiaOrigin"), &jsGet_StlMassProperties_inertiaOrigin);
tpl->PrototypeTemplate()->SetAccessor(String::NewFromUtf8(isolate, "inertiaCm"), &jsGet_StlMassProperties_inertiaCm);
tpl->PrototypeTemplate()->SetAccessor(String::NewFromUtf8(isolate, "rogOrigin"), &jsGet_StlMassProperties_rogOrigin);
tpl->PrototypeTemplate()->SetAccessor(String::NewFromUtf8(isolate, "rogCm"), &jsGet_StlMassProperties_rogCm);
JsWrap_StlMassProperties::constructor.Reset(isolate, tpl->GetFunction());
exports->Set(String::NewFromUtf8(isolate, "StlMassProperties"), tpl->GetFunction());
}
void jsInit_solid_geometry(Handle<Object> exports) {
jsInit_StlSolid(exports);
jsInit_StlFace(exports);
jsInit_StlMassProperties(exports);
}
<commit_msg>Delete solid_geometry_jswrap.cc<commit_after><|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: b2drange.hxx,v $
*
* $Revision: 1.17 $
*
* last change: $Author: obo $ $Date: 2007-07-18 11:04:01 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _BGFX_RANGE_B2DRANGE_HXX
#define _BGFX_RANGE_B2DRANGE_HXX
#ifndef _BGFX_VECTOR_B2DVECTOR_HXX
#include <basegfx/vector/b2dvector.hxx>
#endif
#ifndef _BGFX_POINT_B2DPOINT_HXX
#include <basegfx/point/b2dpoint.hxx>
#endif
#ifndef _BGFX_TUPLE_B2DTUPLE_HXX
#include <basegfx/tuple/b2dtuple.hxx>
#endif
#ifndef _BGFX_RANGE_BASICRANGE_HXX
#include <basegfx/range/basicrange.hxx>
#endif
#include <vector>
namespace basegfx
{
// predeclarations
class B2IRange;
class B2DRange
{
public:
typedef double ValueType;
typedef DoubleTraits TraitsType;
B2DRange()
{
}
explicit B2DRange(const B2DTuple& rTuple)
: maRangeX(rTuple.getX()),
maRangeY(rTuple.getY())
{
}
B2DRange(double x1,
double y1,
double x2,
double y2)
: maRangeX(x1),
maRangeY(y1)
{
maRangeX.expand(x2);
maRangeY.expand(y2);
}
B2DRange(const B2DTuple& rTuple1,
const B2DTuple& rTuple2)
: maRangeX(rTuple1.getX()),
maRangeY(rTuple1.getY())
{
expand( rTuple2 );
}
B2DRange(const B2DRange& rRange)
: maRangeX(rRange.maRangeX),
maRangeY(rRange.maRangeY)
{
}
explicit B2DRange(const B2IRange& rRange);
bool isEmpty() const
{
return (
maRangeX.isEmpty()
|| maRangeY.isEmpty()
);
}
void reset()
{
maRangeX.reset();
maRangeY.reset();
}
bool operator==( const B2DRange& rRange ) const
{
return (maRangeX == rRange.maRangeX
&& maRangeY == rRange.maRangeY);
}
bool operator!=( const B2DRange& rRange ) const
{
return (maRangeX != rRange.maRangeX
|| maRangeY != rRange.maRangeY);
}
void operator=(const B2DRange& rRange)
{
maRangeX = rRange.maRangeX;
maRangeY = rRange.maRangeY;
}
bool equal(const B2DRange& rRange) const
{
return (maRangeX.equal(rRange.maRangeX)
&& maRangeY.equal(rRange.maRangeY));
}
double getMinX() const
{
return maRangeX.getMinimum();
}
double getMinY() const
{
return maRangeY.getMinimum();
}
double getMaxX() const
{
return maRangeX.getMaximum();
}
double getMaxY() const
{
return maRangeY.getMaximum();
}
double getWidth() const
{
return maRangeX.getRange();
}
double getHeight() const
{
return maRangeY.getRange();
}
B2DPoint getMinimum() const
{
return B2DPoint(
maRangeX.getMinimum(),
maRangeY.getMinimum()
);
}
B2DPoint getMaximum() const
{
return B2DPoint(
maRangeX.getMaximum(),
maRangeY.getMaximum()
);
}
B2DVector getRange() const
{
return B2DVector(
maRangeX.getRange(),
maRangeY.getRange()
);
}
B2DPoint getCenter() const
{
return B2DPoint(
maRangeX.getCenter(),
maRangeY.getCenter()
);
}
double getCenterX() const
{
return maRangeX.getCenter();
}
double getCenterY() const
{
return maRangeY.getCenter();
}
bool isInside(const B2DTuple& rTuple) const
{
return (
maRangeX.isInside(rTuple.getX())
&& maRangeY.isInside(rTuple.getY())
);
}
bool isInside(const B2DRange& rRange) const
{
return (
maRangeX.isInside(rRange.maRangeX)
&& maRangeY.isInside(rRange.maRangeY)
);
}
bool overlaps(const B2DRange& rRange) const
{
return (
maRangeX.overlaps(rRange.maRangeX)
&& maRangeY.overlaps(rRange.maRangeY)
);
}
void expand(const B2DTuple& rTuple)
{
maRangeX.expand(rTuple.getX());
maRangeY.expand(rTuple.getY());
}
void expand(const B2DRange& rRange)
{
maRangeX.expand(rRange.maRangeX);
maRangeY.expand(rRange.maRangeY);
}
void intersect(const B2DRange& rRange)
{
maRangeX.intersect(rRange.maRangeX);
maRangeY.intersect(rRange.maRangeY);
}
void grow(double fValue)
{
maRangeX.grow(fValue);
maRangeY.grow(fValue);
}
void transform(const B2DHomMatrix& rMatrix);
private:
typedef ::basegfx::BasicRange< ValueType, TraitsType > MyBasicRange;
MyBasicRange maRangeX;
MyBasicRange maRangeY;
};
/** Round double to nearest integer for 2D range
@return the nearest integer for this range
*/
B2IRange fround(const B2DRange& rRange);
/** Compute the set difference of the two given ranges
This method calculates the symmetric difference (aka XOR)
between the two given ranges, and returning the resulting
ranges. Thus, the result will contain all areas where one, but
not both ranges lie.
@param o_rResult
Result vector. The up to four difference ranges are returned
within this vector
@param rFirst
The first range
@param rSecond
The second range
@return the input vector
*/
::std::vector< B2DRange >& computeSetDifference( ::std::vector< B2DRange >& o_rResult,
const B2DRange& rFirst,
const B2DRange& rSecond );
} // end of namespace basegfx
#endif /* _BGFX_RANGE_B2DRANGE_HXX */
<commit_msg>INTEGRATION: CWS changefileheader (1.17.28); FILE MERGED 2008/04/01 10:48:09 thb 1.17.28.2: #i85898# Stripping all external header guards 2008/03/28 16:05:43 rt 1.17.28.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: b2drange.hxx,v $
* $Revision: 1.18 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _BGFX_RANGE_B2DRANGE_HXX
#define _BGFX_RANGE_B2DRANGE_HXX
#include <basegfx/vector/b2dvector.hxx>
#include <basegfx/point/b2dpoint.hxx>
#include <basegfx/tuple/b2dtuple.hxx>
#include <basegfx/range/basicrange.hxx>
#include <vector>
namespace basegfx
{
// predeclarations
class B2IRange;
class B2DRange
{
public:
typedef double ValueType;
typedef DoubleTraits TraitsType;
B2DRange()
{
}
explicit B2DRange(const B2DTuple& rTuple)
: maRangeX(rTuple.getX()),
maRangeY(rTuple.getY())
{
}
B2DRange(double x1,
double y1,
double x2,
double y2)
: maRangeX(x1),
maRangeY(y1)
{
maRangeX.expand(x2);
maRangeY.expand(y2);
}
B2DRange(const B2DTuple& rTuple1,
const B2DTuple& rTuple2)
: maRangeX(rTuple1.getX()),
maRangeY(rTuple1.getY())
{
expand( rTuple2 );
}
B2DRange(const B2DRange& rRange)
: maRangeX(rRange.maRangeX),
maRangeY(rRange.maRangeY)
{
}
explicit B2DRange(const B2IRange& rRange);
bool isEmpty() const
{
return (
maRangeX.isEmpty()
|| maRangeY.isEmpty()
);
}
void reset()
{
maRangeX.reset();
maRangeY.reset();
}
bool operator==( const B2DRange& rRange ) const
{
return (maRangeX == rRange.maRangeX
&& maRangeY == rRange.maRangeY);
}
bool operator!=( const B2DRange& rRange ) const
{
return (maRangeX != rRange.maRangeX
|| maRangeY != rRange.maRangeY);
}
void operator=(const B2DRange& rRange)
{
maRangeX = rRange.maRangeX;
maRangeY = rRange.maRangeY;
}
bool equal(const B2DRange& rRange) const
{
return (maRangeX.equal(rRange.maRangeX)
&& maRangeY.equal(rRange.maRangeY));
}
double getMinX() const
{
return maRangeX.getMinimum();
}
double getMinY() const
{
return maRangeY.getMinimum();
}
double getMaxX() const
{
return maRangeX.getMaximum();
}
double getMaxY() const
{
return maRangeY.getMaximum();
}
double getWidth() const
{
return maRangeX.getRange();
}
double getHeight() const
{
return maRangeY.getRange();
}
B2DPoint getMinimum() const
{
return B2DPoint(
maRangeX.getMinimum(),
maRangeY.getMinimum()
);
}
B2DPoint getMaximum() const
{
return B2DPoint(
maRangeX.getMaximum(),
maRangeY.getMaximum()
);
}
B2DVector getRange() const
{
return B2DVector(
maRangeX.getRange(),
maRangeY.getRange()
);
}
B2DPoint getCenter() const
{
return B2DPoint(
maRangeX.getCenter(),
maRangeY.getCenter()
);
}
double getCenterX() const
{
return maRangeX.getCenter();
}
double getCenterY() const
{
return maRangeY.getCenter();
}
bool isInside(const B2DTuple& rTuple) const
{
return (
maRangeX.isInside(rTuple.getX())
&& maRangeY.isInside(rTuple.getY())
);
}
bool isInside(const B2DRange& rRange) const
{
return (
maRangeX.isInside(rRange.maRangeX)
&& maRangeY.isInside(rRange.maRangeY)
);
}
bool overlaps(const B2DRange& rRange) const
{
return (
maRangeX.overlaps(rRange.maRangeX)
&& maRangeY.overlaps(rRange.maRangeY)
);
}
void expand(const B2DTuple& rTuple)
{
maRangeX.expand(rTuple.getX());
maRangeY.expand(rTuple.getY());
}
void expand(const B2DRange& rRange)
{
maRangeX.expand(rRange.maRangeX);
maRangeY.expand(rRange.maRangeY);
}
void intersect(const B2DRange& rRange)
{
maRangeX.intersect(rRange.maRangeX);
maRangeY.intersect(rRange.maRangeY);
}
void grow(double fValue)
{
maRangeX.grow(fValue);
maRangeY.grow(fValue);
}
void transform(const B2DHomMatrix& rMatrix);
private:
typedef ::basegfx::BasicRange< ValueType, TraitsType > MyBasicRange;
MyBasicRange maRangeX;
MyBasicRange maRangeY;
};
/** Round double to nearest integer for 2D range
@return the nearest integer for this range
*/
B2IRange fround(const B2DRange& rRange);
/** Compute the set difference of the two given ranges
This method calculates the symmetric difference (aka XOR)
between the two given ranges, and returning the resulting
ranges. Thus, the result will contain all areas where one, but
not both ranges lie.
@param o_rResult
Result vector. The up to four difference ranges are returned
within this vector
@param rFirst
The first range
@param rSecond
The second range
@return the input vector
*/
::std::vector< B2DRange >& computeSetDifference( ::std::vector< B2DRange >& o_rResult,
const B2DRange& rFirst,
const B2DRange& rSecond );
} // end of namespace basegfx
#endif /* _BGFX_RANGE_B2DRANGE_HXX */
<|endoftext|> |
<commit_before>void test()
{
gSystem->Load("libEG");
gSystem->Load("libdime");
gSystem->Load("libTDime");
TDime* dime = new TDime();
dime->SetEnergyCMS(7000.);
dime->Initialize();
TClonesArray* particles = new TClonesArray("TParticle", 100);
for (Int_t i = 0; i < 10; i++)
{
dime->GenerateEvent();
Int_t np = dime->ImportParticles(particles, "All");
printf("\n Imported %3d particles \n", np);
for (Int_t ip = 0; ip < np; ip++) {
TParticle* part = (TParticle*) (particles->At(ip));
part->Print();
}
}
}
<commit_msg>Load libEVGEN<commit_after>void test()
{
gSystem->Load("libEG");
gSystem->Load("libEVGEN.so");
gSystem->Load("libdime");
gSystem->Load("libTDime");
TDime* dime = new TDime();
dime->SetEnergyCMS(7000.);
dime->Initialize();
TClonesArray* particles = new TClonesArray("TParticle", 100);
for (Int_t i = 0; i < 10; i++)
{
dime->GenerateEvent();
Int_t np = dime->ImportParticles(particles, "All");
printf("\n Imported %3d particles \n", np);
for (Int_t ip = 0; ip < np; ip++) {
TParticle* part = (TParticle*) (particles->At(ip));
part->Print();
}
}
}
<|endoftext|> |
<commit_before>/*
March22 Engine Prototype:
A C++ port of Snow Sakura
Code by Sam Lynch,
Amduat Games
Everything else is property of
D.O. and G-Collections
*/
#include "SDL.h" // Main SDL library
#include <SDL_image.h> // SDL Image library
#include <SDL_mixer.h> // SDL Image library
#include "M22Engine.h"
#include <iostream>
#include <chrono>
#define DEBUG_ENABLED false
#define WINDOW_TITLE "March22 Engine Prototype"
#define FPS 60
#define screenW 640
#define screenH 480
#define screenX 600
#define screenY 200
bool QUIT = false;
void Shutdown();
short int InitializeSDL();
short int InitializeSound();
short int InitializeSFX();
short int InitializeMusic();
void UpdateKeyboard();
void UpdateEvents();
void UpdateSound();
void DrawBackground(short int);
int main(int argc, char* argv[])
{
InitializeSDL();
InitializeSound();
M22Graphics::LoadBackgroundsFromIndex("graphics/backgrounds/index.txt");
M22Graphics::textFrame = IMG_LoadTexture(M22Engine::SDL_RENDERER, "graphics/frame.png");
M22Graphics::characterFrameHeaders.push_back(IMG_LoadTexture(M22Engine::SDL_RENDERER, "graphics/text_frames/yuuji.png"));
M22Script::LoadScriptToCurrent("scripts/EVC_001_strings.txt");
while( !QUIT )
{
UpdateEvents();
UpdateKeyboard();
UpdateSound();
switch(M22Engine::GAMESTATE)
{
case M22Engine::GAMESTATES::MAIN_MENU:
DrawBackground(0);
SDL_RenderCopy(M22Engine::SDL_RENDERER, M22Graphics::textFrame, NULL, NULL);
SDL_RenderCopy(M22Engine::SDL_RENDERER, M22Graphics::characterFrameHeaders[M22Script::activeSpeakerIndex], NULL, NULL);
break;
case M22Engine::GAMESTATES::INGAME:
break;
default:
break;
};
SDL_RenderPresent(M22Engine::SDL_RENDERER);
SDL_Delay(1000/FPS);
};
Shutdown();
return 0;
}
void Shutdown()
{
SDL_Quit();
M22Engine::SDL_RENDERER = NULL;
M22Engine::SDL_SCREEN = NULL;
M22Engine::SDL_KEYBOARDSTATE = NULL;
M22Sound::SOUND_FX.clear();
M22Sound::MUSIC.clear();
M22Graphics::BACKGROUNDS.clear();
M22Graphics::characterFrameHeaders.clear();
M22Graphics::textFrame = NULL;
if(DEBUG_ENABLED)
{
printf("\nPress enter to exit...");
getchar();
};
};
short int InitializeSDL()
{
SDL_Init( SDL_INIT_EVERYTHING );
M22Engine::SDL_SCREEN = SDL_CreateWindow(WINDOW_TITLE, screenX, screenY, screenW, screenH, SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI | SDL_WINDOW_OPENGL);
M22Engine::SDL_RENDERER = SDL_CreateRenderer(M22Engine::SDL_SCREEN, -1, SDL_RENDERER_ACCELERATED);
SDL_RenderSetLogicalSize(M22Engine::SDL_RENDERER, screenW, screenH);
if( Mix_OpenAudio( 44100, MIX_DEFAULT_FORMAT, 2, 2048 ) < 0 )
{
printf( "SDL_mixer failed to init! Error: %s\n", Mix_GetError() );
};
Mix_VolumeMusic(int(MIX_MAX_VOLUME*M22Sound::MUSIC_VOLUME));
return 0;
};
short int InitializeMusic()
{
std::fstream input("sfx/music/index.txt");
int length;
if(input)
{
input >> length;
for(int i = 0; i < length; i++)
{
std::string currentfile;
input >> currentfile;
Mix_Music *temp = Mix_LoadMUS(currentfile.c_str());
if(!temp)
{
std::cout << "Failed to load file: " << currentfile << std::endl;
return -1;
};
M22Sound::MUSIC.push_back(temp);
};
}
else
{
std::cout << "Failed to load index file for music!" << std::endl;
return -1;
};
input.close();
return 0;
};
short int InitializeSFX()
{
std::fstream input("sfx/stings/index.txt");
int length;
if(input)
{
input >> length;
for(int i = 0; i < length; i++)
{
std::string currentfile;
input >> currentfile;
Mix_Chunk *temp = Mix_LoadWAV(currentfile.c_str());
if(!temp)
{
std::cout << "Failed to load file: " << currentfile << std::endl;
return -1;
};
M22Sound::SOUND_FX.push_back(temp);
Mix_VolumeChunk(M22Sound::SOUND_FX[i], int(MIX_MAX_VOLUME*M22Sound::SFX_VOLUME));
};
}
else
{
std::cout << "Failed to load index file for music!" << std::endl;
return -1;
};
input.close();
return 0;
};
short int InitializeSound()
{
if(InitializeMusic() != 0)
{
printf("Failed to initialize music!");
return -1;
};
if(InitializeSFX() != 0)
{
printf("Failed to initialize SFX!");
return -1;
};
return 0;
};
void UpdateSound()
{
if(!Mix_PlayingMusic() && DEBUG_ENABLED == false)
{
M22Sound::ChangeMusicTrack(0);
};
return;
};
void UpdateKeyboard()
{
M22Engine::SDL_KEYBOARDSTATE = SDL_GetKeyboardState(NULL);
if(M22Engine::SDL_KEYBOARDSTATE[SDL_SCANCODE_ESCAPE])
{
QUIT=true;
};
if(M22Engine::SDL_KEYBOARDSTATE[SDL_SCANCODE_W] && DEBUG_ENABLED == true)
{
M22Sound::PlaySting(0);
};
return;
};
void UpdateEvents()
{
while( SDL_PollEvent( &M22Engine::SDL_EVENTS ) )
{
switch( M22Engine::SDL_EVENTS.type )
{
case SDL_QUIT:
QUIT = true;
break;
default:
break;
}
};
return;
};
void DrawBackground(short int _index)
{
if(M22Graphics::BACKGROUNDS[_index])
{
// Backgrounds match the 640x480 resolution, so no need for scaling... for now.
SDL_RenderCopy(M22Engine::SDL_RENDERER, M22Graphics::BACKGROUNDS[_index], NULL, NULL);
};
return;
};<commit_msg>v0.1.0<commit_after>/*
March22 Engine Prototype:
A C++ port of Snow Sakura
Code by Sam Lynch,
Amduat Games
Everything else is property of
D.O. and G-Collections
*/
#include "SDL.h" // Main SDL library
#include <SDL_image.h> // SDL Image library
#include <SDL_mixer.h> // SDL Sound library
#include <SDL_ttf.h> // SDL TTF library
#include "M22Engine.h"
#include <iostream>
#include <chrono>
#define DEBUG_ENABLED false
#define WINDOW_TITLE "March22 Engine Prototype "
#define VERSION "v0.1.0"
#define FPS 60
Vec2 ScrSize(640,480);
Vec2 ScrPos(600,200);
bool QUIT = false;
void Shutdown();
short int InitializeSDL();
short int InitializeSound();
short int InitializeSFX();
short int InitializeMusic();
void UpdateKeyboard();
void UpdateEvents();
void UpdateSound();
void DrawBackground(short int);
int main(int argc, char* argv[])
{
InitializeSDL();
InitializeSound();
M22Engine::InitializeM22();
M22Graphics::LoadBackgroundsFromIndex("graphics/backgrounds/index.txt");
M22Graphics::textFrame = IMG_LoadTexture(M22Engine::SDL_RENDERER, "graphics/frame.png");
M22Script::LoadScriptToCurrent("scripts/EVC_001_strings.txt");
M22Graphics::textFont = TTF_OpenFont( "graphics/times.ttf", 19 );
M22Script::ChangeLine(0);
while( !QUIT )
{
UpdateEvents();
UpdateSound();
switch(M22Engine::GAMESTATE)
{
case M22Engine::GAMESTATES::MAIN_MENU:
break;
case M22Engine::GAMESTATES::INGAME:
DrawBackground(M22Engine::ACTIVE_BACKGROUND_INDEX);
SDL_RenderCopy(M22Engine::SDL_RENDERER, M22Graphics::textFrame, NULL, NULL);
SDL_RenderCopy(M22Engine::SDL_RENDERER, M22Graphics::characterFrameHeaders[M22Script::activeSpeakerIndex], NULL, NULL);
M22Script::DrawCurrentLine();
break;
default:
break;
};
SDL_RenderPresent(M22Engine::SDL_RENDERER);
SDL_Delay(1000/FPS);
};
Shutdown();
return 0;
}
void Shutdown()
{
SDL_Quit();
M22Engine::SDL_RENDERER = NULL;
M22Engine::SDL_SCREEN = NULL;
M22Engine::SDL_KEYBOARDSTATE = NULL;
M22Sound::SOUND_FX.clear();
M22Sound::MUSIC.clear();
M22Graphics::BACKGROUNDS.clear();
M22Graphics::characterFrameHeaders.clear();
M22Graphics::textFrame = NULL;
M22Graphics::textFont = NULL;
TTF_Quit();
if(DEBUG_ENABLED)
{
printf("\nPress enter to exit...");
getchar();
};
};
short int InitializeSDL()
{
SDL_Init( SDL_INIT_EVERYTHING );
std::string tempTitle = WINDOW_TITLE;
tempTitle += VERSION;
M22Engine::SDL_SCREEN = SDL_CreateWindow(tempTitle.c_str(), (int)ScrPos.x(), (int)ScrPos.y(), (int)ScrSize.x(), (int)ScrSize.y(), SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI | SDL_WINDOW_OPENGL);
M22Engine::SDL_RENDERER = SDL_CreateRenderer(M22Engine::SDL_SCREEN, -1, SDL_RENDERER_ACCELERATED);
SDL_RenderSetLogicalSize(M22Engine::SDL_RENDERER, (int)ScrSize.x(), (int)ScrSize.y());
if( Mix_OpenAudio( 44100, MIX_DEFAULT_FORMAT, 2, 2048 ) < 0 )
{
printf( "SDL_mixer failed to init! Error: %s\n", Mix_GetError() );
};
Mix_VolumeMusic(int(MIX_MAX_VOLUME*M22Sound::MUSIC_VOLUME));
if( TTF_Init() == -1 )
{
printf( "SDL_TTF failed to init! Error: %s\n", TTF_GetError() );
}
return 0;
};
short int InitializeMusic()
{
std::fstream input("sfx/music/index.txt");
int length;
if(input)
{
input >> length;
for(int i = 0; i < length; i++)
{
std::string currentfile;
input >> currentfile;
Mix_Music *temp = Mix_LoadMUS(currentfile.c_str());
if(!temp)
{
std::cout << "Failed to load file: " << currentfile << std::endl;
return -1;
};
M22Sound::MUSIC.push_back(temp);
};
}
else
{
std::cout << "Failed to load index file for music!" << std::endl;
return -1;
};
input.close();
return 0;
};
short int InitializeSFX()
{
std::fstream input("sfx/stings/index.txt");
int length;
if(input)
{
input >> length;
for(int i = 0; i < length; i++)
{
std::string currentfile;
input >> currentfile;
Mix_Chunk *temp = Mix_LoadWAV(currentfile.c_str());
if(!temp)
{
std::cout << "Failed to load file: " << currentfile << std::endl;
return -1;
};
M22Sound::SOUND_FX.push_back(temp);
Mix_VolumeChunk(M22Sound::SOUND_FX[i], int(MIX_MAX_VOLUME*M22Sound::SFX_VOLUME));
};
}
else
{
std::cout << "Failed to load index file for music!" << std::endl;
return -1;
};
input.close();
return 0;
};
short int InitializeSound()
{
if(InitializeMusic() != 0)
{
printf("Failed to initialize music!");
return -1;
};
if(InitializeSFX() != 0)
{
printf("Failed to initialize SFX!");
return -1;
};
return 0;
};
void UpdateSound()
{
if( (!Mix_PlayingMusic()) && DEBUG_ENABLED == false)
{
M22Sound::ChangeMusicTrack(M22Sound::currentTrack);
};
return;
};
void UpdateKeyboard()
{
M22Engine::SDL_KEYBOARDSTATE = SDL_GetKeyboardState(NULL);
if(M22Engine::SDL_KEYBOARDSTATE[SDL_SCANCODE_ESCAPE])
{
QUIT=true;
};
if(M22Engine::SDL_KEYBOARDSTATE[SDL_SCANCODE_RETURN])
{
M22Script::ChangeLine(++M22Script::currentLineIndex);
};
return;
};
void UpdateEvents()
{
while( SDL_PollEvent( &M22Engine::SDL_EVENTS ) )
{
switch( M22Engine::SDL_EVENTS.type )
{
case SDL_QUIT:
QUIT = true;
break;
case SDL_KEYDOWN:
if(M22Engine::SDL_EVENTS.key.repeat == 0)
{
UpdateKeyboard();
};
break;
default:
break;
}
};
return;
};
void DrawBackground(short int _index)
{
if(M22Graphics::BACKGROUNDS[_index])
{
// Backgrounds match the 640x480 resolution, so no need for scaling... for now.
SDL_RenderCopy(M22Engine::SDL_RENDERER, M22Graphics::BACKGROUNDS[_index], NULL, NULL);
};
return;
};<|endoftext|> |
<commit_before>// Copyright Daniel Wallin 2006. Use, modification and distribution is
// subject to the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <libtorrent/torrent_handle.hpp>
#include <boost/python.hpp>
#include <boost/python/tuple.hpp>
#include <boost/lexical_cast.hpp>
#include "gil.hpp"
using namespace boost::python;
using namespace libtorrent;
namespace
{
list url_seeds(torrent_handle& handle)
{
list ret;
std::set<std::string> urls;
{
allow_threading_guard guard;
urls = handle.url_seeds();
}
for (std::set<std::string>::iterator i(urls.begin())
, end(urls.end()); i != end; ++i)
ret.append(*i);
return ret;
}
list piece_availability(torrent_handle& handle)
{
list ret;
std::vector<int> avail;
{
allow_threading_guard guard;
handle.piece_availability(avail);
}
for (std::vector<int>::iterator i(avail.begin())
, end(avail.end()); i != end; ++i)
ret.append(*i);
return ret;
}
list piece_priorities(torrent_handle& handle)
{
list ret;
std::vector<int> prio;
{
allow_threading_guard guard;
prio = handle.piece_priorities();
}
for (std::vector<int>::iterator i(prio.begin())
, end(prio.end()); i != end; ++i)
ret.append(*i);
return ret;
}
std::vector<announce_entry>::const_iterator begin_trackers(torrent_handle& i)
{
allow_threading_guard guard;
return i.trackers().begin();
}
std::vector<announce_entry>::const_iterator end_trackers(torrent_handle& i)
{
allow_threading_guard guard;
return i.trackers().end();
}
} // namespace unnamed
list file_progress(torrent_handle& handle)
{
std::vector<size_type> p;
{
allow_threading_guard guard;
p.reserve(handle.get_torrent_info().num_files());
handle.file_progress(p);
}
list result;
for (std::vector<size_type>::iterator i(p.begin()), e(p.end()); i != e; ++i)
result.append(*i);
return result;
}
list get_peer_info(torrent_handle const& handle)
{
std::vector<peer_info> pi;
{
allow_threading_guard guard;
handle.get_peer_info(pi);
}
list result;
for (std::vector<peer_info>::iterator i = pi.begin(); i != pi.end(); ++i)
result.append(*i);
return result;
}
void prioritize_pieces(torrent_handle& info, object o)
{
std::vector<int> result;
try
{
object iter_obj = object( handle<>( PyObject_GetIter( o.ptr() ) ));
while( 1 )
{
object obj = extract<object>( iter_obj.attr( "next" )() );
result.push_back(extract<int const>( obj ));
}
}
catch( error_already_set )
{
PyErr_Clear();
info.prioritize_pieces(result);
return;
}
}
void prioritize_files(torrent_handle& info, object o)
{
std::vector<int> result;
try
{
object iter_obj = object( handle<>( PyObject_GetIter( o.ptr() ) ));
while( 1 )
{
object obj = extract<object>( iter_obj.attr( "next" )() );
result.push_back(extract<int const>( obj ));
}
}
catch( error_already_set )
{
PyErr_Clear();
info.prioritize_files(result);
return;
}
}
void replace_trackers(torrent_handle& info, object trackers)
{
object iter(trackers.attr("__iter__")());
std::vector<announce_entry> result;
for (;;)
{
handle<> entry(allow_null(PyIter_Next(iter.ptr())));
if (entry == handle<>())
break;
result.push_back(extract<announce_entry const&>(object(entry)));
}
allow_threading_guard guard;
info.replace_trackers(result);
}
list get_download_queue(torrent_handle& handle)
{
using boost::python::make_tuple;
list ret;
std::vector<partial_piece_info> downloading;
{
allow_threading_guard guard;
handle.get_download_queue(downloading);
}
for (std::vector<partial_piece_info>::iterator i = downloading.begin()
, end(downloading.end()); i != end; ++i)
{
dict partial_piece;
partial_piece["piece_index"] = i->piece_index;
partial_piece["blocks_in_piece"] = i->blocks_in_piece;
list block_list;
for (int k = 0; k < i->blocks_in_piece; ++k)
{
dict block_info;
block_info["state"] = i->blocks[k].state;
block_info["num_peers"] = i->blocks[k].num_peers;
block_info["bytes_progress"] = i->blocks[k].bytes_progress;
block_info["block_size"] = i->blocks[k].block_size;
block_info["peer"] = make_tuple(
boost::lexical_cast<std::string>(i->blocks[k].peer.address()), i->blocks[k].peer.port());
block_list.append(block_info);
}
partial_piece["blocks"] = block_list;
ret.append(partial_piece);
}
return ret;
}
namespace
{
tcp::endpoint tuple_to_endpoint(tuple const& t)
{
return tcp::endpoint(address::from_string(extract<std::string>(t[0])), extract<int>(t[1]));
}
}
void force_reannounce(torrent_handle& th, int s)
{
th.force_reannounce(boost::posix_time::seconds(s));
}
void connect_peer(torrent_handle& th, tuple ip, int source)
{
th.connect_peer(tuple_to_endpoint(ip), source);
}
void set_peer_upload_limit(torrent_handle& th, tuple const& ip, int limit)
{
th.set_peer_upload_limit(tuple_to_endpoint(ip), limit);
}
void set_peer_download_limit(torrent_handle& th, tuple const& ip, int limit)
{
th.set_peer_download_limit(tuple_to_endpoint(ip), limit);
}
void bind_torrent_handle()
{
void (torrent_handle::*force_reannounce0)() const = &torrent_handle::force_reannounce;
int (torrent_handle::*piece_priority0)(int) const = &torrent_handle::piece_priority;
void (torrent_handle::*piece_priority1)(int, int) const = &torrent_handle::piece_priority;
#ifndef TORRENT_DISABLE_RESOLVE_COUNTRIES
bool (torrent_handle::*resolve_countries0)() const = &torrent_handle::resolve_countries;
void (torrent_handle::*resolve_countries1)(bool) = &torrent_handle::resolve_countries;
#endif
return_value_policy<copy_const_reference> copy;
#define _ allow_threads
class_<torrent_handle>("torrent_handle")
.def("get_peer_info", get_peer_info)
.def("status", _(&torrent_handle::status))
.def("get_download_queue", get_download_queue)
.def("file_progress", file_progress)
.def("trackers", range(begin_trackers, end_trackers))
.def("replace_trackers", replace_trackers)
.def("add_url_seed", _(&torrent_handle::add_url_seed))
.def("remove_url_seed", _(&torrent_handle::remove_url_seed))
.def("url_seeds", url_seeds)
.def("has_metadata", _(&torrent_handle::has_metadata))
.def("get_torrent_info", _(&torrent_handle::get_torrent_info), return_internal_reference<>())
.def("is_valid", _(&torrent_handle::is_valid))
.def("is_seed", _(&torrent_handle::is_seed))
.def("is_finished", _(&torrent_handle::is_finished))
.def("is_paused", _(&torrent_handle::is_paused))
.def("pause", _(&torrent_handle::pause))
.def("resume", _(&torrent_handle::resume))
.def("clear_error", _(&torrent_handle::clear_error))
.def("is_auto_managed", _(&torrent_handle::is_auto_managed))
.def("auto_managed", _(&torrent_handle::auto_managed))
.def("queue_position", _(&torrent_handle::queue_position))
.def("queue_position_up", _(&torrent_handle::queue_position_up))
.def("queue_position_down", _(&torrent_handle::queue_position_down))
.def("queue_position_top", _(&torrent_handle::queue_position_top))
.def("queue_position_bottom", _(&torrent_handle::queue_position_bottom))
#ifndef TORRENT_DISABLE_RESOLVE_COUNTRIES
.def("resolve_countries", _(resolve_countries0))
.def("resolve_countries", _(resolve_countries1))
#endif
// deprecated
.def("filter_piece", _(&torrent_handle::filter_piece))
.def("is_piece_filtered", _(&torrent_handle::is_piece_filtered))
.def("piece_availability", piece_availability)
.def("piece_priority", _(piece_priority0))
.def("piece_priority", _(piece_priority1))
.def("prioritize_pieces", prioritize_pieces)
.def("piece_prioritize", piece_priorities)
.def("prioritize_files", prioritize_files)
.def("use_interface", &torrent_handle::use_interface)
.def("write_resume_data", _(&torrent_handle::write_resume_data))
.def("save_resume_data", _(&torrent_handle::save_resume_data))
.def("force_reannounce", _(force_reannounce0))
.def("force_reannounce", force_reannounce)
.def("scrape_tracker", _(&torrent_handle::scrape_tracker))
.def("name", _(&torrent_handle::name))
.def("set_upload_limit", _(&torrent_handle::set_upload_limit))
.def("upload_limit", _(&torrent_handle::upload_limit))
.def("set_download_limit", _(&torrent_handle::set_download_limit))
.def("download_limit", _(&torrent_handle::download_limit))
.def("set_sequential_download", _(&torrent_handle::set_sequential_download))
.def("set_peer_upload_limit", set_peer_upload_limit)
.def("set_peer_download_limit", set_peer_download_limit)
.def("connect_peer", connect_peer)
.def("set_ratio", _(&torrent_handle::set_ratio))
.def("save_path", _(&torrent_handle::save_path))
.def("set_max_uploads", _(&torrent_handle::set_max_uploads))
.def("set_max_connections", _(&torrent_handle::set_max_connections))
.def("set_tracker_login", _(&torrent_handle::set_tracker_login))
.def("move_storage", _(&torrent_handle::move_storage))
.def("info_hash", _(&torrent_handle::info_hash))
.def("force_recheck", _(&torrent_handle::force_recheck))
.def("rename_file", _(&torrent_handle::rename_file))
;
}
<commit_msg>Add torrent_handle::file_priorities to python bindings<commit_after>// Copyright Daniel Wallin 2006. Use, modification and distribution is
// subject to the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <libtorrent/torrent_handle.hpp>
#include <boost/python.hpp>
#include <boost/python/tuple.hpp>
#include <boost/lexical_cast.hpp>
#include "gil.hpp"
using namespace boost::python;
using namespace libtorrent;
namespace
{
list url_seeds(torrent_handle& handle)
{
list ret;
std::set<std::string> urls;
{
allow_threading_guard guard;
urls = handle.url_seeds();
}
for (std::set<std::string>::iterator i(urls.begin())
, end(urls.end()); i != end; ++i)
ret.append(*i);
return ret;
}
list piece_availability(torrent_handle& handle)
{
list ret;
std::vector<int> avail;
{
allow_threading_guard guard;
handle.piece_availability(avail);
}
for (std::vector<int>::iterator i(avail.begin())
, end(avail.end()); i != end; ++i)
ret.append(*i);
return ret;
}
list piece_priorities(torrent_handle& handle)
{
list ret;
std::vector<int> prio;
{
allow_threading_guard guard;
prio = handle.piece_priorities();
}
for (std::vector<int>::iterator i(prio.begin())
, end(prio.end()); i != end; ++i)
ret.append(*i);
return ret;
}
std::vector<announce_entry>::const_iterator begin_trackers(torrent_handle& i)
{
allow_threading_guard guard;
return i.trackers().begin();
}
std::vector<announce_entry>::const_iterator end_trackers(torrent_handle& i)
{
allow_threading_guard guard;
return i.trackers().end();
}
} // namespace unnamed
list file_progress(torrent_handle& handle)
{
std::vector<size_type> p;
{
allow_threading_guard guard;
p.reserve(handle.get_torrent_info().num_files());
handle.file_progress(p);
}
list result;
for (std::vector<size_type>::iterator i(p.begin()), e(p.end()); i != e; ++i)
result.append(*i);
return result;
}
list get_peer_info(torrent_handle const& handle)
{
std::vector<peer_info> pi;
{
allow_threading_guard guard;
handle.get_peer_info(pi);
}
list result;
for (std::vector<peer_info>::iterator i = pi.begin(); i != pi.end(); ++i)
result.append(*i);
return result;
}
void prioritize_pieces(torrent_handle& info, object o)
{
std::vector<int> result;
try
{
object iter_obj = object( handle<>( PyObject_GetIter( o.ptr() ) ));
while( 1 )
{
object obj = extract<object>( iter_obj.attr( "next" )() );
result.push_back(extract<int const>( obj ));
}
}
catch( error_already_set )
{
PyErr_Clear();
info.prioritize_pieces(result);
return;
}
}
void prioritize_files(torrent_handle& info, object o)
{
std::vector<int> result;
try
{
object iter_obj = object( handle<>( PyObject_GetIter( o.ptr() ) ));
while( 1 )
{
object obj = extract<object>( iter_obj.attr( "next" )() );
result.push_back(extract<int const>( obj ));
}
}
catch( error_already_set )
{
PyErr_Clear();
info.prioritize_files(result);
return;
}
}
list file_priorities(torrent_handle& handle)
{
list ret;
std::vector<int> priorities = handle.file_priorities();
for (std::vector<int>::iterator i = priorities.begin(); i != priorities.end(); ++i)
ret.append(*i);
return ret;
}
void replace_trackers(torrent_handle& info, object trackers)
{
object iter(trackers.attr("__iter__")());
std::vector<announce_entry> result;
for (;;)
{
handle<> entry(allow_null(PyIter_Next(iter.ptr())));
if (entry == handle<>())
break;
result.push_back(extract<announce_entry const&>(object(entry)));
}
allow_threading_guard guard;
info.replace_trackers(result);
}
list get_download_queue(torrent_handle& handle)
{
using boost::python::make_tuple;
list ret;
std::vector<partial_piece_info> downloading;
{
allow_threading_guard guard;
handle.get_download_queue(downloading);
}
for (std::vector<partial_piece_info>::iterator i = downloading.begin()
, end(downloading.end()); i != end; ++i)
{
dict partial_piece;
partial_piece["piece_index"] = i->piece_index;
partial_piece["blocks_in_piece"] = i->blocks_in_piece;
list block_list;
for (int k = 0; k < i->blocks_in_piece; ++k)
{
dict block_info;
block_info["state"] = i->blocks[k].state;
block_info["num_peers"] = i->blocks[k].num_peers;
block_info["bytes_progress"] = i->blocks[k].bytes_progress;
block_info["block_size"] = i->blocks[k].block_size;
block_info["peer"] = make_tuple(
boost::lexical_cast<std::string>(i->blocks[k].peer.address()), i->blocks[k].peer.port());
block_list.append(block_info);
}
partial_piece["blocks"] = block_list;
ret.append(partial_piece);
}
return ret;
}
namespace
{
tcp::endpoint tuple_to_endpoint(tuple const& t)
{
return tcp::endpoint(address::from_string(extract<std::string>(t[0])), extract<int>(t[1]));
}
}
void force_reannounce(torrent_handle& th, int s)
{
th.force_reannounce(boost::posix_time::seconds(s));
}
void connect_peer(torrent_handle& th, tuple ip, int source)
{
th.connect_peer(tuple_to_endpoint(ip), source);
}
void set_peer_upload_limit(torrent_handle& th, tuple const& ip, int limit)
{
th.set_peer_upload_limit(tuple_to_endpoint(ip), limit);
}
void set_peer_download_limit(torrent_handle& th, tuple const& ip, int limit)
{
th.set_peer_download_limit(tuple_to_endpoint(ip), limit);
}
void bind_torrent_handle()
{
void (torrent_handle::*force_reannounce0)() const = &torrent_handle::force_reannounce;
int (torrent_handle::*piece_priority0)(int) const = &torrent_handle::piece_priority;
void (torrent_handle::*piece_priority1)(int, int) const = &torrent_handle::piece_priority;
#ifndef TORRENT_DISABLE_RESOLVE_COUNTRIES
bool (torrent_handle::*resolve_countries0)() const = &torrent_handle::resolve_countries;
void (torrent_handle::*resolve_countries1)(bool) = &torrent_handle::resolve_countries;
#endif
return_value_policy<copy_const_reference> copy;
#define _ allow_threads
class_<torrent_handle>("torrent_handle")
.def("get_peer_info", get_peer_info)
.def("status", _(&torrent_handle::status))
.def("get_download_queue", get_download_queue)
.def("file_progress", file_progress)
.def("trackers", range(begin_trackers, end_trackers))
.def("replace_trackers", replace_trackers)
.def("add_url_seed", _(&torrent_handle::add_url_seed))
.def("remove_url_seed", _(&torrent_handle::remove_url_seed))
.def("url_seeds", url_seeds)
.def("has_metadata", _(&torrent_handle::has_metadata))
.def("get_torrent_info", _(&torrent_handle::get_torrent_info), return_internal_reference<>())
.def("is_valid", _(&torrent_handle::is_valid))
.def("is_seed", _(&torrent_handle::is_seed))
.def("is_finished", _(&torrent_handle::is_finished))
.def("is_paused", _(&torrent_handle::is_paused))
.def("pause", _(&torrent_handle::pause))
.def("resume", _(&torrent_handle::resume))
.def("clear_error", _(&torrent_handle::clear_error))
.def("is_auto_managed", _(&torrent_handle::is_auto_managed))
.def("auto_managed", _(&torrent_handle::auto_managed))
.def("queue_position", _(&torrent_handle::queue_position))
.def("queue_position_up", _(&torrent_handle::queue_position_up))
.def("queue_position_down", _(&torrent_handle::queue_position_down))
.def("queue_position_top", _(&torrent_handle::queue_position_top))
.def("queue_position_bottom", _(&torrent_handle::queue_position_bottom))
#ifndef TORRENT_DISABLE_RESOLVE_COUNTRIES
.def("resolve_countries", _(resolve_countries0))
.def("resolve_countries", _(resolve_countries1))
#endif
// deprecated
.def("filter_piece", _(&torrent_handle::filter_piece))
.def("is_piece_filtered", _(&torrent_handle::is_piece_filtered))
.def("piece_availability", piece_availability)
.def("piece_priority", _(piece_priority0))
.def("piece_priority", _(piece_priority1))
.def("prioritize_pieces", prioritize_pieces)
.def("piece_prioritize", piece_priorities)
.def("prioritize_files", prioritize_files)
.def("file_priorities", file_priorities)
.def("use_interface", &torrent_handle::use_interface)
.def("write_resume_data", _(&torrent_handle::write_resume_data))
.def("save_resume_data", _(&torrent_handle::save_resume_data))
.def("force_reannounce", _(force_reannounce0))
.def("force_reannounce", force_reannounce)
.def("scrape_tracker", _(&torrent_handle::scrape_tracker))
.def("name", _(&torrent_handle::name))
.def("set_upload_limit", _(&torrent_handle::set_upload_limit))
.def("upload_limit", _(&torrent_handle::upload_limit))
.def("set_download_limit", _(&torrent_handle::set_download_limit))
.def("download_limit", _(&torrent_handle::download_limit))
.def("set_sequential_download", _(&torrent_handle::set_sequential_download))
.def("set_peer_upload_limit", set_peer_upload_limit)
.def("set_peer_download_limit", set_peer_download_limit)
.def("connect_peer", connect_peer)
.def("set_ratio", _(&torrent_handle::set_ratio))
.def("save_path", _(&torrent_handle::save_path))
.def("set_max_uploads", _(&torrent_handle::set_max_uploads))
.def("set_max_connections", _(&torrent_handle::set_max_connections))
.def("set_tracker_login", _(&torrent_handle::set_tracker_login))
.def("move_storage", _(&torrent_handle::move_storage))
.def("info_hash", _(&torrent_handle::info_hash))
.def("force_recheck", _(&torrent_handle::force_recheck))
.def("rename_file", _(&torrent_handle::rename_file))
;
}
<|endoftext|> |
<commit_before>
#include "DRV8711.h"
uint8_t _SlaveSelectPin;
DRV8711::DRV8711() {
DRV8711(SPI_SlaveSelect);
}
DRV8711::DRV8711(uint8_t SlaveSelectPin) {
_SlaveSelectPin = SlaveSelectPin;
}
void DRV8711::configureRegisters(){
uint16_t CTRL_REG = 0x0000;
uint16_t TORQUE_REG = 0x0000;
CTRL_REG = DTIME_850 + ISGAIN_40 + STEP1_8 + ENBL;
TORQUE_REG = ADDR_TORQUE+SMPLTH_100 + 186;
writeRegister(CTRL_REG);
writeRegister(TORQUE_REG);
Serial.println(CTRL_REG,HEX);
Serial.println(TORQUE_REG,HEX);
}
//
// writes data from MCU to DRV8711
//
void DRV8711::writeRegister(uint16_t Data){
digitalWrite(_SlaveSelectPin,HIGH); // enable slave select
SPI.transfer(0x00FF&(Data/256)); // transfer higher byte
SPI.transfer(0x00FF&Data); // transfer lower byte
digitalWrite(_SlaveSelectPin,LOW); // disable slave select
}
/*
CC2500::CC2500(uint8_t deviceAddress) {
CC2500(deviceAddress, CHANNEL);
}
CC2500::CC2500(uint8_t deviceAddress, uint8_t channel) {
_deviceAddress = deviceAddress;
_channel = channel;
_gdo0 = GDO0;
}
void CC2500::setDeviceAddress(uint8_t deviceAddress) {
_deviceAddress = deviceAddress;
}
void CC2500::setChannel(uint8_t channel) {
_channel = channel;
}
void CC2500::begin() {
SPI.begin();
SPI.setClockDivider(SPI_CLOCK_DIV2);
SPI.setBitOrder(MSBFIRST);
SPI.setDataMode(SPI_MODE0);
digitalWrite(SS,HIGH);
pinMode(SS,OUTPUT);
resetDevice();
delay(100);
configureDeviceSettings();
execStrobeCommand(CC2500_CMD_SRX);
}
void CC2500::writeRegister(uint8_t addr, uint8_t data) {
digitalWrite(SS,LOW);
SPI.transfer(addr|CC2500_WRITE_SINGLE);
SPI.transfer(data);
digitalWrite(SS,HIGH);
}
void CC2500::writeRegisterBurst(uint8_t saddr, uint8_t *data, uint8_t size) {
digitalWrite(SS,LOW);
SPI.transfer(saddr|CC2500_WRITE_BURST);
while (size > 0) {
SPI.transfer(*data++);
size--;
}
digitalWrite(SS,HIGH);
}
uint8_t CC2500::readRegister(uint8_t addr) {
uint8_t recv;
digitalWrite(SS,LOW);
SPI.transfer(addr|CC2500_READ_SINGLE);
recv = SPI.transfer(0x00);
digitalWrite(SS,HIGH);
return recv;
}
void CC2500::readRegisterBurst(uint8_t saddr, uint8_t *data, uint8_t size) {
digitalWrite(SS,LOW);
SPI.transfer(saddr|CC2500_READ_BURST);
while (size > 0) {
*data++ = SPI.transfer(0x00);
size--;
}
digitalWrite(SS,HIGH);
}
void CC2500::execStrobeCommand(uint8_t command) {
digitalWrite(SS,LOW);
SPI.transfer(command);
digitalWrite(SS,HIGH);
}
uint8_t CC2500::readStatusRegister(uint8_t addr) {
return readRegister(addr|CC2500_READ_STATUS);
}
void CC2500::configureDeviceSettings() {
uint8_t paTable[] = {0xFB};
writeRegister(CC2500_IOCFG0, 0x06); // GDO0 = sync word
writeRegister(CC2500_IOCFG2, 0x0B); // GDO2 = serial clock
writeRegister(CC2500_PKTCTRL0, 0x05); // variable packet length; CRC enabled
writeRegister(CC2500_PKTCTRL1, 0x05); // addr. check enabled; status bytes appended
writeRegister(CC2500_PKTLEN, 0xFF); // max. packet length
writeRegister(CC2500_ADDR, _deviceAddress); // device address
writeRegister(CC2500_CHANNR, _channel); // channel number
writeRegister(CC2500_FSCTRL1, 0x07); //
writeRegister(CC2500_FSCTRL0, 0x00); //
writeRegister(CC2500_FREQ2, 0x5D); // RF frequency 2433.000000 MHz
writeRegister(CC2500_FREQ1, 0x93); // RF frequency 2433.000000 MHz
writeRegister(CC2500_FREQ0, 0xB1); // RF frequency 2433.000000 MHz
writeRegister(CC2500_MDMCFG4, 0x2D); //
writeRegister(CC2500_MDMCFG3, 0x3B); // data rate 250.000000 kbps
writeRegister(CC2500_MDMCFG2, 0x73); // MSK; 30/32 sync mode
writeRegister(CC2500_MDMCFG1, 0x22); // 2 bytes preamble
writeRegister(CC2500_MDMCFG0, 0xF8); // channel spacing 199.9500 kHz
writeRegister(CC2500_DEVIANT, 0x00); // modem deviation 0
writeRegister(CC2500_MCSM1, 0x3F); // RX after RX or TX
writeRegister(CC2500_MCSM0, 0x18); //
writeRegister(CC2500_FOCCFG, 0x1D); //
writeRegister(CC2500_BSCFG, 0x1C); //
writeRegister(CC2500_AGCCTRL2, 0xC7); //
writeRegister(CC2500_AGCCTRL1, 0x00); //
writeRegister(CC2500_AGCCTRL0, 0xB2); //
writeRegister(CC2500_FREND1, 0xB6); //
writeRegister(CC2500_FREND0, 0x10); //
writeRegister(CC2500_FSCAL3, 0xEA); //
writeRegister(CC2500_FSCAL2, 0x0A); //
writeRegister(CC2500_FSCAL1, 0x00); //
writeRegister(CC2500_FSCAL0, 0x11); //
writeRegisterBurst(CC2500_PATABLE, paTable, sizeof(paTable));
}
void CC2500::sendTxBuffer(uint8_t *txBuffer, uint8_t size) {
writeRegisterBurst(CC2500_TX_FIFO, txBuffer, size);
execStrobeCommand(CC2500_CMD_STX);
delay(200);
//while(digitalRead(_gdo0) == LOW); // wait for the transfer to start
//while(digitalRead(_gdo0) == HIGH); // wait for the transfer to end
}
int8_t CC2500::receiveRxBuffer(uint8_t *rxBuffer, uint8_t size) {
uint8_t pktLength;
uint8_t rxInfo[2];
if (readStatusRegister(CC2500_RXBYTES)&CC2500_NUM_RXBYTES) {
pktLength = readRegister(CC2500_RX_FIFO);
if (pktLength <= size) {
readRegisterBurst(CC2500_RX_FIFO, rxBuffer, pktLength);
} else {
readRegisterBurst(CC2500_RX_FIFO, rxBuffer, size);
pktLength -= size;
while (pktLength > 0) {
readRegister(CC2500_RX_FIFO); // dummy read to empty the FIFO
pktLength--;
}
}
readRegisterBurst(CC2500_RX_FIFO, rxInfo, sizeof(rxInfo));
}
return rxInfo[0]; // RSSI
}
uint8_t CC2500::getChipVersion() {
return readStatusRegister(CC2500_REG_VERSION);
}
*/
/*
get status byte (including rx fifo fill) by execuring a read from the NOP command strobe register
*/
/*
uint8_t CC2500::getStatusByte() {
uint8_t recv;
digitalWrite(SS,LOW);
recv = SPI.transfer(CC2500_CMD_SNOP|CC2500_READ_SINGLE);
digitalWrite(SS,HIGH);
return recv;
}
void CC2500::resetDevice() {
execStrobeCommand(CC2500_CMD_SRES);
}
*/<commit_msg>- added raw config for remaining registers to overcome stall error<commit_after>
#include "DRV8711.h"
uint8_t _SlaveSelectPin;
DRV8711::DRV8711() {
DRV8711(SPI_SlaveSelect);
}
DRV8711::DRV8711(uint8_t SlaveSelectPin) {
_SlaveSelectPin = SlaveSelectPin;
}
void DRV8711::configureRegisters(){
uint16_t CTRL_REG = 0x0000;
uint16_t TORQUE_REG = 0x0000;
CTRL_REG = DTIME_850 + ISGAIN_40 + STEP1_8 + ENBL;
TORQUE_REG = ADDR_TORQUE + SMPLTH_50 + 186;
writeRegister(CTRL_REG);
writeRegister(TORQUE_REG);
writeRegister(0x2030); // off register
writeRegister(0x3108); // ABT register
writeRegister(0x4310); // DECAY register
writeRegister(0x5F40); // STALL register
writeRegister(0x60AA); // STALL register
writeRegister(0x7000); // clear status register
Serial.println(CTRL_REG,HEX);
Serial.println(TORQUE_REG,HEX);
}
//
// writes data from MCU to DRV8711
//
void DRV8711::writeRegister(uint16_t Data){
digitalWrite(_SlaveSelectPin,HIGH); // enable slave select
SPI.transfer(0x00FF&(Data/256)); // transfer higher byte
SPI.transfer(0x00FF&Data); // transfer lower byte
digitalWrite(_SlaveSelectPin,LOW); // disable slave select
}
<|endoftext|> |
<commit_before>/// \file urbi/ustarter.hh
// This file is part of UObject Component Architecture
// Copyright (c) 2007 Gostai S.A.S.
//
// Permission to use, copy, modify, and redistribute this software for
// non-commercial use is hereby granted.
//
// This software is provided "as is" without warranty of any kind,
// either expressed or implied, including but not limited to the
// implied warranties of fitness for a particular purpose.
//
// For more information, comments, bug reports: http://www.urbiforge.com
#ifndef URBI_STARTER_HH
# define URBI_STARTER_HH
# include <algorithm>
# include <string>
# include <urbi/fwd.hh>
/// This macro must be called once for every UObject class.
# define UStart(X) \
::urbi::URBIStarter<X> X ## ____URBI_object(std::string(#X), \
::urbi::objectlist)
/// This macro must be called once for every UObject class.
# define UStartRename(X,Name) \
::urbi::URBIStarter<X> Name ## ____URBI_object(std::string(#Name), \
::urbi::objectlist)
/// This macro must be called once for each UObjectHub class.
# define UStartHub(X) \
::urbi::URBIStarterHub<X> x ## ____URBI_object(std::string(#X), \
::urbi::objecthublist)
namespace urbi
{
typedef std::list<baseURBIStarter*> UStartlist;
typedef std::list<baseURBIStarterHub*> UStartlistHub;
// Two singleton lists to handle the object and hubobject registration.
EXTERN_STATIC_INSTANCE(UStartlist, objectlist);
EXTERN_STATIC_INSTANCE(UStartlistHub, objecthublist);
/// URBIStarter base class used to store heterogeneous template
/// class objects in starterlist.
class baseURBIStarter
{
public:
baseURBIStarter(const std::string& name)
: name(name)
{}
virtual ~baseURBIStarter() {}
virtual UObject* getUObject() = 0;
/// Called before deletion.
virtual void clean() = 0;
/// Used to provide a wrapper to initialize objects in starterlist.
virtual void init(const std::string&) = 0;
/// Used to provide a copy of a C++ object based on its name.
virtual void copy(const std::string&) = 0;
std::string name;
};
//! This is the class containing URBI starters
/** A starter is a class whose job is to start an instance of a particular
* UObject subclass, resulting in the initialization of this object
* (registration to the kernel)
*/
template <class T>
class URBIStarter
: public baseURBIStarter
{
public:
URBIStarter(const std::string& name, UStartlist& _slist)
: baseURBIStarter(name)
{
slist = &_slist;
slist->push_back(dynamic_cast<baseURBIStarter*>(this));
}
virtual ~URBIStarter()
{
clean();
}
virtual void clean()
{
delete getUObject();
UStartlist::iterator toerase =
std::find(slist->begin(), slist->end(),
dynamic_cast<baseURBIStarter*>(this));
if (toerase != slist->end())
slist->erase(toerase);
}
virtual void
copy(const std::string& objname)
{
URBIStarter<T>* ustarter = new URBIStarter<T>(objname,*slist);
ustarter->init(objname);
UObject *uso = dynamic_cast<UObject*>(ustarter->object);
getUObject()->members.push_back(uso);
uso->derived = true;
uso->classname = getUObject()->classname;
if (uso->autogroup)
uso->addAutoGroup();
}
/// Access to the object from the outside.
virtual UObject* getUObject()
{
return dynamic_cast<UObject*>(object);
}
protected:
/// Called when the object is ready to be initialized.
virtual void init(const std::string& objname)
{
object = new T(objname);
}
UStartlist *slist;
T* object;
};
#define SETBACKCASTCTOR(T) \
inline \
UValue \
back_cast(T& t) \
{ \
return UValue(t); \
}
SETBACKCASTCTOR(bool)
SETBACKCASTCTOR(int)
SETBACKCASTCTOR(long)
SETBACKCASTCTOR(ufloat)
SETBACKCASTCTOR(UValue)
SETBACKCASTCTOR(char *)
SETBACKCASTCTOR(void *)
SETBACKCASTCTOR(const std::string)
SETBACKCASTCTOR(std::string)
SETBACKCASTCTOR(const UBinary)
SETBACKCASTCTOR(const UList)
SETBACKCASTCTOR(const UObjectStruct)
SETBACKCASTCTOR(const USound)
SETBACKCASTCTOR(const UImage)
/// URBIStarter base class used to store heterogeneous template
/// class objects in starterlist
class baseURBIStarterHub
{
public:
baseURBIStarterHub(const std::string& name)
: name(name)
{};
virtual ~baseURBIStarterHub() {};
/// Used to provide a wrapper to initialize objects in starterlist.
virtual void init(const std::string&) = 0;
virtual UObjectHub* getUObjectHub() = 0;
std::string name;
};
//! This is the class containing URBI starters
/** A starter is a class whose job is to start an instance of a particular
* UObject subclass, resulting in the initialization of this object
* (registration to the kernel)
*/
template <class T> class URBIStarterHub : public baseURBIStarterHub
{
public:
URBIStarterHub(const std::string& name, UStartlistHub& _slist)
: baseURBIStarterHub(name)
{
slist = &_slist;
slist->push_back(dynamic_cast<baseURBIStarterHub*>(this));
}
virtual ~URBIStarterHub() {/* noone can kill a hub*/ };
protected:
/// Called when the object is ready to be initialized.
virtual void init(const std::string& objname)
{
object = new T(objname);
}
/// Access to the object from the outside.
virtual UObjectHub* getUObjectHub()
{
return dynamic_cast<UObjectHub*>(object);
}
UStartlistHub *slist;
T* object;
};
} // end namespace urbi
#endif // ! URBI_STARTER_HH
<commit_msg>Factor macros.<commit_after>/// \file urbi/ustarter.hh
// This file is part of UObject Component Architecture
// Copyright (c) 2007, 2008 Gostai S.A.S.
//
// Permission to use, copy, modify, and redistribute this software for
// non-commercial use is hereby granted.
//
// This software is provided "as is" without warranty of any kind,
// either expressed or implied, including but not limited to the
// implied warranties of fitness for a particular purpose.
//
// For more information, comments, bug reports: http://www.urbiforge.com
#ifndef URBI_STARTER_HH
# define URBI_STARTER_HH
# include <algorithm>
# include <string>
# include <urbi/fwd.hh>
/// This macro must be called once for every UObject class.
# define UStartRename(Type, Name) \
::urbi::URBIStarter<Type> \
Name ## ____URBI_object(std::string(#Name), ::urbi::objectlist)
/// This macro must be called once for every UObject class.
# define UStart(Type) \
UStartRename(Type, Type)
/// This macro must be called once for each UObjectHub class.
# define UStartHub(X) \
::urbi::URBIStarterHub<X> \
x ## ____URBI_object(std::string(#X), ::urbi::objecthublist)
namespace urbi
{
typedef std::list<baseURBIStarter*> UStartlist;
typedef std::list<baseURBIStarterHub*> UStartlistHub;
// Two singleton lists to handle the object and hubobject registration.
EXTERN_STATIC_INSTANCE(UStartlist, objectlist);
EXTERN_STATIC_INSTANCE(UStartlistHub, objecthublist);
/// URBIStarter base class used to store heterogeneous template
/// class objects in starterlist.
class baseURBIStarter
{
public:
baseURBIStarter(const std::string& name)
: name(name)
{}
virtual ~baseURBIStarter() {}
virtual UObject* getUObject() = 0;
/// Called before deletion.
virtual void clean() = 0;
/// Used to provide a wrapper to initialize objects in starterlist.
virtual void init(const std::string&) = 0;
/// Used to provide a copy of a C++ object based on its name.
virtual void copy(const std::string&) = 0;
std::string name;
};
//! This is the class containing URBI starters
/** A starter is a class whose job is to start an instance of a particular
* UObject subclass, resulting in the initialization of this object
* (registration to the kernel)
*/
template <class T>
class URBIStarter
: public baseURBIStarter
{
public:
URBIStarter(const std::string& name, UStartlist& _slist)
: baseURBIStarter(name)
{
slist = &_slist;
slist->push_back(dynamic_cast<baseURBIStarter*>(this));
}
virtual ~URBIStarter()
{
clean();
}
virtual void clean()
{
delete getUObject();
UStartlist::iterator toerase =
std::find(slist->begin(), slist->end(),
dynamic_cast<baseURBIStarter*>(this));
if (toerase != slist->end())
slist->erase(toerase);
}
virtual void
copy(const std::string& objname)
{
URBIStarter<T>* ustarter = new URBIStarter<T>(objname,*slist);
ustarter->init(objname);
UObject *uso = dynamic_cast<UObject*>(ustarter->object);
getUObject()->members.push_back(uso);
uso->derived = true;
uso->classname = getUObject()->classname;
if (uso->autogroup)
uso->addAutoGroup();
}
/// Access to the object from the outside.
virtual UObject* getUObject()
{
return dynamic_cast<UObject*>(object);
}
protected:
/// Called when the object is ready to be initialized.
virtual void init(const std::string& objname)
{
object = new T(objname);
}
UStartlist *slist;
T* object;
};
#define SETBACKCASTCTOR(T) \
inline \
UValue \
back_cast(T& t) \
{ \
return UValue(t); \
}
SETBACKCASTCTOR(bool)
SETBACKCASTCTOR(int)
SETBACKCASTCTOR(long)
SETBACKCASTCTOR(ufloat)
SETBACKCASTCTOR(UValue)
SETBACKCASTCTOR(char *)
SETBACKCASTCTOR(void *)
SETBACKCASTCTOR(const std::string)
SETBACKCASTCTOR(std::string)
SETBACKCASTCTOR(const UBinary)
SETBACKCASTCTOR(const UList)
SETBACKCASTCTOR(const UObjectStruct)
SETBACKCASTCTOR(const USound)
SETBACKCASTCTOR(const UImage)
/// URBIStarter base class used to store heterogeneous template
/// class objects in starterlist
class baseURBIStarterHub
{
public:
baseURBIStarterHub(const std::string& name)
: name(name)
{};
virtual ~baseURBIStarterHub() {};
/// Used to provide a wrapper to initialize objects in starterlist.
virtual void init(const std::string&) = 0;
virtual UObjectHub* getUObjectHub() = 0;
std::string name;
};
//! This is the class containing URBI starters
/** A starter is a class whose job is to start an instance of a particular
* UObject subclass, resulting in the initialization of this object
* (registration to the kernel)
*/
template <class T> class URBIStarterHub : public baseURBIStarterHub
{
public:
URBIStarterHub(const std::string& name, UStartlistHub& _slist)
: baseURBIStarterHub(name)
{
slist = &_slist;
slist->push_back(dynamic_cast<baseURBIStarterHub*>(this));
}
virtual ~URBIStarterHub() {/* noone can kill a hub*/ };
protected:
/// Called when the object is ready to be initialized.
virtual void init(const std::string& objname)
{
object = new T(objname);
}
/// Access to the object from the outside.
virtual UObjectHub* getUObjectHub()
{
return dynamic_cast<UObjectHub*>(object);
}
UStartlistHub *slist;
T* object;
};
} // end namespace urbi
#endif // ! URBI_STARTER_HH
<|endoftext|> |
<commit_before>#ifndef MJOLNIR_CORE_SYSTEM_HPP
#define MJOLNIR_CORE_SYSTEM_HPP
#include <mjolnir/core/Unit.hpp>
#include <mjolnir/core/Particle.hpp>
#include <mjolnir/core/Topology.hpp>
#include <mjolnir/core/SimulatorTraits.hpp>
#include <mjolnir/core/BoundaryCondition.hpp>
#include <mjolnir/core/RandomNumberGenerator.hpp>
#include <mjolnir/util/logger.hpp>
#include <vector>
#include <map>
#include <cassert>
namespace mjolnir
{
template<typename traitsT>
class System
{
public:
using traits_type = traitsT;
using string_type = std::string;
using real_type = typename traits_type::real_type;
using coordinate_type = typename traits_type::coordinate_type;
using boundary_type = typename traits_type::boundary_type;
using topology_type = Topology;
using attribute_type = std::map<std::string, real_type>;
using rng_type = RandomNumberGenerator<traits_type>;
using particle_type = Particle<real_type, coordinate_type>;
using particle_view_type = ParticleView<real_type, coordinate_type>;
using particle_const_view_type = ParticleConstView<real_type, coordinate_type>;
using real_container_type = std::vector<real_type>;
using coordinate_container_type = std::vector<coordinate_type>;
using string_container_type = std::vector<std::string>;
public:
System(const std::size_t num_particles, const boundary_type& bound)
: velocity_initialized_(false), boundary_(bound), attributes_(),
num_particles_(num_particles), masses_ (num_particles),
rmasses_ (num_particles), positions_(num_particles),
velocities_ (num_particles), forces_ (num_particles),
names_ (num_particles), groups_ (num_particles)
{}
~System() = default;
System(const System&) = default;
System(System&&) = default;
System& operator=(const System&) = default;
System& operator=(System&&) = default;
void initialize(rng_type& rng)
{
MJOLNIR_GET_DEFAULT_LOGGER();
MJOLNIR_LOG_FUNCTION();
// make all the particles inside the boundary
for(auto& p : this->positions_)
{
p = this->boundary_.adjust_position(p);
}
if(this->velocity_initialized_)
{
MJOLNIR_LOG_NOTICE(
"velocity is already given, nothing to initialize in System");
return ;
}
if(!this->has_attribute("temperature"))
{
throw std::runtime_error("[error] to generate velocity, "
"system.attributes.temperature is required.");
}
const real_type kB = physics::constants<real_type>::kB();
const real_type T_ref = this->attribute("temperature");
MJOLNIR_LOG_NOTICE("generating velocity with T = ", T_ref, "...");
// generate Maxwell-Boltzmann distribution
const real_type kBT = kB * T_ref;
for(std::size_t i=0; i<this->size(); ++i)
{
const auto vel_coef = std::sqrt(kBT / this->mass(i));
math::X(this->velocity(i)) = rng.gaussian(0, vel_coef);
math::Y(this->velocity(i)) = rng.gaussian(0, vel_coef);
math::Z(this->velocity(i)) = rng.gaussian(0, vel_coef);
}
MJOLNIR_LOG_NOTICE("done.");
return;
}
coordinate_type adjust_direction(coordinate_type dr) const noexcept
{return boundary_.adjust_direction(dr);}
coordinate_type adjust_position(coordinate_type dr) const noexcept
{return boundary_.adjust_position(dr);}
std::size_t size() const noexcept {return num_particles_;}
particle_view_type operator[](std::size_t i) noexcept
{
return particle_view_type{
masses_[i], rmasses_[i],
positions_[i], velocities_[i], forces_[i],
names_[i], groups_[i]
};
}
particle_const_view_type operator[](std::size_t i) const noexcept
{
return particle_const_view_type{
masses_[i], rmasses_[i],
positions_[i], velocities_[i], forces_[i],
names_[i], groups_[i]
};
}
particle_view_type at(std::size_t i)
{
return particle_view_type{
masses_.at(i), rmasses_.at(i),
positions_.at(i), velocities_.at(i), forces_.at(i),
names_.at(i), groups_.at(i)
};
}
particle_const_view_type at(std::size_t i) const
{
return particle_const_view_type{
masses_.at(i), rmasses_.at(i),
positions_.at(i), velocities_.at(i), forces_.at(i),
names_.at(i), groups_.at(i)
};
}
// When parallelizing a code, forces are often calculated separately in
// several computational units, like cores, nodes, gpu devices, etc. To
// make it consistent, we may need to do something with forces calculated
// separately. Those functions are provided for such an specialized
// situation. Here, for the normal case, we do not need to do anything.
void preprocess_force() noexcept {/* do nothing */}
void postprocess_force() noexcept {/* do nothing */}
real_type mass (std::size_t i) const noexcept {return masses_[i];}
real_type& mass (std::size_t i) noexcept {return masses_[i];}
real_type rmass(std::size_t i) const noexcept {return rmasses_[i];}
real_type& rmass(std::size_t i) noexcept {return rmasses_[i];}
coordinate_type const& position(std::size_t i) const noexcept {return positions_[i];}
coordinate_type& position(std::size_t i) noexcept {return positions_[i];}
coordinate_type const& velocity(std::size_t i) const noexcept {return velocities_[i];}
coordinate_type& velocity(std::size_t i) noexcept {return velocities_[i];}
coordinate_type const& force (std::size_t i) const noexcept {return forces_[i];}
coordinate_type& force (std::size_t i) noexcept {return forces_[i];}
string_type const& name (std::size_t i) const noexcept {return names_[i];}
string_type& name (std::size_t i) noexcept {return names_[i];}
string_type const& group(std::size_t i) const noexcept {return groups_[i];}
string_type& group(std::size_t i) noexcept {return groups_[i];}
boundary_type& boundary() noexcept {return boundary_;}
boundary_type const& boundary() const noexcept {return boundary_;}
// system attributes like `reference temperature`, `ionic strength`, ...
// assuming it will not be called so often.
real_type attribute(const std::string& key) const {return attributes_.at(key);}
real_type& attribute(const std::string& key) {return attributes_[key];}
bool has_attribute(const std::string& key) const {return attributes_.count(key) == 1;}
attribute_type const& attributes() const noexcept {return attributes_;}
bool velocity_initialized() const noexcept {return velocity_initialized_;}
bool& velocity_initialized() noexcept {return velocity_initialized_;}
coordinate_container_type const& forces() const noexcept {return forces_;}
coordinate_container_type& forces() noexcept {return forces_;}
private:
bool velocity_initialized_;
boundary_type boundary_;
attribute_type attributes_;
std::size_t num_particles_;
real_container_type masses_;
real_container_type rmasses_; // r for reciprocal
coordinate_container_type positions_;
coordinate_container_type velocities_;
coordinate_container_type forces_;
string_container_type names_;
string_container_type groups_;
#ifdef MJOLNIR_WITH_OPENMP
// OpenMP implementation uses its own System<OpenMP> to avoid data race.
// So this implementation should not be instanciated with OpenMP Traits.
static_assert(!is_openmp_simulator_traits<traits_type>::value,
"this is the default implementation, not for OpenMP");
#endif
};
#ifdef MJOLNIR_SEPARATE_BUILD
extern template class System<SimulatorTraits<double, UnlimitedBoundary>>;
extern template class System<SimulatorTraits<float, UnlimitedBoundary>>;
extern template class System<SimulatorTraits<double, CuboidalPeriodicBoundary>>;
extern template class System<SimulatorTraits<float, CuboidalPeriodicBoundary>>;
#endif
} // mjolnir
#endif// MJOLNIR_SYSTEM_HPP
<commit_msg>fix: typo<commit_after>#ifndef MJOLNIR_CORE_SYSTEM_HPP
#define MJOLNIR_CORE_SYSTEM_HPP
#include <mjolnir/core/Unit.hpp>
#include <mjolnir/core/Particle.hpp>
#include <mjolnir/core/Topology.hpp>
#include <mjolnir/core/SimulatorTraits.hpp>
#include <mjolnir/core/BoundaryCondition.hpp>
#include <mjolnir/core/RandomNumberGenerator.hpp>
#include <mjolnir/util/logger.hpp>
#include <vector>
#include <map>
#include <cassert>
namespace mjolnir
{
template<typename traitsT>
class System
{
public:
using traits_type = traitsT;
using string_type = std::string;
using real_type = typename traits_type::real_type;
using coordinate_type = typename traits_type::coordinate_type;
using boundary_type = typename traits_type::boundary_type;
using topology_type = Topology;
using attribute_type = std::map<std::string, real_type>;
using rng_type = RandomNumberGenerator<traits_type>;
using particle_type = Particle<real_type, coordinate_type>;
using particle_view_type = ParticleView<real_type, coordinate_type>;
using particle_const_view_type = ParticleConstView<real_type, coordinate_type>;
using real_container_type = std::vector<real_type>;
using coordinate_container_type = std::vector<coordinate_type>;
using string_container_type = std::vector<std::string>;
public:
System(const std::size_t num_particles, const boundary_type& bound)
: velocity_initialized_(false), boundary_(bound), attributes_(),
num_particles_(num_particles), masses_ (num_particles),
rmasses_ (num_particles), positions_(num_particles),
velocities_ (num_particles), forces_ (num_particles),
names_ (num_particles), groups_ (num_particles)
{}
~System() = default;
System(const System&) = default;
System(System&&) = default;
System& operator=(const System&) = default;
System& operator=(System&&) = default;
void initialize(rng_type& rng)
{
MJOLNIR_GET_DEFAULT_LOGGER();
MJOLNIR_LOG_FUNCTION();
// make all the particles inside the boundary
for(auto& p : this->positions_)
{
p = this->boundary_.adjust_position(p);
}
if(this->velocity_initialized_)
{
MJOLNIR_LOG_NOTICE(
"velocity is already given, nothing to initialize in System");
return ;
}
if(!this->has_attribute("temperature"))
{
throw std::runtime_error("[error] to generate velocity, "
"system.attributes.temperature is required.");
}
const real_type kB = physics::constants<real_type>::kB();
const real_type T_ref = this->attribute("temperature");
MJOLNIR_LOG_NOTICE("generating velocity with T = ", T_ref, "...");
// generate Maxwell-Boltzmann distribution
const real_type kBT = kB * T_ref;
for(std::size_t i=0; i<this->size(); ++i)
{
const auto vel_coef = std::sqrt(kBT / this->mass(i));
math::X(this->velocity(i)) = rng.gaussian(0, vel_coef);
math::Y(this->velocity(i)) = rng.gaussian(0, vel_coef);
math::Z(this->velocity(i)) = rng.gaussian(0, vel_coef);
}
MJOLNIR_LOG_NOTICE("done.");
return;
}
coordinate_type adjust_direction(coordinate_type dr) const noexcept
{return boundary_.adjust_direction(dr);}
coordinate_type adjust_position(coordinate_type dr) const noexcept
{return boundary_.adjust_position(dr);}
std::size_t size() const noexcept {return num_particles_;}
particle_view_type operator[](std::size_t i) noexcept
{
return particle_view_type{
masses_[i], rmasses_[i],
positions_[i], velocities_[i], forces_[i],
names_[i], groups_[i]
};
}
particle_const_view_type operator[](std::size_t i) const noexcept
{
return particle_const_view_type{
masses_[i], rmasses_[i],
positions_[i], velocities_[i], forces_[i],
names_[i], groups_[i]
};
}
particle_view_type at(std::size_t i)
{
return particle_view_type{
masses_.at(i), rmasses_.at(i),
positions_.at(i), velocities_.at(i), forces_.at(i),
names_.at(i), groups_.at(i)
};
}
particle_const_view_type at(std::size_t i) const
{
return particle_const_view_type{
masses_.at(i), rmasses_.at(i),
positions_.at(i), velocities_.at(i), forces_.at(i),
names_.at(i), groups_.at(i)
};
}
// When parallelizing a code, forces are often calculated separately in
// several computational units, like cores, nodes, gpu devices, etc. To
// make it consistent, we may need to do something with forces calculated
// separately. Those functions are provided for such an specialized
// situation. Here, for the normal case, we do not need to do anything.
void preprocess_forces() noexcept {/* do nothing */}
void postprocess_forces() noexcept {/* do nothing */}
real_type mass (std::size_t i) const noexcept {return masses_[i];}
real_type& mass (std::size_t i) noexcept {return masses_[i];}
real_type rmass(std::size_t i) const noexcept {return rmasses_[i];}
real_type& rmass(std::size_t i) noexcept {return rmasses_[i];}
coordinate_type const& position(std::size_t i) const noexcept {return positions_[i];}
coordinate_type& position(std::size_t i) noexcept {return positions_[i];}
coordinate_type const& velocity(std::size_t i) const noexcept {return velocities_[i];}
coordinate_type& velocity(std::size_t i) noexcept {return velocities_[i];}
coordinate_type const& force (std::size_t i) const noexcept {return forces_[i];}
coordinate_type& force (std::size_t i) noexcept {return forces_[i];}
string_type const& name (std::size_t i) const noexcept {return names_[i];}
string_type& name (std::size_t i) noexcept {return names_[i];}
string_type const& group(std::size_t i) const noexcept {return groups_[i];}
string_type& group(std::size_t i) noexcept {return groups_[i];}
boundary_type& boundary() noexcept {return boundary_;}
boundary_type const& boundary() const noexcept {return boundary_;}
// system attributes like `reference temperature`, `ionic strength`, ...
// assuming it will not be called so often.
real_type attribute(const std::string& key) const {return attributes_.at(key);}
real_type& attribute(const std::string& key) {return attributes_[key];}
bool has_attribute(const std::string& key) const {return attributes_.count(key) == 1;}
attribute_type const& attributes() const noexcept {return attributes_;}
bool velocity_initialized() const noexcept {return velocity_initialized_;}
bool& velocity_initialized() noexcept {return velocity_initialized_;}
coordinate_container_type const& forces() const noexcept {return forces_;}
coordinate_container_type& forces() noexcept {return forces_;}
private:
bool velocity_initialized_;
boundary_type boundary_;
attribute_type attributes_;
std::size_t num_particles_;
real_container_type masses_;
real_container_type rmasses_; // r for reciprocal
coordinate_container_type positions_;
coordinate_container_type velocities_;
coordinate_container_type forces_;
string_container_type names_;
string_container_type groups_;
#ifdef MJOLNIR_WITH_OPENMP
// OpenMP implementation uses its own System<OpenMP> to avoid data race.
// So this implementation should not be instanciated with OpenMP Traits.
static_assert(!is_openmp_simulator_traits<traits_type>::value,
"this is the default implementation, not for OpenMP");
#endif
};
#ifdef MJOLNIR_SEPARATE_BUILD
extern template class System<SimulatorTraits<double, UnlimitedBoundary>>;
extern template class System<SimulatorTraits<float, UnlimitedBoundary>>;
extern template class System<SimulatorTraits<double, CuboidalPeriodicBoundary>>;
extern template class System<SimulatorTraits<float, CuboidalPeriodicBoundary>>;
#endif
} // mjolnir
#endif// MJOLNIR_SYSTEM_HPP
<|endoftext|> |
<commit_before>// Copyright (c) 2010 Hewlett-Packard Development Company, L.P. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
extern "C" {
#include <mlt/framework/mlt_producer.h>
#include <mlt/framework/mlt_frame.h>
}
#include <webvfx/image.h>
#include "factory.h"
#include "service_locker.h"
#include "service_manager.h"
static const char* kWebVfxProducerPropertyName = "WebVfxProducer";
static const char* kWebVfxPositionPropertyName = "webvfx.position";
static int producerGetImage(mlt_frame frame, uint8_t **buffer, mlt_image_format *format, int *width, int *height, int /*writable*/) {
int error = 0;
mlt_properties properties = MLT_FRAME_PROPERTIES(frame);
mlt_producer producer = (mlt_producer)mlt_properties_get_data(properties, kWebVfxProducerPropertyName, NULL);
mlt_properties producer_props = MLT_PRODUCER_PROPERTIES(producer);
int size;
int bpp;
bool hasTransparency = false;
{
MLTWebVfx::ServiceLocker locker(MLT_PRODUCER_SERVICE(producer));
if (!locker.initialize(*width, *height))
return 1;
if (mlt_properties_get_int( producer_props, "transparent") ) {
*format = mlt_image_rgb24a;
hasTransparency = true;
}
else {
*format = mlt_image_rgb24;
}
// Get bpp from image format
mlt_image_format_size(*format, 0, 0, &bpp);
size = *width * *height * bpp;
*buffer = (uint8_t*)mlt_pool_alloc(size);
// When not using transparency, this will make the background black...
memset( *buffer, 255, size );
WebVfx::Image outputImage(*buffer, *width, *height, size, hasTransparency);
locker.getManager()->render(&outputImage,
mlt_properties_get_position(properties, kWebVfxPositionPropertyName),
mlt_producer_get_length(producer), hasTransparency);
}
mlt_frame_set_image(frame, *buffer, size, mlt_pool_release);
if (hasTransparency) {
// Create the alpha channel
int alpha_size = *width * *height;
uint8_t *alpha = (uint8_t *)mlt_pool_alloc( alpha_size );
// Initialise the alpha
memset( alpha, 255, alpha_size );
mlt_frame_set_alpha(frame, alpha, alpha_size, mlt_pool_release);
}
return error;
}
static int getFrame(mlt_producer producer, mlt_frame_ptr frame, int /*index*/) {
// Generate a frame
*frame = mlt_frame_init(MLT_PRODUCER_SERVICE(producer));
if (*frame) {
// Obtain properties of frame and producer
mlt_properties properties = MLT_FRAME_PROPERTIES(*frame);
// Set the producer on the frame properties
mlt_properties_set_data(properties, kWebVfxProducerPropertyName, producer, 0, NULL, NULL);
// Update timecode on the frame we're creating
mlt_position position = mlt_producer_position(producer);
mlt_frame_set_position(*frame, position);
mlt_properties_set_position(properties, kWebVfxPositionPropertyName, position);
// Set producer-specific frame properties
mlt_properties_set_int(properties, "progressive", 1);
// Push the get_image method
mlt_frame_push_get_image(*frame, producerGetImage);
}
// Calculate the next timecode
mlt_producer_prepare_next(producer);
return 0;
}
static void producer_close( mlt_producer parent )
{
// Close the parent
parent->close = NULL;
mlt_producer_close( parent );
// Free the memory
free( parent );
}
mlt_service MLTWebVfx::createProducer(mlt_profile profile) {
mlt_producer producer = mlt_producer_new(profile);
if (producer) {
producer->get_frame = getFrame;
producer->close = (mlt_destructor) producer_close;
mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
mlt_properties_set_int( properties, "meta.media.progressive", 1 );
mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 1 );
mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 1 );
mlt_properties_set_int(properties, "meta.media.width", profile->width);
mlt_properties_set_int(properties, "meta.media.height", profile->height);
return MLT_PRODUCER_SERVICE(producer);
}
return 0;
}
<commit_msg>Fix comment about background color.<commit_after>// Copyright (c) 2010 Hewlett-Packard Development Company, L.P. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
extern "C" {
#include <mlt/framework/mlt_producer.h>
#include <mlt/framework/mlt_frame.h>
}
#include <webvfx/image.h>
#include "factory.h"
#include "service_locker.h"
#include "service_manager.h"
static const char* kWebVfxProducerPropertyName = "WebVfxProducer";
static const char* kWebVfxPositionPropertyName = "webvfx.position";
static int producerGetImage(mlt_frame frame, uint8_t **buffer, mlt_image_format *format, int *width, int *height, int /*writable*/) {
int error = 0;
mlt_properties properties = MLT_FRAME_PROPERTIES(frame);
mlt_producer producer = (mlt_producer)mlt_properties_get_data(properties, kWebVfxProducerPropertyName, NULL);
mlt_properties producer_props = MLT_PRODUCER_PROPERTIES(producer);
int size;
int bpp;
bool hasTransparency = false;
{
MLTWebVfx::ServiceLocker locker(MLT_PRODUCER_SERVICE(producer));
if (!locker.initialize(*width, *height))
return 1;
if (mlt_properties_get_int( producer_props, "transparent") ) {
*format = mlt_image_rgb24a;
hasTransparency = true;
}
else {
*format = mlt_image_rgb24;
}
// Get bpp from image format
mlt_image_format_size(*format, 0, 0, &bpp);
size = *width * *height * bpp;
*buffer = (uint8_t*)mlt_pool_alloc(size);
// When not using transparency, this will make the background white.
memset(*buffer, 255, size);
WebVfx::Image outputImage(*buffer, *width, *height, size, hasTransparency);
locker.getManager()->render(&outputImage,
mlt_properties_get_position(properties, kWebVfxPositionPropertyName),
mlt_producer_get_length(producer), hasTransparency);
}
mlt_frame_set_image(frame, *buffer, size, mlt_pool_release);
if (hasTransparency) {
// Create the alpha channel
int alpha_size = *width * *height;
uint8_t *alpha = (uint8_t *)mlt_pool_alloc( alpha_size );
// Initialise the alpha
memset( alpha, 255, alpha_size );
mlt_frame_set_alpha(frame, alpha, alpha_size, mlt_pool_release);
}
return error;
}
static int getFrame(mlt_producer producer, mlt_frame_ptr frame, int /*index*/) {
// Generate a frame
*frame = mlt_frame_init(MLT_PRODUCER_SERVICE(producer));
if (*frame) {
// Obtain properties of frame and producer
mlt_properties properties = MLT_FRAME_PROPERTIES(*frame);
// Set the producer on the frame properties
mlt_properties_set_data(properties, kWebVfxProducerPropertyName, producer, 0, NULL, NULL);
// Update timecode on the frame we're creating
mlt_position position = mlt_producer_position(producer);
mlt_frame_set_position(*frame, position);
mlt_properties_set_position(properties, kWebVfxPositionPropertyName, position);
// Set producer-specific frame properties
mlt_properties_set_int(properties, "progressive", 1);
// Push the get_image method
mlt_frame_push_get_image(*frame, producerGetImage);
}
// Calculate the next timecode
mlt_producer_prepare_next(producer);
return 0;
}
static void producer_close( mlt_producer parent )
{
// Close the parent
parent->close = NULL;
mlt_producer_close( parent );
// Free the memory
free( parent );
}
mlt_service MLTWebVfx::createProducer(mlt_profile profile) {
mlt_producer producer = mlt_producer_new(profile);
if (producer) {
producer->get_frame = getFrame;
producer->close = (mlt_destructor) producer_close;
mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
mlt_properties_set_int( properties, "meta.media.progressive", 1 );
mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 1 );
mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 1 );
mlt_properties_set_int(properties, "meta.media.width", profile->width);
mlt_properties_set_int(properties, "meta.media.height", profile->height);
return MLT_PRODUCER_SERVICE(producer);
}
return 0;
}
<|endoftext|> |
<commit_before>#include "ctmatutils.h"
#include "clib/ct.h"
void checkNArgs(const int n, const int nrhs)
{
if (n != nrhs) {
mexErrMsgTxt("Wrong number of arguments.");
}
}
void kineticsmethods(int nlhs, mxArray* plhs[],
int nrhs, const mxArray* prhs[])
{
double vv = 0.0;
int job = getInt(prhs[2]);
int kin, irxn;
// construct a new instance
if (job == 0) {
checkNArgs(8, nrhs);
int root = getInt(prhs[1]);
int iph = getInt(prhs[3]);
int in1 = getInt(prhs[4]);
int in2 = getInt(prhs[5]);
int in3 = getInt(prhs[6]);
int in4 = getInt(prhs[7]);
vv = (double) newKineticsFromXML(root, iph, in1, in2, in3, in4);
plhs[0] = mxCreateNumericMatrix(1,1,mxDOUBLE_CLASS,mxREAL);
double* h = mxGetPr(plhs[0]);
*h = vv;
return;
}
// methods
else if (job > 0) {
int isp = 1;
if (job < 5 || job > 6) {
checkNArgs(4,nrhs);
} else {
checkNArgs(5,nrhs);
isp = getInt(prhs[4]);
}
kin = getInt(prhs[1]);
irxn = getInt(prhs[3]);
// get scalar attributes
if (job < 10) {
switch (job) {
case 1:
vv = (double) kin_nReactions(kin);
break;
case 2:
vv = kin_multiplier(kin, irxn-1);
break;
case 3:
vv = (double) kin_nSpecies(kin);
break;
case 4:
vv = kin_isReversible(kin,irxn-1);
break;
case 5:
vv = kin_reactantStoichCoeff(kin, isp - 1, irxn-1);
break;
case 6:
vv = kin_productStoichCoeff(kin, isp - 1, irxn-1);
break;
default:
mexErrMsgTxt("unknown job");
}
plhs[0] = mxCreateNumericMatrix(1,1,mxDOUBLE_CLASS,mxREAL);
double* h = mxGetPr(plhs[0]);
*h = vv;
return;
} else if (job < 20) {
// get reaction array attributes
mwSize nr = (mwSize) kin_nReactions(kin);
plhs[0] = mxCreateNumericMatrix(nr,1,mxDOUBLE_CLASS,mxREAL);
double* h = mxGetPr(plhs[0]);
int ok = -10;
switch (job) {
case 11:
ok = kin_getFwdRatesOfProgress(kin,nr,h);
break;
case 12:
ok = kin_getRevRatesOfProgress(kin,nr,h);
break;
case 13:
ok = kin_getNetRatesOfProgress(kin,nr,h);
break;
case 14:
ok = kin_getEquilibriumConstants(kin,nr,h);
break;
case 15:
ok = kin_getFwdRateConstants(kin,nr,h);
break;
case 16:
ok = kin_getRevRateConstants(kin,1,nr,h);
break;
default:
;
}
if (ok < 0) {
mexErrMsgTxt("error computing rates of progress");
}
} else if (job < 30) {
mwSize nsp = (mwSize) kin_nSpecies(kin);
plhs[0] = mxCreateNumericMatrix(nsp,1,mxDOUBLE_CLASS,mxREAL);
double* h = mxGetPr(plhs[0]);
int ok = -10;
switch (job) {
case 21:
ok = kin_getCreationRates(kin,nsp,h);
break;
case 22:
ok = kin_getDestructionRates(kin,nsp,h);
break;
case 23:
ok = kin_getNetProductionRates(kin,nsp,h);
break;
case 24:
ok = kin_getSourceTerms(kin, nsp, h);
break;
default:
;
}
if (ok < 0) {
mexErrMsgTxt("error computing production rates");
}
} else if (job < 40) {
char* buf;
int iok = -1, buflen = 80;
switch (job) {
case 31:
buf = (char*)mxCalloc(buflen, sizeof(char));
iok = kin_getReactionString(kin, irxn-1, buflen, buf);
break;
default:
;
}
if (iok >= 0) {
plhs[0] = mxCreateString(buf);
return;
} else {
reportError();
}
}
}
else {
// set attributes
int iok = -1;
job = -job;
kin = getInt(prhs[1]);
irxn = getInt(prhs[3]);
if (job < 10) {
checkNArgs(5,nrhs);
double v = getDouble(prhs[4]);
switch (job) {
case 1:
iok = kin_setMultiplier(kin,irxn-1,v);
break;
case 3:
iok = delKinetics(kin);
break;
case 5:
iok = kin_advanceCoverages(kin,v);
break;
default:
mexErrMsgTxt("unknown job");
}
}
if (iok < 0) {
reportError();
}
}
}
<commit_msg>[Matlab] Fix detection of errors when importing Kinetics<commit_after>#include "ctmatutils.h"
#include "clib/ct.h"
void checkNArgs(const int n, const int nrhs)
{
if (n != nrhs) {
mexErrMsgTxt("Wrong number of arguments.");
}
}
void kineticsmethods(int nlhs, mxArray* plhs[],
int nrhs, const mxArray* prhs[])
{
double vv = 0.0;
int job = getInt(prhs[2]);
int kin, irxn;
// construct a new instance
if (job == 0) {
checkNArgs(8, nrhs);
int root = getInt(prhs[1]);
int iph = getInt(prhs[3]);
int in1 = getInt(prhs[4]);
int in2 = getInt(prhs[5]);
int in3 = getInt(prhs[6]);
int in4 = getInt(prhs[7]);
vv = static_cast<int>(newKineticsFromXML(root, iph, in1, in2, in3, in4));
plhs[0] = mxCreateNumericMatrix(1,1,mxDOUBLE_CLASS,mxREAL);
double* h = mxGetPr(plhs[0]);
*h = vv;
return;
}
// methods
else if (job > 0) {
int isp = 1;
if (job < 5 || job > 6) {
checkNArgs(4,nrhs);
} else {
checkNArgs(5,nrhs);
isp = getInt(prhs[4]);
}
kin = getInt(prhs[1]);
irxn = getInt(prhs[3]);
// get scalar attributes
if (job < 10) {
switch (job) {
case 1:
vv = (double) kin_nReactions(kin);
break;
case 2:
vv = kin_multiplier(kin, irxn-1);
break;
case 3:
vv = (double) kin_nSpecies(kin);
break;
case 4:
vv = kin_isReversible(kin,irxn-1);
break;
case 5:
vv = kin_reactantStoichCoeff(kin, isp - 1, irxn-1);
break;
case 6:
vv = kin_productStoichCoeff(kin, isp - 1, irxn-1);
break;
default:
mexErrMsgTxt("unknown job");
}
plhs[0] = mxCreateNumericMatrix(1,1,mxDOUBLE_CLASS,mxREAL);
double* h = mxGetPr(plhs[0]);
*h = vv;
return;
} else if (job < 20) {
// get reaction array attributes
mwSize nr = (mwSize) kin_nReactions(kin);
plhs[0] = mxCreateNumericMatrix(nr,1,mxDOUBLE_CLASS,mxREAL);
double* h = mxGetPr(plhs[0]);
int ok = -10;
switch (job) {
case 11:
ok = kin_getFwdRatesOfProgress(kin,nr,h);
break;
case 12:
ok = kin_getRevRatesOfProgress(kin,nr,h);
break;
case 13:
ok = kin_getNetRatesOfProgress(kin,nr,h);
break;
case 14:
ok = kin_getEquilibriumConstants(kin,nr,h);
break;
case 15:
ok = kin_getFwdRateConstants(kin,nr,h);
break;
case 16:
ok = kin_getRevRateConstants(kin,1,nr,h);
break;
default:
;
}
if (ok < 0) {
mexErrMsgTxt("error computing rates of progress");
}
} else if (job < 30) {
mwSize nsp = (mwSize) kin_nSpecies(kin);
plhs[0] = mxCreateNumericMatrix(nsp,1,mxDOUBLE_CLASS,mxREAL);
double* h = mxGetPr(plhs[0]);
int ok = -10;
switch (job) {
case 21:
ok = kin_getCreationRates(kin,nsp,h);
break;
case 22:
ok = kin_getDestructionRates(kin,nsp,h);
break;
case 23:
ok = kin_getNetProductionRates(kin,nsp,h);
break;
case 24:
ok = kin_getSourceTerms(kin, nsp, h);
break;
default:
;
}
if (ok < 0) {
mexErrMsgTxt("error computing production rates");
}
} else if (job < 40) {
char* buf;
int iok = -1, buflen = 80;
switch (job) {
case 31:
buf = (char*)mxCalloc(buflen, sizeof(char));
iok = kin_getReactionString(kin, irxn-1, buflen, buf);
break;
default:
;
}
if (iok >= 0) {
plhs[0] = mxCreateString(buf);
return;
} else {
reportError();
}
}
}
else {
// set attributes
int iok = -1;
job = -job;
kin = getInt(prhs[1]);
irxn = getInt(prhs[3]);
if (job < 10) {
checkNArgs(5,nrhs);
double v = getDouble(prhs[4]);
switch (job) {
case 1:
iok = kin_setMultiplier(kin,irxn-1,v);
break;
case 3:
iok = delKinetics(kin);
break;
case 5:
iok = kin_advanceCoverages(kin,v);
break;
default:
mexErrMsgTxt("unknown job");
}
}
if (iok < 0) {
reportError();
}
}
}
<|endoftext|> |
<commit_before>#include <Poco/Exception.h>
#include <Poco/Data/Statement.h>
#include <Poco/Data/RowIterator.h>
#include <Poco/Data/Row.h>
#include <Poco/Data/RecordSet.h>
#include "di/Injectable.h"
#include "dao/TransactionManager.h"
#include "dao/poco/PocoSQLRoleInGatewayDao.h"
#include "dao/poco/PocoSQLGatewayDao.h"
#include "dao/poco/PocoSQLIdentityDao.h"
#include "dao/poco/PocoDaoManager.h"
#include "model/User.h"
#include "model/Gateway.h"
using namespace std;
using namespace Poco;
using namespace Poco::Data;
using namespace Poco::Data::Keywords;
using namespace BeeeOn;
BEEEON_OBJECT_BEGIN(BeeeOn, PocoSQLRoleInGatewayDao)
BEEEON_OBJECT_CASTABLE(RoleInGatewayDao)
BEEEON_OBJECT_REF("daoManager", &PocoSQLRoleInGatewayDao::setDaoManager)
BEEEON_OBJECT_REF("transactionManager", &PocoSQLRoleInGatewayDao::setTransactionManager)
BEEEON_OBJECT_REF("sqlLoader", &PocoSQLRoleInGatewayDao::setSQLLoader)
BEEEON_OBJECT_HOOK("done", &PocoSQLRoleInGatewayDao::loadQueries)
BEEEON_OBJECT_END(BeeeOn, PocoSQLRoleInGatewayDao)
PocoSQLRoleInGatewayDao::PocoSQLRoleInGatewayDao()
{
registerQuery(m_queryCreate);
registerQuery(m_queryUpdate);
registerQuery(m_queryRemove);
registerQuery(m_queryRemoveUser);
registerQuery(m_queryRemoveAll);
registerQuery(m_queryIsUser);
registerQuery(m_queryIsRegistered);
registerQuery(m_queryFetchById);
registerQuery(m_queryFetchByGatewayId);
registerQuery(m_queryFetchLegacyByGatewayId);
registerQuery(m_queryFetchAccessLevel);
registerQuery(m_queryFetchAccessibleGateways);
registerQuery(m_queryHasOnlyNonAdminExcept);
}
void PocoSQLRoleInGatewayDao::create(RoleInGateway &role)
{
assureHasId(role.gateway());
assureHasId(role.identity());
role.setId(RoleInGatewayID::random());
string id(role.id().toString());
string gatewayID(role.gateway().id().toString());
string identityID(role.identity().id().toString());
unsigned int level = role.level();
unsigned long created = role.created().timestamp().epochTime();
Statement sql = (session() << m_queryCreate(),
use(id, "id"),
use(gatewayID, "gateway_id"),
use(identityID, "identity_id"),
use(level, "level"),
use(created, "created")
);
execute(sql);
}
bool PocoSQLRoleInGatewayDao::update(RoleInGateway &role)
{
assureHasId(role);
string id(role.id().toString());
unsigned int level = role.level();
Statement sql = (session() << m_queryUpdate(),
use(level, "level"),
use(id, "id")
);
return execute(sql) > 0;
}
bool PocoSQLRoleInGatewayDao::fetch(RoleInGateway &role)
{
assureHasId(role);
string roleID(role.id().toString());
Statement sql = (session() << m_queryFetchById(),
use(roleID, "role_id")
);
if (execute(sql) == 0)
return false;
RecordSet result(sql);
return parseSingle(result, role);
}
void PocoSQLRoleInGatewayDao::fetchBy(std::vector<RoleInGateway> &roles,
const Gateway &gateway)
{
assureHasId(gateway);
string gatewayID(gateway.id().toString());
Statement sql = (session() << m_queryFetchByGatewayId(),
use(gatewayID, "gateway_id")
);
execute(sql);
RecordSet result(sql);
parseMany<RoleInGateway>(result, roles);
}
void PocoSQLRoleInGatewayDao::fetchBy(std::vector<LegacyRoleInGateway> &roles,
const Gateway &gateway)
{
assureHasId(gateway);
string gatewayID(gateway.id().toString());
Statement sql = (session() << m_queryFetchLegacyByGatewayId(),
use(gatewayID, "gateway_id")
);
execute(sql);
RecordSet result(sql);
parseMany<LegacyRoleInGateway>(result, roles);
}
bool PocoSQLRoleInGatewayDao::remove(const RoleInGateway &role)
{
assureHasId(role);
string id(role.id().toString());
Statement sql = (session() << m_queryRemove(),
use(id, "id")
);
return execute(sql) > 0;
}
bool PocoSQLRoleInGatewayDao::remove(
const Gateway &gateway, const User &user)
{
assureHasId(gateway);
assureHasId(user);
string gatewayID(gateway.id().toString());
string userID(user.id().toString());
Statement sql = (session() << m_queryRemoveUser(),
use(userID, "user_id"),
use(gatewayID, "gateway_id")
);
return execute(sql) > 0;
}
void PocoSQLRoleInGatewayDao::removeAll(const Gateway &gateway)
{
assureHasId(gateway);
string gatewayID(gateway.id().toString());
Statement sql = (session() << m_queryRemoveAll(),
use(gatewayID, "gateway_id")
);
execute(sql);
}
bool PocoSQLRoleInGatewayDao::isUser(const RoleInGateway &role,
const User &user)
{
assureHasId(role);
assureHasId(user);
string roleID(role.id().toString());
string userID(user.id().toString());
bool result = false;
Statement sql = (session() << m_queryIsUser(),
use(roleID, "role_id"),
use(userID, "user_id"),
into(result)
);
execute(sql);
return result;
}
bool PocoSQLRoleInGatewayDao::isRegistered(
const Gateway &gateway)
{
assureHasId(gateway);
string gatewayID(gateway.id().toString());
bool result = false;
Statement sql = (session() << m_queryIsRegistered(),
use(gatewayID, "gateway_id"),
into(result)
);
execute(sql);
return result;
}
bool PocoSQLRoleInGatewayDao::hasOnlyNonAdminExcept(
const Gateway &gateway, const User &user)
{
assureHasId(gateway);
assureHasId(user);
string gatewayID(gateway.id().toString());
string userID(user.id().toString());
unsigned int level = AccessLevel::admin();
bool result = false;
Statement sql = (session() << m_queryHasOnlyNonAdminExcept(),
use(level, "level"),
use(gatewayID, "gateway_id"),
use(userID, "user_id"),
into(result)
);
execute(sql);
return result;
}
AccessLevel PocoSQLRoleInGatewayDao::fetchAccessLevel(
const Gateway &gateway,
const User &user)
{
assureHasId(gateway);
assureHasId(user);
string gatewayID(gateway.id().toString());
string userID(user.id().toString());
Nullable<unsigned int> level;
Statement sql = (session() << m_queryFetchAccessLevel(),
use(gatewayID, "gateway_id"),
use(userID, "user_id"),
into(level)
);
execute(sql);
return level.isNull()? AccessLevel::none() : AccessLevel(level);
}
void PocoSQLRoleInGatewayDao::fetchAccessibleGateways(
std::vector<Gateway> &list,
const User &user,
const AccessLevel &atLeast)
{
assureHasId(user);
string userID(user.id().toString());
unsigned int level = atLeast;
Statement sql = (session() << m_queryFetchAccessibleGateways(),
use(level, "at_least"),
use(userID, "user_id")
);
execute(sql);
RecordSet result(sql);
PocoSQLGatewayDao::parseMany<Gateway>(result, list);
}
bool PocoSQLRoleInGatewayDao::parseSingle(Row &result,
RoleInGateway &role, const string &prefix)
{
if (hasColumn(result, prefix + "id"))
role.setId(RoleInGatewayID::parse(result[prefix + "id"]));
role.setLevel(AccessLevel(result[prefix + "level"].convert<unsigned int>()));
role.setCreated(Timestamp::fromEpochTime(result[prefix + "created"]));
Gateway gateway(GatewayID::parse(result[prefix + "gateway_id"]));
role.setGateway(gateway);
Identity identity;
if (!PocoSQLIdentityDao::parseIfIDNotNull(result, identity, prefix + "identity_"))
throw IllegalStateException("identity is incomplete in query request");
role.setIdentity(identity);
markLoaded(role);
return true;
}
bool PocoSQLRoleInGatewayDao::parseSingle(Row &result,
LegacyRoleInGateway &role, const string &prefix)
{
if (!parseSingle(result, static_cast<RoleInGateway &>(role)))
return false;
role.setOwner(result[prefix + "is_owner"]);
role.setFirstName(result[prefix + "first_name"]);
role.setLastName(result[prefix + "last_name"]);
const Poco::Dynamic::Var &picture = result[prefix + "picture"];
role.setPicture(picture.isEmpty()? URI() : URI(picture.toString()));
markLoaded(role);
return true;
}
<commit_msg>PocoSQLRoleInGatewayDao: fix segfault while extracting Nullable<commit_after>#include <Poco/Exception.h>
#include <Poco/Data/Statement.h>
#include <Poco/Data/RowIterator.h>
#include <Poco/Data/Row.h>
#include <Poco/Data/RecordSet.h>
#include "di/Injectable.h"
#include "dao/TransactionManager.h"
#include "dao/poco/PocoSQLRoleInGatewayDao.h"
#include "dao/poco/PocoSQLGatewayDao.h"
#include "dao/poco/PocoSQLIdentityDao.h"
#include "dao/poco/PocoDaoManager.h"
#include "model/User.h"
#include "model/Gateway.h"
using namespace std;
using namespace Poco;
using namespace Poco::Data;
using namespace Poco::Data::Keywords;
using namespace BeeeOn;
BEEEON_OBJECT_BEGIN(BeeeOn, PocoSQLRoleInGatewayDao)
BEEEON_OBJECT_CASTABLE(RoleInGatewayDao)
BEEEON_OBJECT_REF("daoManager", &PocoSQLRoleInGatewayDao::setDaoManager)
BEEEON_OBJECT_REF("transactionManager", &PocoSQLRoleInGatewayDao::setTransactionManager)
BEEEON_OBJECT_REF("sqlLoader", &PocoSQLRoleInGatewayDao::setSQLLoader)
BEEEON_OBJECT_HOOK("done", &PocoSQLRoleInGatewayDao::loadQueries)
BEEEON_OBJECT_END(BeeeOn, PocoSQLRoleInGatewayDao)
PocoSQLRoleInGatewayDao::PocoSQLRoleInGatewayDao()
{
registerQuery(m_queryCreate);
registerQuery(m_queryUpdate);
registerQuery(m_queryRemove);
registerQuery(m_queryRemoveUser);
registerQuery(m_queryRemoveAll);
registerQuery(m_queryIsUser);
registerQuery(m_queryIsRegistered);
registerQuery(m_queryFetchById);
registerQuery(m_queryFetchByGatewayId);
registerQuery(m_queryFetchLegacyByGatewayId);
registerQuery(m_queryFetchAccessLevel);
registerQuery(m_queryFetchAccessibleGateways);
registerQuery(m_queryHasOnlyNonAdminExcept);
}
void PocoSQLRoleInGatewayDao::create(RoleInGateway &role)
{
assureHasId(role.gateway());
assureHasId(role.identity());
role.setId(RoleInGatewayID::random());
string id(role.id().toString());
string gatewayID(role.gateway().id().toString());
string identityID(role.identity().id().toString());
unsigned int level = role.level();
unsigned long created = role.created().timestamp().epochTime();
Statement sql = (session() << m_queryCreate(),
use(id, "id"),
use(gatewayID, "gateway_id"),
use(identityID, "identity_id"),
use(level, "level"),
use(created, "created")
);
execute(sql);
}
bool PocoSQLRoleInGatewayDao::update(RoleInGateway &role)
{
assureHasId(role);
string id(role.id().toString());
unsigned int level = role.level();
Statement sql = (session() << m_queryUpdate(),
use(level, "level"),
use(id, "id")
);
return execute(sql) > 0;
}
bool PocoSQLRoleInGatewayDao::fetch(RoleInGateway &role)
{
assureHasId(role);
string roleID(role.id().toString());
Statement sql = (session() << m_queryFetchById(),
use(roleID, "role_id")
);
if (execute(sql) == 0)
return false;
RecordSet result(sql);
return parseSingle(result, role);
}
void PocoSQLRoleInGatewayDao::fetchBy(std::vector<RoleInGateway> &roles,
const Gateway &gateway)
{
assureHasId(gateway);
string gatewayID(gateway.id().toString());
Statement sql = (session() << m_queryFetchByGatewayId(),
use(gatewayID, "gateway_id")
);
execute(sql);
RecordSet result(sql);
parseMany<RoleInGateway>(result, roles);
}
void PocoSQLRoleInGatewayDao::fetchBy(std::vector<LegacyRoleInGateway> &roles,
const Gateway &gateway)
{
assureHasId(gateway);
string gatewayID(gateway.id().toString());
Statement sql = (session() << m_queryFetchLegacyByGatewayId(),
use(gatewayID, "gateway_id")
);
execute(sql);
RecordSet result(sql);
parseMany<LegacyRoleInGateway>(result, roles);
}
bool PocoSQLRoleInGatewayDao::remove(const RoleInGateway &role)
{
assureHasId(role);
string id(role.id().toString());
Statement sql = (session() << m_queryRemove(),
use(id, "id")
);
return execute(sql) > 0;
}
bool PocoSQLRoleInGatewayDao::remove(
const Gateway &gateway, const User &user)
{
assureHasId(gateway);
assureHasId(user);
string gatewayID(gateway.id().toString());
string userID(user.id().toString());
Statement sql = (session() << m_queryRemoveUser(),
use(userID, "user_id"),
use(gatewayID, "gateway_id")
);
return execute(sql) > 0;
}
void PocoSQLRoleInGatewayDao::removeAll(const Gateway &gateway)
{
assureHasId(gateway);
string gatewayID(gateway.id().toString());
Statement sql = (session() << m_queryRemoveAll(),
use(gatewayID, "gateway_id")
);
execute(sql);
}
bool PocoSQLRoleInGatewayDao::isUser(const RoleInGateway &role,
const User &user)
{
assureHasId(role);
assureHasId(user);
string roleID(role.id().toString());
string userID(user.id().toString());
bool result = false;
Statement sql = (session() << m_queryIsUser(),
use(roleID, "role_id"),
use(userID, "user_id"),
into(result)
);
execute(sql);
return result;
}
bool PocoSQLRoleInGatewayDao::isRegistered(
const Gateway &gateway)
{
assureHasId(gateway);
string gatewayID(gateway.id().toString());
bool result = false;
Statement sql = (session() << m_queryIsRegistered(),
use(gatewayID, "gateway_id"),
into(result)
);
execute(sql);
return result;
}
bool PocoSQLRoleInGatewayDao::hasOnlyNonAdminExcept(
const Gateway &gateway, const User &user)
{
assureHasId(gateway);
assureHasId(user);
string gatewayID(gateway.id().toString());
string userID(user.id().toString());
unsigned int level = AccessLevel::admin();
bool result = false;
Statement sql = (session() << m_queryHasOnlyNonAdminExcept(),
use(level, "level"),
use(gatewayID, "gateway_id"),
use(userID, "user_id"),
into(result)
);
execute(sql);
return result;
}
AccessLevel PocoSQLRoleInGatewayDao::fetchAccessLevel(
const Gateway &gateway,
const User &user)
{
assureHasId(gateway);
assureHasId(user);
string gatewayID(gateway.id().toString());
string userID(user.id().toString());
Nullable<unsigned int> level(0);
Statement sql = (session() << m_queryFetchAccessLevel(),
use(gatewayID, "gateway_id"),
use(userID, "user_id"),
into(level)
);
execute(sql);
return level.isNull()? AccessLevel::none() : AccessLevel(level);
}
void PocoSQLRoleInGatewayDao::fetchAccessibleGateways(
std::vector<Gateway> &list,
const User &user,
const AccessLevel &atLeast)
{
assureHasId(user);
string userID(user.id().toString());
unsigned int level = atLeast;
Statement sql = (session() << m_queryFetchAccessibleGateways(),
use(level, "at_least"),
use(userID, "user_id")
);
execute(sql);
RecordSet result(sql);
PocoSQLGatewayDao::parseMany<Gateway>(result, list);
}
bool PocoSQLRoleInGatewayDao::parseSingle(Row &result,
RoleInGateway &role, const string &prefix)
{
if (hasColumn(result, prefix + "id"))
role.setId(RoleInGatewayID::parse(result[prefix + "id"]));
role.setLevel(AccessLevel(result[prefix + "level"].convert<unsigned int>()));
role.setCreated(Timestamp::fromEpochTime(result[prefix + "created"]));
Gateway gateway(GatewayID::parse(result[prefix + "gateway_id"]));
role.setGateway(gateway);
Identity identity;
if (!PocoSQLIdentityDao::parseIfIDNotNull(result, identity, prefix + "identity_"))
throw IllegalStateException("identity is incomplete in query request");
role.setIdentity(identity);
markLoaded(role);
return true;
}
bool PocoSQLRoleInGatewayDao::parseSingle(Row &result,
LegacyRoleInGateway &role, const string &prefix)
{
if (!parseSingle(result, static_cast<RoleInGateway &>(role)))
return false;
role.setOwner(result[prefix + "is_owner"]);
role.setFirstName(result[prefix + "first_name"]);
role.setLastName(result[prefix + "last_name"]);
const Poco::Dynamic::Var &picture = result[prefix + "picture"];
role.setPicture(picture.isEmpty()? URI() : URI(picture.toString()));
markLoaded(role);
return true;
}
<|endoftext|> |
<commit_before>// -------------------------------------------------------------
// a simple Arduino Teensy3.1 CAN driver
// by teachop
//
#include "FlexCAN.h"
#include "kinetis_flexcan.h"
static const int txb = 8; // with default settings, all buffers before this are consumed by the FIFO
static const int txBuffers = 8;
static const int rxb = 0;
// -------------------------------------------------------------
FlexCAN::FlexCAN(uint32_t baud)
{
// set up the pins, 3=PTA12=CAN0_TX, 4=PTA13=CAN0_RX
CORE_PIN3_CONFIG = PORT_PCR_MUX(2);
CORE_PIN4_CONFIG = PORT_PCR_MUX(2);// | PORT_PCR_PE | PORT_PCR_PS;
// select clock source
SIM_SCGC6 |= SIM_SCGC6_FLEXCAN0;
FLEXCAN0_CTRL1 |= FLEXCAN_CTRL_CLK_SRC;
// enable CAN
FLEXCAN0_MCR |= FLEXCAN_MCR_FRZ;
FLEXCAN0_MCR &= ~FLEXCAN_MCR_MDIS;
while(FLEXCAN0_MCR & FLEXCAN_MCR_LPM_ACK)
;
// soft reset
FLEXCAN0_MCR ^= FLEXCAN_MCR_SOFT_RST;
while(FLEXCAN0_MCR & FLEXCAN_MCR_SOFT_RST)
;
// wait for freeze ack
while(!(FLEXCAN0_MCR & FLEXCAN_MCR_FRZ_ACK))
;
// disable self-reception
FLEXCAN0_MCR |= FLEXCAN_MCR_SRX_DIS;
//enable RX FIFO
FLEXCAN0_MCR |= FLEXCAN_MCR_FEN;
// segment timings from freescale loopback test
if ( 250000 == baud ) {
FLEXCAN0_CTRL1 = (FLEXCAN_CTRL_PROPSEG(2) | FLEXCAN_CTRL_RJW(1)
| FLEXCAN_CTRL_PSEG1(3) | FLEXCAN_CTRL_PSEG2(3) | FLEXCAN_CTRL_PRESDIV(15));
} else if ( 500000 == baud ) {
FLEXCAN0_CTRL1 = (FLEXCAN_CTRL_PROPSEG(2) | FLEXCAN_CTRL_RJW(1)
| FLEXCAN_CTRL_PSEG1(3) | FLEXCAN_CTRL_PSEG2(3) | FLEXCAN_CTRL_PRESDIV(7));
} else if ( 1000000 == baud ) {
FLEXCAN0_CTRL1 = (FLEXCAN_CTRL_PROPSEG(3) | FLEXCAN_CTRL_RJW(0)
| FLEXCAN_CTRL_PSEG1(0) | FLEXCAN_CTRL_PSEG2(1) | FLEXCAN_CTRL_PRESDIV(5));
} else { // 125000
FLEXCAN0_CTRL1 = (FLEXCAN_CTRL_PROPSEG(2) | FLEXCAN_CTRL_RJW(2)
| FLEXCAN_CTRL_PSEG1(3) | FLEXCAN_CTRL_PSEG2(3) | FLEXCAN_CTRL_PRESDIV(31));
}
// Default mask is allow everything
defaultMask.rtr = 0;
defaultMask.ext = 0;
defaultMask.id = 0;
}
// -------------------------------------------------------------
void FlexCAN::end(void)
{
// enter freeze mode
FLEXCAN0_MCR |= (FLEXCAN_MCR_HALT);
while(!(FLEXCAN0_MCR & FLEXCAN_MCR_FRZ_ACK))
;
}
// -------------------------------------------------------------
void FlexCAN::begin(const CAN_filter_t &mask)
{
FLEXCAN0_RXMGMASK = 0;
//enable reception of all messages that fit the mask
if (mask.ext) {
FLEXCAN0_RXFGMASK = ((mask.rtr?1:0) << 31) | ((mask.ext?1:0) << 30) | ((mask.id & FLEXCAN_MB_ID_EXT_MASK) << 1);
} else {
FLEXCAN0_RXFGMASK = ((mask.rtr?1:0) << 31) | ((mask.ext?1:0) << 30) | (FLEXCAN_MB_ID_IDSTD(mask.id) << 1);
}
// start the CAN
FLEXCAN0_MCR &= ~(FLEXCAN_MCR_HALT);
// wait till exit of freeze mode
while(FLEXCAN0_MCR & FLEXCAN_MCR_FRZ_ACK);
// wait till ready
while(FLEXCAN0_MCR & FLEXCAN_MCR_NOT_RDY);
//set tx buffers to inactive
for (int i = txb; i < txb + txBuffers; i++) {
FLEXCAN0_MBn_CS(i) = FLEXCAN_MB_CS_CODE(FLEXCAN_MB_CODE_TX_INACTIVE);
}
}
// -------------------------------------------------------------
void FlexCAN::setFilter(const CAN_filter_t &filter, uint8_t n)
{
if ( 8 > n ) {
if (filter.ext) {
FLEXCAN0_IDFLT_TAB(n) = ((filter.rtr?1:0) << 31) | ((filter.ext?1:0) << 30) | ((filter.id & FLEXCAN_MB_ID_EXT_MASK) << 1);
} else {
FLEXCAN0_IDFLT_TAB(n) = ((filter.rtr?1:0) << 31) | ((filter.ext?1:0) << 30) | (FLEXCAN_MB_ID_IDSTD(filter.id) << 1);
}
}
}
// -------------------------------------------------------------
int FlexCAN::available(void)
{
//In FIFO mode, the following interrupt flag signals availability of a frame
return (FLEXCAN0_IFLAG1 & FLEXCAN_IMASK1_BUF5M)? 1:0;
}
// -------------------------------------------------------------
int FlexCAN::read(CAN_message_t &msg)
{
unsigned long int startMillis;
startMillis = msg.timeout? millis() : 0;
while( !available() ) {
if ( !msg.timeout || (msg.timeout<=(millis()-startMillis)) ) {
// early EXIT nothing here
return 0;
}
yield();
}
// get identifier and dlc
msg.len = FLEXCAN_get_length(FLEXCAN0_MBn_CS(rxb));
msg.ext = (FLEXCAN0_MBn_CS(rxb) & FLEXCAN_MB_CS_IDE)? 1:0;
msg.id = (FLEXCAN0_MBn_ID(rxb) & FLEXCAN_MB_ID_EXT_MASK);
if(!msg.ext) {
msg.id >>= FLEXCAN_MB_ID_STD_BIT_NO;
}
// copy out message
uint32_t dataIn = FLEXCAN0_MBn_WORD0(rxb);
msg.buf[3] = dataIn;
dataIn >>=8;
msg.buf[2] = dataIn;
dataIn >>=8;
msg.buf[1] = dataIn;
dataIn >>=8;
msg.buf[0] = dataIn;
if ( 4 < msg.len ) {
dataIn = FLEXCAN0_MBn_WORD1(rxb);
msg.buf[7] = dataIn;
dataIn >>=8;
msg.buf[6] = dataIn;
dataIn >>=8;
msg.buf[5] = dataIn;
dataIn >>=8;
msg.buf[4] = dataIn;
}
for( int loop=msg.len; loop<8; ++loop ) {
msg.buf[loop] = 0;
}
//notify FIFO that message has been read
FLEXCAN0_IFLAG1 = FLEXCAN_IMASK1_BUF5M;
return 1;
}
// -------------------------------------------------------------
int FlexCAN::write(const CAN_message_t &msg)
{
unsigned long int startMillis;
startMillis = msg.timeout? millis() : 0;
// find an available buffer
int buffer = -1;
for ( int index = txb; ; ) {
if ((FLEXCAN0_MBn_CS(index) & FLEXCAN_MB_CS_CODE_MASK) == FLEXCAN_MB_CS_CODE(FLEXCAN_MB_CODE_TX_INACTIVE)) {
buffer = index;
break;// found one
}
if ( !msg.timeout ) {
if ( ++index >= (txb+txBuffers) ) {
return 0;// early EXIT no buffers available
}
} else {
// blocking mode, only 1 txb used to guarantee frames in order
if ( msg.timeout <= (millis()-startMillis) ) {
return 0;// timed out
}
yield();
}
}
// transmit the frame
FLEXCAN0_MBn_CS(buffer) = FLEXCAN_MB_CS_CODE(FLEXCAN_MB_CODE_TX_INACTIVE);
if(msg.ext) {
FLEXCAN0_MBn_ID(buffer) = (msg.id & FLEXCAN_MB_ID_EXT_MASK);
} else {
FLEXCAN0_MBn_ID(buffer) = FLEXCAN_MB_ID_IDSTD(msg.id);
}
FLEXCAN0_MBn_WORD0(buffer) = (msg.buf[0]<<24)|(msg.buf[1]<<16)|(msg.buf[2]<<8)|msg.buf[3];
FLEXCAN0_MBn_WORD1(buffer) = (msg.buf[4]<<24)|(msg.buf[5]<<16)|(msg.buf[6]<<8)|msg.buf[7];
if(msg.ext) {
FLEXCAN0_MBn_CS(buffer) = FLEXCAN_MB_CS_CODE(FLEXCAN_MB_CODE_TX_ONCE)
| FLEXCAN_MB_CS_LENGTH(msg.len) | FLEXCAN_MB_CS_SRR | FLEXCAN_MB_CS_IDE;
} else {
FLEXCAN0_MBn_CS(buffer) = FLEXCAN_MB_CS_CODE(FLEXCAN_MB_CODE_TX_ONCE)
| FLEXCAN_MB_CS_LENGTH(msg.len);
}
return 1;
}
<commit_msg>clock can from 16mhz xtal<commit_after>// -------------------------------------------------------------
// a simple Arduino Teensy3.1 CAN driver
// by teachop
//
#include "FlexCAN.h"
#include "kinetis_flexcan.h"
static const int txb = 8; // with default settings, all buffers before this are consumed by the FIFO
static const int txBuffers = 8;
static const int rxb = 0;
// -------------------------------------------------------------
FlexCAN::FlexCAN(uint32_t baud)
{
// set up the pins, 3=PTA12=CAN0_TX, 4=PTA13=CAN0_RX
CORE_PIN3_CONFIG = PORT_PCR_MUX(2);
CORE_PIN4_CONFIG = PORT_PCR_MUX(2);// | PORT_PCR_PE | PORT_PCR_PS;
// select clock source
OSC0_CR |= OSC_ERCLKEN;
SIM_SCGC6 |= SIM_SCGC6_FLEXCAN0;
FLEXCAN0_CTRL1 &= ~FLEXCAN_CTRL_CLK_SRC;
// enable CAN
FLEXCAN0_MCR |= FLEXCAN_MCR_FRZ;
FLEXCAN0_MCR &= ~FLEXCAN_MCR_MDIS;
while(FLEXCAN0_MCR & FLEXCAN_MCR_LPM_ACK)
;
// soft reset
FLEXCAN0_MCR ^= FLEXCAN_MCR_SOFT_RST;
while(FLEXCAN0_MCR & FLEXCAN_MCR_SOFT_RST)
;
// wait for freeze ack
while(!(FLEXCAN0_MCR & FLEXCAN_MCR_FRZ_ACK))
;
// disable self-reception
FLEXCAN0_MCR |= FLEXCAN_MCR_SRX_DIS;
//enable RX FIFO
FLEXCAN0_MCR |= FLEXCAN_MCR_FEN;
// segment timings from freescale loopback test
if ( 250000 == baud ) {
FLEXCAN0_CTRL1 = (FLEXCAN_CTRL_PROPSEG(2) | FLEXCAN_CTRL_RJW(1)
| FLEXCAN_CTRL_PSEG1(7) | FLEXCAN_CTRL_PSEG2(3) | FLEXCAN_CTRL_PRESDIV(3));
} else if ( 500000 == baud ) {
FLEXCAN0_CTRL1 = (FLEXCAN_CTRL_PROPSEG(2) | FLEXCAN_CTRL_RJW(1)
| FLEXCAN_CTRL_PSEG1(7) | FLEXCAN_CTRL_PSEG2(3) | FLEXCAN_CTRL_PRESDIV(1));
} else if ( 1000000 == baud ) {
FLEXCAN0_CTRL1 = (FLEXCAN_CTRL_PROPSEG(2) | FLEXCAN_CTRL_RJW(0)
| FLEXCAN_CTRL_PSEG1(1) | FLEXCAN_CTRL_PSEG2(1) | FLEXCAN_CTRL_PRESDIV(1));
} else { // 125000
FLEXCAN0_CTRL1 = (FLEXCAN_CTRL_PROPSEG(2) | FLEXCAN_CTRL_RJW(1)
| FLEXCAN_CTRL_PSEG1(7) | FLEXCAN_CTRL_PSEG2(3) | FLEXCAN_CTRL_PRESDIV(7));
}
// Default mask is allow everything
defaultMask.rtr = 0;
defaultMask.ext = 0;
defaultMask.id = 0;
}
// -------------------------------------------------------------
void FlexCAN::end(void)
{
// enter freeze mode
FLEXCAN0_MCR |= (FLEXCAN_MCR_HALT);
while(!(FLEXCAN0_MCR & FLEXCAN_MCR_FRZ_ACK))
;
}
// -------------------------------------------------------------
void FlexCAN::begin(const CAN_filter_t &mask)
{
FLEXCAN0_RXMGMASK = 0;
//enable reception of all messages that fit the mask
if (mask.ext) {
FLEXCAN0_RXFGMASK = ((mask.rtr?1:0) << 31) | ((mask.ext?1:0) << 30) | ((mask.id & FLEXCAN_MB_ID_EXT_MASK) << 1);
} else {
FLEXCAN0_RXFGMASK = ((mask.rtr?1:0) << 31) | ((mask.ext?1:0) << 30) | (FLEXCAN_MB_ID_IDSTD(mask.id) << 1);
}
// start the CAN
FLEXCAN0_MCR &= ~(FLEXCAN_MCR_HALT);
// wait till exit of freeze mode
while(FLEXCAN0_MCR & FLEXCAN_MCR_FRZ_ACK);
// wait till ready
while(FLEXCAN0_MCR & FLEXCAN_MCR_NOT_RDY);
//set tx buffers to inactive
for (int i = txb; i < txb + txBuffers; i++) {
FLEXCAN0_MBn_CS(i) = FLEXCAN_MB_CS_CODE(FLEXCAN_MB_CODE_TX_INACTIVE);
}
}
// -------------------------------------------------------------
void FlexCAN::setFilter(const CAN_filter_t &filter, uint8_t n)
{
if ( 8 > n ) {
if (filter.ext) {
FLEXCAN0_IDFLT_TAB(n) = ((filter.rtr?1:0) << 31) | ((filter.ext?1:0) << 30) | ((filter.id & FLEXCAN_MB_ID_EXT_MASK) << 1);
} else {
FLEXCAN0_IDFLT_TAB(n) = ((filter.rtr?1:0) << 31) | ((filter.ext?1:0) << 30) | (FLEXCAN_MB_ID_IDSTD(filter.id) << 1);
}
}
}
// -------------------------------------------------------------
int FlexCAN::available(void)
{
//In FIFO mode, the following interrupt flag signals availability of a frame
return (FLEXCAN0_IFLAG1 & FLEXCAN_IMASK1_BUF5M)? 1:0;
}
// -------------------------------------------------------------
int FlexCAN::read(CAN_message_t &msg)
{
unsigned long int startMillis;
startMillis = msg.timeout? millis() : 0;
while( !available() ) {
if ( !msg.timeout || (msg.timeout<=(millis()-startMillis)) ) {
// early EXIT nothing here
return 0;
}
yield();
}
// get identifier and dlc
msg.len = FLEXCAN_get_length(FLEXCAN0_MBn_CS(rxb));
msg.ext = (FLEXCAN0_MBn_CS(rxb) & FLEXCAN_MB_CS_IDE)? 1:0;
msg.id = (FLEXCAN0_MBn_ID(rxb) & FLEXCAN_MB_ID_EXT_MASK);
if(!msg.ext) {
msg.id >>= FLEXCAN_MB_ID_STD_BIT_NO;
}
// copy out message
uint32_t dataIn = FLEXCAN0_MBn_WORD0(rxb);
msg.buf[3] = dataIn;
dataIn >>=8;
msg.buf[2] = dataIn;
dataIn >>=8;
msg.buf[1] = dataIn;
dataIn >>=8;
msg.buf[0] = dataIn;
if ( 4 < msg.len ) {
dataIn = FLEXCAN0_MBn_WORD1(rxb);
msg.buf[7] = dataIn;
dataIn >>=8;
msg.buf[6] = dataIn;
dataIn >>=8;
msg.buf[5] = dataIn;
dataIn >>=8;
msg.buf[4] = dataIn;
}
for( int loop=msg.len; loop<8; ++loop ) {
msg.buf[loop] = 0;
}
//notify FIFO that message has been read
FLEXCAN0_IFLAG1 = FLEXCAN_IMASK1_BUF5M;
return 1;
}
// -------------------------------------------------------------
int FlexCAN::write(const CAN_message_t &msg)
{
unsigned long int startMillis;
startMillis = msg.timeout? millis() : 0;
// find an available buffer
int buffer = -1;
for ( int index = txb; ; ) {
if ((FLEXCAN0_MBn_CS(index) & FLEXCAN_MB_CS_CODE_MASK) == FLEXCAN_MB_CS_CODE(FLEXCAN_MB_CODE_TX_INACTIVE)) {
buffer = index;
break;// found one
}
if ( !msg.timeout ) {
if ( ++index >= (txb+txBuffers) ) {
return 0;// early EXIT no buffers available
}
} else {
// blocking mode, only 1 txb used to guarantee frames in order
if ( msg.timeout <= (millis()-startMillis) ) {
return 0;// timed out
}
yield();
}
}
// transmit the frame
FLEXCAN0_MBn_CS(buffer) = FLEXCAN_MB_CS_CODE(FLEXCAN_MB_CODE_TX_INACTIVE);
if(msg.ext) {
FLEXCAN0_MBn_ID(buffer) = (msg.id & FLEXCAN_MB_ID_EXT_MASK);
} else {
FLEXCAN0_MBn_ID(buffer) = FLEXCAN_MB_ID_IDSTD(msg.id);
}
FLEXCAN0_MBn_WORD0(buffer) = (msg.buf[0]<<24)|(msg.buf[1]<<16)|(msg.buf[2]<<8)|msg.buf[3];
FLEXCAN0_MBn_WORD1(buffer) = (msg.buf[4]<<24)|(msg.buf[5]<<16)|(msg.buf[6]<<8)|msg.buf[7];
if(msg.ext) {
FLEXCAN0_MBn_CS(buffer) = FLEXCAN_MB_CS_CODE(FLEXCAN_MB_CODE_TX_ONCE)
| FLEXCAN_MB_CS_LENGTH(msg.len) | FLEXCAN_MB_CS_SRR | FLEXCAN_MB_CS_IDE;
} else {
FLEXCAN0_MBn_CS(buffer) = FLEXCAN_MB_CS_CODE(FLEXCAN_MB_CODE_TX_ONCE)
| FLEXCAN_MB_CS_LENGTH(msg.len);
}
return 1;
}
<|endoftext|> |
<commit_before>// Copyright 2014 MongoDB Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "catch.hpp"
#include "helpers.hpp"
#include <mongocxx/test_util/client_helpers.hh>
#include <mongocxx/database.hpp>
#include <bsoncxx/builder/stream/helpers.hpp>
#include <mongocxx/client.hpp>
#include <mongocxx/exception/logic_error.hpp>
#include <mongocxx/instance.hpp>
#include <mongocxx/options/modify_collection.hpp>
#include <mongocxx/private/libmongoc.hh>
#include <mongocxx/private/libbson.hh>
#include <mongocxx/validation_criteria.hpp>
using namespace mongocxx;
using bsoncxx::builder::stream::close_document;
using bsoncxx::builder::stream::document;
using bsoncxx::builder::stream::finalize;
using bsoncxx::builder::stream::open_document;
TEST_CASE("A default constructed database is false-ish", "[database]") {
instance::current();
database d;
REQUIRE(!d);
}
TEST_CASE("A default constructed database cannot perform operations", "[database]") {
instance::current();
database d;
REQUIRE_THROWS_AS(d.name(), mongocxx::logic_error);
}
TEST_CASE("database copy", "[database]") {
instance::current();
client mongodb_client{uri{}};
std::string dbname{"foo"};
std::string dbname2{"bar"};
database db = mongodb_client[dbname];
database db2{db};
database db3 = mongodb_client[dbname2];
db3 = db;
REQUIRE(db2.name() == stdx::string_view{dbname});
REQUIRE(db3.name() == stdx::string_view{dbname});
}
TEST_CASE("A database", "[database]") {
stdx::string_view database_name{"database"};
MOCK_CLIENT
MOCK_DATABASE
instance::current();
client mongo_client{uri{}};
SECTION("is created by a client") {
bool called = false;
get_database->interpose([&](mongoc_client_t*, const char* d_name) {
called = true;
REQUIRE(database_name == stdx::string_view{d_name});
return nullptr;
});
database obtained_database = mongo_client[database_name];
REQUIRE(obtained_database);
REQUIRE(called);
REQUIRE(obtained_database.name() == database_name);
}
SECTION("cleans up its underlying mongoc database on destruction") {
bool destroy_called = false;
database_destroy->interpose([&](mongoc_database_t*) { destroy_called = true; });
{
database database = mongo_client["database"];
REQUIRE(!destroy_called);
}
REQUIRE(destroy_called);
}
SECTION("is dropped") {
bool drop_called = false;
database_drop->interpose([&](mongoc_database_t*, bson_error_t*) {
drop_called = true;
return true;
});
database database = mongo_client["database"];
REQUIRE(!drop_called);
database.drop();
REQUIRE(drop_called);
}
SECTION("throws an exception when dropping causes an error") {
database_drop->interpose([&](mongoc_database_t*, bson_error_t* error) {
bson_set_error(error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG,
"expected error from mock");
return false;
});
database database = mongo_client["database"];
REQUIRE_THROWS(database.drop());
}
SECTION("throws an exception when has_collection causes an error") {
database_has_collection->interpose(
[](mongoc_database_t*, const char*, bson_error_t* error) {
bson_set_error(error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG,
"expected error from mock");
return false;
});
database database = mongo_client["database"];
REQUIRE_THROWS(database.has_collection("some_collection"));
}
SECTION("supports move operations") {
bool destroy_called = false;
database_destroy->interpose([&](mongoc_database_t*) { destroy_called = true; });
{
client mongo_client{uri{}};
database a = mongo_client[database_name];
database b{std::move(a)};
REQUIRE(!destroy_called);
database c = std::move(b);
REQUIRE(!destroy_called);
}
REQUIRE(destroy_called);
}
SECTION("Read Concern", "[database]") {
database mongo_database(mongo_client["database"]);
auto database_set_rc_called = false;
read_concern rc{};
rc.acknowledge_level(read_concern::level::k_majority);
database_set_read_concern->interpose(
[&database_set_rc_called](::mongoc_database_t*, const ::mongoc_read_concern_t* rc_t) {
REQUIRE(rc_t);
const auto result = libmongoc::read_concern_get_level(rc_t);
REQUIRE(result);
REQUIRE(strcmp(result, "majority") == 0);
database_set_rc_called = true;
});
mongo_database.read_concern(rc);
REQUIRE(database_set_rc_called);
}
SECTION("has a read preferences which may be set and obtained") {
bool destroy_called = false;
database_destroy->interpose([&](mongoc_database_t*) { destroy_called = true; });
database mongo_database(mongo_client["database"]);
read_preference preference{read_preference::read_mode::k_secondary_preferred};
auto deleter = [](mongoc_read_prefs_t* var) { mongoc_read_prefs_destroy(var); };
std::unique_ptr<mongoc_read_prefs_t, decltype(deleter)> saved_preference(nullptr, deleter);
bool called = false;
database_set_preference->interpose([&](mongoc_database_t*,
const mongoc_read_prefs_t* read_prefs) {
called = true;
saved_preference.reset(mongoc_read_prefs_copy(read_prefs));
REQUIRE(
mongoc_read_prefs_get_mode(read_prefs) ==
static_cast<mongoc_read_mode_t>(read_preference::read_mode::k_secondary_preferred));
});
database_get_preference->interpose([&](const mongoc_database_t*) {
return saved_preference.get();
}).forever();
mongo_database.read_preference(std::move(preference));
REQUIRE(called);
REQUIRE(read_preference::read_mode::k_secondary_preferred ==
mongo_database.read_preference().mode());
}
SECTION("has a write concern which may be set and obtained") {
bool destroy_called = false;
database_destroy->interpose([&](mongoc_database_t*) { destroy_called = true; });
database mongo_database(mongo_client[database_name]);
write_concern concern;
concern.majority(std::chrono::milliseconds(100));
mongoc_write_concern_t* underlying_wc;
bool set_called = false;
database_set_concern->interpose(
[&](mongoc_database_t*, const mongoc_write_concern_t* concern) {
set_called = true;
underlying_wc = mongoc_write_concern_copy(concern);
});
bool get_called = false;
database_get_concern->interpose([&](const mongoc_database_t*) {
get_called = true;
return underlying_wc;
});
mongo_database.write_concern(concern);
REQUIRE(set_called);
MOCK_CONCERN
bool copy_called = false;
concern_copy->interpose([&](const mongoc_write_concern_t*) {
copy_called = true;
return mongoc_write_concern_copy(underlying_wc);
});
REQUIRE(concern.majority() == mongo_database.write_concern().majority());
REQUIRE(get_called);
REQUIRE(copy_called);
libmongoc::write_concern_destroy(underlying_wc);
}
SECTION("may create a collection") {
MOCK_COLLECTION
stdx::string_view collection_name{"dummy_collection"};
database database = mongo_client[database_name];
collection obtained_collection = database[collection_name];
REQUIRE(obtained_collection.name() == collection_name);
}
SECTION("supports run_command") {
bool called = false;
bsoncxx::document::value doc = bsoncxx::builder::stream::document{}
<< "foo" << 5 << bsoncxx::builder::stream::finalize;
libbson::scoped_bson_t bson_doc{doc.view()};
database_command_simple->interpose([&](mongoc_database_t*, const bson_t*,
const mongoc_read_prefs_t*, bson_t* reply,
bson_error_t*) {
called = true;
::bson_copy_to(bson_doc.bson(), reply);
return true;
});
database database = mongo_client[database_name];
bsoncxx::document::value command = bsoncxx::builder::stream::document{}
<< "command" << 1 << bsoncxx::builder::stream::finalize;
auto response = database.run_command(command.view());
REQUIRE(called);
REQUIRE(response.view()["foo"].get_int32() == 5);
}
}
TEST_CASE("Database integration tests", "[database]") {
instance::current();
client mongo_client{uri{}};
stdx::string_view database_name{"database"};
database database = mongo_client[database_name];
stdx::string_view collection_name{"collection"};
SECTION("A database may create a collection via create_collection") {
SECTION("without any options") {
database[collection_name].drop();
collection obtained_collection = database.create_collection(collection_name);
REQUIRE(obtained_collection.name() == collection_name);
}
SECTION("with options") {
database[collection_name].drop();
options::create_collection opts;
opts.capped(true);
opts.size(256);
opts.max(100);
opts.no_padding(false);
collection obtained_collection = database.create_collection(collection_name, opts);
REQUIRE(obtained_collection.name() == collection_name);
}
SECTION("but raises exception when collection already exists") {
database[collection_name].drop();
database.create_collection(collection_name);
REQUIRE_THROWS(database.create_collection(collection_name));
}
database[collection_name].drop();
}
SECTION("A collection may be modified via modify_collection") {
database.create_collection(collection_name);
auto rule = document{} << "email" << open_document << "$exists"
<< "true" << close_document << finalize;
validation_criteria criteria;
criteria.rule(rule.view());
options::modify_collection opts;
opts.validation_criteria(criteria);
auto res = database.modify_collection(collection_name, opts);
auto cursor = database.list_collections();
for (auto&& coll : cursor) {
if (coll["name"].get_utf8().value == collection_name) {
REQUIRE(coll["options"]["validator"].get_document().value == rule);
}
}
}
SECTION("A database may be dropped") {
database[collection_name].drop();
database.create_collection(collection_name);
REQUIRE(database.has_collection(collection_name));
database.drop();
REQUIRE(!database.has_collection(collection_name));
}
SECTION("read_concern is inherited from parent", "[database]") {
read_concern::level majority = read_concern::level::k_majority;
read_concern::level local = read_concern::level::k_local;
read_concern rc{};
rc.acknowledge_level(majority);
mongo_client.read_concern(rc);
mongocxx::database rc_db = mongo_client[database_name];
SECTION("when parent is a client") {
REQUIRE(rc_db.read_concern().acknowledge_level() == majority);
}
SECTION("except when read_concern is explicitly set") {
read_concern set_rc{};
set_rc.acknowledge_level(read_concern::level::k_local);
rc_db.read_concern(set_rc);
REQUIRE(rc_db.read_concern().acknowledge_level() == local);
}
}
SECTION("A view can be created on a database", "[database]") {
database[collection_name].drop();
database["view"].drop();
database[collection_name].insert_one({});
database[collection_name].insert_one({});
collection view =
database.create_view("view", collection_name,
options::create_view().pipeline(std::move(pipeline({}).limit(1))));
if (test_util::get_max_wire_version(mongo_client) >= 5) {
// The server supports views.
REQUIRE(view.count(bsoncxx::document::view{}) == 1);
} else {
// The server doesn't support views. On these versions of the server, view creation
// requests are treated as ordinary collection creation requests.
REQUIRE(view.count(bsoncxx::document::view{}) == 0);
}
}
}
<commit_msg>CXX-971 "Database integration tests": drop collection at section start<commit_after>// Copyright 2014 MongoDB Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "catch.hpp"
#include "helpers.hpp"
#include <mongocxx/test_util/client_helpers.hh>
#include <mongocxx/database.hpp>
#include <bsoncxx/builder/stream/helpers.hpp>
#include <mongocxx/client.hpp>
#include <mongocxx/exception/logic_error.hpp>
#include <mongocxx/instance.hpp>
#include <mongocxx/options/modify_collection.hpp>
#include <mongocxx/private/libmongoc.hh>
#include <mongocxx/private/libbson.hh>
#include <mongocxx/validation_criteria.hpp>
using namespace mongocxx;
using bsoncxx::builder::stream::close_document;
using bsoncxx::builder::stream::document;
using bsoncxx::builder::stream::finalize;
using bsoncxx::builder::stream::open_document;
TEST_CASE("A default constructed database is false-ish", "[database]") {
instance::current();
database d;
REQUIRE(!d);
}
TEST_CASE("A default constructed database cannot perform operations", "[database]") {
instance::current();
database d;
REQUIRE_THROWS_AS(d.name(), mongocxx::logic_error);
}
TEST_CASE("database copy", "[database]") {
instance::current();
client mongodb_client{uri{}};
std::string dbname{"foo"};
std::string dbname2{"bar"};
database db = mongodb_client[dbname];
database db2{db};
database db3 = mongodb_client[dbname2];
db3 = db;
REQUIRE(db2.name() == stdx::string_view{dbname});
REQUIRE(db3.name() == stdx::string_view{dbname});
}
TEST_CASE("A database", "[database]") {
stdx::string_view database_name{"database"};
MOCK_CLIENT
MOCK_DATABASE
instance::current();
client mongo_client{uri{}};
SECTION("is created by a client") {
bool called = false;
get_database->interpose([&](mongoc_client_t*, const char* d_name) {
called = true;
REQUIRE(database_name == stdx::string_view{d_name});
return nullptr;
});
database obtained_database = mongo_client[database_name];
REQUIRE(obtained_database);
REQUIRE(called);
REQUIRE(obtained_database.name() == database_name);
}
SECTION("cleans up its underlying mongoc database on destruction") {
bool destroy_called = false;
database_destroy->interpose([&](mongoc_database_t*) { destroy_called = true; });
{
database database = mongo_client["database"];
REQUIRE(!destroy_called);
}
REQUIRE(destroy_called);
}
SECTION("is dropped") {
bool drop_called = false;
database_drop->interpose([&](mongoc_database_t*, bson_error_t*) {
drop_called = true;
return true;
});
database database = mongo_client["database"];
REQUIRE(!drop_called);
database.drop();
REQUIRE(drop_called);
}
SECTION("throws an exception when dropping causes an error") {
database_drop->interpose([&](mongoc_database_t*, bson_error_t* error) {
bson_set_error(error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG,
"expected error from mock");
return false;
});
database database = mongo_client["database"];
REQUIRE_THROWS(database.drop());
}
SECTION("throws an exception when has_collection causes an error") {
database_has_collection->interpose(
[](mongoc_database_t*, const char*, bson_error_t* error) {
bson_set_error(error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG,
"expected error from mock");
return false;
});
database database = mongo_client["database"];
REQUIRE_THROWS(database.has_collection("some_collection"));
}
SECTION("supports move operations") {
bool destroy_called = false;
database_destroy->interpose([&](mongoc_database_t*) { destroy_called = true; });
{
client mongo_client{uri{}};
database a = mongo_client[database_name];
database b{std::move(a)};
REQUIRE(!destroy_called);
database c = std::move(b);
REQUIRE(!destroy_called);
}
REQUIRE(destroy_called);
}
SECTION("Read Concern", "[database]") {
database mongo_database(mongo_client["database"]);
auto database_set_rc_called = false;
read_concern rc{};
rc.acknowledge_level(read_concern::level::k_majority);
database_set_read_concern->interpose(
[&database_set_rc_called](::mongoc_database_t*, const ::mongoc_read_concern_t* rc_t) {
REQUIRE(rc_t);
const auto result = libmongoc::read_concern_get_level(rc_t);
REQUIRE(result);
REQUIRE(strcmp(result, "majority") == 0);
database_set_rc_called = true;
});
mongo_database.read_concern(rc);
REQUIRE(database_set_rc_called);
}
SECTION("has a read preferences which may be set and obtained") {
bool destroy_called = false;
database_destroy->interpose([&](mongoc_database_t*) { destroy_called = true; });
database mongo_database(mongo_client["database"]);
read_preference preference{read_preference::read_mode::k_secondary_preferred};
auto deleter = [](mongoc_read_prefs_t* var) { mongoc_read_prefs_destroy(var); };
std::unique_ptr<mongoc_read_prefs_t, decltype(deleter)> saved_preference(nullptr, deleter);
bool called = false;
database_set_preference->interpose([&](mongoc_database_t*,
const mongoc_read_prefs_t* read_prefs) {
called = true;
saved_preference.reset(mongoc_read_prefs_copy(read_prefs));
REQUIRE(
mongoc_read_prefs_get_mode(read_prefs) ==
static_cast<mongoc_read_mode_t>(read_preference::read_mode::k_secondary_preferred));
});
database_get_preference->interpose([&](const mongoc_database_t*) {
return saved_preference.get();
}).forever();
mongo_database.read_preference(std::move(preference));
REQUIRE(called);
REQUIRE(read_preference::read_mode::k_secondary_preferred ==
mongo_database.read_preference().mode());
}
SECTION("has a write concern which may be set and obtained") {
bool destroy_called = false;
database_destroy->interpose([&](mongoc_database_t*) { destroy_called = true; });
database mongo_database(mongo_client[database_name]);
write_concern concern;
concern.majority(std::chrono::milliseconds(100));
mongoc_write_concern_t* underlying_wc;
bool set_called = false;
database_set_concern->interpose(
[&](mongoc_database_t*, const mongoc_write_concern_t* concern) {
set_called = true;
underlying_wc = mongoc_write_concern_copy(concern);
});
bool get_called = false;
database_get_concern->interpose([&](const mongoc_database_t*) {
get_called = true;
return underlying_wc;
});
mongo_database.write_concern(concern);
REQUIRE(set_called);
MOCK_CONCERN
bool copy_called = false;
concern_copy->interpose([&](const mongoc_write_concern_t*) {
copy_called = true;
return mongoc_write_concern_copy(underlying_wc);
});
REQUIRE(concern.majority() == mongo_database.write_concern().majority());
REQUIRE(get_called);
REQUIRE(copy_called);
libmongoc::write_concern_destroy(underlying_wc);
}
SECTION("may create a collection") {
MOCK_COLLECTION
stdx::string_view collection_name{"dummy_collection"};
database database = mongo_client[database_name];
collection obtained_collection = database[collection_name];
REQUIRE(obtained_collection.name() == collection_name);
}
SECTION("supports run_command") {
bool called = false;
bsoncxx::document::value doc = bsoncxx::builder::stream::document{}
<< "foo" << 5 << bsoncxx::builder::stream::finalize;
libbson::scoped_bson_t bson_doc{doc.view()};
database_command_simple->interpose([&](mongoc_database_t*, const bson_t*,
const mongoc_read_prefs_t*, bson_t* reply,
bson_error_t*) {
called = true;
::bson_copy_to(bson_doc.bson(), reply);
return true;
});
database database = mongo_client[database_name];
bsoncxx::document::value command = bsoncxx::builder::stream::document{}
<< "command" << 1 << bsoncxx::builder::stream::finalize;
auto response = database.run_command(command.view());
REQUIRE(called);
REQUIRE(response.view()["foo"].get_int32() == 5);
}
}
TEST_CASE("Database integration tests", "[database]") {
instance::current();
client mongo_client{uri{}};
stdx::string_view database_name{"database"};
database database = mongo_client[database_name];
stdx::string_view collection_name{"collection"};
SECTION("A database may create a collection via create_collection") {
database[collection_name].drop();
SECTION("without any options") {
collection obtained_collection = database.create_collection(collection_name);
REQUIRE(obtained_collection.name() == collection_name);
}
SECTION("with options") {
options::create_collection opts;
opts.capped(true);
opts.size(256);
opts.max(100);
opts.no_padding(false);
collection obtained_collection = database.create_collection(collection_name, opts);
REQUIRE(obtained_collection.name() == collection_name);
}
SECTION("but raises exception when collection already exists") {
database.create_collection(collection_name);
REQUIRE_THROWS(database.create_collection(collection_name));
}
}
SECTION("A collection may be modified via modify_collection") {
database[collection_name].drop();
database.create_collection(collection_name);
auto rule = document{} << "email" << open_document << "$exists"
<< "true" << close_document << finalize;
validation_criteria criteria;
criteria.rule(rule.view());
options::modify_collection opts;
opts.validation_criteria(criteria);
auto res = database.modify_collection(collection_name, opts);
auto cursor = database.list_collections();
for (auto&& coll : cursor) {
if (coll["name"].get_utf8().value == collection_name) {
REQUIRE(coll["options"]["validator"].get_document().value == rule);
}
}
}
SECTION("A database may be dropped") {
database[collection_name].drop();
database.create_collection(collection_name);
REQUIRE(database.has_collection(collection_name));
database.drop();
REQUIRE(!database.has_collection(collection_name));
}
SECTION("read_concern is inherited from parent", "[database]") {
read_concern::level majority = read_concern::level::k_majority;
read_concern::level local = read_concern::level::k_local;
read_concern rc{};
rc.acknowledge_level(majority);
mongo_client.read_concern(rc);
mongocxx::database rc_db = mongo_client[database_name];
SECTION("when parent is a client") {
REQUIRE(rc_db.read_concern().acknowledge_level() == majority);
}
SECTION("except when read_concern is explicitly set") {
read_concern set_rc{};
set_rc.acknowledge_level(read_concern::level::k_local);
rc_db.read_concern(set_rc);
REQUIRE(rc_db.read_concern().acknowledge_level() == local);
}
}
SECTION("A view can be created on a database", "[database]") {
database[collection_name].drop();
database["view"].drop();
database[collection_name].insert_one({});
database[collection_name].insert_one({});
collection view =
database.create_view("view", collection_name,
options::create_view().pipeline(std::move(pipeline({}).limit(1))));
if (test_util::get_max_wire_version(mongo_client) >= 5) {
// The server supports views.
REQUIRE(view.count(bsoncxx::document::view{}) == 1);
} else {
// The server doesn't support views. On these versions of the server, view creation
// requests are treated as ordinary collection creation requests.
REQUIRE(view.count(bsoncxx::document::view{}) == 0);
}
}
}
<|endoftext|> |
<commit_before><commit_msg>Add columns to gtk task manager.<commit_after><|endoftext|> |
<commit_before>#include <iostream>
#include <sstream>
#include <map>
//#include <queue>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
struct index_sort {
bool operator()(pair<string, unsigned int> const & a, pair<string, unsigned int> const & b) {
return a.second > b.second; // sort by frequencies
}
};
typedef vector< pair<string, unsigned int> > URLheap;
int main(int argc, char *argv[]) {
string url_line;
string url;
string word;
istringstream ss;
map<string, URLheap > indexer;
map<string, unsigned int> frequency;
while (!cin.eof()) {
// get url followed by all the words
getline(cin, url_line);
ss.str(url_line);
ss >> url;
URLheap heap; // adding on to same heap, this is a problem, might need new pointer
indexer[url] = heap;
while (ss >> word) {
// count the frequency of each word
if (frequency.find(word) == frequency.end()) {
frequency[word] = 1;
} else {
frequency[word] += 1;
}
}
// add those frequency pairs to the url indexer
for (auto it = frequency.begin(); it != frequency.end(); it++) {
indexer[url].push_back(*it);
push_heap(indexer[url].begin(), indexer[url].end(), index_sort());
}
url_line.clear();
ss.clear();
//url.clear();
}
//Test prints
for (auto it = indexer.begin(); it != indexer.end(); it++) {
cout << it->first << endl;
for (auto jt = it->second.begin(); jt != it->second.end(); jt++) {
cout << jt->first << ": " << jt->second << " ";
}
cout << endl;
}
return 0;
}
//make_map() { }
//
//reduce_map() { }
<commit_msg>Cannot get it to print the second url yet, but seems to work<commit_after>#include <iostream>
#include <sstream>
#include <map>
//#include <queue>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
struct index_sort {
bool operator()(pair<string, unsigned int> const & a, pair<string, unsigned int> const & b) {
return a.second > b.second; // sort by frequencies
}
};
typedef vector< pair<string, unsigned int> > URLheap;
int main(int argc, char *argv[]) {
string url_line;
string url;
string word;
istringstream ss;
map<string, URLheap > indexer;
map<string, unsigned int> frequency;
while (!cin.eof()) {
// get url followed by all the words
getline(cin, url_line);
ss.str(url_line);
ss >> url;
URLheap heap; // adding on to same heap, this is a problem, might need new pointer
indexer[url] = heap;
while (ss >> word) {
// count the frequency of each word
cout << word;
if (frequency.find(word) == frequency.end()) {
frequency[word] = 1;
} else {
frequency[word] += 1;
}
cout << frequency[word];
}
// add those frequency pairs to the url indexer
for (auto it = frequency.begin(); it != frequency.end(); it++) {
indexer[url].push_back(*it);
push_heap(indexer[url].begin(), indexer[url].end(), index_sort());
}
url_line.clear();
ss.clear();
frequency.clear();
}
//Test prints
for (auto it = indexer.begin(); it != indexer.end(); it++) {
cout << it->first << endl;
for (auto jt = it->second.begin(); jt != it->second.end(); jt++) {
cout << jt->first << ": " << jt->second << " ";
}
cout << endl;
}
return 0;
}
//make_map() { }
//
//reduce_map() { }
<|endoftext|> |
<commit_before>#include "Manager.h"
#include <QDebug>
#include <QMenu>
#include <QApplication>
#include <QDesktopWidget>
#include <QScreen>
#include <QThread>
#include <QSettings>
#include <QClipboard>
#include <QMessageBox>
#include "Settings.h"
#include "SettingsEditor.h"
#include "SelectionDialog.h"
#include "GlobalActionHelper.h"
#include "Recognizer.h"
#include "Translator.h"
#include "ResultDialog.h"
#include "LanguageHelper.h"
Manager::Manager(QObject *parent) :
QObject(parent),
trayIcon_ (new QSystemTrayIcon (QIcon (":/images/icon.png"), this)),
dictionary_ (new LanguageHelper),
selection_ (new SelectionDialog (*dictionary_)),
resultDialog_ (new ResultDialog),
captureAction_ (NULL), repeatAction_ (NULL), clipboardAction_ (NULL),
useResultDialog_ (true)
{
GlobalActionHelper::init ();
qRegisterMetaType<ProcessingItem>();
// Recognizer
Recognizer* recognizer = new Recognizer;
connect (selection_, SIGNAL (selected (ProcessingItem)),
recognizer, SLOT (recognize (ProcessingItem)));
connect (recognizer, SIGNAL (error (QString)),
SLOT (showError (QString)));
connect (this, SIGNAL (settingsEdited ()),
recognizer, SLOT (applySettings ()));
QThread* recognizerThread = new QThread (this);
recognizer->moveToThread (recognizerThread);
recognizerThread->start ();
// Translator
Translator* translator = new Translator;
connect (recognizer, SIGNAL (recognized (ProcessingItem)),
translator, SLOT (translate (ProcessingItem)));
connect (translator, SIGNAL (error (QString)),
SLOT (showError (QString)));
connect (this, SIGNAL (settingsEdited ()),
translator, SLOT (applySettings ()));
QThread* translatorThread = new QThread (this);
translator->moveToThread (translatorThread);
translatorThread->start ();
connect (translator, SIGNAL (translated (ProcessingItem)),
SLOT (showResult (ProcessingItem)));
connect (this, SIGNAL (showPixmap (QPixmap)),
selection_, SLOT (setPixmap (QPixmap)));
connect (this, SIGNAL (settingsEdited ()), selection_, SLOT (updateMenu ()));
connect (this, SIGNAL (settingsEdited ()), this, SLOT (applySettings ()));
selection_->setWindowIcon (trayIcon_->icon ());
resultDialog_->setWindowIcon (trayIcon_->icon ());
connect (trayIcon_, SIGNAL (activated (QSystemTrayIcon::ActivationReason)),
SLOT (processTrayAction (QSystemTrayIcon::ActivationReason)));
trayIcon_->setContextMenu (trayContextMenu ());
trayIcon_->show ();
applySettings ();
}
QMenu*Manager::trayContextMenu()
{
QMenu* menu = new QMenu ();
captureAction_ = menu->addAction (tr ("Захват"), this, SLOT (capture ()));
QMenu* translateMenu = menu->addMenu (tr ("Перевод"));
repeatAction_ = translateMenu->addAction (tr ("Повторить"), this,
SLOT (showLast ()));
clipboardAction_ = translateMenu->addAction (tr ("Скопировать"), this,
SLOT (copyLastToClipboard ()));
menu->addAction (tr ("Настройки"), this, SLOT (settings ()));
menu->addAction (tr ("О программе"), this, SLOT (about ()));
menu->addAction (tr ("Выход"), this, SLOT (close ()));
return menu;
}
void Manager::applySettings()
{
QSettings settings;
settings.beginGroup (settings_names::guiGroup);
QString captureHotkey = settings.value (settings_names::captureHotkey,
settings_values::captureHotkey).toString ();
Q_CHECK_PTR (captureAction_);
GlobalActionHelper::removeGlobal (captureAction_);
captureAction_->setShortcut (captureHotkey);
GlobalActionHelper::makeGlobal (captureAction_);
QString repeatHotkey = settings.value (settings_names::repeatHotkey,
settings_values::repeatHotkey).toString ();
Q_CHECK_PTR (repeatAction_);
GlobalActionHelper::removeGlobal (repeatAction_);
repeatAction_->setShortcut (repeatHotkey);
GlobalActionHelper::makeGlobal (repeatAction_);
QString clipboardHotkey = settings.value (settings_names::clipboardHotkey,
settings_values::clipboardHotkey).toString ();
Q_CHECK_PTR (clipboardAction_);
GlobalActionHelper::removeGlobal (clipboardAction_);
clipboardAction_->setShortcut (clipboardHotkey);
GlobalActionHelper::makeGlobal (clipboardAction_);
// Depends on SettingsEditor button indexes. 1==dialog
useResultDialog_ = settings.value (settings_names::resultShowType,
settings_values::resultShowType).toBool ();
Q_CHECK_PTR (dictionary_);
dictionary_->updateAvailableOcrLanguages ();
}
Manager::~Manager()
{
}
void Manager::capture()
{
QList<QScreen*> screens = QApplication::screens ();
Q_ASSERT (!screens.isEmpty ());
QScreen* screen = screens.first ();
Q_CHECK_PTR (screen);
WId desktopId = QApplication::desktop ()->winId ();
QPixmap pixmap = screen->grabWindow (desktopId);
Q_ASSERT (!pixmap.isNull ());
emit showPixmap (pixmap);
}
void Manager::settings()
{
SettingsEditor editor (*dictionary_);
editor.setWindowIcon (trayIcon_->icon ());
connect (&editor, SIGNAL (settingsEdited ()), SIGNAL (settingsEdited ()));
editor.exec ();
}
void Manager::close()
{
QApplication::quit ();
}
void Manager::about()
{
QString text = tr ("Программа для распознавания текста на экране.\n"\
"Создана с использованием Qt, tesseract-ocr, Google Translate.\n"
"Автор: Gres (translator@gres.biz)");
QMessageBox message (QMessageBox::Information, tr ("О программе"), text,
QMessageBox::Ok);
message.setIconPixmap (trayIcon_->icon ().pixmap (QSize (64, 64)));
message.exec ();
}
void Manager::processTrayAction(QSystemTrayIcon::ActivationReason reason)
{
if (reason == QSystemTrayIcon::Trigger)
{
showLast ();
}
else if (reason == QSystemTrayIcon::MiddleClick)
{
copyLastToClipboard ();
}
}
void Manager::showLast()
{
if (lastItem_.isValid ())
{
showResult (lastItem_);
}
}
void Manager::copyLastToClipboard()
{
if (lastItem_.isValid ())
{
QClipboard* clipboard = QApplication::clipboard ();
QString message = lastItem_.recognized + " - " + lastItem_.translated;
clipboard->setText (message);
trayIcon_->showMessage (tr ("Перевод"),
tr ("Последний перевод был скопирован в буфер обмена."),
QSystemTrayIcon::Information);
}
}
void Manager::showResult(ProcessingItem item)
{
Q_ASSERT (item.isValid ());
lastItem_ = item;
if (useResultDialog_)
{
resultDialog_->showResult (item);
}
else
{
QString message = item.recognized + " - " + item.translated;
trayIcon_->showMessage (tr ("Перевод"), message, QSystemTrayIcon::Information);
}
}
void Manager::showError(QString text)
{
qCritical () << text;
trayIcon_->showMessage (tr ("Ошибка"), text, QSystemTrayIcon::Critical);
}
<commit_msg>trying to quit threads on quit<commit_after>#include "Manager.h"
#include <QDebug>
#include <QMenu>
#include <QApplication>
#include <QDesktopWidget>
#include <QScreen>
#include <QThread>
#include <QSettings>
#include <QClipboard>
#include <QMessageBox>
#include "Settings.h"
#include "SettingsEditor.h"
#include "SelectionDialog.h"
#include "GlobalActionHelper.h"
#include "Recognizer.h"
#include "Translator.h"
#include "ResultDialog.h"
#include "LanguageHelper.h"
Manager::Manager(QObject *parent) :
QObject(parent),
trayIcon_ (new QSystemTrayIcon (QIcon (":/images/icon.png"), this)),
dictionary_ (new LanguageHelper),
selection_ (new SelectionDialog (*dictionary_)),
resultDialog_ (new ResultDialog),
captureAction_ (NULL), repeatAction_ (NULL), clipboardAction_ (NULL),
useResultDialog_ (true)
{
GlobalActionHelper::init ();
qRegisterMetaType<ProcessingItem>();
// Recognizer
Recognizer* recognizer = new Recognizer;
connect (selection_, SIGNAL (selected (ProcessingItem)),
recognizer, SLOT (recognize (ProcessingItem)));
connect (recognizer, SIGNAL (error (QString)),
SLOT (showError (QString)));
connect (this, SIGNAL (settingsEdited ()),
recognizer, SLOT (applySettings ()));
QThread* recognizerThread = new QThread (this);
recognizer->moveToThread (recognizerThread);
recognizerThread->start ();
connect (qApp, SIGNAL (aboutToQuit ()), recognizerThread, SLOT (quit ()));
// Translator
Translator* translator = new Translator;
connect (recognizer, SIGNAL (recognized (ProcessingItem)),
translator, SLOT (translate (ProcessingItem)));
connect (translator, SIGNAL (error (QString)),
SLOT (showError (QString)));
connect (this, SIGNAL (settingsEdited ()),
translator, SLOT (applySettings ()));
QThread* translatorThread = new QThread (this);
translator->moveToThread (translatorThread);
translatorThread->start ();
connect (qApp, SIGNAL (aboutToQuit ()), translatorThread, SLOT (quit ()));
connect (translator, SIGNAL (translated (ProcessingItem)),
SLOT (showResult (ProcessingItem)));
connect (this, SIGNAL (showPixmap (QPixmap)),
selection_, SLOT (setPixmap (QPixmap)));
connect (this, SIGNAL (settingsEdited ()), selection_, SLOT (updateMenu ()));
connect (this, SIGNAL (settingsEdited ()), this, SLOT (applySettings ()));
selection_->setWindowIcon (trayIcon_->icon ());
resultDialog_->setWindowIcon (trayIcon_->icon ());
connect (trayIcon_, SIGNAL (activated (QSystemTrayIcon::ActivationReason)),
SLOT (processTrayAction (QSystemTrayIcon::ActivationReason)));
trayIcon_->setContextMenu (trayContextMenu ());
trayIcon_->show ();
applySettings ();
}
QMenu*Manager::trayContextMenu()
{
QMenu* menu = new QMenu ();
captureAction_ = menu->addAction (tr ("Захват"), this, SLOT (capture ()));
QMenu* translateMenu = menu->addMenu (tr ("Перевод"));
repeatAction_ = translateMenu->addAction (tr ("Повторить"), this,
SLOT (showLast ()));
clipboardAction_ = translateMenu->addAction (tr ("Скопировать"), this,
SLOT (copyLastToClipboard ()));
menu->addAction (tr ("Настройки"), this, SLOT (settings ()));
menu->addAction (tr ("О программе"), this, SLOT (about ()));
menu->addAction (tr ("Выход"), this, SLOT (close ()));
return menu;
}
void Manager::applySettings()
{
QSettings settings;
settings.beginGroup (settings_names::guiGroup);
QString captureHotkey = settings.value (settings_names::captureHotkey,
settings_values::captureHotkey).toString ();
Q_CHECK_PTR (captureAction_);
GlobalActionHelper::removeGlobal (captureAction_);
captureAction_->setShortcut (captureHotkey);
GlobalActionHelper::makeGlobal (captureAction_);
QString repeatHotkey = settings.value (settings_names::repeatHotkey,
settings_values::repeatHotkey).toString ();
Q_CHECK_PTR (repeatAction_);
GlobalActionHelper::removeGlobal (repeatAction_);
repeatAction_->setShortcut (repeatHotkey);
GlobalActionHelper::makeGlobal (repeatAction_);
QString clipboardHotkey = settings.value (settings_names::clipboardHotkey,
settings_values::clipboardHotkey).toString ();
Q_CHECK_PTR (clipboardAction_);
GlobalActionHelper::removeGlobal (clipboardAction_);
clipboardAction_->setShortcut (clipboardHotkey);
GlobalActionHelper::makeGlobal (clipboardAction_);
// Depends on SettingsEditor button indexes. 1==dialog
useResultDialog_ = settings.value (settings_names::resultShowType,
settings_values::resultShowType).toBool ();
Q_CHECK_PTR (dictionary_);
dictionary_->updateAvailableOcrLanguages ();
}
Manager::~Manager()
{
}
void Manager::capture()
{
QList<QScreen*> screens = QApplication::screens ();
Q_ASSERT (!screens.isEmpty ());
QScreen* screen = screens.first ();
Q_CHECK_PTR (screen);
WId desktopId = QApplication::desktop ()->winId ();
QPixmap pixmap = screen->grabWindow (desktopId);
Q_ASSERT (!pixmap.isNull ());
emit showPixmap (pixmap);
}
void Manager::settings()
{
SettingsEditor editor (*dictionary_);
editor.setWindowIcon (trayIcon_->icon ());
connect (&editor, SIGNAL (settingsEdited ()), SIGNAL (settingsEdited ()));
editor.exec ();
}
void Manager::close()
{
QApplication::quit ();
}
void Manager::about()
{
QString text = tr ("Программа для распознавания текста на экране.\n"\
"Создана с использованием Qt, tesseract-ocr, Google Translate.\n"
"Автор: Gres (translator@gres.biz)");
QMessageBox message (QMessageBox::Information, tr ("О программе"), text,
QMessageBox::Ok);
message.setIconPixmap (trayIcon_->icon ().pixmap (QSize (64, 64)));
message.exec ();
}
void Manager::processTrayAction(QSystemTrayIcon::ActivationReason reason)
{
if (reason == QSystemTrayIcon::Trigger)
{
showLast ();
}
else if (reason == QSystemTrayIcon::MiddleClick)
{
copyLastToClipboard ();
}
}
void Manager::showLast()
{
if (lastItem_.isValid ())
{
showResult (lastItem_);
}
}
void Manager::copyLastToClipboard()
{
if (lastItem_.isValid ())
{
QClipboard* clipboard = QApplication::clipboard ();
QString message = lastItem_.recognized + " - " + lastItem_.translated;
clipboard->setText (message);
trayIcon_->showMessage (tr ("Перевод"),
tr ("Последний перевод был скопирован в буфер обмена."),
QSystemTrayIcon::Information);
}
}
void Manager::showResult(ProcessingItem item)
{
Q_ASSERT (item.isValid ());
lastItem_ = item;
if (useResultDialog_)
{
resultDialog_->showResult (item);
}
else
{
QString message = item.recognized + " - " + item.translated;
trayIcon_->showMessage (tr ("Перевод"), message, QSystemTrayIcon::Information);
}
}
void Manager::showError(QString text)
{
qCritical () << text;
trayIcon_->showMessage (tr ("Ошибка"), text, QSystemTrayIcon::Critical);
}
<|endoftext|> |
<commit_before>#include "vector.h"
#include "MinIMU9.h"
#include "exceptions.h"
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <wordexp.h>
MinIMU9::MinIMU9(const char * i2cDeviceName) :
compass(i2cDeviceName), gyro(i2cDeviceName)
{
}
void MinIMU9::checkConnection()
{
uint8_t result = compass.readMagReg(LSM303_WHO_AM_I_M);
if (result != 0x3C)
{
throw std::runtime_error("Error getting \"Who Am I\" register.\n");
}
}
void MinIMU9::enable()
{
compass.enable();
gyro.enable();
}
void MinIMU9::loadCalibration()
{
wordexp_t expansion_result;
wordexp("~/.minimu9-ahrs-cal", &expansion_result, 0);
std::ifstream file(expansion_result.we_wordv[0]);
if (file.fail())
{
throw posix_error("Failed to open calibration file ~/.minimu9-ahrs-cal.");
}
file >> mag_min(0) >> mag_max(0) >> mag_min(1) >> mag_max(1) >> mag_min(2) >> mag_max(2);
if (file.fail() || file.bad())
{
throw std::runtime_error("Failed to parse calibration file ~/.minimu9-ahrs-cal.");
}
}
void MinIMU9::measureOffsets()
{
// LSM303 accelerometer: 8 g sensitivity. 3.8 mg/digit; 1 g = 256.
// TODO: unify this with the other place in the code where we scale accelerometer readings.
gyro_offset = vector::Zero();
const int sampleCount = 32;
for(int i = 0; i < sampleCount; i++)
{
gyro.read();
gyro_offset += vector_from_ints(&gyro.g);
usleep(20*1000);
}
gyro_offset /= sampleCount;
}
vector MinIMU9::readMag()
{
compass.readMag();
IMU::raw_m = int_vector_from_ints(&compass.m);
vector v;
v(0) = (float)(compass.m[0] - mag_min(0)) / (mag_max(0) - mag_min(0)) * 2 - 1;
v(1) = (float)(compass.m[1] - mag_min(1)) / (mag_max(1) - mag_min(1)) * 2 - 1;
v(2) = (float)(compass.m[2] - mag_min(2)) / (mag_max(2) - mag_min(2)) * 2 - 1;
return v;
}
vector MinIMU9::readAcc()
{
// LSM303 accelerometer: At 8 g sensitivity, the datasheet says
// we get 3.9 mg/digit.
// TODO: double check this figure using the correct datasheet
const float accel_scale = 0.0039;
compass.readAcc();
IMU::raw_a = int_vector_from_ints(&compass.a);
return ( vector_from_ints(&compass.a) - accel_offset ) * accel_scale;
}
vector MinIMU9::readGyro()
{
// At the full-scale=2000 dps setting, the gyro datasheet says
// we get 0.07 dps/digit.
const float gyro_scale = 0.07 * 3.14159265 / 180;
gyro.read();
IMU::raw_g = int_vector_from_ints(&gyro.g);
return ( vector_from_ints(&gyro.g) - gyro_offset ) * gyro_scale;
}
<commit_msg>Got rid of one last use of accel_offset.<commit_after>#include "vector.h"
#include "MinIMU9.h"
#include "exceptions.h"
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <wordexp.h>
MinIMU9::MinIMU9(const char * i2cDeviceName) :
compass(i2cDeviceName), gyro(i2cDeviceName)
{
}
void MinIMU9::checkConnection()
{
uint8_t result = compass.readMagReg(LSM303_WHO_AM_I_M);
if (result != 0x3C)
{
throw std::runtime_error("Error getting \"Who Am I\" register.\n");
}
}
void MinIMU9::enable()
{
compass.enable();
gyro.enable();
}
void MinIMU9::loadCalibration()
{
wordexp_t expansion_result;
wordexp("~/.minimu9-ahrs-cal", &expansion_result, 0);
std::ifstream file(expansion_result.we_wordv[0]);
if (file.fail())
{
throw posix_error("Failed to open calibration file ~/.minimu9-ahrs-cal.");
}
file >> mag_min(0) >> mag_max(0) >> mag_min(1) >> mag_max(1) >> mag_min(2) >> mag_max(2);
if (file.fail() || file.bad())
{
throw std::runtime_error("Failed to parse calibration file ~/.minimu9-ahrs-cal.");
}
}
void MinIMU9::measureOffsets()
{
// LSM303 accelerometer: 8 g sensitivity. 3.8 mg/digit; 1 g = 256.
// TODO: unify this with the other place in the code where we scale accelerometer readings.
gyro_offset = vector::Zero();
const int sampleCount = 32;
for(int i = 0; i < sampleCount; i++)
{
gyro.read();
gyro_offset += vector_from_ints(&gyro.g);
usleep(20*1000);
}
gyro_offset /= sampleCount;
}
vector MinIMU9::readMag()
{
compass.readMag();
IMU::raw_m = int_vector_from_ints(&compass.m);
vector v;
v(0) = (float)(compass.m[0] - mag_min(0)) / (mag_max(0) - mag_min(0)) * 2 - 1;
v(1) = (float)(compass.m[1] - mag_min(1)) / (mag_max(1) - mag_min(1)) * 2 - 1;
v(2) = (float)(compass.m[2] - mag_min(2)) / (mag_max(2) - mag_min(2)) * 2 - 1;
return v;
}
vector MinIMU9::readAcc()
{
// LSM303 accelerometer: At 8 g sensitivity, the datasheet says
// we get 3.9 mg/digit.
// TODO: double check this figure using the correct datasheet
const float accel_scale = 0.0039;
compass.readAcc();
IMU::raw_a = int_vector_from_ints(&compass.a);
return vector_from_ints(&compass.a) * accel_scale;
}
vector MinIMU9::readGyro()
{
// At the full-scale=2000 dps setting, the gyro datasheet says
// we get 0.07 dps/digit.
const float gyro_scale = 0.07 * 3.14159265 / 180;
gyro.read();
IMU::raw_g = int_vector_from_ints(&gyro.g);
return ( vector_from_ints(&gyro.g) - gyro_offset ) * gyro_scale;
}
<|endoftext|> |
<commit_before>#include <cstdio>
#include <fstream>
#include <SDL2/SDL.h>
#include "PrjHndl.h"
#include "TxtRead.h"
#include "compression/KidDec.h"
#include "compression/ReadPlain.h"
#include "FW_KENSC/comper.h"
#include "FW_KENSC/enigma.h"
#include "FW_KENSC/kosinski.h"
#include "FW_KENSC/nemesis.h"
#include "FW_KENSC/saxman.h"
using namespace std;
#define FILE_MAP_DEFAULT "MapDefault.bin"
#define TYPE_AMOUNT 17
char infoTypes[TYPE_AMOUNT][32] = {
"Palette File:",
"Mapping File:",
"Art File:",
"Palette Offset:",
"Mapping Offset:",
"Art Offset:",
"Palette Length:",
"Mapping Length:",
"Art Length:",
"Mapping Compression:",
"Art Compression:",
"x-Size:",
"y-Size:",
"Tile Offset:",
"Letter Offset:",
"Number Offset:",
"Save File:"
};
static long ComprFunc(const fileCompression compression, const char* const srcfile, FILE* dst, long Pointer, int length)
{
switch (compression)
{
case NONE:
length = ReadPlain(srcfile, dst, Pointer, length);
break;
case KIDCHAMELEON:
length = KidDec(srcfile, dst, Pointer, length);
break;
}
return length;
}
static long ComprFunc(const fileCompression compression, istream &fin, iostream &fout, long Pointer, int length)
{
switch (compression)
{
case ENIGMA:
length = enigma::decode(fin, fout, Pointer, false);
break;
case KOSINSKI:
length = kosinski::decode(fin, fout, Pointer, false, 16u);
break;
case NEMESIS:
length = nemesis::decode(fin, fout, Pointer, 0);
break;
case COMPER:
length = comper::decode(fin, fout, Pointer);
break;
case SAXMAN:
length = saxman::decode(fin, fout, Pointer, 0);
break;
}
return length;
}
ProjectData::ProjectData(const char* const prjtxt) {
palOffset = mapOffset = artOffset = 0;
palLength = mapLength = artLength = 0;
mapCompr = artCompr = INVALID;
xSize = ySize = 0;
tileOffset = 0;
letterOffset = 0; numberOffset = 0;
strcpy(saveName, "");
FILE* prjfile = fopen(prjtxt, "r");
if (prjfile == NULL) {
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", "Please drag and drop your project file onto this program to start it.", NULL);
exit(1);
}
while (!feof(prjfile)) {
char line[256];
fgets(line, 256, prjfile);
for (int type=0; type < TYPE_AMOUNT; ++type) {
char* content = strsrch(line, infoTypes[type]);
if (content != NULL) AssignInfo(type, content);
}
}
}
void ProjectData::AssignInfo(int type, char* content) {
switch(type) {
case 0: strcpy(palName, trimString(content)); break;
case 1: strcpy(mapName, trimString(content)); break;
case 2: strcpy(artName, trimString(content)); break;
case 3: palOffset = strtol(content, NULL, 0); break;
case 4: mapOffset = strtol(content, NULL, 0); break;
case 5: artOffset = strtol(content, NULL, 0); break;
case 6: palLength = strtol(content, NULL, 0); break;
case 7: mapLength = strtol(content, NULL, 0); break;
case 8: artLength = strtol(content, NULL, 0); break;
case 9: mapCompr = readComprType(content); break;
case 10: artCompr = readComprType(content); break;
case 11: xSize = strtol(content, NULL, 0); break;
case 12: ySize = strtol(content, NULL, 0); break;
case 13: tileOffset = strtol(content, NULL, 0); break;
case 14: letterOffset = strtol(content, NULL, 0); break;
case 15: numberOffset = strtol(content, NULL, 0); break;
case 16: strcpy(saveName, trimString(content)); break;
}
}
void ProjectData::LoadArt(const char* const filename)
{
if (artCompr == INVALID)
{
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", "Invalid art compression format. Should be one of the following:\n\n'None'\n'Enigma'\n'Kosinski'\n'Nemesis'\n'Kid Chameleon'", NULL);
exit(1);
}
if (artCompr == NONE || artCompr == KIDCHAMELEON)
{
FILE* artfile = fopen(filename, "w+b");
artLength = ComprFunc(artCompr, artName, artfile, artOffset, artLength);
fclose(artfile);
}
else
{
ifstream fin(artName, ios::in|ios::binary);
fstream fout(filename, ios::in|ios::out|ios::binary|ios::trunc);
artLength = ComprFunc(artCompr, fin, fout, artOffset, artLength);
fin.close();
fout.close();
}
if (artLength < 0)
{
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", "Could not decompress art file. Are you sure the compression is correct?", NULL);
exit(1);
}
tileAmount = artLength/0x20;
}
void ProjectData::LoadMap(const char* const filename) {
if (mapCompr != NONE && mapCompr != ENIGMA) {
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", "Invalid map compression format. Should be one of the following:\n\n'None'\n'Enigma'", NULL);
exit(1);
}
FILE* mapfile;
if (mapCompr == NONE)
{
mapfile = fopen(filename, "wb");
mapLength = ComprFunc(mapCompr, mapName, mapfile, mapOffset, mapLength);
fclose(mapfile);
}
else //if (mapCompr == ENIGMA)
{
ifstream fin(mapName, ios::in|ios::binary);
fstream fout(filename, ios::in|ios::out|ios::binary|ios::trunc);
mapLength = ComprFunc(mapCompr, fin, fout, mapOffset, mapLength);
fin.close();
fout.close();
}
mapfile = fopen(filename, "r+b");
if (mapLength < 0) {
//file could not be decompressed or found
mapLength = 2*xSize*ySize;
if (!CheckCreateBlankFile(mapName, mapfile, mapOffset, mapLength)) {
//file is existant but could not be decompressed
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", "Could not decompress map file. Are you sure the compression is correct?", NULL);
exit(1);
} else {
//file non-existant, blank template created
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_INFORMATION, "Information", "No map file found, created blank template.", NULL);
}
}
fclose(mapfile);
if (mapLength < 2*xSize*ySize) {
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_WARNING, "Warning", "Specified size exceeds map size.\nField has been trimmed vertically.", NULL);
ySize = (mapLength/xSize) / 2;
if (ySize == 0) exit(1);
}
if (strlen(saveName) == 0) {
if (mapOffset == 0) strcpy(saveName, mapName); //overwrite existing map
else strcpy(saveName, FILE_MAP_DEFAULT); //write to default file
}
}
void ProjectData::LoadPal(const char* const filename) {
FILE* palfile = fopen(filename, "wb");
palLength = ReadPlain(palName, palfile, palOffset, palLength);
if (palLength < 0) {
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", "Palette file not found. Are you sure the path is correct?", NULL);
exit(1);
}
fclose(palfile);
}
void ProjectData::SaveMap(const char* filename) {
if (mapCompr == NONE) {
remove(saveName);
rename(filename, saveName);
} else if (mapCompr == ENIGMA) {
ifstream fin(filename, ios::in|ios::binary);
fstream fout(saveName, ios::in|ios::out|ios::binary|ios::trunc);
enigma::encode(fin, fout, false);
fin.close();
fout.close();
remove(filename);
} else {
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", "Invalid map compression format. Should be one of the following:\n\n'None'\n'Enigma'", NULL);
exit(1);
}
}
<commit_msg>Making TYPE_AMOUNT dynamic? It's a little hard to get the result of sizeof at compile time<commit_after>#include <cstdio>
#include <fstream>
#include <SDL2/SDL.h>
#include "PrjHndl.h"
#include "TxtRead.h"
#include "compression/KidDec.h"
#include "compression/ReadPlain.h"
#include "FW_KENSC/comper.h"
#include "FW_KENSC/enigma.h"
#include "FW_KENSC/kosinski.h"
#include "FW_KENSC/nemesis.h"
#include "FW_KENSC/saxman.h"
using namespace std;
#define FILE_MAP_DEFAULT "MapDefault.bin"
#define TYPE_AMOUNT sizeof(infoTypes)/32
char infoTypes[][32] = {
"Palette File:",
"Mapping File:",
"Art File:",
"Palette Offset:",
"Mapping Offset:",
"Art Offset:",
"Palette Length:",
"Mapping Length:",
"Art Length:",
"Mapping Compression:",
"Art Compression:",
"x-Size:",
"y-Size:",
"Tile Offset:",
"Letter Offset:",
"Number Offset:",
"Save File:"
};
static long ComprFunc(const fileCompression compression, const char* const srcfile, FILE* dst, long Pointer, int length)
{
switch (compression)
{
case NONE:
length = ReadPlain(srcfile, dst, Pointer, length);
break;
case KIDCHAMELEON:
length = KidDec(srcfile, dst, Pointer, length);
break;
}
return length;
}
static long ComprFunc(const fileCompression compression, istream &fin, iostream &fout, long Pointer, int length)
{
switch (compression)
{
case ENIGMA:
length = enigma::decode(fin, fout, Pointer, false);
break;
case KOSINSKI:
length = kosinski::decode(fin, fout, Pointer, false, 16u);
break;
case NEMESIS:
length = nemesis::decode(fin, fout, Pointer, 0);
break;
case COMPER:
length = comper::decode(fin, fout, Pointer);
break;
case SAXMAN:
length = saxman::decode(fin, fout, Pointer, 0);
break;
}
return length;
}
ProjectData::ProjectData(const char* const prjtxt) {
palOffset = mapOffset = artOffset = 0;
palLength = mapLength = artLength = 0;
mapCompr = artCompr = INVALID;
xSize = ySize = 0;
tileOffset = 0;
letterOffset = 0; numberOffset = 0;
strcpy(saveName, "");
FILE* prjfile = fopen(prjtxt, "r");
if (prjfile == NULL) {
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", "Please drag and drop your project file onto this program to start it.", NULL);
exit(1);
}
while (!feof(prjfile)) {
char line[256];
fgets(line, 256, prjfile);
for (int type=0; type < TYPE_AMOUNT; ++type) {
char* content = strsrch(line, infoTypes[type]);
if (content != NULL) AssignInfo(type, content);
}
}
}
void ProjectData::AssignInfo(int type, char* content) {
switch(type) {
case 0: strcpy(palName, trimString(content)); break;
case 1: strcpy(mapName, trimString(content)); break;
case 2: strcpy(artName, trimString(content)); break;
case 3: palOffset = strtol(content, NULL, 0); break;
case 4: mapOffset = strtol(content, NULL, 0); break;
case 5: artOffset = strtol(content, NULL, 0); break;
case 6: palLength = strtol(content, NULL, 0); break;
case 7: mapLength = strtol(content, NULL, 0); break;
case 8: artLength = strtol(content, NULL, 0); break;
case 9: mapCompr = readComprType(content); break;
case 10: artCompr = readComprType(content); break;
case 11: xSize = strtol(content, NULL, 0); break;
case 12: ySize = strtol(content, NULL, 0); break;
case 13: tileOffset = strtol(content, NULL, 0); break;
case 14: letterOffset = strtol(content, NULL, 0); break;
case 15: numberOffset = strtol(content, NULL, 0); break;
case 16: strcpy(saveName, trimString(content)); break;
}
}
void ProjectData::LoadArt(const char* const filename)
{
if (artCompr == INVALID)
{
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", "Invalid art compression format. Should be one of the following:\n\n'None'\n'Enigma'\n'Kosinski'\n'Nemesis'\n'Kid Chameleon'", NULL);
exit(1);
}
if (artCompr == NONE || artCompr == KIDCHAMELEON)
{
FILE* artfile = fopen(filename, "w+b");
artLength = ComprFunc(artCompr, artName, artfile, artOffset, artLength);
fclose(artfile);
}
else
{
ifstream fin(artName, ios::in|ios::binary);
fstream fout(filename, ios::in|ios::out|ios::binary|ios::trunc);
artLength = ComprFunc(artCompr, fin, fout, artOffset, artLength);
fin.close();
fout.close();
}
if (artLength < 0)
{
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", "Could not decompress art file. Are you sure the compression is correct?", NULL);
exit(1);
}
tileAmount = artLength/0x20;
}
void ProjectData::LoadMap(const char* const filename) {
if (mapCompr != NONE && mapCompr != ENIGMA) {
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", "Invalid map compression format. Should be one of the following:\n\n'None'\n'Enigma'", NULL);
exit(1);
}
FILE* mapfile;
if (mapCompr == NONE)
{
mapfile = fopen(filename, "wb");
mapLength = ComprFunc(mapCompr, mapName, mapfile, mapOffset, mapLength);
fclose(mapfile);
}
else //if (mapCompr == ENIGMA)
{
ifstream fin(mapName, ios::in|ios::binary);
fstream fout(filename, ios::in|ios::out|ios::binary|ios::trunc);
mapLength = ComprFunc(mapCompr, fin, fout, mapOffset, mapLength);
fin.close();
fout.close();
}
mapfile = fopen(filename, "r+b");
if (mapLength < 0) {
//file could not be decompressed or found
mapLength = 2*xSize*ySize;
if (!CheckCreateBlankFile(mapName, mapfile, mapOffset, mapLength)) {
//file is existant but could not be decompressed
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", "Could not decompress map file. Are you sure the compression is correct?", NULL);
exit(1);
} else {
//file non-existant, blank template created
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_INFORMATION, "Information", "No map file found, created blank template.", NULL);
}
}
fclose(mapfile);
if (mapLength < 2*xSize*ySize) {
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_WARNING, "Warning", "Specified size exceeds map size.\nField has been trimmed vertically.", NULL);
ySize = (mapLength/xSize) / 2;
if (ySize == 0) exit(1);
}
if (strlen(saveName) == 0) {
if (mapOffset == 0) strcpy(saveName, mapName); //overwrite existing map
else strcpy(saveName, FILE_MAP_DEFAULT); //write to default file
}
}
void ProjectData::LoadPal(const char* const filename) {
FILE* palfile = fopen(filename, "wb");
palLength = ReadPlain(palName, palfile, palOffset, palLength);
if (palLength < 0) {
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", "Palette file not found. Are you sure the path is correct?", NULL);
exit(1);
}
fclose(palfile);
}
void ProjectData::SaveMap(const char* filename) {
if (mapCompr == NONE) {
remove(saveName);
rename(filename, saveName);
} else if (mapCompr == ENIGMA) {
ifstream fin(filename, ios::in|ios::binary);
fstream fout(saveName, ios::in|ios::out|ios::binary|ios::trunc);
enigma::encode(fin, fout, false);
fin.close();
fout.close();
remove(filename);
} else {
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", "Invalid map compression format. Should be one of the following:\n\n'None'\n'Enigma'", NULL);
exit(1);
}
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <stdlib.h>
using namespace std;
///Please fix bugs if any DON'T THINK I'M GONNA DO IT FOR YOU GUYS...
int choice; ///Global Variable...cause i'm very Lazy :p
int siz;
void whatToDoSelector(int arr[]);
void menu(int arr[]);
void binarySearch(int arr[], int num){
system("clear");
int first=0;
int last=siz-1;
int middle = (last + first)/2;
int temp=0;
while(first <= last){
if(arr[middle] < num){
first = middle-1;
}else if(arr[middle] == num){
temp++;
cout << "Yes this element is in this array at position: " << middle << endl;
break;
}else{
last = middle-1;
}
middle = (first + last)/2;
}
if(temp==0){
cout << "No element found!!!" << endl;
}
cout << endl << endl;
cout << "Press any key to go back...";
//int tp;
//cin >> tp;
menu(arr);
}
void larEle(int arr[]){
int temp = 0;
for(int i=0;i<siz;i++)
{
if(arr[i]>temp)
temp=arr[i];
}
cout << "The biggest number is: " << temp << endl;
}
void sortArr(int arr[]){
for(int i=0; i<siz; i++){
for(int j=0; j<siz-i; ++j){
if(arr[j] > arr[j+1]){
arr[j] ^= arr[j+1];
arr[j+1] ^= arr[j];
arr[j] ^= arr[j+1];
}
}
}
cout << "Sorted element is: ";
for(int i=0; i<siz; ++i){
cout << arr[i] << ' ';
}
}
void sqCu(int arr[]){
}
void takeInput(int arr[]){
cout << "Please Enter the size of the array: ";
cin >> siz;
cout << "Please enter the values in the array: " << endl;
for(int i=0; i<siz; ++i){
cout << "Value of Element " << i+1 << " : ";
cin >> arr[i];
}
}
void menu(int arr[]){
system("clear");
cout << "#####################################################################" << endl;
cout << " **PLEASE SELECT ANY ONE OF THE FOLLOWING: **" << endl;
cout << "--1-> FIND POSITION OF THE ELEMENT IN ARRAY." << endl;
cout << "--2-> PRINT LARGEST ELEMENT OF ARRAY." << endl;
cout << "--3-> SORT THE ARRAY." << endl;
cout << "--4-> PRINT SQUARE OF EVEN ELEMENT AND CUBE OF ODD ELEMENT." << endl;
cout << "--5-> QUIT." << endl;
cout << "#####################################################################" << endl;
cout << endl << endl << endl;
cout << "Please enter your choice: ";
cin >> choice;
whatToDoSelector(arr);
}
void whatToDoSelector(int arr[]){
if(choice==1){
int num;
cout << "Please enter the number: ";
cin >> num;
binarySearch(arr, num);
}else if(choice==2){
larEle(arr);
}else if(choice==3){
sortArr(arr);
}else if(choice==4){
sqCu(arr);
}else
exit(0);
}
int main()
{
int arr[50];
takeInput(arr);
menu(arr);
}
<commit_msg>Delete QUES-11.cpp<commit_after><|endoftext|> |
<commit_before>//инициализация библиотек
#include <windows.h>
#include <conio.h>
#include <iostream>
//устанавливаем пространство имён
using namespace std;
//класс Sokoban, в котором описана вся игра
class Sokoban
{
private:
//выбранный уровень
unsigned short int lvl;
unsigned short int boxNum;
unsigned short int boxInPlace;
public:
//конструктор
Sokoban()
{
setLVL(1);
menu();
}
//выбор уровня
void setLVL(int level)
{
lvl = level;
}
//получение уровня
int getLVL()
{
return lvl;
}
//изменение уровня (тут оно херовое, надо научить его двигаться в обе стороны)
void changeLVL()
{
/*TODO: прописать if для нажатых клавиш влево/вправо*/
/*Также нужно сделать так, чтобы счётчик уровней не опускался ниже 1 и не поднимался выше количества уровней*/
unsigned short int newLVL = getLVL() + 1;
setLVL(newLVL);
}
//кол-во коробок на уровне
void setBox(int boxes)
{
boxNum = boxes;
}
//меню (тут надо будет ебаться)
void menu()
{
}
class tile
{
private:
bool box;
bool playerPos;
bool wall;
bool winPlace;
public:
//конструктор
tile ()
{
/*
box = false;
playerPos = false;
wall = false;
winPlace = false;
*/
//НАДО ПОЛУЧИТЬ НАЗВАНИЕ УРОВНЯ
//А ДЛЯ ЭТОГО СДЕЛАТЬ ОТДЕЛЬНЫЙ ПРИВАТНЫЙ МЕТОД
ifstream fin (lvlName);
lvlGen();
}
//геттеры
bool getBox()
{
return box;
}
bool getPlayerPos()
{
return playerPos;
}
bool getWall()
{
return wall;
}
bool getWinPlace()
{
return winPlace;
}
//сеттеры
void setBox(bool boxState)
{
box = boxState;
}
void setPlayerPos(bool playerPosState)
{
playerPos = playerPosState
}
void setWall(bool wallState)
{
wall = wallState;
}
void setWinPlace(bool winPlaceState)
{
winPlace = winPlaceState;
}
void lvlGen()
{
//НАДО ПОЛУЧИТЬ НАЗВАНИЕ УРОВНЯ
//А ДЛЯ ЭТОГО СДЕЛАТЬ ОТДЕЛЬНЫЙ ПРИВАТНЫЙ МЕТОД
ifstream fin (lvlName);
//в начало уровней надо поместить кол-во строк/столбцов
fin >> rows >> columns;
for (int i = 0; i < rows ; i++)
for (int j = 0; j < columns + 1; j++)
{
//считываем один символ
tileSpec = getline (fin, 1);
switch (tilespec)
{
case '#':
{
array[i,j].setWall(true);
}
case '@':
{
array[i,j].setBox(true);
}
case '+':
{
array[i,j].setPlayerPos(true);
}
case '$':
{
array[i,j].setWinPlace(true);
}
}
}
//СЮДА ЖЕ ВСУНУТЬ ОТРИСОВКУ УРОВНЯ
}
};
};
void main()
{
}
/*
Легенда:
+ тип public
- тип private
*/
//Итак, что нам нужно
/*
данные:
-счётчик уровней: lvl
-количестов ящиков на уровне: boxNum
-количество установленных на нужное место ящиков: boxInPlace
методы:
конструктор: Sokoban (тут надо реализовать запуск меню, меню - отдельный подкласс)
+выбор уровня: setLVL
+меню: menu
+получение уровня: getLVL (для последующего счётчика уровней)
+смена уровня: changeLVL
+кол-во коробок на уровне: setBox
*/
/*
Итак, появляется новый класс: tile
данные:
-наличие коробки: box
-позиция игрока: playerPos
-наличие стены: wall
-место для коробки: winPlace
методы:
+4 геттера
+4 сеттера
//это для каждых данных
*/
<commit_msg>Добавлен класс игрока<commit_after>//инициализация библиотек
#include <windows.h>
#include <conio.h>
#include <iostream>
//устанавливаем пространство имён
using namespace std;
//класс Sokoban, в котором описана вся игра
class Sokoban
{
private:
//выбранный уровень
unsigned short int lvl;
unsigned short int boxNum;
unsigned short int boxInPlace;
public:
//конструктор
Sokoban()
{
setLVL(1);
menu();
}
//выбор уровня
void setLVL(int level)
{
lvl = level;
}
//получение уровня
int getLVL()
{
return lvl;
}
//изменение уровня (тут оно херовое, надо научить его двигаться в обе стороны)
void changeLVL()
{
/*TODO: прописать if для нажатых клавиш влево/вправо*/
/*Также нужно сделать так, чтобы счётчик уровней не опускался ниже 1 и не поднимался выше количества уровней*/
unsigned short int newLVL = getLVL() + 1;
setLVL(newLVL);
}
//кол-во коробок на уровне
void setBox(int boxes)
{
boxNum = boxes;
}
//меню (тут надо будет ебаться)
void menu()
{
}
class tile
{
private:
bool box;
bool playerPos;
bool wall;
bool winPlace;
public:
//конструктор
tile ()
{
/*
box = false;
playerPos = false;
wall = false;
winPlace = false;
*/
//НАДО ПОЛУЧИТЬ НАЗВАНИЕ УРОВНЯ
//А ДЛЯ ЭТОГО СДЕЛАТЬ ОТДЕЛЬНЫЙ ПРИВАТНЫЙ МЕТОД
ifstream fin (lvlName);
lvlGen();
}
//геттеры
bool getBox()
{
return box;
}
bool getPlayerPos()
{
return playerPos;
}
bool getWall()
{
return wall;
}
bool getWinPlace()
{
return winPlace;
}
//сеттеры
void setBox(bool boxState)
{
box = boxState;
}
void setPlayerPos(bool playerPosState)
{
playerPos = playerPosState
}
void setWall(bool wallState)
{
wall = wallState;
}
void setWinPlace(bool winPlaceState)
{
winPlace = winPlaceState;
}
void lvlGen()
{
//НАДО ПОЛУЧИТЬ НАЗВАНИЕ УРОВНЯ
//А ДЛЯ ЭТОГО СДЕЛАТЬ ОТДЕЛЬНЫЙ ПРИВАТНЫЙ МЕТОД
ifstream fin (lvlName);
//в начало уровней надо поместить кол-во строк/столбцов
fin >> rows >> columns;
for (int i = 0; i < rows ; i++)
for (int j = 0; j < columns + 1; j++)
{
//считываем один символ
tileSpec = getline (fin, 1);
switch (tilespec)
{
case '#':
{
array[i,j].setWall(true);
}
case '@':
{
array[i,j].setBox(true);
}
case '+':
{
array[i,j].setPlayerPos(true);
}
case '$':
{
array[i,j].setWinPlace(true);
}
}
}
//СЮДА ЖЕ ВСУНУТЬ ОТРИСОВКУ УРОВНЯ
}
};
class player
{
private:
int PlayerCoordinateX, PlayerCoordinateY;//Координаты, где стоит игрок
bool CanMovePlayer(int MoveInX, int MoveInY)/*Метод, который проверяет, может ли игрок двигаться влево или вправо,
MoveInX и MoveInY - смещение от координат героя, ожидаемый диапазон значений от -1 до +1*/
{
if (tile[PlayerCoordinateX + MoveInX][PlayerCoordinateY + MoveInY].getWall != true)//Если там не стена
{
if (tile[PlayerCoordinateX + MoveInX][PlayerCoordinateY + MoveInY].getBox == true &&
(title[CoordinateX + 2 * MoveInX][CoordinateY + 2 * MoveInY].getBox != true) or (title[CoordinateX + 2 * MoveInX][CoordinateY + 2 * MoveInY].getWall != true))//Если там не две коробки или коробка+стена
return true; //можно
else return false;//иначе нельзя
}
else return false; //инача нельзя
};
public:
void MovePlayer(int MoveInX, int MoveInY)/*Метод, который двигает игрка влево или вправо,
MoveInX и MoveInY - смещение от координат героя, ожидаемый диапазон значений от -1 до +1*/
{
if (player.CanMovePlayer(MoveInX , MoveInY) == true)
{
tile[PlayerCoordinateX + MoveInX][PlayerCoordinateY + MoveInY].setBox(false);//убрать коробку
tile[PlayerCoordinateX + 2 * MoveInX][PlayerCoordinateY + 2 * MoveInY].setBox(true);//поставить коробку
tile[PlayerCoordinateX][PlayerCoordinateY].setPlayerPos(false);//Убрать игрока с клетки
tile[PlayerCoordinateX + MoveInX][PlayerCoordinateY + MoveInY].setPlayerPos(true);//Поставить игрока на новую клетку
PlayerCoordinateX = PlayerCoordinateX + MoveInX;//Записать новые координаты игрока
PlayerCoordinateY = PlayerCoordinateY + MoveInY;
}/*Сама коробка двигаться не может, поэтому нет нужны в написании метода её отдельного движения*/
};
};
};
void main()
{
}
/*
Легенда:
+ тип public
- тип private
*/
//Итак, что нам нужно
/*
данные:
-счётчик уровней: lvl
-количестов ящиков на уровне: boxNum
-количество установленных на нужное место ящиков: boxInPlace
методы:
конструктор: Sokoban (тут надо реализовать запуск меню, меню - отдельный подкласс)
+выбор уровня: setLVL
+меню: menu
+получение уровня: getLVL (для последующего счётчика уровней)
+смена уровня: changeLVL
+кол-во коробок на уровне: setBox
*/
/*
Итак, появляется новый класс: tile
данные:
-наличие коробки: box
-позиция игрока: playerPos
-наличие стены: wall
-место для коробки: winPlace
методы:
+4 геттера
+4 сеттера
//это для каждых данных
*/
<|endoftext|> |
<commit_before>/*
* Copyright 2018 Google Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
// Implementation of bed_reader.h
#include "deepvariant/util/bed_reader.h"
#include "absl/strings/str_split.h"
#include "deepvariant/util/genomics/bed.pb.h"
#include "deepvariant/util/utils.h"
#include "deepvariant/util/vendor/zlib_compression_options.h"
#include "deepvariant/util/vendor/zlib_inputstream.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/io/buffered_inputstream.h"
#include "tensorflow/core/lib/io/compression.h"
#include "tensorflow/core/lib/io/random_inputstream.h"
#include "tensorflow/core/lib/strings/numbers.h"
#include "tensorflow/core/lib/strings/strcat.h"
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/platform/file_system.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/types.h"
namespace nucleus {
namespace tf = tensorflow;
using tensorflow::string;
// 256 KB read buffer.
constexpr int READER_BUFFER_SIZE = 256 * 1024;
// BED-specific attributes.
constexpr char BED_COMMENT_CHAR = '#';
// -----------------------------------------------------------------------------
//
// Reader for BED format data.
//
// -----------------------------------------------------------------------------
namespace {
bool ValidNumBedFields(const int fields) {
return (fields == 3 || fields == 4 || fields == 5 || fields == 6 ||
fields == 8 || fields == 9 || fields == 12);
}
// Read the next non-comment line.
tf::Status NextNonCommentLine(
const std::unique_ptr<tf::io::BufferedInputStream>& instream,
string* line) {
TF_RETURN_IF_ERROR(instream->ReadLine(line));
while ((*line)[0] == BED_COMMENT_CHAR) {
TF_RETURN_IF_ERROR(instream->ReadLine(line));
}
return tf::Status::OK();
}
tf::Status ConvertToPb(const string& line, const int desiredNumFields,
int* numTokensSeen,
nucleus::genomics::v1::BedRecord* record) {
CHECK(record != nullptr) << "BED record cannot be null";
record->Clear();
std::vector<string> tokens = absl::StrSplit(line, '\t');
int numTokens = static_cast<int>(tokens.size());
*numTokensSeen = numTokens;
if (!ValidNumBedFields(numTokens)) {
return tf::errors::Unknown("BED record has invalid number of fields");
}
int numFields =
desiredNumFields == 0 ? numTokens : std::min(numTokens, desiredNumFields);
int64 int64Value;
record->set_reference_name(tokens[0]);
tf::strings::safe_strto64(tokens[1], &int64Value);
record->set_start(int64Value);
tf::strings::safe_strto64(tokens[2], &int64Value);
record->set_end(int64Value);
if (numFields > 3) record->set_name(tokens[3]);
if (numFields > 4) {
double value;
tf::strings::safe_strtod(tokens[4].c_str(), &value);
record->set_score(value);
}
if (numFields > 5) {
if (tokens[5] == "+")
record->set_strand(nucleus::genomics::v1::BedRecord::FORWARD_STRAND);
else if (tokens[5] == "-")
record->set_strand(nucleus::genomics::v1::BedRecord::REVERSE_STRAND);
else if (tokens[5] == ".")
record->set_strand(nucleus::genomics::v1::BedRecord::NO_STRAND);
else
return tf::errors::Unknown("Invalid BED record with unknown strand");
}
if (numFields > 7) {
tf::strings::safe_strto64(tokens[6], &int64Value);
record->set_thick_start(int64Value);
tf::strings::safe_strto64(tokens[7], &int64Value);
record->set_thick_end(int64Value);
}
if (numFields > 8) record->set_item_rgb(tokens[8]);
if (numFields >= 12) {
int32 int32Value;
tf::strings::safe_strto32(tokens[9], &int32Value);
record->set_block_count(int32Value);
record->set_block_sizes(tokens[10]);
record->set_block_starts(tokens[11]);
}
return tf::Status::OK();
}
// Peeks into the path to the first BED record and returns the number of fields
// in the record.
// NOTE: This is quite heavyweight. Reading upon initialization and then
// rewinding the stream to 0 is a nicer solution, but currently has a memory
// leak in the compressed stream reset implementation.
tf::Status GetNumFields(const string& path, bool isCompressed, int* numFields) {
std::unique_ptr<tensorflow::RandomAccessFile> sp;
tf::Status status =
tf::Env::Default()->NewRandomAccessFile(path.c_str(), &sp);
if (!status.ok()) {
return tf::errors::NotFound(tf::strings::StrCat("Could not open ", path));
}
tensorflow::RandomAccessFile* fp = sp.release();
std::unique_ptr<tensorflow::io::BufferedInputStream> bi;
string line;
if (isCompressed) {
std::unique_ptr<tensorflow::io::RandomAccessInputStream> fs;
std::unique_ptr<tensorflow::io::ZlibInputStream> zs;
fs.reset(new tf::io::RandomAccessInputStream(fp));
zs.reset(new tf::io::ZlibInputStream(
fs.get(), READER_BUFFER_SIZE, READER_BUFFER_SIZE,
tf::io::ZlibCompressionOptions::GZIP()));
bi.reset(new tf::io::BufferedInputStream(zs.get(), READER_BUFFER_SIZE));
TF_RETURN_IF_ERROR(NextNonCommentLine(bi, &line));
bi.reset();
zs.reset();
fs.reset();
} else {
bi.reset(new tf::io::BufferedInputStream(fp, READER_BUFFER_SIZE));
TF_RETURN_IF_ERROR(NextNonCommentLine(bi, &line));
bi.reset();
}
delete fp;
std::vector<string> tokens = absl::StrSplit(line, '\t');
*numFields = static_cast<int>(tokens.size());
return tf::Status::OK();
}
} // namespace
// Iterable class for traversing all BED records in the file.
class BedFullFileIterable : public BedIterable {
public:
// Advance to the next record.
StatusOr<bool> Next(nucleus::genomics::v1::BedRecord* out) override;
// Constructor is invoked via BedReader::Iterate.
BedFullFileIterable(const BedReader* reader);
~BedFullFileIterable() override;
};
StatusOr<std::unique_ptr<BedReader>> BedReader::FromFile(
const string& bed_path,
const nucleus::genomics::v1::BedReaderOptions& options) {
int numFieldsInBed;
TF_RETURN_IF_ERROR(
GetNumFields(bed_path,
options.compression_type() ==
nucleus::genomics::v1::BedReaderOptions::GZIP,
&numFieldsInBed));
nucleus::genomics::v1::BedHeader header;
header.set_num_fields(numFieldsInBed);
// Ensure options are valid.
if (options.num_fields() != 0 && (options.num_fields() > numFieldsInBed ||
!ValidNumBedFields(options.num_fields()))) {
return tf::errors::InvalidArgument(
"Invalid requested number of fields to parse");
}
std::unique_ptr<tensorflow::RandomAccessFile> fp;
tf::Status status =
tf::Env::Default()->NewRandomAccessFile(bed_path.c_str(), &fp);
if (!status.ok()) {
return tf::errors::NotFound(
tf::strings::StrCat("Could not open ", bed_path));
}
return std::unique_ptr<BedReader>(
new BedReader(fp.release(), options, header));
}
BedReader::BedReader(tensorflow::RandomAccessFile* fp,
const nucleus::genomics::v1::BedReaderOptions& options,
const nucleus::genomics::v1::BedHeader& header)
: options_(options), header_(header), src_(fp) {
if (options.compression_type() ==
nucleus::genomics::v1::BedReaderOptions::GZIP) {
file_stream_.reset(new tf::io::RandomAccessInputStream(src_));
zlib_stream_.reset(new tf::io::ZlibInputStream(
file_stream_.get(), READER_BUFFER_SIZE, READER_BUFFER_SIZE,
tf::io::ZlibCompressionOptions::GZIP()));
buffered_inputstream_.reset(new tf::io::BufferedInputStream(
zlib_stream_.get(), READER_BUFFER_SIZE));
} else {
buffered_inputstream_.reset(
new tf::io::BufferedInputStream(src_, READER_BUFFER_SIZE));
}
}
BedReader::~BedReader() {
if (src_) {
TF_CHECK_OK(Close());
}
}
tf::Status BedReader::Close() {
if (src_ == nullptr) {
return tf::errors::FailedPrecondition("BedReader already closed");
}
buffered_inputstream_.reset();
zlib_stream_.reset();
file_stream_.reset();
delete src_;
src_ = nullptr;
return tf::Status::OK();
}
// Ensures the number of fields is consistent across all records in the BED.
tf::Status BedReader::Validate(const int numTokens) const {
if (header_.num_fields() != numTokens) {
return tf::errors::Unknown(
"Invalid BED with varying number of fields in file");
}
return tf::Status::OK();
}
StatusOr<std::shared_ptr<BedIterable>> BedReader::Iterate() const {
if (src_ == nullptr)
return tf::errors::FailedPrecondition("Cannot Iterate a closed BedReader.");
return StatusOr<std::shared_ptr<BedIterable>>(
MakeIterable<BedFullFileIterable>(this));
}
// Iterable class definitions.
StatusOr<bool> BedFullFileIterable::Next(
nucleus::genomics::v1::BedRecord* out) {
TF_RETURN_IF_ERROR(CheckIsAlive());
const BedReader* bed_reader = static_cast<const BedReader*>(reader_);
string line;
tf::Status status = NextNonCommentLine(bed_reader->Stream(), &line);
if (tf::errors::IsOutOfRange(status)) {
return false;
} else if (!status.ok()) {
return status;
}
int numTokens;
TF_RETURN_IF_ERROR(
ConvertToPb(line, bed_reader->Options().num_fields(), &numTokens, out));
TF_RETURN_IF_ERROR(bed_reader->Validate(numTokens));
return true;
}
BedFullFileIterable::~BedFullFileIterable() {}
BedFullFileIterable::BedFullFileIterable(const BedReader* reader)
: Iterable(reader) {}
} // namespace nucleus
<commit_msg>Internal change.<commit_after>/*
* Copyright 2018 Google Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
// Implementation of bed_reader.h
#include "deepvariant/util/bed_reader.h"
#include "absl/strings/str_split.h"
#include "deepvariant/util/genomics/bed.pb.h"
#include "deepvariant/util/utils.h"
#include "deepvariant/util/vendor/zlib_compression_options.h"
#include "deepvariant/util/vendor/zlib_inputstream.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/io/buffered_inputstream.h"
#include "tensorflow/core/lib/io/compression.h"
#include "tensorflow/core/lib/io/random_inputstream.h"
#include "tensorflow/core/lib/strings/numbers.h"
#include "tensorflow/core/lib/strings/strcat.h"
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/platform/file_system.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/types.h"
namespace nucleus {
namespace tf = tensorflow;
using tensorflow::int32;
using tensorflow::int64;
using tensorflow::string;
// 256 KB read buffer.
constexpr int READER_BUFFER_SIZE = 256 * 1024;
// BED-specific attributes.
constexpr char BED_COMMENT_CHAR = '#';
// -----------------------------------------------------------------------------
//
// Reader for BED format data.
//
// -----------------------------------------------------------------------------
namespace {
bool ValidNumBedFields(const int fields) {
return (fields == 3 || fields == 4 || fields == 5 || fields == 6 ||
fields == 8 || fields == 9 || fields == 12);
}
// Read the next non-comment line.
tf::Status NextNonCommentLine(
const std::unique_ptr<tf::io::BufferedInputStream>& instream,
string* line) {
TF_RETURN_IF_ERROR(instream->ReadLine(line));
while ((*line)[0] == BED_COMMENT_CHAR) {
TF_RETURN_IF_ERROR(instream->ReadLine(line));
}
return tf::Status::OK();
}
tf::Status ConvertToPb(const string& line, const int desiredNumFields,
int* numTokensSeen,
nucleus::genomics::v1::BedRecord* record) {
CHECK(record != nullptr) << "BED record cannot be null";
record->Clear();
std::vector<string> tokens = absl::StrSplit(line, '\t');
int numTokens = static_cast<int>(tokens.size());
*numTokensSeen = numTokens;
if (!ValidNumBedFields(numTokens)) {
return tf::errors::Unknown("BED record has invalid number of fields");
}
int numFields =
desiredNumFields == 0 ? numTokens : std::min(numTokens, desiredNumFields);
int64 int64Value;
record->set_reference_name(tokens[0]);
tf::strings::safe_strto64(tokens[1], &int64Value);
record->set_start(int64Value);
tf::strings::safe_strto64(tokens[2], &int64Value);
record->set_end(int64Value);
if (numFields > 3) record->set_name(tokens[3]);
if (numFields > 4) {
double value;
tf::strings::safe_strtod(tokens[4].c_str(), &value);
record->set_score(value);
}
if (numFields > 5) {
if (tokens[5] == "+")
record->set_strand(nucleus::genomics::v1::BedRecord::FORWARD_STRAND);
else if (tokens[5] == "-")
record->set_strand(nucleus::genomics::v1::BedRecord::REVERSE_STRAND);
else if (tokens[5] == ".")
record->set_strand(nucleus::genomics::v1::BedRecord::NO_STRAND);
else
return tf::errors::Unknown("Invalid BED record with unknown strand");
}
if (numFields > 7) {
tf::strings::safe_strto64(tokens[6], &int64Value);
record->set_thick_start(int64Value);
tf::strings::safe_strto64(tokens[7], &int64Value);
record->set_thick_end(int64Value);
}
if (numFields > 8) record->set_item_rgb(tokens[8]);
if (numFields >= 12) {
int32 int32Value;
tf::strings::safe_strto32(tokens[9], &int32Value);
record->set_block_count(int32Value);
record->set_block_sizes(tokens[10]);
record->set_block_starts(tokens[11]);
}
return tf::Status::OK();
}
// Peeks into the path to the first BED record and returns the number of fields
// in the record.
// NOTE: This is quite heavyweight. Reading upon initialization and then
// rewinding the stream to 0 is a nicer solution, but currently has a memory
// leak in the compressed stream reset implementation.
tf::Status GetNumFields(const string& path, bool isCompressed, int* numFields) {
std::unique_ptr<tensorflow::RandomAccessFile> sp;
tf::Status status =
tf::Env::Default()->NewRandomAccessFile(path.c_str(), &sp);
if (!status.ok()) {
return tf::errors::NotFound(tf::strings::StrCat("Could not open ", path));
}
tensorflow::RandomAccessFile* fp = sp.release();
std::unique_ptr<tensorflow::io::BufferedInputStream> bi;
string line;
if (isCompressed) {
std::unique_ptr<tensorflow::io::RandomAccessInputStream> fs;
std::unique_ptr<tensorflow::io::ZlibInputStream> zs;
fs.reset(new tf::io::RandomAccessInputStream(fp));
zs.reset(new tf::io::ZlibInputStream(
fs.get(), READER_BUFFER_SIZE, READER_BUFFER_SIZE,
tf::io::ZlibCompressionOptions::GZIP()));
bi.reset(new tf::io::BufferedInputStream(zs.get(), READER_BUFFER_SIZE));
TF_RETURN_IF_ERROR(NextNonCommentLine(bi, &line));
bi.reset();
zs.reset();
fs.reset();
} else {
bi.reset(new tf::io::BufferedInputStream(fp, READER_BUFFER_SIZE));
TF_RETURN_IF_ERROR(NextNonCommentLine(bi, &line));
bi.reset();
}
delete fp;
std::vector<string> tokens = absl::StrSplit(line, '\t');
*numFields = static_cast<int>(tokens.size());
return tf::Status::OK();
}
} // namespace
// Iterable class for traversing all BED records in the file.
class BedFullFileIterable : public BedIterable {
public:
// Advance to the next record.
StatusOr<bool> Next(nucleus::genomics::v1::BedRecord* out) override;
// Constructor is invoked via BedReader::Iterate.
BedFullFileIterable(const BedReader* reader);
~BedFullFileIterable() override;
};
StatusOr<std::unique_ptr<BedReader>> BedReader::FromFile(
const string& bed_path,
const nucleus::genomics::v1::BedReaderOptions& options) {
int numFieldsInBed;
TF_RETURN_IF_ERROR(
GetNumFields(bed_path,
options.compression_type() ==
nucleus::genomics::v1::BedReaderOptions::GZIP,
&numFieldsInBed));
nucleus::genomics::v1::BedHeader header;
header.set_num_fields(numFieldsInBed);
// Ensure options are valid.
if (options.num_fields() != 0 && (options.num_fields() > numFieldsInBed ||
!ValidNumBedFields(options.num_fields()))) {
return tf::errors::InvalidArgument(
"Invalid requested number of fields to parse");
}
std::unique_ptr<tensorflow::RandomAccessFile> fp;
tf::Status status =
tf::Env::Default()->NewRandomAccessFile(bed_path.c_str(), &fp);
if (!status.ok()) {
return tf::errors::NotFound(
tf::strings::StrCat("Could not open ", bed_path));
}
return std::unique_ptr<BedReader>(
new BedReader(fp.release(), options, header));
}
BedReader::BedReader(tensorflow::RandomAccessFile* fp,
const nucleus::genomics::v1::BedReaderOptions& options,
const nucleus::genomics::v1::BedHeader& header)
: options_(options), header_(header), src_(fp) {
if (options.compression_type() ==
nucleus::genomics::v1::BedReaderOptions::GZIP) {
file_stream_.reset(new tf::io::RandomAccessInputStream(src_));
zlib_stream_.reset(new tf::io::ZlibInputStream(
file_stream_.get(), READER_BUFFER_SIZE, READER_BUFFER_SIZE,
tf::io::ZlibCompressionOptions::GZIP()));
buffered_inputstream_.reset(new tf::io::BufferedInputStream(
zlib_stream_.get(), READER_BUFFER_SIZE));
} else {
buffered_inputstream_.reset(
new tf::io::BufferedInputStream(src_, READER_BUFFER_SIZE));
}
}
BedReader::~BedReader() {
if (src_) {
TF_CHECK_OK(Close());
}
}
tf::Status BedReader::Close() {
if (src_ == nullptr) {
return tf::errors::FailedPrecondition("BedReader already closed");
}
buffered_inputstream_.reset();
zlib_stream_.reset();
file_stream_.reset();
delete src_;
src_ = nullptr;
return tf::Status::OK();
}
// Ensures the number of fields is consistent across all records in the BED.
tf::Status BedReader::Validate(const int numTokens) const {
if (header_.num_fields() != numTokens) {
return tf::errors::Unknown(
"Invalid BED with varying number of fields in file");
}
return tf::Status::OK();
}
StatusOr<std::shared_ptr<BedIterable>> BedReader::Iterate() const {
if (src_ == nullptr)
return tf::errors::FailedPrecondition("Cannot Iterate a closed BedReader.");
return StatusOr<std::shared_ptr<BedIterable>>(
MakeIterable<BedFullFileIterable>(this));
}
// Iterable class definitions.
StatusOr<bool> BedFullFileIterable::Next(
nucleus::genomics::v1::BedRecord* out) {
TF_RETURN_IF_ERROR(CheckIsAlive());
const BedReader* bed_reader = static_cast<const BedReader*>(reader_);
string line;
tf::Status status = NextNonCommentLine(bed_reader->Stream(), &line);
if (tf::errors::IsOutOfRange(status)) {
return false;
} else if (!status.ok()) {
return status;
}
int numTokens;
TF_RETURN_IF_ERROR(
ConvertToPb(line, bed_reader->Options().num_fields(), &numTokens, out));
TF_RETURN_IF_ERROR(bed_reader->Validate(numTokens));
return true;
}
BedFullFileIterable::~BedFullFileIterable() {}
BedFullFileIterable::BedFullFileIterable(const BedReader* reader)
: Iterable(reader) {}
} // namespace nucleus
<|endoftext|> |
<commit_before>/*
Copyright 2016 The Trustees of Princeton University
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 "core.h"
#include "server.h"
#include "syndicate-ag.h"
#define AG_DEFAULT_DRIVER_EXEC_STR "/usr/local/lib/syndicate/ag-driver"
#define AG_DRIVER_NUM_ROLES 4
char const* AG_DRIVER_ROLES[ AG_DRIVER_NUM_ROLES ] = {
"serialize",
"deserialize",
"read",
"crawl"
};
// core AG control structure
struct AG_state {
struct UG_state* ug_core;
pthread_rwlock_t lock;
};
// read-lock state. return 0 on success
int AG_state_rlock( struct AG_state* state ) {
return pthread_rwlock_rdlock( &state->lock );
}
// write-lock state. return 0 on success
int AG_state_wlock( struct AG_state* state ) {
return pthread_rwlock_wrlock( &state->lock );
}
// unlock state. return 0 on success
int AG_state_unlock( struct AG_state* state ) {
return pthread_rwlock_unlock( &state->lock );
}
// set up the AG
// return a client on success
// return NULL on error
struct AG_state* AG_init( int argc, char** argv ) {
int rc = 0;
struct UG_state* ug = NULL;
struct AG_state* ag = NULL;
struct md_opts* overrides = md_opts_new( 1 );
if( overrides == NULL ) {
return NULL;
}
md_opts_default( overrides );
md_opts_set_client( overrides, false );
md_opts_set_gateway_type( overrides, SYNDICATE_AG );
md_opts_set_driver_config( overrides, AG_DEFAULT_DRIVER_EXEC_STR, AG_DRIVER_ROLES, AG_DRIVER_NUM_ROLES );
ag = SG_CALLOC( struct AG_state, 1 );
if( ag == NULL ) {
// OOM
md_opts_free( overrides );
SG_safe_free( overrides );
return NULL;
}
// create UG core
ug = UG_init_ex( argc, argv, overrides, ag );
md_opts_free( overrides );
SG_safe_free( overrides );
if( ug == NULL ) {
SG_error("%s", "UG_init failed\n");
SG_safe_free( ag );
return NULL;
}
ag->ug_core = ug;
rc = pthread_rwlock_init( &ag->lock, NULL );
if( rc != 0 ) {
SG_error("pthread_rwlock_init rc = %d\n", rc );
UG_shutdown( ug );
SG_safe_free( ag );
return NULL;
}
// add AG server-side behaviors
AG_server_install_methods( AG_state_gateway( ag ) );
return ag;
}
// run the AG's server-side logic
// return 0 on success
// return -EINVAL if we already started the UG
// return -ENOMEM on OOM
// return -errno on failure to fork
int AG_main( struct AG_state* state ) {
return UG_main( state->ug_core );
}
// shut down the AG, given a state bundle passed from UG_init
// always succeeds
int AG_shutdown( struct AG_state* state ) {
int rc = 0;
rc = UG_shutdown( state->ug_core );
if( rc != 0 ) {
SG_error("UG_shutdown rc = %d\n", rc );
return rc;
}
pthread_rwlock_destroy( &state->lock );
memset( state, 0, sizeof(struct AG_state) );
return 0;
}
// get a pointer to the gateway core
struct SG_gateway* AG_state_gateway( struct AG_state* state ) {
return UG_state_gateway( state->ug_core );
}
// get a pointer to the filesystem core
struct fskit_core* AG_state_fs( struct AG_state* state ) {
return UG_state_fs( state->ug_core );
}
// get a pointer to the UG
struct UG_state* AG_state_ug( struct AG_state* state ) {
return state->ug_core;
}
<commit_msg>Add 'refresh' driver process<commit_after>/*
Copyright 2016 The Trustees of Princeton University
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 "core.h"
#include "server.h"
#include "syndicate-ag.h"
#define AG_DEFAULT_DRIVER_EXEC_STR "/usr/local/lib/syndicate/ag-driver"
#define AG_DRIVER_NUM_ROLES 5
char const* AG_DRIVER_ROLES[ AG_DRIVER_NUM_ROLES ] = {
"serialize",
"deserialize",
"read",
"crawl",
"refresh"
};
// core AG control structure
struct AG_state {
struct UG_state* ug_core;
pthread_rwlock_t lock;
};
// read-lock state. return 0 on success
int AG_state_rlock( struct AG_state* state ) {
return pthread_rwlock_rdlock( &state->lock );
}
// write-lock state. return 0 on success
int AG_state_wlock( struct AG_state* state ) {
return pthread_rwlock_wrlock( &state->lock );
}
// unlock state. return 0 on success
int AG_state_unlock( struct AG_state* state ) {
return pthread_rwlock_unlock( &state->lock );
}
// set up the AG
// return a client on success
// return NULL on error
struct AG_state* AG_init( int argc, char** argv ) {
int rc = 0;
struct UG_state* ug = NULL;
struct AG_state* ag = NULL;
struct md_opts* overrides = md_opts_new( 1 );
if( overrides == NULL ) {
return NULL;
}
md_opts_default( overrides );
md_opts_set_client( overrides, false );
md_opts_set_gateway_type( overrides, SYNDICATE_AG );
md_opts_set_driver_config( overrides, AG_DEFAULT_DRIVER_EXEC_STR, AG_DRIVER_ROLES, AG_DRIVER_NUM_ROLES );
ag = SG_CALLOC( struct AG_state, 1 );
if( ag == NULL ) {
// OOM
md_opts_free( overrides );
SG_safe_free( overrides );
return NULL;
}
// create UG core
ug = UG_init_ex( argc, argv, overrides, ag );
md_opts_free( overrides );
SG_safe_free( overrides );
if( ug == NULL ) {
SG_error("%s", "UG_init failed\n");
SG_safe_free( ag );
return NULL;
}
ag->ug_core = ug;
rc = pthread_rwlock_init( &ag->lock, NULL );
if( rc != 0 ) {
SG_error("pthread_rwlock_init rc = %d\n", rc );
UG_shutdown( ug );
SG_safe_free( ag );
return NULL;
}
// add AG server-side behaviors
AG_server_install_methods( AG_state_gateway( ag ) );
return ag;
}
// run the AG's server-side logic
// return 0 on success
// return -EINVAL if we already started the UG
// return -ENOMEM on OOM
// return -errno on failure to fork
int AG_main( struct AG_state* state ) {
return UG_main( state->ug_core );
}
// shut down the AG, given a state bundle passed from UG_init
// always succeeds
int AG_shutdown( struct AG_state* state ) {
int rc = 0;
rc = UG_shutdown( state->ug_core );
if( rc != 0 ) {
SG_error("UG_shutdown rc = %d\n", rc );
return rc;
}
pthread_rwlock_destroy( &state->lock );
memset( state, 0, sizeof(struct AG_state) );
return 0;
}
// get a pointer to the gateway core
struct SG_gateway* AG_state_gateway( struct AG_state* state ) {
return UG_state_gateway( state->ug_core );
}
// get a pointer to the filesystem core
struct fskit_core* AG_state_fs( struct AG_state* state ) {
return UG_state_fs( state->ug_core );
}
// get a pointer to the UG
struct UG_state* AG_state_ug( struct AG_state* state ) {
return state->ug_core;
}
<|endoftext|> |
<commit_before>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2015 Scientific Computing and Imaging Institute,
University of Utah.
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/Math/ReportMatrixSliceMeasure.h>
#include <Core/Datatypes/Matrix.h>
#include <Dataflow/Network/Module.h>
#include <Core/Algorithms/Math/ReportMatrixSliceMeasureAlgo.h>
using namespace SCIRun::Modules::Math;
using namespace SCIRun::Dataflow::Networks;
using namespace SCIRun::Core::Algorithms;
using namespace SCIRun::Core::Datatypes;
/// @class ReportMatrixSliceMeasure
/// @brief This module computes a measure on each row of the input matrix and
/// stores the result in the output matrix.
const ModuleLookupInfo ReportMatrixSliceMeasure::staticInfo_("ReportMatrixSliceMeasure", "Math", "SCIRun");
ReportMatrixSliceMeasure::ReportMatrixSliceMeasure() : Module(staticInfo_)
{
INITIALIZE_PORT(InputMatrix);
INITIALIZE_PORT(OutputMatrix);
}
void ReportMatrixSliceMeasure::setStateDefaults()
{
setStateIntFromAlgo(Variables::Operator);
setStateIntFromAlgo(Variables::Method);
}
void
ReportMatrixSliceMeasure::execute()
{
MatrixHandle input, output;
auto input = getRequiredInput(InputMatrix);
if (needToExecute())
{
setAlgoIntFromState(Variables::Operator);
setAlgoIntFromState(Variables::Method);
auto output = algo().run_generic(withInputData((InputMatrix, input)));
sendOutputFromAlgorithm(OutputMatrix, output);
//MatrixHandle output=input;
//sendOutput(OutputMatrix, output);
}
}
<commit_msg>builds, not working. column commented out.<commit_after>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2015 Scientific Computing and Imaging Institute,
University of Utah.
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/Math/ReportMatrixSliceMeasure.h>
#include <Core/Datatypes/Matrix.h>
#include <Dataflow/Network/Module.h>
#include <Core/Algorithms/Math/ReportMatrixSliceMeasureAlgo.h>
using namespace SCIRun::Modules::Math;
using namespace SCIRun::Dataflow::Networks;
using namespace SCIRun::Core::Algorithms;
using namespace SCIRun::Core::Datatypes;
/// @class ReportMatrixSliceMeasure
/// @brief This module computes a measure on each row of the input matrix and
/// stores the result in the output matrix.
const ModuleLookupInfo ReportMatrixSliceMeasure::staticInfo_("ReportMatrixSliceMeasure", "Math", "SCIRun");
ReportMatrixSliceMeasure::ReportMatrixSliceMeasure() : Module(staticInfo_)
{
INITIALIZE_PORT(InputMatrix);
INITIALIZE_PORT(OutputMatrix);
}
void ReportMatrixSliceMeasure::setStateDefaults()
{
setStateIntFromAlgo(Variables::Operator);
setStateIntFromAlgo(Variables::Method);
}
void
ReportMatrixSliceMeasure::execute()
{
auto input = getRequiredInput(InputMatrix);
if (needToExecute())
{
setAlgoIntFromState(Variables::Operator);
setAlgoIntFromState(Variables::Method);
auto output = algo().run_generic(withInputData((InputMatrix, input)));
sendOutputFromAlgorithm(OutputMatrix, output);
//MatrixHandle output=input;
//sendOutput(OutputMatrix, output);
}
}
<|endoftext|> |
<commit_before>/*===========================================================================*\
* *
* OpenMesh *
* Copyright (C) 2001-2011 by Computer Graphics Group, RWTH Aachen *
* www.openmesh.org *
* *
*---------------------------------------------------------------------------*
* This file is part of OpenMesh. *
* *
* OpenMesh is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License as *
* published by the Free Software Foundation, either version 3 of *
* the License, or (at your option) any later version with the *
* following exceptions: *
* *
* If other files instantiate templates or use macros *
* or inline functions from this file, or you compile this file and *
* link it with other files to produce an executable, this file does *
* not by itself cause the resulting executable to be covered by the *
* GNU Lesser General Public License. This exception does not however *
* invalidate any other reasons why the executable file might be *
* covered by the GNU Lesser General Public License. *
* *
* OpenMesh 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 LesserGeneral Public *
* License along with OpenMesh. If not, *
* see <http://www.gnu.org/licenses/>. *
* *
\*===========================================================================*/
/*===========================================================================*\
* *
* $Revision: 460 $ *
* $Date: 2011-11-16 10:45:08 +0100 (Mi, 16 Nov 2011) $ *
* *
\*===========================================================================*/
/** \file McDecimaterT.cc
*/
//=============================================================================
//
// CLASS McDecimaterT - IMPLEMENTATION
//
//=============================================================================
#define OPENMESH_MULTIPLE_CHOICE_DECIMATER_DECIMATERT_CC
//== INCLUDES =================================================================
#include <OpenMesh/Tools/Decimater/McDecimaterT.hh>
#include <vector>
#if defined(OM_CC_MIPS)
# include <float.h>
#else
# include <cfloat>
#endif
#ifdef USE_OPENMP
#include <omp.h>
#endif
//== NAMESPACE ===============================================================
namespace OpenMesh {
namespace Decimater {
//== IMPLEMENTATION ==========================================================
template<class Mesh>
McDecimaterT<Mesh>::McDecimaterT(Mesh& _mesh) :
BaseDecimaterT<Mesh>(_mesh),
mesh_(_mesh), randomSamples_(10) {
// default properties
mesh_.request_vertex_status();
mesh_.request_halfedge_status();
mesh_.request_edge_status();
mesh_.request_face_status();
mesh_.request_face_normals();
}
//-----------------------------------------------------------------------------
template<class Mesh>
McDecimaterT<Mesh>::~McDecimaterT() {
// default properties
mesh_.release_vertex_status();
mesh_.release_edge_status();
mesh_.release_halfedge_status();
mesh_.release_face_status();
mesh_.release_face_normals();
}
//-----------------------------------------------------------------------------
template<class Mesh>
size_t McDecimaterT<Mesh>::decimate(size_t _n_collapses) {
if (!this->is_initialized())
return 0;
unsigned int n_collapses(0);
bool collapsesUnchanged = false;
// old n_collapses in order to check for convergence
unsigned int oldCollapses = 0;
// number of iterations where no new collapses where
// performed in a row
unsigned int noCollapses = 0;
while ( n_collapses < _n_collapses) {
if (noCollapses > 20) {
omlog() << "[McDecimater] : no collapses performed in over 20 iterations in a row\n";
break;
}
// Optimal id and value will be collected during the random sampling
typename Mesh::HalfedgeHandle bestHandle(-1);
typename Mesh::HalfedgeHandle tmpHandle(-1);
double bestEnergy = FLT_MAX;
double energy = FLT_MAX;
// Generate random samples for collapses
#ifdef USE_OPENMP
#pragma omp parallel for private(energy,tmpHandle) shared(bestEnergy,bestHandle)
#endif
for ( int i = 0; i < (int)randomSamples_; ++i) {
// Random halfedge handle
tmpHandle = typename Mesh::HalfedgeHandle((static_cast<double>(rand()) / RAND_MAX) * (mesh_.n_halfedges()-1) );
// if it is not deleted, we analyse it
if ( ! mesh_.status(tmpHandle).deleted() ) {
CollapseInfo ci(mesh_, tmpHandle);
// Check if legal we analyze the priority of this collapse operation
if (this->is_collapse_legal(ci)) {
#ifdef USE_OPENMP
#pragma omp critical(energyUpdate)
{
#endif
energy = this->collapse_priority(ci);
if (energy != ModBaseT<Mesh>::ILLEGAL_COLLAPSE) {
// Check if the current samples energy is better than any energy before
if ( energy < bestEnergy ) {
bestEnergy = energy;
bestHandle = tmpHandle;
}
}
#ifdef USE_OPENMP
}
#endif
} else {
continue;
}
}
}
// Found the best energy?
if ( bestEnergy != FLT_MAX ) {
// setup collapse info
CollapseInfo ci(mesh_, bestHandle);
// check topological correctness AGAIN !
if (!this->is_collapse_legal(ci))
continue;
// pre-processing
this->preprocess_collapse(ci);
// perform collapse
mesh_.collapse(bestHandle);
++n_collapses;
// store current collapses state
oldCollapses = n_collapses;
noCollapses = 0;
collapsesUnchanged = false;
// update triangle normals
typename Mesh::VertexFaceIter vf_it = mesh_.vf_iter(ci.v1);
for (; vf_it; ++vf_it)
if (!mesh_.status(vf_it).deleted())
mesh_.set_normal(vf_it, mesh_.calc_face_normal(vf_it.handle()));
// post-process collapse
this->postprocess_collapse(ci);
} else {
if (oldCollapses == n_collapses) {
if (collapsesUnchanged == false) {
noCollapses = 1;
collapsesUnchanged = true;
} else {
noCollapses++;
}
}
}
}
// DON'T do garbage collection here! It's up to the application.
return n_collapses;
}
//-----------------------------------------------------------------------------
template<class Mesh>
size_t McDecimaterT<Mesh>::decimate_to_faces(size_t _nv, size_t _nf) {
if (!this->is_initialized())
return 0;
// check if no vertex or face contraints were set
if ( (_nv == 0) && (_nf == 1) )
return decimate_constraints_only(1.0);
unsigned int nv = mesh_.n_vertices();
unsigned int nf = mesh_.n_faces();
unsigned int n_collapses(0);
bool collapsesUnchanged = false;
// old n_collapses in order to check for convergence
unsigned int oldCollapses = 0;
// number of iterations where no new collapses where
// performed in a row
unsigned int noCollapses = 0;
while ((_nv < nv) && (_nf < nf)) {
if (noCollapses > 20) {
omlog() << "[McDecimater] : no collapses performed in over 20 iterations in a row\n";
break;
}
// Optimal id and value will be collected during the random sampling
typename Mesh::HalfedgeHandle bestHandle(-1);
typename Mesh::HalfedgeHandle tmpHandle(-1);
double bestEnergy = FLT_MAX;
double energy = FLT_MAX;
// Generate random samples for collapses
#ifdef USE_OPENMP
#pragma omp parallel for private(energy,tmpHandle) shared(bestEnergy,bestHandle)
#endif
for (int i = 0; i < (int) randomSamples_; ++i) {
// Random halfedge handle
tmpHandle = typename Mesh::HalfedgeHandle((static_cast<double>(rand()) / RAND_MAX) * (mesh_.n_halfedges() - 1));
// if it is not deleted, we analyse it
if (!mesh_.status(tmpHandle).deleted()) {
CollapseInfo ci(mesh_, tmpHandle);
// Check if legal we analyze the priority of this collapse operation
if (this->is_collapse_legal(ci)) {
#ifdef USE_OPENMP
#pragma omp critical(energyUpdate)
{
#endif
energy = this->collapse_priority(ci);
if (energy != ModBaseT<Mesh>::ILLEGAL_COLLAPSE) {
// Check if the current samples energy is better than any energy before
if (energy < bestEnergy) {
bestEnergy = energy;
bestHandle = tmpHandle;
}
}
#ifdef USE_OPENMP
}
#endif
} else {
continue;
}
}
}
// Found the best energy?
if ( bestEnergy != FLT_MAX ) {
// setup collapse info
CollapseInfo ci(mesh_, bestHandle);
// check topological correctness AGAIN !
if (!this->is_collapse_legal(ci))
continue;
// adjust complexity in advance (need boundary status)
// One vertex is killed by the collapse
--nv;
// If we are at a boundary, one face is lost,
// otherwise two
if (mesh_.is_boundary(ci.v0v1) || mesh_.is_boundary(ci.v1v0))
--nf;
else
nf -= 2;
// pre-processing
this->preprocess_collapse(ci);
// perform collapse
mesh_.collapse(bestHandle);
++n_collapses;
// store current collapses state
oldCollapses = n_collapses;
noCollapses = 0;
collapsesUnchanged = false;
// update triangle normals
typename Mesh::VertexFaceIter vf_it = mesh_.vf_iter(ci.v1);
for (; vf_it; ++vf_it)
if (!mesh_.status(vf_it).deleted())
mesh_.set_normal(vf_it, mesh_.calc_face_normal(vf_it.handle()));
// post-process collapse
this->postprocess_collapse(ci);
} else {
if (oldCollapses == n_collapses) {
if (collapsesUnchanged == false) {
noCollapses = 1;
collapsesUnchanged = true;
} else {
noCollapses++;
}
}
}
}
// DON'T do garbage collection here! It's up to the application.
return n_collapses;
}
//-----------------------------------------------------------------------------
template<class Mesh>
size_t McDecimaterT<Mesh>::decimate_constraints_only(float _factor) {
if (!this->is_initialized())
return 0;
if (_factor < 1.0)
this->set_error_tolerance_factor(_factor);
unsigned int n_collapses(0);
unsigned int nv = mesh_.n_vertices();
unsigned int nf = mesh_.n_faces();
bool lastCollapseIllegal = false;
// number of illegal collapses that occured in a row
unsigned int illegalCollapses = 0;
bool collapsesUnchanged = false;
// old n_collapses in order to check for convergence
unsigned int oldCollapses = 0;
// number of iterations where no new collapses where
// performed in a row
unsigned int noCollapses = 0;
while ((noCollapses <= 20) && (illegalCollapses <= 10) && (nv > 0) && (nf > 1)) {
// Optimal id and value will be collected during the random sampling
typename Mesh::HalfedgeHandle bestHandle(-1);
typename Mesh::HalfedgeHandle tmpHandle(-1);
double bestEnergy = FLT_MAX;
double energy = FLT_MAX;
// Generate random samples for collapses
#ifdef USE_OPENMP
#pragma omp parallel for private(energy,tmpHandle) shared(bestEnergy,bestHandle)
#endif
for (int i = 0; i < (int) randomSamples_; ++i) {
// Random halfedge handle
tmpHandle = typename Mesh::HalfedgeHandle((static_cast<double>(rand()) / RAND_MAX) * (mesh_.n_halfedges() - 1));
// if it is not deleted, we analyse it
if (!mesh_.status(tmpHandle).deleted()) {
CollapseInfo ci(mesh_, tmpHandle);
// Check if legal we analyze the priority of this collapse operation
if (this->is_collapse_legal(ci)) {
#ifdef USE_OPENMP
#pragma omp critical(energyUpdate)
{
#endif
energy = this->collapse_priority(ci);
if (energy == ModBaseT<Mesh>::ILLEGAL_COLLAPSE) {
if (lastCollapseIllegal) {
illegalCollapses++;
} else {
illegalCollapses = 1;
lastCollapseIllegal = true;
}
} else {
illegalCollapses = 0;
lastCollapseIllegal = false;
// Check if the current samples energy is better than any energy before
if (energy < bestEnergy) {
bestEnergy = energy;
bestHandle = tmpHandle;
}
}
#ifdef USE_OPENMP
}
#endif
} else {
continue;
}
}
}
// Found the best energy?
if ( bestEnergy != FLT_MAX ) {
// setup collapse info
CollapseInfo ci(mesh_, bestHandle);
// check topological correctness AGAIN !
if (!this->is_collapse_legal(ci))
continue;
// adjust complexity in advance (need boundary status)
// One vertex is killed by the collapse
--nv;
// If we are at a boundary, one face is lost,
// otherwise two
if (mesh_.is_boundary(ci.v0v1) || mesh_.is_boundary(ci.v1v0))
--nf;
else
nf -= 2;
// pre-processing
this->preprocess_collapse(ci);
// perform collapse
mesh_.collapse(bestHandle);
++n_collapses;
// store current collapses state
oldCollapses = n_collapses;
noCollapses = 0;
collapsesUnchanged = false;
// update triangle normals
typename Mesh::VertexFaceIter vf_it = mesh_.vf_iter(ci.v1);
for (; vf_it; ++vf_it)
if (!mesh_.status(vf_it).deleted())
mesh_.set_normal(vf_it, mesh_.calc_face_normal(vf_it.handle()));
// post-process collapse
this->postprocess_collapse(ci);
} else {
if (oldCollapses == n_collapses) {
if (collapsesUnchanged == false) {
noCollapses = 1;
collapsesUnchanged = true;
} else {
noCollapses++;
}
}
}
}
if (_factor < 1.0)
this->set_error_tolerance_factor(1.0);
// DON'T do garbage collection here! It's up to the application.
return n_collapses;
}
//=============================================================================
}// END_NS_MC_DECIMATER
} // END_NS_OPENMESH
//=============================================================================
<commit_msg>Minor speedup of McDecimater<commit_after>/*===========================================================================*\
* *
* OpenMesh *
* Copyright (C) 2001-2011 by Computer Graphics Group, RWTH Aachen *
* www.openmesh.org *
* *
*---------------------------------------------------------------------------*
* This file is part of OpenMesh. *
* *
* OpenMesh is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License as *
* published by the Free Software Foundation, either version 3 of *
* the License, or (at your option) any later version with the *
* following exceptions: *
* *
* If other files instantiate templates or use macros *
* or inline functions from this file, or you compile this file and *
* link it with other files to produce an executable, this file does *
* not by itself cause the resulting executable to be covered by the *
* GNU Lesser General Public License. This exception does not however *
* invalidate any other reasons why the executable file might be *
* covered by the GNU Lesser General Public License. *
* *
* OpenMesh 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 LesserGeneral Public *
* License along with OpenMesh. If not, *
* see <http://www.gnu.org/licenses/>. *
* *
\*===========================================================================*/
/*===========================================================================*\
* *
* $Revision: 460 $ *
* $Date: 2011-11-16 10:45:08 +0100 (Mi, 16 Nov 2011) $ *
* *
\*===========================================================================*/
/** \file McDecimaterT.cc
*/
//=============================================================================
//
// CLASS McDecimaterT - IMPLEMENTATION
//
//=============================================================================
#define OPENMESH_MULTIPLE_CHOICE_DECIMATER_DECIMATERT_CC
//== INCLUDES =================================================================
#include <OpenMesh/Tools/Decimater/McDecimaterT.hh>
#include <vector>
#if defined(OM_CC_MIPS)
# include <float.h>
#else
# include <cfloat>
#endif
//== NAMESPACE ===============================================================
namespace OpenMesh {
namespace Decimater {
//== IMPLEMENTATION ==========================================================
template<class Mesh>
McDecimaterT<Mesh>::McDecimaterT(Mesh& _mesh) :
BaseDecimaterT<Mesh>(_mesh),
mesh_(_mesh), randomSamples_(10) {
// default properties
mesh_.request_vertex_status();
mesh_.request_halfedge_status();
mesh_.request_edge_status();
mesh_.request_face_status();
mesh_.request_face_normals();
}
//-----------------------------------------------------------------------------
template<class Mesh>
McDecimaterT<Mesh>::~McDecimaterT() {
// default properties
mesh_.release_vertex_status();
mesh_.release_edge_status();
mesh_.release_halfedge_status();
mesh_.release_face_status();
mesh_.release_face_normals();
}
//-----------------------------------------------------------------------------
template<class Mesh>
size_t McDecimaterT<Mesh>::decimate(size_t _n_collapses) {
if (!this->is_initialized())
return 0;
unsigned int n_collapses(0);
bool collapsesUnchanged = false;
// old n_collapses in order to check for convergence
unsigned int oldCollapses = 0;
// number of iterations where no new collapses where
// performed in a row
unsigned int noCollapses = 0;
while ( n_collapses < _n_collapses) {
if (noCollapses > 20) {
omlog() << "[McDecimater] : no collapses performed in over 20 iterations in a row\n";
break;
}
// Optimal id and value will be collected during the random sampling
typename Mesh::HalfedgeHandle bestHandle(-1);
typename Mesh::HalfedgeHandle tmpHandle(-1);
double bestEnergy = FLT_MAX;
double energy = FLT_MAX;
// Generate random samples for collapses
for ( int i = 0; i < (int)randomSamples_; ++i) {
// Random halfedge handle
tmpHandle = typename Mesh::HalfedgeHandle((static_cast<double>(rand()) / RAND_MAX) * (mesh_.n_halfedges()-1) );
// if it is not deleted, we analyse it
if ( ! mesh_.status(tmpHandle).deleted() ) {
CollapseInfo ci(mesh_, tmpHandle);
// Check if legal we analyze the priority of this collapse operation
if (this->is_collapse_legal(ci)) {
energy = this->collapse_priority(ci);
if (energy != ModBaseT<Mesh>::ILLEGAL_COLLAPSE) {
// Check if the current samples energy is better than any energy before
if ( energy < bestEnergy ) {
bestEnergy = energy;
bestHandle = tmpHandle;
}
}
} else {
continue;
}
}
}
// Found the best energy?
if ( bestEnergy != FLT_MAX ) {
// setup collapse info
CollapseInfo ci(mesh_, bestHandle);
// check topological correctness AGAIN !
if (!this->is_collapse_legal(ci))
continue;
// pre-processing
this->preprocess_collapse(ci);
// perform collapse
mesh_.collapse(bestHandle);
++n_collapses;
// store current collapses state
oldCollapses = n_collapses;
noCollapses = 0;
collapsesUnchanged = false;
// update triangle normals
typename Mesh::VertexFaceIter vf_it = mesh_.vf_iter(ci.v1);
for (; vf_it; ++vf_it)
if (!mesh_.status(vf_it).deleted())
mesh_.set_normal(vf_it, mesh_.calc_face_normal(vf_it.handle()));
// post-process collapse
this->postprocess_collapse(ci);
} else {
if (oldCollapses == n_collapses) {
if (collapsesUnchanged == false) {
noCollapses = 1;
collapsesUnchanged = true;
} else {
noCollapses++;
}
}
}
}
// DON'T do garbage collection here! It's up to the application.
return n_collapses;
}
//-----------------------------------------------------------------------------
template<class Mesh>
size_t McDecimaterT<Mesh>::decimate_to_faces(size_t _nv, size_t _nf) {
if (!this->is_initialized())
return 0;
// check if no vertex or face contraints were set
if ( (_nv == 0) && (_nf == 1) )
return decimate_constraints_only(1.0);
unsigned int nv = mesh_.n_vertices();
unsigned int nf = mesh_.n_faces();
unsigned int n_collapses(0);
bool collapsesUnchanged = false;
// old n_collapses in order to check for convergence
unsigned int oldCollapses = 0;
// number of iterations where no new collapses where
// performed in a row
unsigned int noCollapses = 0;
while ((_nv < nv) && (_nf < nf)) {
if (noCollapses > 20) {
omlog() << "[McDecimater] : no collapses performed in over 20 iterations in a row\n";
break;
}
// Optimal id and value will be collected during the random sampling
typename Mesh::HalfedgeHandle bestHandle(-1);
typename Mesh::HalfedgeHandle tmpHandle(-1);
double bestEnergy = FLT_MAX;
double energy = FLT_MAX;
// Generate random samples for collapses
for (int i = 0; i < (int) randomSamples_; ++i) {
// Random halfedge handle
tmpHandle = typename Mesh::HalfedgeHandle((static_cast<double>(rand()) / RAND_MAX) * (mesh_.n_halfedges() - 1));
// if it is not deleted, we analyse it
if (!mesh_.status(tmpHandle).deleted()) {
CollapseInfo ci(mesh_, tmpHandle);
// Check if legal we analyze the priority of this collapse operation
if (this->is_collapse_legal(ci)) {
energy = this->collapse_priority(ci);
if (energy != ModBaseT<Mesh>::ILLEGAL_COLLAPSE) {
// Check if the current samples energy is better than any energy before
if (energy < bestEnergy) {
bestEnergy = energy;
bestHandle = tmpHandle;
}
}
} else {
continue;
}
}
}
// Found the best energy?
if ( bestEnergy != FLT_MAX ) {
// setup collapse info
CollapseInfo ci(mesh_, bestHandle);
// check topological correctness AGAIN !
if (!this->is_collapse_legal(ci))
continue;
// adjust complexity in advance (need boundary status)
// One vertex is killed by the collapse
--nv;
// If we are at a boundary, one face is lost,
// otherwise two
if (mesh_.is_boundary(ci.v0v1) || mesh_.is_boundary(ci.v1v0))
--nf;
else
nf -= 2;
// pre-processing
this->preprocess_collapse(ci);
// perform collapse
mesh_.collapse(bestHandle);
++n_collapses;
// store current collapses state
oldCollapses = n_collapses;
noCollapses = 0;
collapsesUnchanged = false;
// update triangle normals
typename Mesh::VertexFaceIter vf_it = mesh_.vf_iter(ci.v1);
for (; vf_it; ++vf_it)
if (!mesh_.status(vf_it).deleted())
mesh_.set_normal(vf_it, mesh_.calc_face_normal(vf_it.handle()));
// post-process collapse
this->postprocess_collapse(ci);
} else {
if (oldCollapses == n_collapses) {
if (collapsesUnchanged == false) {
noCollapses = 1;
collapsesUnchanged = true;
} else {
noCollapses++;
}
}
}
}
// DON'T do garbage collection here! It's up to the application.
return n_collapses;
}
//-----------------------------------------------------------------------------
template<class Mesh>
size_t McDecimaterT<Mesh>::decimate_constraints_only(float _factor) {
if (!this->is_initialized())
return 0;
if (_factor < 1.0)
this->set_error_tolerance_factor(_factor);
unsigned int n_collapses(0);
unsigned int nv = mesh_.n_vertices();
unsigned int nf = mesh_.n_faces();
bool lastCollapseIllegal = false;
// number of illegal collapses that occured in a row
unsigned int illegalCollapses = 0;
bool collapsesUnchanged = false;
// old n_collapses in order to check for convergence
unsigned int oldCollapses = 0;
// number of iterations where no new collapses where
// performed in a row
unsigned int noCollapses = 0;
double energy = FLT_MAX;
double bestEnergy = FLT_MAX;
while ((noCollapses <= 50) && (illegalCollapses <= 50) && (nv > 0) && (nf > 1)) {
// Optimal id and value will be collected during the random sampling
typename Mesh::HalfedgeHandle bestHandle(-1);
typename Mesh::HalfedgeHandle tmpHandle(-1);
bestEnergy = FLT_MAX;
const double randomNormalizer = (1.0 / RAND_MAX) * (mesh_.n_halfedges() - 1);
// Generate random samples for collapses
for (int i = 0; i < (int) randomSamples_; ++i) {
// Random halfedge handle
tmpHandle = typename Mesh::HalfedgeHandle(int(rand() * randomNormalizer ) );
// if it is not deleted, we analyze it
if (!mesh_.status(mesh_.edge_handle(tmpHandle)).deleted()) {
CollapseInfo ci(mesh_, tmpHandle);
// Check if legal we analyze the priority of this collapse operation
if (this->is_collapse_legal(ci)) {
energy = this->collapse_priority(ci);
if (energy == ModBaseT<Mesh>::ILLEGAL_COLLAPSE) {
if (lastCollapseIllegal) {
illegalCollapses++;
} else {
illegalCollapses = 1;
lastCollapseIllegal = true;
}
} else {
illegalCollapses = 0;
lastCollapseIllegal = false;
// Check if the current samples energy is better than any energy before
if (energy < bestEnergy) {
bestEnergy = energy;
bestHandle = tmpHandle;
}
}
} else {
continue;
}
}
}
// Found the best energy?
if ( bestEnergy != FLT_MAX ) {
// setup collapse info
CollapseInfo ci(mesh_, bestHandle);
// check topological correctness AGAIN !
if (!this->is_collapse_legal(ci))
continue;
// adjust complexity in advance (need boundary status)
// One vertex is killed by the collapse
--nv;
// If we are at a boundary, one face is lost,
// otherwise two
if (mesh_.is_boundary(ci.v0v1) || mesh_.is_boundary(ci.v1v0))
--nf;
else
nf -= 2;
// pre-processing
this->preprocess_collapse(ci);
// perform collapse
mesh_.collapse(bestHandle);
++n_collapses;
// store current collapses state
oldCollapses = n_collapses;
noCollapses = 0;
collapsesUnchanged = false;
// update triangle normals
typename Mesh::VertexFaceIter vf_it = mesh_.vf_iter(ci.v1);
for (; vf_it; ++vf_it)
if (!mesh_.status(vf_it).deleted())
mesh_.set_normal(vf_it, mesh_.calc_face_normal(vf_it.handle()));
// post-process collapse
this->postprocess_collapse(ci);
} else {
if (oldCollapses == n_collapses) {
if (collapsesUnchanged == false) {
noCollapses = 1;
collapsesUnchanged = true;
} else {
noCollapses++;
}
}
}
}
if (_factor < 1.0)
this->set_error_tolerance_factor(1.0);
// DON'T do garbage collection here! It's up to the application.
return n_collapses;
}
//=============================================================================
}// END_NS_MC_DECIMATER
} // END_NS_OPENMESH
//=============================================================================
<|endoftext|> |
<commit_before>/*******************************************************************************
* tests/core/test_hash_table.cpp
*
* Part of Project c7a.
*
*
* This file has no license. Only Chuck Norris can compile it.
******************************************************************************/
#include <c7a/core/reduce_pre_table.hpp>
#include <c7a/core/reduce_post_table.hpp>
#include "gtest/gtest.h"
#include <tests/c7a_tests.hpp>
#include "c7a/api/context.hpp"
#include <stdio.h>
#include <functional>
#include <cstdio>
TEST(PreTable, CreateEmptyTable) {
auto emit = [](int in) {
std::cout << in << std::endl;
};
auto key_ex = [](int in) { return in; };
auto red_fn = [](int in1, int in2) {
return in1 + in2;
};
c7a::core::ReducePreTable<decltype(key_ex), decltype(red_fn), decltype(emit)>
table(1, key_ex, red_fn, {emit});
assert(table.Size() == 0);
}
TEST(PostTable, CreateEmptyTable) {
auto emit = [](int in) {
std::cout << in << std::endl;
};
auto key_ex = [](int in) { return in; };
auto red_fn = [](int in1, int in2) {
return in1 + in2;
};
c7a::core::ReducePostTable<decltype(key_ex), decltype(red_fn), decltype(emit)>
table(key_ex, red_fn, {emit});
assert(table.Size() == 0);
}
TEST(PreTable, AddIntegers) {
auto emit = [](int in) {
std::cout << in << std::endl;
};
auto key_ex = [](int in) { return in; };
auto red_fn = [](int in1, int in2) {
return in1 + in2;
};
c7a::core::ReducePreTable<decltype(key_ex), decltype(red_fn), decltype(emit)>
table(1, key_ex, red_fn, {emit});
table.Insert(1);
table.Insert(2);
table.Insert(3);
assert(table.Size() == 3);
table.Insert(2);
assert(table.Size() == 3);
}
TEST(PostTable, AddIntegers) {
auto emit = [](int in) {
std::cout << in << std::endl;
};
auto key_ex = [](int in) { return in; };
auto red_fn = [](int in1, int in2) {
return in1 + in2;
};
c7a::core::ReducePostTable<decltype(key_ex), decltype(red_fn), decltype(emit)>
table(key_ex, red_fn, {emit});
table.Insert(1);
table.Insert(2);
table.Insert(3);
assert(table.Size() == 3);
table.Insert(2);
assert(table.Size() == 3);
}
TEST(PreTable, PopIntegers) {
auto emit = [](int in) {
std::cout << in << std::endl;
};
auto key_ex = [](int in) { return in; };
auto red_fn = [](int in1, int in2) {
return in1 + in2;
};
c7a::core::ReducePreTable<decltype(key_ex), decltype(red_fn), decltype(emit)>
table(1, key_ex, red_fn, {emit});
table.SetMaxSize(3);
table.Insert(1);
table.Insert(2);
table.Insert(3);
table.Insert(4);
assert(table.Size() == 0);
table.Insert(1);
assert(table.Size() == 1);
}
TEST(PreTable, FlushIntegers) {
auto emit = [](int in) {
std::cout << in << std::endl;
};
auto key_ex = [](int in) { return in; };
auto red_fn = [](int in1, int in2) {
return in1 + in2;
};
c7a::core::ReducePreTable<decltype(key_ex), decltype(red_fn), decltype(emit)>
table(1, key_ex, red_fn, {emit});
table.Insert(1);
table.Insert(2);
table.Insert(3);
assert(table.Size() == 3);
table.Flush();
assert(table.Size() == 0);
table.Insert(1);
assert(table.Size() == 1);
}
TEST(PostTable, FlushIntegers) {
auto emit = [](int in) {
std::cout << in << std::endl;
};
auto key_ex = [](int in) { return in; };
auto red_fn = [](int in1, int in2) {
return in1 + in2;
};
c7a::core::ReducePostTable<decltype(key_ex), decltype(red_fn), decltype(emit)>
table(key_ex, red_fn, {emit});
table.Insert(1);
table.Insert(2);
table.Insert(3);
assert(table.Size() == 3);
table.Flush();
assert(table.Size() == 0);
table.Insert(1);
assert(table.Size() == 1);
}
TEST(PreTable, ComplexType) {
using StringPair = std::pair<std::string, double>;
auto emit = [](StringPair in) {
std::cout << in.second << std::endl;
};
auto key_ex = [](StringPair in) { return in.first; };
auto red_fn = [](StringPair in1, StringPair in2) {
return std::make_pair(in1.first, in1.second + in2.second);
};
c7a::core::ReducePreTable<decltype(key_ex), decltype(red_fn), decltype(emit)>
table(1, key_ex, red_fn, {emit});
table.SetMaxSize(3);
table.Insert(std::make_pair("hallo", 1));
table.Insert(std::make_pair("hello", 2));
table.Insert(std::make_pair("bonjour", 3));
assert(table.Size() == 3);
table.Insert(std::make_pair("hello", 5));
assert(table.Size() == 3);
table.Insert(std::make_pair("baguette", 42));
assert(table.Size() == 0);
}
TEST(PostTable, ComplexType) {
using StringPair = std::pair<std::string, double>;
auto emit = [](StringPair in) {
std::cout << in.second << std::endl;
};
auto key_ex = [](StringPair in) { return in.first; };
auto red_fn = [](StringPair in1, StringPair in2) {
return std::make_pair(in1.first, in1.second + in2.second);
};
c7a::core::ReducePostTable<decltype(key_ex), decltype(red_fn), decltype(emit)>
table(key_ex, red_fn, {emit});
table.Insert(std::make_pair("hallo", 1));
table.Insert(std::make_pair("hello", 2));
table.Insert(std::make_pair("bonjour", 3));
assert(table.Size() == 3);
table.Insert(std::make_pair("hello", 5));
assert(table.Size() == 3);
table.Insert(std::make_pair("baguette", 42));
assert(table.Size() == 4);
}
TEST(PreTable, MultipleWorkers) {
auto emit = [](int in) {
std::cout << in << std::endl;
};
auto key_ex = [](int in) { return in; };
auto red_fn = [](int in1, int in2) {
return in1 + in2;
};
c7a::core::ReducePreTable<decltype(key_ex), decltype(red_fn), decltype(emit)>
table(2, key_ex, red_fn, {emit});
assert(table.Size() == 0);
table.SetMaxSize(5);
for (int i = 0; i < 6; i++) {
table.Insert(i * 35001);
}
assert(table.Size() <= 3);
assert(table.Size() > 0);
}
// TODO(ms): add one test with a for loop inserting 10000 items. -> trigger
// resize!
/******************************************************************************/
<commit_msg>test for reduce_test_table with multiple emitters<commit_after>/*******************************************************************************
* tests/core/test_hash_table.cpp
*
* Part of Project c7a.
*
*
* This file has no license. Only Chuck Norris can compile it.
******************************************************************************/
#include <c7a/core/reduce_pre_table.hpp>
#include <c7a/core/reduce_post_table.hpp>
#include "gtest/gtest.h"
#include <tests/c7a_tests.hpp>
#include "c7a/api/context.hpp"
#include <stdio.h>
#include <functional>
#include <cstdio>
TEST(PreTable, CreateEmptyTable) {
auto emit = [](int in) {
std::cout << in << std::endl;
};
auto key_ex = [](int in) { return in; };
auto red_fn = [](int in1, int in2) {
return in1 + in2;
};
c7a::core::ReducePreTable<decltype(key_ex), decltype(red_fn), decltype(emit)>
table(1, key_ex, red_fn, {emit});
assert(table.Size() == 0);
}
TEST(PostTable, CreateEmptyTable) {
auto emit = [](int in) {
std::cout << in << std::endl;
};
auto key_ex = [](int in) { return in; };
auto red_fn = [](int in1, int in2) {
return in1 + in2;
};
c7a::core::ReducePostTable<decltype(key_ex), decltype(red_fn), decltype(emit)>
table(key_ex, red_fn, {emit});
assert(table.Size() == 0);
}
TEST(PreTable, AddIntegers) {
auto emit = [](int in) {
std::cout << in << std::endl;
};
auto key_ex = [](int in) { return in; };
auto red_fn = [](int in1, int in2) {
return in1 + in2;
};
c7a::core::ReducePreTable<decltype(key_ex), decltype(red_fn), decltype(emit)>
table(1, key_ex, red_fn, {emit});
table.Insert(1);
table.Insert(2);
table.Insert(3);
assert(table.Size() == 3);
table.Insert(2);
assert(table.Size() == 3);
}
TEST(PostTable, AddIntegers) {
auto emit = [](int in) {
std::cout << in << std::endl;
};
auto key_ex = [](int in) { return in; };
auto red_fn = [](int in1, int in2) {
return in1 + in2;
};
c7a::core::ReducePostTable<decltype(key_ex), decltype(red_fn), decltype(emit)>
table(key_ex, red_fn, {emit});
table.Insert(1);
table.Insert(2);
table.Insert(3);
assert(table.Size() == 3);
table.Insert(2);
assert(table.Size() == 3);
}
TEST(PreTable, PopIntegers) {
auto emit = [](int in) {
std::cout << in << std::endl;
};
auto key_ex = [](int in) { return in; };
auto red_fn = [](int in1, int in2) {
return in1 + in2;
};
c7a::core::ReducePreTable<decltype(key_ex), decltype(red_fn), decltype(emit)>
table(1, key_ex, red_fn, {emit});
table.SetMaxSize(3);
table.Insert(1);
table.Insert(2);
table.Insert(3);
table.Insert(4);
assert(table.Size() == 0);
table.Insert(1);
assert(table.Size() == 1);
}
TEST(PreTable, FlushIntegers) {
auto emit = [](int in) {
std::cout << in << std::endl;
};
auto key_ex = [](int in) { return in; };
auto red_fn = [](int in1, int in2) {
return in1 + in2;
};
c7a::core::ReducePreTable<decltype(key_ex), decltype(red_fn), decltype(emit)>
table(1, key_ex, red_fn, {emit});
table.Insert(1);
table.Insert(2);
table.Insert(3);
assert(table.Size() == 3);
table.Flush();
assert(table.Size() == 0);
table.Insert(1);
assert(table.Size() == 1);
}
TEST(PostTable, FlushIntegers) {
auto emit = [](int in) {
std::cout << in << std::endl;
};
auto key_ex = [](int in) { return in; };
auto red_fn = [](int in1, int in2) {
return in1 + in2;
};
c7a::core::ReducePostTable<decltype(key_ex), decltype(red_fn), decltype(emit)>
table(key_ex, red_fn, {emit});
table.Insert(1);
table.Insert(2);
table.Insert(3);
assert(table.Size() == 3);
table.Flush();
assert(table.Size() == 0);
table.Insert(1);
assert(table.Size() == 1);
}
TEST(PostTable, MultipleEmitters) {
std::vector<int> vec1;
auto emit1 = [&vec1](int in) {
vec1.push_back(in);
};
auto key_ex = [](int in) { return in; };
auto red_fn = [](int in1, int in2) {
return in1 + in2;
};
std::vector<decltype(emit1)> emitters;
emitters.push_back(emit1);
emitters.push_back(emit1);
emitters.push_back(emit1);
c7a::core::ReducePostTable<decltype(key_ex), decltype(red_fn), decltype(emit1)>
table(key_ex, red_fn, emitters);
table.Insert(1);
table.Insert(2);
table.Insert(3);
assert(table.Size() == 3);
table.Flush();
assert(table.Size() == 0);
table.Insert(1);
assert(table.Size() == 1);
assert(vec1.size() == 9);
}
TEST(PreTable, ComplexType) {
using StringPair = std::pair<std::string, double>;
auto emit = [](StringPair in) {
std::cout << in.second << std::endl;
};
auto key_ex = [](StringPair in) { return in.first; };
auto red_fn = [](StringPair in1, StringPair in2) {
return std::make_pair(in1.first, in1.second + in2.second);
};
c7a::core::ReducePreTable<decltype(key_ex), decltype(red_fn), decltype(emit)>
table(1, key_ex, red_fn, {emit});
table.SetMaxSize(3);
table.Insert(std::make_pair("hallo", 1));
table.Insert(std::make_pair("hello", 2));
table.Insert(std::make_pair("bonjour", 3));
assert(table.Size() == 3);
table.Insert(std::make_pair("hello", 5));
assert(table.Size() == 3);
table.Insert(std::make_pair("baguette", 42));
assert(table.Size() == 0);
}
TEST(PostTable, ComplexType) {
using StringPair = std::pair<std::string, double>;
auto emit = [](StringPair in) {
std::cout << in.second << std::endl;
};
auto key_ex = [](StringPair in) { return in.first; };
auto red_fn = [](StringPair in1, StringPair in2) {
return std::make_pair(in1.first, in1.second + in2.second);
};
c7a::core::ReducePostTable<decltype(key_ex), decltype(red_fn), decltype(emit)>
table(key_ex, red_fn, {emit});
table.Insert(std::make_pair("hallo", 1));
table.Insert(std::make_pair("hello", 2));
table.Insert(std::make_pair("bonjour", 3));
assert(table.Size() == 3);
table.Insert(std::make_pair("hello", 5));
assert(table.Size() == 3);
table.Insert(std::make_pair("baguette", 42));
assert(table.Size() == 4);
}
TEST(PreTable, MultipleWorkers) {
auto emit = [](int in) {
std::cout << in << std::endl;
};
auto key_ex = [](int in) { return in; };
auto red_fn = [](int in1, int in2) {
return in1 + in2;
};
c7a::core::ReducePreTable<decltype(key_ex), decltype(red_fn), decltype(emit)>
table(2, key_ex, red_fn, {emit});
assert(table.Size() == 0);
table.SetMaxSize(5);
for (int i = 0; i < 6; i++) {
table.Insert(i * 35001);
}
assert(table.Size() <= 3);
assert(table.Size() > 0);
}
// TODO(ms): add one test with a for loop inserting 10000 items. -> trigger
// resize!
/******************************************************************************/
<|endoftext|> |
<commit_before>#include <vector>
#include <libport/containers.hh>
using namespace libport;
static std::vector<unsigned> v;
static bool
odd(unsigned i)
{
return i % 2 == 0;
}
int main()
{
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.push_back(4);
v.push_back(5);
assert(v.size() == 5);
erase_if(v, odd);
assert(v.size() == 3);
assert(libport::has(v, 1));
assert(libport::has(v, 3));
assert(libport::has(v, 5));
}
<commit_msg>Take address of template function.<commit_after>#include <vector>
#include <libport/containers.hh>
using namespace libport;
static std::vector<unsigned> v;
static bool
odd(unsigned i)
{
return i % 2 == 0;
}
int main()
{
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.push_back(4);
v.push_back(5);
assert(v.size() == 5);
erase_if(v, &odd);
assert(v.size() == 3);
assert(libport::has(v, 1));
assert(libport::has(v, 3));
assert(libport::has(v, 5));
}
<|endoftext|> |
<commit_before>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All right reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Justin Madsen
// =============================================================================
//
// test the pacTire for 3 distinct slip cases, then compare force/moment output
// v. slip (kappa, alpha) to Adams/Car testrig output
// 1) pure longitudinal slip (V_yc = tan(alpha) = 0)
// 2) pure lateral slip, (kappa ~= 0)
// 3) combined slip
//
// we will run our vehicle with default rigid tires, but calculate the output
// for the pacjeka tire in the background
//
// =============================================================================
#include <vector>
#include "core/ChFileutils.h"
#include "core/ChStream.h"
#include "physics/ChSystem.h"
#include "physics/ChLinkDistance.h"
#include "utils/ChUtilsInputOutput.h"
#include "utils/ChUtilsData.h"
#include "subsys/tire/ChPacejkaTire.h"
#include "subsys/terrain/FlatTerrain.h"
#include "ChronoT_config.h"
using namespace chrono;
const std::string out_dir = "../PACTEST";
const std::string pov_dir = out_dir + "/POVRAY";
// ============== PacTire settings go here
const int num_pts = 801; // # of data points in the slip ranges
const double step_size = 0.01; // seconds, arbitrary unless calculating transient slip
const double alpha_lim = CH_C_PI_4/3.0; // slip angle in range [-lim,lim] or [0,lim]
const double kappa_lim = 1; // slip rate in range [-lim,lim] or [0,lim]
const double F_z = 8000; // vertical force, [N]
const ChVehicleSide m_side = LEFT;
const double gamma = 10.0 * CH_C_PI/180.0; // gamma, in radians
// for the transient model
const bool use_transient_slip = true; // use kinematic or transient contact slips?
const std::string pacParamFile = utils::GetModelDataFile("hmmwv/pactest.tir");
// output data filenames
std::string out_name_long = "test_pacTire_pureLongSlip.csv";
std::string out_name_lat = "test_pacTire_pureLatSlip.csv";
std::string out_name_latGamma = "test_pacTire_pureLatSlipGamma.csv";
std::string out_name_combined = "test_pacTire_combinedSlip.csv";
const double time_end = (num_pts - 1)*step_size;
int main(int argc, char* argv[])
{
SetChronoDataPath(CHRONO_DATA_DIR);
// flat rigid terrain, height = 0 for all (x,y)
FlatTerrain flat_terrain(0);
// Create the Pac tires, try to open param file and load empirical constants
ChPacejkaTire tire_long("LONGITUDINAL", pacParamFile, flat_terrain, F_z, use_transient_slip);
ChPacejkaTire tire_lat("LATERAL", pacParamFile, flat_terrain, F_z, use_transient_slip);
ChPacejkaTire tire_lat_gamma("LATERAL_GAMMA", pacParamFile, flat_terrain, F_z, use_transient_slip);
ChPacejkaTire tire_combined("COMBINED", pacParamFile, flat_terrain, F_z, use_transient_slip);
// initialize the tire on the left or right side
tire_long.Initialize(m_side);
tire_lat.Initialize(m_side);
tire_lat_gamma.Initialize(m_side);
tire_combined.Initialize(m_side);
// record pacTire output for each of the 3 slip cases
ChTireForces long_forces(1);
ChTireForces lat_forces(1);
ChTireForces latGamma_forces(1);
ChTireForces combined_forces(1);
// update body state based on varying input variables to pacTire:
// alpha, kappa and gamma
ChWheelState long_state;
ChWheelState lat_state;
ChWheelState latGamma_state;
ChWheelState combined_state;
// keep track of the input variable values
std::vector<double> latSlip_range;
std::vector<double> longSlip_range;
latSlip_range.resize(num_pts);
longSlip_range.resize(num_pts);
double time = 0.0;
// get the bounds of the slip angles from the input *.tire file
double k_min, k_max, a_min, a_max;
k_min = -kappa_lim;
k_max = kappa_lim;
a_min = -alpha_lim;
a_max = alpha_lim;
// at IC, go straight ahead at zero slip
double kappa_t = k_min;
double alpha_t = 0;
double tanalpha_t = tan(alpha_t);
double gamma_t = 0.1 * alpha_t;
// unless we're only using steady-state EQs, then just sweep min to max
if (!use_transient_slip)
{
alpha_t = a_min;
tanalpha_t = tan(alpha_t);
gamma_t = 0.1 * alpha_t;
} else {
out_name_long = "test_pacTire_pureLongSlip_transient.csv";
out_name_lat = "test_pacTire_pureLatSlip_transient.csv";
out_name_latGamma = "test_pacTire_pacLatSlipGamma_transient.csv";
out_name_combined = "test_pacTire_combinedSlip_transient.csv";
}
// calculate the increments for each slip case (assuming constant per step)
double kappa_incr = (k_max - k_min) / double(num_pts);
double alpha_incr = (a_max - a_min) / double(num_pts);
// horizontal velocity (x,y components) is constant throughout all runs
double vel_xy = tire_long.get_longvl();
// time step is arbitrary, steps determined by slip array length
for (size_t step = 0; step < num_pts; step++)
{
// tire input slip quantities
tanalpha_t = tan(alpha_t);
latSlip_range[step] = tanalpha_t;
longSlip_range[step] = kappa_t;
// **** longitudinal states
long_state = tire_long.getState_from_KAG(kappa_t, 0, 0, vel_xy);
// **** lateral states
lat_state = tire_lat.getState_from_KAG(0, alpha_t, 0, vel_xy);
// ***** lateral w/ specified gamma
latGamma_state = tire_lat_gamma.getState_from_KAG(0, alpha_t, gamma, vel_xy);
// **** combined states
combined_state = tire_combined.getState_from_KAG(kappa_t, alpha_t, gamma_t, vel_xy);
// DEBUGGING
if (step == 200)
int arg = 2;
// update all 4 types of tires, with current wheel state data
tire_long.Update(time, long_state);
tire_lat.Update(time, lat_state);
tire_lat_gamma.Update(time, latGamma_state);
tire_combined.Update(time, combined_state);
// advance the slip displacements, calculate reactions
tire_long.Advance(step_size);
tire_lat.Advance(step_size);
tire_lat_gamma.Advance(step_size);
tire_combined.Advance(step_size);
// see what the calculated reactions are
long_forces[0] = tire_long.GetTireForce();
lat_forces[0] = tire_lat.GetTireForce();
latGamma_forces[0] = tire_lat_gamma.GetTireForce();
combined_forces[0] = tire_combined.GetTireForce();
// output any data at the end of the step
tire_long.WriteOutData(time, out_name_long);
tire_lat.WriteOutData(time, out_name_lat);
tire_lat_gamma.WriteOutData(time, out_name_latGamma);
tire_combined.WriteOutData(time, out_name_combined);
// std::cout << "step: " << step << ", kappa = " << kappa_t << ", alpha = " << alpha_t << ", tan(alpha) = " << tanalpha_t << std::endl;
// increment time, update long. & lat. slips for the next time step
time += step_size;
// constant increments. sine waves would be better
if (use_transient_slip)
{
// do a powered lane change
// Careful !!!!
// need to properly mimic Adams/Car kappa, alpha vs. time
// kappa is linear
kappa_t += kappa_incr;
// lateral angle is a sine wave
alpha_t = abs(a_max) * sin(2.0 * chrono::CH_C_PI * time / time_end);
}
else {
kappa_t += kappa_incr;
alpha_t += alpha_incr;
}
}
// clean up anything
return 0;
}
<commit_msg>Fix for GCC error - do not use global variables.<commit_after>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All right reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Justin Madsen
// =============================================================================
//
// test the pacTire for 3 distinct slip cases, then compare force/moment output
// v. slip (kappa, alpha) to Adams/Car testrig output
// 1) pure longitudinal slip (V_yc = tan(alpha) = 0)
// 2) pure lateral slip, (kappa ~= 0)
// 3) combined slip
//
// we will run our vehicle with default rigid tires, but calculate the output
// for the pacjeka tire in the background
//
// =============================================================================
#include <vector>
#include "core/ChFileutils.h"
#include "core/ChStream.h"
#include "physics/ChSystem.h"
#include "physics/ChLinkDistance.h"
#include "utils/ChUtilsInputOutput.h"
#include "utils/ChUtilsData.h"
#include "subsys/tire/ChPacejkaTire.h"
#include "subsys/terrain/FlatTerrain.h"
#include "ChronoT_config.h"
using namespace chrono;
int main(int argc, char* argv[])
{
// Output directory names
const std::string out_dir = "../PACTEST";
const std::string pov_dir = out_dir + "/POVRAY";
// ============== PacTire settings go here
const int num_pts = 801; // # of data points in the slip ranges
const double step_size = 0.01; // seconds, arbitrary unless calculating transient slip
const double alpha_lim = CH_C_PI_4 / 3.0; // slip angle in range [-lim,lim] or [0,lim]
const double kappa_lim = 1; // slip rate in range [-lim,lim] or [0,lim]
const double F_z = 8000; // vertical force, [N]
const ChVehicleSide m_side = LEFT;
const double gamma = 10.0 * CH_C_PI / 180.0; // gamma, in radians
// for the transient model
const bool use_transient_slip = true; // use kinematic or transient contact slips?
const std::string pacParamFile = utils::GetModelDataFile("hmmwv/pactest.tir");
// output data filenames
std::string out_name_long = "test_pacTire_pureLongSlip.csv";
std::string out_name_lat = "test_pacTire_pureLatSlip.csv";
std::string out_name_latGamma = "test_pacTire_pureLatSlipGamma.csv";
std::string out_name_combined = "test_pacTire_combinedSlip.csv";
const double time_end = (num_pts - 1)*step_size;
// Set the path to the Chrono data files.
SetChronoDataPath(CHRONO_DATA_DIR);
// flat rigid terrain, height = 0 for all (x,y)
FlatTerrain flat_terrain(0);
// Create the Pac tires, try to open param file and load empirical constants
ChPacejkaTire tire_long("LONGITUDINAL", pacParamFile, flat_terrain, F_z, use_transient_slip);
ChPacejkaTire tire_lat("LATERAL", pacParamFile, flat_terrain, F_z, use_transient_slip);
ChPacejkaTire tire_lat_gamma("LATERAL_GAMMA", pacParamFile, flat_terrain, F_z, use_transient_slip);
ChPacejkaTire tire_combined("COMBINED", pacParamFile, flat_terrain, F_z, use_transient_slip);
// initialize the tire on the left or right side
tire_long.Initialize(m_side);
tire_lat.Initialize(m_side);
tire_lat_gamma.Initialize(m_side);
tire_combined.Initialize(m_side);
// record pacTire output for each of the 3 slip cases
ChTireForces long_forces(1);
ChTireForces lat_forces(1);
ChTireForces latGamma_forces(1);
ChTireForces combined_forces(1);
// update body state based on varying input variables to pacTire:
// alpha, kappa and gamma
ChWheelState long_state;
ChWheelState lat_state;
ChWheelState latGamma_state;
ChWheelState combined_state;
// keep track of the input variable values
std::vector<double> latSlip_range;
std::vector<double> longSlip_range;
latSlip_range.resize(num_pts);
longSlip_range.resize(num_pts);
double time = 0.0;
// get the bounds of the slip angles from the input *.tire file
double k_min, k_max, a_min, a_max;
k_min = -kappa_lim;
k_max = kappa_lim;
a_min = -alpha_lim;
a_max = alpha_lim;
// at IC, go straight ahead at zero slip
double kappa_t = k_min;
double alpha_t = 0;
double tanalpha_t = tan(alpha_t);
double gamma_t = 0.1 * alpha_t;
// unless we're only using steady-state EQs, then just sweep min to max
if (!use_transient_slip)
{
alpha_t = a_min;
tanalpha_t = tan(alpha_t);
gamma_t = 0.1 * alpha_t;
} else {
out_name_long = "test_pacTire_pureLongSlip_transient.csv";
out_name_lat = "test_pacTire_pureLatSlip_transient.csv";
out_name_latGamma = "test_pacTire_pacLatSlipGamma_transient.csv";
out_name_combined = "test_pacTire_combinedSlip_transient.csv";
}
// calculate the increments for each slip case (assuming constant per step)
double kappa_incr = (k_max - k_min) / double(num_pts);
double alpha_incr = (a_max - a_min) / double(num_pts);
// horizontal velocity (x,y components) is constant throughout all runs
double vel_xy = tire_long.get_longvl();
// time step is arbitrary, steps determined by slip array length
for (size_t step = 0; step < num_pts; step++)
{
// tire input slip quantities
tanalpha_t = tan(alpha_t);
latSlip_range[step] = tanalpha_t;
longSlip_range[step] = kappa_t;
// **** longitudinal states
long_state = tire_long.getState_from_KAG(kappa_t, 0, 0, vel_xy);
// **** lateral states
lat_state = tire_lat.getState_from_KAG(0, alpha_t, 0, vel_xy);
// ***** lateral w/ specified gamma
latGamma_state = tire_lat_gamma.getState_from_KAG(0, alpha_t, gamma, vel_xy);
// **** combined states
combined_state = tire_combined.getState_from_KAG(kappa_t, alpha_t, gamma_t, vel_xy);
// DEBUGGING
if (step == 200)
int arg = 2;
// update all 4 types of tires, with current wheel state data
tire_long.Update(time, long_state);
tire_lat.Update(time, lat_state);
tire_lat_gamma.Update(time, latGamma_state);
tire_combined.Update(time, combined_state);
// advance the slip displacements, calculate reactions
tire_long.Advance(step_size);
tire_lat.Advance(step_size);
tire_lat_gamma.Advance(step_size);
tire_combined.Advance(step_size);
// see what the calculated reactions are
long_forces[0] = tire_long.GetTireForce();
lat_forces[0] = tire_lat.GetTireForce();
latGamma_forces[0] = tire_lat_gamma.GetTireForce();
combined_forces[0] = tire_combined.GetTireForce();
// output any data at the end of the step
tire_long.WriteOutData(time, out_name_long);
tire_lat.WriteOutData(time, out_name_lat);
tire_lat_gamma.WriteOutData(time, out_name_latGamma);
tire_combined.WriteOutData(time, out_name_combined);
// std::cout << "step: " << step << ", kappa = " << kappa_t << ", alpha = " << alpha_t << ", tan(alpha) = " << tanalpha_t << std::endl;
// increment time, update long. & lat. slips for the next time step
time += step_size;
// constant increments. sine waves would be better
if (use_transient_slip)
{
// do a powered lane change
// Careful !!!!
// need to properly mimic Adams/Car kappa, alpha vs. time
// kappa is linear
kappa_t += kappa_incr;
// lateral angle is a sine wave
alpha_t = abs(a_max) * sin(2.0 * chrono::CH_C_PI * time / time_end);
}
else {
kappa_t += kappa_incr;
alpha_t += alpha_incr;
}
}
// clean up anything
return 0;
}
<|endoftext|> |
<commit_before>#define CATCH_CONFIG_MAIN
#include "catch.hpp"
#include <iostream>
#include <vector>
#include "filters.h"
#include "yaml-cpp/yaml.h"
#include "sceneLoader.h"
using namespace Tangram;
using namespace YAML;
SceneLoader sceneLoader;
Context ctx;
Feature civic, bmw1, bike;
void init() {
civic.props.stringProps.clear();
civic.props.numericProps.clear();
civic.props.stringProps["name"] = "civic";
civic.props.stringProps["brand"] = "honda";
civic.props.stringProps["check"] = "true";
civic.props.numericProps["wheel"] = 4;
civic.props.stringProps["drive"] = "fwd";
civic.props.stringProps["type"] = "car";
civic.props.numericProps["fancy"] = 0;
bmw1.props.stringProps.clear();
bmw1.props.numericProps.clear();
bmw1.props.stringProps["name"] = "bmw320i";
bmw1.props.stringProps["brand"] = "bmw";
bmw1.props.stringProps["check"] = "false";
bmw1.props.stringProps["series"] = "3";
bmw1.props.numericProps["wheel"] = 4;
bmw1.props.stringProps["drive"] = "all";
bmw1.props.stringProps["type"] = "car";
bmw1.props.numericProps["fancy"] = 1;
bike.props.stringProps.clear();
bike.props.numericProps.clear();
bike.props.stringProps["name"] = "cb1100";
bike.props.stringProps["brand"] = "honda";
bike.props.numericProps["wheel"] = 2;
bike.props.stringProps["type"] = "bike";
bike.props.stringProps["series"] = "CB";
bike.props.stringProps["check"] = "available";
bike.props.numericProps["fancy"] = 1;
for (auto& it : ctx) {
delete it.second;
it.second = nullptr;
}
ctx["$vroom"] = new NumValue(1);
ctx["$zooooom"] = new StrValue("false");
}
//1. basic predicate
TEST_CASE( "yaml-filter-tests: basic predicate test", "[filters][core][yaml]") {
init();
YAML::Node node = YAML::Load("filter: { series: 3}");
Filter* filter = sceneLoader.generateFilter(node["filter"]);
REQUIRE(!filter->eval(civic, ctx));
REQUIRE(filter->eval(bmw1, ctx));
REQUIRE(!filter->eval(bike, ctx));
delete filter;
}
//2. predicate with valueList
TEST_CASE( "yaml-filter-tests: predicate with valueList", "[filters][core][yaml]") {
init();
YAML::Node node = YAML::Load("filter: { name : [civic, bmw320i] }");
Filter* filter = sceneLoader.generateFilter(node["filter"]);
REQUIRE(filter->eval(civic, ctx));
REQUIRE(filter->eval(bmw1, ctx));
REQUIRE(!filter->eval(bike, ctx));
delete filter;
}
//3. range min
TEST_CASE( "yaml-filter-tests: range min", "[filters][core][yaml]") {
init();
YAML::Node node = YAML::Load("filter: {wheel : {min : 3}}");
Filter* filter = sceneLoader.generateFilter(node["filter"]);
REQUIRE(filter->eval(civic, ctx));
REQUIRE(filter->eval(bmw1, ctx));
REQUIRE(!filter->eval(bike, ctx));
delete filter;
}
//4. range max
TEST_CASE( "yaml-filter-tests: range max", "[filters][core][yaml]") {
init();
YAML::Node node = YAML::Load("filter: {wheel : {max : 2}}");
Filter* filter = sceneLoader.generateFilter(node["filter"]);
REQUIRE(!filter->eval(civic, ctx));
REQUIRE(!filter->eval(bmw1, ctx));
REQUIRE(!filter->eval(bike, ctx));
delete filter;
}
//5. range min max
TEST_CASE( "yaml-filter-tests: range min max", "[filters][core][yaml]") {
init();
YAML::Node node = YAML::Load("filter: {wheel : {min : 2, max : 5}}");
Filter* filter = sceneLoader.generateFilter(node["filter"]);
REQUIRE(filter->eval(civic, ctx));
REQUIRE(filter->eval(bmw1, ctx));
REQUIRE(filter->eval(bike, ctx));
delete filter;
}
//6. any
TEST_CASE( "yaml-filter-tests: any", "[filters][core][yaml]") {
init();
YAML::Node node = YAML::Load("filter: {any : [{name : civic}, {name : bmw320i}]}");
Filter* filter = sceneLoader.generateFilter(node["filter"]);
REQUIRE(filter->eval(civic, ctx));
REQUIRE(filter->eval(bmw1, ctx));
REQUIRE(!filter->eval(bike, ctx));
delete filter;
}
//7. all
TEST_CASE( "yaml-filter-tests: all", "[filters][core][yaml]") {
init();
//YAML::Node node = YAML::Load("filter: {any : [{name : civic}, {name : bmw320i}]}");
YAML::Node node = YAML::Load("filter: {all : [ {name : civic}, {brand : honda}, {wheel: 4} ] }");
Filter* filter = sceneLoader.generateFilter(node["filter"]);
REQUIRE(filter->eval(civic, ctx));
REQUIRE(!filter->eval(bmw1, ctx));
REQUIRE(!filter->eval(bike, ctx));
delete filter;
}
//8. none
TEST_CASE( "yaml-filter-tests: none", "[filters][core][yaml]") {
init();
YAML::Node node = YAML::Load("filter: {none : [{name : civic}, {name : bmw320i}]}");
Filter* filter = sceneLoader.generateFilter(node["filter"]);
REQUIRE(!filter->eval(civic, ctx));
REQUIRE(!filter->eval(bmw1, ctx));
REQUIRE(filter->eval(bike, ctx));
delete filter;
}
//9. not
TEST_CASE( "yaml-filter-tests: not", "[filters][core][yaml]") {
init();
YAML::Node node = YAML::Load("filter: {not : {name : civic}}");
Filter* filter = sceneLoader.generateFilter(node["filter"]);
REQUIRE(!filter->eval(civic, ctx));
REQUIRE(filter->eval(bmw1, ctx));
REQUIRE(filter->eval(bike, ctx));
delete filter;
}
//10. basic predicate with context
TEST_CASE( "yaml-filter-tests: context filter", "[filters][core][yaml]") {
init();
YAML::Node node = YAML::Load("filter: {$vroom : 1}");
Filter* filter = sceneLoader.generateFilter(node["filter"]);
REQUIRE(filter->eval(civic, ctx));
REQUIRE(filter->eval(bmw1, ctx));
REQUIRE(filter->eval(bike, ctx));
delete filter;
}
TEST_CASE( "yaml-filter-tests: boolean filter", "[filters][core][yaml]") {
init();
YAML::Node node = YAML::Load("filter: {fancy : true}");
Filter* filter = sceneLoader.generateFilter(node["filter"]);
REQUIRE(!filter->eval(civic, ctx));
REQUIRE(filter->eval(bmw1, ctx));
REQUIRE(filter->eval(bike, ctx));
delete filter;
}
TEST_CASE( "yaml-filter-tests: bogus filter", "[filters][core][yaml]") {
init();
YAML::Node node = YAML::Load("filter: {max: bogus}");
Filter* filter = sceneLoader.generateFilter(node["filter"]);
REQUIRE(!filter->eval(civic, ctx));
REQUIRE(!filter->eval(bmw1, ctx));
REQUIRE(!filter->eval(bike, ctx));
delete filter;
}
TEST_CASE( "yaml-filter-tests: true/false as string value", "[filters][core][yaml]") {
init();
YAML::Node node = YAML::Load("filter: {any : [{check: true}, {check: false}]}");
Filter* filter = sceneLoader.generateFilter(node["filter"]);
REQUIRE(filter->eval(civic, ctx));
REQUIRE(filter->eval(bmw1, ctx));
REQUIRE(!filter->eval(bike, ctx));
delete filter;
}
<commit_msg>Add test for boolean filter as existence check<commit_after>#define CATCH_CONFIG_MAIN
#include "catch.hpp"
#include <iostream>
#include <vector>
#include "filters.h"
#include "yaml-cpp/yaml.h"
#include "sceneLoader.h"
using namespace Tangram;
using namespace YAML;
SceneLoader sceneLoader;
Context ctx;
Feature civic, bmw1, bike;
void init() {
civic.props.stringProps.clear();
civic.props.numericProps.clear();
civic.props.stringProps["name"] = "civic";
civic.props.stringProps["brand"] = "honda";
civic.props.stringProps["check"] = "true";
civic.props.numericProps["wheel"] = 4;
civic.props.stringProps["drive"] = "fwd";
civic.props.stringProps["type"] = "car";
civic.props.numericProps["fancy"] = 0;
bmw1.props.stringProps.clear();
bmw1.props.numericProps.clear();
bmw1.props.stringProps["name"] = "bmw320i";
bmw1.props.stringProps["brand"] = "bmw";
bmw1.props.stringProps["check"] = "false";
bmw1.props.stringProps["series"] = "3";
bmw1.props.numericProps["wheel"] = 4;
bmw1.props.stringProps["drive"] = "all";
bmw1.props.stringProps["type"] = "car";
bmw1.props.numericProps["fancy"] = 1;
bike.props.stringProps.clear();
bike.props.numericProps.clear();
bike.props.stringProps["name"] = "cb1100";
bike.props.stringProps["brand"] = "honda";
bike.props.numericProps["wheel"] = 2;
bike.props.stringProps["type"] = "bike";
bike.props.stringProps["series"] = "CB";
bike.props.stringProps["check"] = "available";
bike.props.numericProps["fancy"] = 1;
for (auto& it : ctx) {
delete it.second;
it.second = nullptr;
}
ctx["$vroom"] = new NumValue(1);
ctx["$zooooom"] = new StrValue("false");
}
//1. basic predicate
TEST_CASE( "yaml-filter-tests: basic predicate test", "[filters][core][yaml]") {
init();
YAML::Node node = YAML::Load("filter: { series: 3}");
Filter* filter = sceneLoader.generateFilter(node["filter"]);
REQUIRE(!filter->eval(civic, ctx));
REQUIRE(filter->eval(bmw1, ctx));
REQUIRE(!filter->eval(bike, ctx));
delete filter;
}
//2. predicate with valueList
TEST_CASE( "yaml-filter-tests: predicate with valueList", "[filters][core][yaml]") {
init();
YAML::Node node = YAML::Load("filter: { name : [civic, bmw320i] }");
Filter* filter = sceneLoader.generateFilter(node["filter"]);
REQUIRE(filter->eval(civic, ctx));
REQUIRE(filter->eval(bmw1, ctx));
REQUIRE(!filter->eval(bike, ctx));
delete filter;
}
//3. range min
TEST_CASE( "yaml-filter-tests: range min", "[filters][core][yaml]") {
init();
YAML::Node node = YAML::Load("filter: {wheel : {min : 3}}");
Filter* filter = sceneLoader.generateFilter(node["filter"]);
REQUIRE(filter->eval(civic, ctx));
REQUIRE(filter->eval(bmw1, ctx));
REQUIRE(!filter->eval(bike, ctx));
delete filter;
}
//4. range max
TEST_CASE( "yaml-filter-tests: range max", "[filters][core][yaml]") {
init();
YAML::Node node = YAML::Load("filter: {wheel : {max : 2}}");
Filter* filter = sceneLoader.generateFilter(node["filter"]);
REQUIRE(!filter->eval(civic, ctx));
REQUIRE(!filter->eval(bmw1, ctx));
REQUIRE(!filter->eval(bike, ctx));
delete filter;
}
//5. range min max
TEST_CASE( "yaml-filter-tests: range min max", "[filters][core][yaml]") {
init();
YAML::Node node = YAML::Load("filter: {wheel : {min : 2, max : 5}}");
Filter* filter = sceneLoader.generateFilter(node["filter"]);
REQUIRE(filter->eval(civic, ctx));
REQUIRE(filter->eval(bmw1, ctx));
REQUIRE(filter->eval(bike, ctx));
delete filter;
}
//6. any
TEST_CASE( "yaml-filter-tests: any", "[filters][core][yaml]") {
init();
YAML::Node node = YAML::Load("filter: {any : [{name : civic}, {name : bmw320i}]}");
Filter* filter = sceneLoader.generateFilter(node["filter"]);
REQUIRE(filter->eval(civic, ctx));
REQUIRE(filter->eval(bmw1, ctx));
REQUIRE(!filter->eval(bike, ctx));
delete filter;
}
//7. all
TEST_CASE( "yaml-filter-tests: all", "[filters][core][yaml]") {
init();
//YAML::Node node = YAML::Load("filter: {any : [{name : civic}, {name : bmw320i}]}");
YAML::Node node = YAML::Load("filter: {all : [ {name : civic}, {brand : honda}, {wheel: 4} ] }");
Filter* filter = sceneLoader.generateFilter(node["filter"]);
REQUIRE(filter->eval(civic, ctx));
REQUIRE(!filter->eval(bmw1, ctx));
REQUIRE(!filter->eval(bike, ctx));
delete filter;
}
//8. none
TEST_CASE( "yaml-filter-tests: none", "[filters][core][yaml]") {
init();
YAML::Node node = YAML::Load("filter: {none : [{name : civic}, {name : bmw320i}]}");
Filter* filter = sceneLoader.generateFilter(node["filter"]);
REQUIRE(!filter->eval(civic, ctx));
REQUIRE(!filter->eval(bmw1, ctx));
REQUIRE(filter->eval(bike, ctx));
delete filter;
}
//9. not
TEST_CASE( "yaml-filter-tests: not", "[filters][core][yaml]") {
init();
YAML::Node node = YAML::Load("filter: {not : {name : civic}}");
Filter* filter = sceneLoader.generateFilter(node["filter"]);
REQUIRE(!filter->eval(civic, ctx));
REQUIRE(filter->eval(bmw1, ctx));
REQUIRE(filter->eval(bike, ctx));
delete filter;
}
//10. basic predicate with context
TEST_CASE( "yaml-filter-tests: context filter", "[filters][core][yaml]") {
init();
YAML::Node node = YAML::Load("filter: {$vroom : 1}");
Filter* filter = sceneLoader.generateFilter(node["filter"]);
REQUIRE(filter->eval(civic, ctx));
REQUIRE(filter->eval(bmw1, ctx));
REQUIRE(filter->eval(bike, ctx));
delete filter;
}
TEST_CASE( "yaml-filter-tests: boolean filter", "[filters][core][yaml]") {
init();
YAML::Node node = YAML::Load("filter: {fancy : true}");
Filter* filter = sceneLoader.generateFilter(node["filter"]);
REQUIRE(!filter->eval(civic, ctx));
REQUIRE(filter->eval(bmw1, ctx));
REQUIRE(filter->eval(bike, ctx));
delete filter;
}
TEST_CASE( "yaml-filter-tests: bogus filter", "[filters][core][yaml]") {
init();
YAML::Node node = YAML::Load("filter: {max: bogus}");
Filter* filter = sceneLoader.generateFilter(node["filter"]);
REQUIRE(!filter->eval(civic, ctx));
REQUIRE(!filter->eval(bmw1, ctx));
REQUIRE(!filter->eval(bike, ctx));
delete filter;
}
TEST_CASE( "yaml-filter-tests: true/false as string value", "[filters][core][yaml]") {
init();
YAML::Node node = YAML::Load("filter: {any : [{check: true}, {check: false}]}");
Filter* filter = sceneLoader.generateFilter(node["filter"]);
REQUIRE(filter->eval(civic, ctx));
REQUIRE(filter->eval(bmw1, ctx));
REQUIRE(!filter->eval(bike, ctx));
delete filter;
}
TEST_CASE( "yaml-filter-tests: boolean filter as existence check", "[filters][core][yaml]") {
init();
YAML::Node node = YAML::Load("filter: { drive : true }");
Filter* filter = sceneLoader.generateFilter(node["filter"]);
REQUIRE(filter->eval(civic, ctx));
REQUIRE(filter->eval(bmw1, ctx));
REQUIRE(!filter->eval(bike, ctx));
delete filter;
}
<|endoftext|> |
<commit_before>#include "PWSfile.h"
#include "PWSfileV1V2.h"
#include <io.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <errno.h>
PWSfile *PWSfile::MakePWSfile(const CMyString &a_filename, VERSION &version,
RWmode mode, int &status)
{
if (mode == Read && !FileExists(a_filename)) {
status = CANT_OPEN_FILE;
return NULL;
}
switch (version) {
case V17:
case V20:
status = SUCCESS;
return new PWSfileV1V2(a_filename, mode, version);
case V30: // XXX ...
status = UNSUPPORTED_VERSION;
return NULL;
case UNKNOWN_VERSION:
ASSERT(mode == Read);
// XXX need to quickly determine file version
version = V20;
status = SUCCESS;
return new PWSfileV1V2(a_filename, mode, version);
default:
ASSERT(0);
status = FAILURE; return NULL;
}
}
bool PWSfile::FileExists(const CMyString &filename)
{
struct _stat statbuf;
int status;
status = ::_tstat(filename, &statbuf);
return (status == 0);
}
int PWSfile::RenameFile(const CMyString &oldname, const CMyString &newname)
{
_tremove(newname); // otherwise rename will fail if newname exists
int status = _trename(oldname, newname);
return (status == 0) ? SUCCESS : FAILURE;
}
PWSfile::PWSfile(const CMyString &filename, RWmode mode)
: m_filename(filename), m_passkey(_T("")), m_defusername(_T("")),
m_curversion(UNKNOWN_VERSION), m_rw(mode),
m_fd(NULL), m_prefString(_T("")), m_fish(NULL)
{
}
PWSfile::~PWSfile()
{
Close(); // idempotent
}
int PWSfile::Close()
{
delete m_fish;
m_fish = NULL;
if (m_fd != NULL) {
fclose(m_fd);
m_fd = NULL;
}
return SUCCESS;
}
int PWSfile::WriteCBC(unsigned char type, const CString &data)
{
// We do a double cast because the LPCSTR cast operator is overridden
// by the CString class to access the pointer we need,
// but we in fact need it as an unsigned char. Grrrr.
LPCSTR datastr = LPCSTR(data);
return WriteCBC(type, (const unsigned char *)datastr,
data.GetLength());
}
int PWSfile::WriteCBC(unsigned char type, const unsigned char *data,
unsigned int length)
{
ASSERT(m_fish != NULL && m_IV != NULL);
return _writecbc(m_fd, data, length, type, m_fish, m_IV);
}
int PWSfile::ReadCBC(unsigned char &type, CMyString &data)
{
unsigned char *buffer = NULL;
unsigned int buffer_len = 0;
int retval;
ASSERT(m_fish != NULL && m_IV != NULL);
retval = _readcbc(m_fd, buffer, buffer_len, type, m_fish, m_IV);
if (buffer_len > 0) {
CMyString str(LPCSTR(buffer), buffer_len);
data = str;
trashMemory(buffer, buffer_len);
delete[] buffer;
} else {
data = _T("");
// no need to delete[] buffer, since _readcbc will not allocate if
// buffer_len is zero
}
return retval;
}
int PWSfile::CheckPassword(const CMyString &filename, const CMyString &passkey)
{
// XXX start with V3 check
int status = PWSfileV1V2::CheckPassword(filename, passkey);
return status;
}
<commit_msg>Implemented general CheckPassword<commit_after>#include "PWSfile.h"
#include "PWSfileV1V2.h"
#include "PWSfileV3.h"
#include <io.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <errno.h>
PWSfile *PWSfile::MakePWSfile(const CMyString &a_filename, VERSION &version,
RWmode mode, int &status)
{
if (mode == Read && !FileExists(a_filename)) {
status = CANT_OPEN_FILE;
return NULL;
}
switch (version) {
case V17:
case V20:
status = SUCCESS;
return new PWSfileV1V2(a_filename, mode, version);
case V30: // XXX ...
status = UNSUPPORTED_VERSION;
return NULL;
case UNKNOWN_VERSION:
ASSERT(mode == Read);
// XXX need to quickly determine file version
version = V20;
status = SUCCESS;
return new PWSfileV1V2(a_filename, mode, version);
default:
ASSERT(0);
status = FAILURE; return NULL;
}
}
bool PWSfile::FileExists(const CMyString &filename)
{
struct _stat statbuf;
int status;
status = ::_tstat(filename, &statbuf);
return (status == 0);
}
int PWSfile::RenameFile(const CMyString &oldname, const CMyString &newname)
{
_tremove(newname); // otherwise rename will fail if newname exists
int status = _trename(oldname, newname);
return (status == 0) ? SUCCESS : FAILURE;
}
PWSfile::PWSfile(const CMyString &filename, RWmode mode)
: m_filename(filename), m_passkey(_T("")), m_defusername(_T("")),
m_curversion(UNKNOWN_VERSION), m_rw(mode),
m_fd(NULL), m_prefString(_T("")), m_fish(NULL)
{
}
PWSfile::~PWSfile()
{
Close(); // idempotent
}
int PWSfile::Close()
{
delete m_fish;
m_fish = NULL;
if (m_fd != NULL) {
fclose(m_fd);
m_fd = NULL;
}
return SUCCESS;
}
int PWSfile::WriteCBC(unsigned char type, const CString &data)
{
// We do a double cast because the LPCSTR cast operator is overridden
// by the CString class to access the pointer we need,
// but we in fact need it as an unsigned char. Grrrr.
LPCSTR datastr = LPCSTR(data);
return WriteCBC(type, (const unsigned char *)datastr,
data.GetLength());
}
int PWSfile::WriteCBC(unsigned char type, const unsigned char *data,
unsigned int length)
{
ASSERT(m_fish != NULL && m_IV != NULL);
return _writecbc(m_fd, data, length, type, m_fish, m_IV);
}
int PWSfile::ReadCBC(unsigned char &type, CMyString &data)
{
unsigned char *buffer = NULL;
unsigned int buffer_len = 0;
int retval;
ASSERT(m_fish != NULL && m_IV != NULL);
retval = _readcbc(m_fd, buffer, buffer_len, type, m_fish, m_IV);
if (buffer_len > 0) {
CMyString str(LPCSTR(buffer), buffer_len);
data = str;
trashMemory(buffer, buffer_len);
delete[] buffer;
} else {
data = _T("");
// no need to delete[] buffer, since _readcbc will not allocate if
// buffer_len is zero
}
return retval;
}
int PWSfile::CheckPassword(const CMyString &filename, const CMyString &passkey)
{
int status = PWSfileV3::CheckPassword(filename, passkey);
if (status == NOT_PWS3_FILE)
status = PWSfileV1V2::CheckPassword(filename, passkey);
return status;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2013 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "GLTestContext.h"
#include "GpuTimer.h"
#include "gl/GrGLUtil.h"
namespace {
class GLFenceSync : public sk_gpu_test::FenceSync {
public:
static std::unique_ptr<GLFenceSync> MakeIfSupported(const sk_gpu_test::GLTestContext*);
sk_gpu_test::PlatformFence SK_WARN_UNUSED_RESULT insertFence() const override;
bool waitFence(sk_gpu_test::PlatformFence fence) const override;
void deleteFence(sk_gpu_test::PlatformFence fence) const override;
private:
GLFenceSync(const sk_gpu_test::GLTestContext*, const char* ext = "");
bool validate() { return fGLFenceSync && fGLClientWaitSync && fGLDeleteSync; }
static constexpr GrGLenum GL_SYNC_GPU_COMMANDS_COMPLETE = 0x9117;
static constexpr GrGLenum GL_WAIT_FAILED = 0x911d;
static constexpr GrGLbitfield GL_SYNC_FLUSH_COMMANDS_BIT = 0x00000001;
typedef struct __GLsync *GLsync;
GR_STATIC_ASSERT(sizeof(GLsync) <= sizeof(sk_gpu_test::PlatformFence));
typedef GLsync (GR_GL_FUNCTION_TYPE* GLFenceSyncProc) (GrGLenum, GrGLbitfield);
typedef GrGLenum (GR_GL_FUNCTION_TYPE* GLClientWaitSyncProc) (GLsync, GrGLbitfield, GrGLuint64);
typedef GrGLvoid (GR_GL_FUNCTION_TYPE* GLDeleteSyncProc) (GLsync);
GLFenceSyncProc fGLFenceSync;
GLClientWaitSyncProc fGLClientWaitSync;
GLDeleteSyncProc fGLDeleteSync;
typedef FenceSync INHERITED;
};
std::unique_ptr<GLFenceSync> GLFenceSync::MakeIfSupported(const sk_gpu_test::GLTestContext* ctx) {
std::unique_ptr<GLFenceSync> ret;
if (kGL_GrGLStandard == ctx->gl()->fStandard) {
if (GrGLGetVersion(ctx->gl()) < GR_GL_VER(3,2) && !ctx->gl()->hasExtension("GL_ARB_sync")) {
return nullptr;
}
ret.reset(new GLFenceSync(ctx));
} else {
if (!ctx->gl()->hasExtension("GL_APPLE_sync")) {
return nullptr;
}
ret.reset(new GLFenceSync(ctx, "APPLE"));
}
if (!ret->validate()) {
ret = nullptr;
}
return ret;
}
GLFenceSync::GLFenceSync(const sk_gpu_test::GLTestContext* ctx, const char* ext) {
ctx->getGLProcAddress(&fGLFenceSync, "glFenceSync");
ctx->getGLProcAddress(&fGLClientWaitSync, "glClientWaitSync");
ctx->getGLProcAddress(&fGLDeleteSync, "glDeleteSync");
}
sk_gpu_test::PlatformFence GLFenceSync::insertFence() const {
__GLsync* glsync = fGLFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0);
return reinterpret_cast<sk_gpu_test::PlatformFence>(glsync);
}
bool GLFenceSync::waitFence(sk_gpu_test::PlatformFence fence) const {
GLsync glsync = reinterpret_cast<GLsync>(fence);
return GL_WAIT_FAILED != fGLClientWaitSync(glsync, GL_SYNC_FLUSH_COMMANDS_BIT, -1);
}
void GLFenceSync::deleteFence(sk_gpu_test::PlatformFence fence) const {
GLsync glsync = reinterpret_cast<GLsync>(fence);
fGLDeleteSync(glsync);
}
class GLGpuTimer : public sk_gpu_test::GpuTimer {
public:
static std::unique_ptr<GLGpuTimer> MakeIfSupported(const sk_gpu_test::GLTestContext*);
QueryStatus checkQueryStatus(sk_gpu_test::PlatformTimerQuery) override;
std::chrono::nanoseconds getTimeElapsed(sk_gpu_test::PlatformTimerQuery) override;
void deleteQuery(sk_gpu_test::PlatformTimerQuery) override;
private:
GLGpuTimer(bool disjointSupport, const sk_gpu_test::GLTestContext*, const char* ext = "");
bool validate() const;
sk_gpu_test::PlatformTimerQuery onQueueTimerStart() const override;
void onQueueTimerStop(sk_gpu_test::PlatformTimerQuery) const override;
static constexpr GrGLenum GL_QUERY_RESULT = 0x8866;
static constexpr GrGLenum GL_QUERY_RESULT_AVAILABLE = 0x8867;
static constexpr GrGLenum GL_TIME_ELAPSED = 0x88bf;
static constexpr GrGLenum GL_GPU_DISJOINT = 0x8fbb;
typedef void (GR_GL_FUNCTION_TYPE* GLGetIntegervProc) (GrGLenum, GrGLint*);
typedef void (GR_GL_FUNCTION_TYPE* GLGenQueriesProc) (GrGLsizei, GrGLuint*);
typedef void (GR_GL_FUNCTION_TYPE* GLDeleteQueriesProc) (GrGLsizei, const GrGLuint*);
typedef void (GR_GL_FUNCTION_TYPE* GLBeginQueryProc) (GrGLenum, GrGLuint);
typedef void (GR_GL_FUNCTION_TYPE* GLEndQueryProc) (GrGLenum);
typedef void (GR_GL_FUNCTION_TYPE* GLGetQueryObjectuivProc) (GrGLuint, GrGLenum, GrGLuint*);
typedef void (GR_GL_FUNCTION_TYPE* GLGetQueryObjectui64vProc) (GrGLuint, GrGLenum, GrGLuint64*);
GLGetIntegervProc fGLGetIntegerv;
GLGenQueriesProc fGLGenQueries;
GLDeleteQueriesProc fGLDeleteQueries;
GLBeginQueryProc fGLBeginQuery;
GLEndQueryProc fGLEndQuery;
GLGetQueryObjectuivProc fGLGetQueryObjectuiv;
GLGetQueryObjectui64vProc fGLGetQueryObjectui64v;
typedef sk_gpu_test::GpuTimer INHERITED;
};
std::unique_ptr<GLGpuTimer> GLGpuTimer::MakeIfSupported(const sk_gpu_test::GLTestContext* ctx) {
std::unique_ptr<GLGpuTimer> ret;
const GrGLInterface* gl = ctx->gl();
if (gl->fExtensions.has("GL_EXT_disjoint_timer_query")) {
ret.reset(new GLGpuTimer(true, ctx, "EXT"));
} else if (kGL_GrGLStandard == gl->fStandard &&
(GrGLGetVersion(gl) > GR_GL_VER(3,3) || gl->fExtensions.has("GL_ARB_timer_query"))) {
ret.reset(new GLGpuTimer(false, ctx));
} else if (gl->fExtensions.has("GL_EXT_timer_query")) {
ret.reset(new GLGpuTimer(false, ctx, "EXT"));
}
if (ret && !ret->validate()) {
ret = nullptr;
}
return ret;
}
GLGpuTimer::GLGpuTimer(bool disjointSupport, const sk_gpu_test::GLTestContext* ctx, const char* ext)
: INHERITED(disjointSupport) {
ctx->getGLProcAddress(&fGLGetIntegerv, "glGetIntegerv");
ctx->getGLProcAddress(&fGLGenQueries, "glGenQueries", ext);
ctx->getGLProcAddress(&fGLDeleteQueries, "glDeleteQueries", ext);
ctx->getGLProcAddress(&fGLBeginQuery, "glBeginQuery", ext);
ctx->getGLProcAddress(&fGLEndQuery, "glEndQuery", ext);
ctx->getGLProcAddress(&fGLGetQueryObjectuiv, "glGetQueryObjectuiv", ext);
ctx->getGLProcAddress(&fGLGetQueryObjectui64v, "glGetQueryObjectui64v", ext);
}
bool GLGpuTimer::validate() const {
return fGLGetIntegerv && fGLGenQueries && fGLDeleteQueries && fGLBeginQuery && fGLEndQuery &&
fGLGetQueryObjectuiv && fGLGetQueryObjectui64v;
}
sk_gpu_test::PlatformTimerQuery GLGpuTimer::onQueueTimerStart() const {
GrGLuint queryID;
fGLGenQueries(1, &queryID);
if (!queryID) {
return sk_gpu_test::kInvalidTimerQuery;
}
if (this->disjointSupport()) {
// Clear the disjoint flag.
GrGLint disjoint;
fGLGetIntegerv(GL_GPU_DISJOINT, &disjoint);
}
fGLBeginQuery(GL_TIME_ELAPSED, queryID);
return static_cast<sk_gpu_test::PlatformTimerQuery>(queryID);
}
void GLGpuTimer::onQueueTimerStop(sk_gpu_test::PlatformTimerQuery platformTimer) const {
if (sk_gpu_test::kInvalidTimerQuery == platformTimer) {
return;
}
fGLEndQuery(GL_TIME_ELAPSED);
}
sk_gpu_test::GpuTimer::QueryStatus
GLGpuTimer::checkQueryStatus(sk_gpu_test::PlatformTimerQuery platformTimer) {
const GrGLuint queryID = static_cast<GrGLuint>(platformTimer);
if (!queryID) {
return QueryStatus::kInvalid;
}
GrGLuint available = 0;
fGLGetQueryObjectuiv(queryID, GL_QUERY_RESULT_AVAILABLE, &available);
if (!available) {
return QueryStatus::kPending;
}
if (this->disjointSupport()) {
GrGLint disjoint = 1;
fGLGetIntegerv(GL_GPU_DISJOINT, &disjoint);
if (disjoint) {
return QueryStatus::kDisjoint;
}
}
return QueryStatus::kAccurate;
}
std::chrono::nanoseconds GLGpuTimer::getTimeElapsed(sk_gpu_test::PlatformTimerQuery platformTimer) {
SkASSERT(this->checkQueryStatus(platformTimer) >= QueryStatus::kDisjoint);
const GrGLuint queryID = static_cast<GrGLuint>(platformTimer);
GrGLuint64 nanoseconds;
fGLGetQueryObjectui64v(queryID, GL_QUERY_RESULT, &nanoseconds);
return std::chrono::nanoseconds(nanoseconds);
}
void GLGpuTimer::deleteQuery(sk_gpu_test::PlatformTimerQuery platformTimer) {
const GrGLuint queryID = static_cast<GrGLuint>(platformTimer);
fGLDeleteQueries(1, &queryID);
}
GR_STATIC_ASSERT(sizeof(GrGLuint) <= sizeof(sk_gpu_test::PlatformTimerQuery));
} // anonymous namespace
namespace sk_gpu_test {
GLTestContext::GLTestContext() : TestContext() {}
GLTestContext::~GLTestContext() {
SkASSERT(nullptr == fGL.get());
}
void GLTestContext::init(const GrGLInterface* gl, std::unique_ptr<FenceSync> fenceSync) {
SkASSERT(!fGL.get());
fGL.reset(gl);
fFenceSync = fenceSync ? std::move(fenceSync) : GLFenceSync::MakeIfSupported(this);
fGpuTimer = GLGpuTimer::MakeIfSupported(this);
}
void GLTestContext::teardown() {
fGL.reset(nullptr);
INHERITED::teardown();
}
void GLTestContext::testAbandon() {
INHERITED::testAbandon();
if (fGL) {
fGL->abandon();
}
}
void GLTestContext::submit() {
if (fGL) {
GR_GL_CALL(fGL.get(), Flush());
}
}
void GLTestContext::finish() {
if (fGL) {
GR_GL_CALL(fGL.get(), Finish());
}
}
GrGLint GLTestContext::createTextureRectangle(int width, int height, GrGLenum internalFormat,
GrGLenum externalFormat, GrGLenum externalType,
GrGLvoid* data) {
if (!(kGL_GrGLStandard == fGL->fStandard && GrGLGetVersion(fGL.get()) >= GR_GL_VER(3, 1)) &&
!fGL->fExtensions.has("GL_ARB_texture_rectangle")) {
return 0;
}
if (GrGLGetGLSLVersion(fGL.get()) < GR_GLSL_VER(1, 40)) {
return 0;
}
GrGLuint id;
GR_GL_CALL(fGL.get(), GenTextures(1, &id));
GR_GL_CALL(fGL.get(), BindTexture(GR_GL_TEXTURE_RECTANGLE, id));
GR_GL_CALL(fGL.get(), TexParameteri(GR_GL_TEXTURE_RECTANGLE, GR_GL_TEXTURE_MAG_FILTER,
GR_GL_NEAREST));
GR_GL_CALL(fGL.get(), TexParameteri(GR_GL_TEXTURE_RECTANGLE, GR_GL_TEXTURE_MIN_FILTER,
GR_GL_NEAREST));
GR_GL_CALL(fGL.get(), TexParameteri(GR_GL_TEXTURE_RECTANGLE, GR_GL_TEXTURE_WRAP_S,
GR_GL_CLAMP_TO_EDGE));
GR_GL_CALL(fGL.get(), TexParameteri(GR_GL_TEXTURE_RECTANGLE, GR_GL_TEXTURE_WRAP_T,
GR_GL_CLAMP_TO_EDGE));
GR_GL_CALL(fGL.get(), TexImage2D(GR_GL_TEXTURE_RECTANGLE, 0, internalFormat, width, height, 0,
externalFormat, externalType, data));
return id;
}
} // namespace sk_gpu_test
<commit_msg>Enable fence sync support in ES3 test contexts<commit_after>/*
* Copyright 2013 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "GLTestContext.h"
#include "GpuTimer.h"
#include "gl/GrGLUtil.h"
namespace {
class GLFenceSync : public sk_gpu_test::FenceSync {
public:
static std::unique_ptr<GLFenceSync> MakeIfSupported(const sk_gpu_test::GLTestContext*);
sk_gpu_test::PlatformFence SK_WARN_UNUSED_RESULT insertFence() const override;
bool waitFence(sk_gpu_test::PlatformFence fence) const override;
void deleteFence(sk_gpu_test::PlatformFence fence) const override;
private:
GLFenceSync(const sk_gpu_test::GLTestContext*, const char* ext = "");
bool validate() { return fGLFenceSync && fGLClientWaitSync && fGLDeleteSync; }
static constexpr GrGLenum GL_SYNC_GPU_COMMANDS_COMPLETE = 0x9117;
static constexpr GrGLenum GL_WAIT_FAILED = 0x911d;
static constexpr GrGLbitfield GL_SYNC_FLUSH_COMMANDS_BIT = 0x00000001;
typedef struct __GLsync *GLsync;
GR_STATIC_ASSERT(sizeof(GLsync) <= sizeof(sk_gpu_test::PlatformFence));
typedef GLsync (GR_GL_FUNCTION_TYPE* GLFenceSyncProc) (GrGLenum, GrGLbitfield);
typedef GrGLenum (GR_GL_FUNCTION_TYPE* GLClientWaitSyncProc) (GLsync, GrGLbitfield, GrGLuint64);
typedef GrGLvoid (GR_GL_FUNCTION_TYPE* GLDeleteSyncProc) (GLsync);
GLFenceSyncProc fGLFenceSync;
GLClientWaitSyncProc fGLClientWaitSync;
GLDeleteSyncProc fGLDeleteSync;
typedef FenceSync INHERITED;
};
std::unique_ptr<GLFenceSync> GLFenceSync::MakeIfSupported(const sk_gpu_test::GLTestContext* ctx) {
std::unique_ptr<GLFenceSync> ret;
if (kGL_GrGLStandard == ctx->gl()->fStandard) {
if (GrGLGetVersion(ctx->gl()) < GR_GL_VER(3,2) && !ctx->gl()->hasExtension("GL_ARB_sync")) {
return nullptr;
}
ret.reset(new GLFenceSync(ctx));
} else {
if (ctx->gl()->hasExtension("GL_APPLE_sync")) {
ret.reset(new GLFenceSync(ctx, "APPLE"));
} else if (GrGLGetVersion(ctx->gl()) >= GR_GL_VER(3, 0)) {
ret.reset(new GLFenceSync(ctx));
} else {
return nullptr;
}
}
if (!ret->validate()) {
ret = nullptr;
}
return ret;
}
GLFenceSync::GLFenceSync(const sk_gpu_test::GLTestContext* ctx, const char* ext) {
ctx->getGLProcAddress(&fGLFenceSync, "glFenceSync");
ctx->getGLProcAddress(&fGLClientWaitSync, "glClientWaitSync");
ctx->getGLProcAddress(&fGLDeleteSync, "glDeleteSync");
}
sk_gpu_test::PlatformFence GLFenceSync::insertFence() const {
__GLsync* glsync = fGLFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0);
return reinterpret_cast<sk_gpu_test::PlatformFence>(glsync);
}
bool GLFenceSync::waitFence(sk_gpu_test::PlatformFence fence) const {
GLsync glsync = reinterpret_cast<GLsync>(fence);
return GL_WAIT_FAILED != fGLClientWaitSync(glsync, GL_SYNC_FLUSH_COMMANDS_BIT, -1);
}
void GLFenceSync::deleteFence(sk_gpu_test::PlatformFence fence) const {
GLsync glsync = reinterpret_cast<GLsync>(fence);
fGLDeleteSync(glsync);
}
class GLGpuTimer : public sk_gpu_test::GpuTimer {
public:
static std::unique_ptr<GLGpuTimer> MakeIfSupported(const sk_gpu_test::GLTestContext*);
QueryStatus checkQueryStatus(sk_gpu_test::PlatformTimerQuery) override;
std::chrono::nanoseconds getTimeElapsed(sk_gpu_test::PlatformTimerQuery) override;
void deleteQuery(sk_gpu_test::PlatformTimerQuery) override;
private:
GLGpuTimer(bool disjointSupport, const sk_gpu_test::GLTestContext*, const char* ext = "");
bool validate() const;
sk_gpu_test::PlatformTimerQuery onQueueTimerStart() const override;
void onQueueTimerStop(sk_gpu_test::PlatformTimerQuery) const override;
static constexpr GrGLenum GL_QUERY_RESULT = 0x8866;
static constexpr GrGLenum GL_QUERY_RESULT_AVAILABLE = 0x8867;
static constexpr GrGLenum GL_TIME_ELAPSED = 0x88bf;
static constexpr GrGLenum GL_GPU_DISJOINT = 0x8fbb;
typedef void (GR_GL_FUNCTION_TYPE* GLGetIntegervProc) (GrGLenum, GrGLint*);
typedef void (GR_GL_FUNCTION_TYPE* GLGenQueriesProc) (GrGLsizei, GrGLuint*);
typedef void (GR_GL_FUNCTION_TYPE* GLDeleteQueriesProc) (GrGLsizei, const GrGLuint*);
typedef void (GR_GL_FUNCTION_TYPE* GLBeginQueryProc) (GrGLenum, GrGLuint);
typedef void (GR_GL_FUNCTION_TYPE* GLEndQueryProc) (GrGLenum);
typedef void (GR_GL_FUNCTION_TYPE* GLGetQueryObjectuivProc) (GrGLuint, GrGLenum, GrGLuint*);
typedef void (GR_GL_FUNCTION_TYPE* GLGetQueryObjectui64vProc) (GrGLuint, GrGLenum, GrGLuint64*);
GLGetIntegervProc fGLGetIntegerv;
GLGenQueriesProc fGLGenQueries;
GLDeleteQueriesProc fGLDeleteQueries;
GLBeginQueryProc fGLBeginQuery;
GLEndQueryProc fGLEndQuery;
GLGetQueryObjectuivProc fGLGetQueryObjectuiv;
GLGetQueryObjectui64vProc fGLGetQueryObjectui64v;
typedef sk_gpu_test::GpuTimer INHERITED;
};
std::unique_ptr<GLGpuTimer> GLGpuTimer::MakeIfSupported(const sk_gpu_test::GLTestContext* ctx) {
std::unique_ptr<GLGpuTimer> ret;
const GrGLInterface* gl = ctx->gl();
if (gl->fExtensions.has("GL_EXT_disjoint_timer_query")) {
ret.reset(new GLGpuTimer(true, ctx, "EXT"));
} else if (kGL_GrGLStandard == gl->fStandard &&
(GrGLGetVersion(gl) > GR_GL_VER(3,3) || gl->fExtensions.has("GL_ARB_timer_query"))) {
ret.reset(new GLGpuTimer(false, ctx));
} else if (gl->fExtensions.has("GL_EXT_timer_query")) {
ret.reset(new GLGpuTimer(false, ctx, "EXT"));
}
if (ret && !ret->validate()) {
ret = nullptr;
}
return ret;
}
GLGpuTimer::GLGpuTimer(bool disjointSupport, const sk_gpu_test::GLTestContext* ctx, const char* ext)
: INHERITED(disjointSupport) {
ctx->getGLProcAddress(&fGLGetIntegerv, "glGetIntegerv");
ctx->getGLProcAddress(&fGLGenQueries, "glGenQueries", ext);
ctx->getGLProcAddress(&fGLDeleteQueries, "glDeleteQueries", ext);
ctx->getGLProcAddress(&fGLBeginQuery, "glBeginQuery", ext);
ctx->getGLProcAddress(&fGLEndQuery, "glEndQuery", ext);
ctx->getGLProcAddress(&fGLGetQueryObjectuiv, "glGetQueryObjectuiv", ext);
ctx->getGLProcAddress(&fGLGetQueryObjectui64v, "glGetQueryObjectui64v", ext);
}
bool GLGpuTimer::validate() const {
return fGLGetIntegerv && fGLGenQueries && fGLDeleteQueries && fGLBeginQuery && fGLEndQuery &&
fGLGetQueryObjectuiv && fGLGetQueryObjectui64v;
}
sk_gpu_test::PlatformTimerQuery GLGpuTimer::onQueueTimerStart() const {
GrGLuint queryID;
fGLGenQueries(1, &queryID);
if (!queryID) {
return sk_gpu_test::kInvalidTimerQuery;
}
if (this->disjointSupport()) {
// Clear the disjoint flag.
GrGLint disjoint;
fGLGetIntegerv(GL_GPU_DISJOINT, &disjoint);
}
fGLBeginQuery(GL_TIME_ELAPSED, queryID);
return static_cast<sk_gpu_test::PlatformTimerQuery>(queryID);
}
void GLGpuTimer::onQueueTimerStop(sk_gpu_test::PlatformTimerQuery platformTimer) const {
if (sk_gpu_test::kInvalidTimerQuery == platformTimer) {
return;
}
fGLEndQuery(GL_TIME_ELAPSED);
}
sk_gpu_test::GpuTimer::QueryStatus
GLGpuTimer::checkQueryStatus(sk_gpu_test::PlatformTimerQuery platformTimer) {
const GrGLuint queryID = static_cast<GrGLuint>(platformTimer);
if (!queryID) {
return QueryStatus::kInvalid;
}
GrGLuint available = 0;
fGLGetQueryObjectuiv(queryID, GL_QUERY_RESULT_AVAILABLE, &available);
if (!available) {
return QueryStatus::kPending;
}
if (this->disjointSupport()) {
GrGLint disjoint = 1;
fGLGetIntegerv(GL_GPU_DISJOINT, &disjoint);
if (disjoint) {
return QueryStatus::kDisjoint;
}
}
return QueryStatus::kAccurate;
}
std::chrono::nanoseconds GLGpuTimer::getTimeElapsed(sk_gpu_test::PlatformTimerQuery platformTimer) {
SkASSERT(this->checkQueryStatus(platformTimer) >= QueryStatus::kDisjoint);
const GrGLuint queryID = static_cast<GrGLuint>(platformTimer);
GrGLuint64 nanoseconds;
fGLGetQueryObjectui64v(queryID, GL_QUERY_RESULT, &nanoseconds);
return std::chrono::nanoseconds(nanoseconds);
}
void GLGpuTimer::deleteQuery(sk_gpu_test::PlatformTimerQuery platformTimer) {
const GrGLuint queryID = static_cast<GrGLuint>(platformTimer);
fGLDeleteQueries(1, &queryID);
}
GR_STATIC_ASSERT(sizeof(GrGLuint) <= sizeof(sk_gpu_test::PlatformTimerQuery));
} // anonymous namespace
namespace sk_gpu_test {
GLTestContext::GLTestContext() : TestContext() {}
GLTestContext::~GLTestContext() {
SkASSERT(nullptr == fGL.get());
}
void GLTestContext::init(const GrGLInterface* gl, std::unique_ptr<FenceSync> fenceSync) {
SkASSERT(!fGL.get());
fGL.reset(gl);
fFenceSync = fenceSync ? std::move(fenceSync) : GLFenceSync::MakeIfSupported(this);
fGpuTimer = GLGpuTimer::MakeIfSupported(this);
}
void GLTestContext::teardown() {
fGL.reset(nullptr);
INHERITED::teardown();
}
void GLTestContext::testAbandon() {
INHERITED::testAbandon();
if (fGL) {
fGL->abandon();
}
}
void GLTestContext::submit() {
if (fGL) {
GR_GL_CALL(fGL.get(), Flush());
}
}
void GLTestContext::finish() {
if (fGL) {
GR_GL_CALL(fGL.get(), Finish());
}
}
GrGLint GLTestContext::createTextureRectangle(int width, int height, GrGLenum internalFormat,
GrGLenum externalFormat, GrGLenum externalType,
GrGLvoid* data) {
if (!(kGL_GrGLStandard == fGL->fStandard && GrGLGetVersion(fGL.get()) >= GR_GL_VER(3, 1)) &&
!fGL->fExtensions.has("GL_ARB_texture_rectangle")) {
return 0;
}
if (GrGLGetGLSLVersion(fGL.get()) < GR_GLSL_VER(1, 40)) {
return 0;
}
GrGLuint id;
GR_GL_CALL(fGL.get(), GenTextures(1, &id));
GR_GL_CALL(fGL.get(), BindTexture(GR_GL_TEXTURE_RECTANGLE, id));
GR_GL_CALL(fGL.get(), TexParameteri(GR_GL_TEXTURE_RECTANGLE, GR_GL_TEXTURE_MAG_FILTER,
GR_GL_NEAREST));
GR_GL_CALL(fGL.get(), TexParameteri(GR_GL_TEXTURE_RECTANGLE, GR_GL_TEXTURE_MIN_FILTER,
GR_GL_NEAREST));
GR_GL_CALL(fGL.get(), TexParameteri(GR_GL_TEXTURE_RECTANGLE, GR_GL_TEXTURE_WRAP_S,
GR_GL_CLAMP_TO_EDGE));
GR_GL_CALL(fGL.get(), TexParameteri(GR_GL_TEXTURE_RECTANGLE, GR_GL_TEXTURE_WRAP_T,
GR_GL_CLAMP_TO_EDGE));
GR_GL_CALL(fGL.get(), TexImage2D(GR_GL_TEXTURE_RECTANGLE, 0, internalFormat, width, height, 0,
externalFormat, externalType, data));
return id;
}
} // namespace sk_gpu_test
<|endoftext|> |
<commit_before>//===-LTOCodeGenerator.cpp - LLVM Link Time Optimizer ---------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the Link Time Optimization library. This library is
// intended to be used by linker to optimize code at link time.
//
//===----------------------------------------------------------------------===//
#include "LTOCodeGenerator.h"
#include "LTOModule.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Analysis/Passes.h"
#include "llvm/Analysis/Verifier.h"
#include "llvm/Bitcode/ReaderWriter.h"
#include "llvm/Config/config.h"
#include "llvm/Constants.h"
#include "llvm/DataLayout.h"
#include "llvm/DerivedTypes.h"
#include "llvm/LLVMContext.h"
#include "llvm/Linker.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/SubtargetFeature.h"
#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FormattedStream.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/TargetRegistry.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Support/ToolOutputFile.h"
#include "llvm/Support/system_error.h"
#include "llvm/Target/Mangler.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Target/TargetRegisterInfo.h"
#include "llvm/Transforms/IPO.h"
#include "llvm/Transforms/IPO/PassManagerBuilder.h"
using namespace llvm;
static cl::opt<bool>
DisableInline("disable-inlining", cl::init(false),
cl::desc("Do not run the inliner pass"));
static cl::opt<bool>
DisableGVNLoadPRE("disable-gvn-loadpre", cl::init(false),
cl::desc("Do not run the GVN load PRE pass"));
const char* LTOCodeGenerator::getVersionString() {
#ifdef LLVM_VERSION_INFO
return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
#else
return PACKAGE_NAME " version " PACKAGE_VERSION;
#endif
}
LTOCodeGenerator::LTOCodeGenerator()
: _context(getGlobalContext()),
_linker("LinkTimeOptimizer", "ld-temp.o", _context), _target(NULL),
_emitDwarfDebugInfo(false), _scopeRestrictionsDone(false),
_exportDynamic(false), _codeModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC),
_nativeObjectFile(NULL) {
InitializeAllTargets();
InitializeAllTargetMCs();
InitializeAllAsmPrinters();
}
LTOCodeGenerator::~LTOCodeGenerator() {
delete _target;
delete _nativeObjectFile;
for (std::vector<char*>::iterator I = _codegenOptions.begin(),
E = _codegenOptions.end(); I != E; ++I)
free(*I);
}
bool LTOCodeGenerator::addModule(LTOModule* mod, std::string& errMsg) {
bool ret = _linker.LinkInModule(mod->getLLVVMModule(), &errMsg);
const std::vector<const char*> &undefs = mod->getAsmUndefinedRefs();
for (int i = 0, e = undefs.size(); i != e; ++i)
_asmUndefinedRefs[undefs[i]] = 1;
return ret;
}
bool LTOCodeGenerator::setDebugInfo(lto_debug_model debug,
std::string& errMsg) {
switch (debug) {
case LTO_DEBUG_MODEL_NONE:
_emitDwarfDebugInfo = false;
return false;
case LTO_DEBUG_MODEL_DWARF:
_emitDwarfDebugInfo = true;
return false;
}
llvm_unreachable("Unknown debug format!");
}
bool LTOCodeGenerator::setCodePICModel(lto_codegen_model model,
std::string& errMsg) {
switch (model) {
case LTO_CODEGEN_PIC_MODEL_STATIC:
case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
_codeModel = model;
return false;
}
llvm_unreachable("Unknown PIC model!");
}
bool LTOCodeGenerator::writeMergedModules(const char *path,
std::string &errMsg) {
if (determineTarget(errMsg))
return true;
// mark which symbols can not be internalized
applyScopeRestrictions();
// create output file
std::string ErrInfo;
tool_output_file Out(path, ErrInfo,
raw_fd_ostream::F_Binary);
if (!ErrInfo.empty()) {
errMsg = "could not open bitcode file for writing: ";
errMsg += path;
return true;
}
// write bitcode to it
WriteBitcodeToFile(_linker.getModule(), Out.os());
Out.os().close();
if (Out.os().has_error()) {
errMsg = "could not write bitcode file: ";
errMsg += path;
Out.os().clear_error();
return true;
}
Out.keep();
return false;
}
bool LTOCodeGenerator::compile_to_file(const char** name, std::string& errMsg) {
// make unique temp .o file to put generated object file
sys::PathWithStatus uniqueObjPath("lto-llvm.o");
if (uniqueObjPath.createTemporaryFileOnDisk(false, &errMsg)) {
uniqueObjPath.eraseFromDisk();
return true;
}
sys::RemoveFileOnSignal(uniqueObjPath);
// generate object file
bool genResult = false;
tool_output_file objFile(uniqueObjPath.c_str(), errMsg);
if (!errMsg.empty()) {
uniqueObjPath.eraseFromDisk();
return true;
}
genResult = this->generateObjectFile(objFile.os(), errMsg);
objFile.os().close();
if (objFile.os().has_error()) {
objFile.os().clear_error();
uniqueObjPath.eraseFromDisk();
return true;
}
objFile.keep();
if (genResult) {
uniqueObjPath.eraseFromDisk();
return true;
}
_nativeObjectPath = uniqueObjPath.str();
*name = _nativeObjectPath.c_str();
return false;
}
const void* LTOCodeGenerator::compile(size_t* length, std::string& errMsg) {
const char *name;
if (compile_to_file(&name, errMsg))
return NULL;
// remove old buffer if compile() called twice
delete _nativeObjectFile;
// read .o file into memory buffer
OwningPtr<MemoryBuffer> BuffPtr;
if (error_code ec = MemoryBuffer::getFile(name, BuffPtr, -1, false)) {
errMsg = ec.message();
sys::Path(_nativeObjectPath).eraseFromDisk();
return NULL;
}
_nativeObjectFile = BuffPtr.take();
// remove temp files
sys::Path(_nativeObjectPath).eraseFromDisk();
// return buffer, unless error
if (_nativeObjectFile == NULL)
return NULL;
*length = _nativeObjectFile->getBufferSize();
return _nativeObjectFile->getBufferStart();
}
bool LTOCodeGenerator::determineTarget(std::string& errMsg) {
if (_target != NULL)
return false;
std::string TripleStr = _linker.getModule()->getTargetTriple();
if (TripleStr.empty())
TripleStr = sys::getDefaultTargetTriple();
llvm::Triple Triple(TripleStr);
// create target machine from info for merged modules
const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
if (march == NULL)
return true;
// The relocation model is actually a static member of TargetMachine and
// needs to be set before the TargetMachine is instantiated.
Reloc::Model RelocModel = Reloc::Default;
switch (_codeModel) {
case LTO_CODEGEN_PIC_MODEL_STATIC:
RelocModel = Reloc::Static;
break;
case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
RelocModel = Reloc::PIC_;
break;
case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
RelocModel = Reloc::DynamicNoPIC;
break;
}
// construct LTOModule, hand over ownership of module and target
SubtargetFeatures Features;
Features.getDefaultSubtargetFeatures(Triple);
std::string FeatureStr = Features.getString();
// Set a default CPU for Darwin triples.
if (_mCpu.empty() && Triple.isOSDarwin()) {
if (Triple.getArch() == llvm::Triple::x86_64)
_mCpu = "core2";
else if (Triple.getArch() == llvm::Triple::x86)
_mCpu = "yonah";
}
TargetOptions Options;
LTOModule::getTargetOptions(Options);
_target = march->createTargetMachine(TripleStr, _mCpu, FeatureStr, Options,
RelocModel, CodeModel::Default,
CodeGenOpt::Aggressive);
return false;
}
void LTOCodeGenerator::
applyRestriction(GlobalValue &GV,
std::vector<const char*> &mustPreserveList,
SmallPtrSet<GlobalValue*, 8> &asmUsed,
Mangler &mangler) {
SmallString<64> Buffer;
mangler.getNameWithPrefix(Buffer, &GV, false);
if (GV.isDeclaration())
return;
if (_mustPreserveSymbols.count(Buffer))
mustPreserveList.push_back(GV.getName().data());
if (_asmUndefinedRefs.count(Buffer))
asmUsed.insert(&GV);
}
static void findUsedValues(GlobalVariable *LLVMUsed,
SmallPtrSet<GlobalValue*, 8> &UsedValues) {
if (LLVMUsed == 0) return;
ConstantArray *Inits = dyn_cast<ConstantArray>(LLVMUsed->getInitializer());
if (Inits == 0) return;
for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
if (GlobalValue *GV =
dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
UsedValues.insert(GV);
}
void LTOCodeGenerator::applyScopeRestrictions() {
if (_scopeRestrictionsDone) return;
Module *mergedModule = _linker.getModule();
// Start off with a verification pass.
PassManager passes;
passes.add(createVerifierPass());
// mark which symbols can not be internalized
MCContext Context(*_target->getMCAsmInfo(), *_target->getRegisterInfo(),NULL);
Mangler mangler(Context, *_target->getDataLayout());
std::vector<const char*> mustPreserveList;
SmallPtrSet<GlobalValue*, 8> asmUsed;
for (Module::iterator f = mergedModule->begin(),
e = mergedModule->end(); f != e; ++f)
applyRestriction(*f, mustPreserveList, asmUsed, mangler);
for (Module::global_iterator v = mergedModule->global_begin(),
e = mergedModule->global_end(); v != e; ++v)
applyRestriction(*v, mustPreserveList, asmUsed, mangler);
for (Module::alias_iterator a = mergedModule->alias_begin(),
e = mergedModule->alias_end(); a != e; ++a)
applyRestriction(*a, mustPreserveList, asmUsed, mangler);
GlobalVariable *LLVMCompilerUsed =
mergedModule->getGlobalVariable("llvm.compiler.used");
findUsedValues(LLVMCompilerUsed, asmUsed);
if (LLVMCompilerUsed)
LLVMCompilerUsed->eraseFromParent();
llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(_context);
std::vector<Constant*> asmUsed2;
for (SmallPtrSet<GlobalValue*, 16>::const_iterator i = asmUsed.begin(),
e = asmUsed.end(); i !=e; ++i) {
GlobalValue *GV = *i;
Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
asmUsed2.push_back(c);
}
llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
LLVMCompilerUsed =
new llvm::GlobalVariable(*mergedModule, ATy, false,
llvm::GlobalValue::AppendingLinkage,
llvm::ConstantArray::get(ATy, asmUsed2),
"llvm.compiler.used");
LLVMCompilerUsed->setSection("llvm.metadata");
if (!_exportDynamic)
passes.add(createInternalizePass(mustPreserveList));
// apply scope restrictions
passes.run(*mergedModule);
_scopeRestrictionsDone = true;
}
/// Optimize merged modules using various IPO passes
bool LTOCodeGenerator::generateObjectFile(raw_ostream &out,
std::string &errMsg) {
if (this->determineTarget(errMsg))
return true;
Module* mergedModule = _linker.getModule();
// if options were requested, set them
if (!_codegenOptions.empty())
cl::ParseCommandLineOptions(_codegenOptions.size(),
const_cast<char **>(&_codegenOptions[0]));
// mark which symbols can not be internalized
this->applyScopeRestrictions();
// Instantiate the pass manager to organize the passes.
PassManager passes;
// Start off with a verification pass.
passes.add(createVerifierPass());
// Add an appropriate DataLayout instance for this module...
passes.add(new DataLayout(*_target->getDataLayout()));
passes.add(new TargetTransformInfo(_target->getScalarTargetTransformInfo(),
_target->getVectorTargetTransformInfo()));
// Enabling internalize here would use its AllButMain variant. It
// keeps only main if it exists and does nothing for libraries. Instead
// we create the pass ourselves with the symbol list provided by the linker.
PassManagerBuilder().populateLTOPassManager(passes,
/*Internalize=*/!_exportDynamic,
!DisableInline,
DisableGVNLoadPRE);
// Make sure everything is still good.
passes.add(createVerifierPass());
FunctionPassManager *codeGenPasses = new FunctionPassManager(mergedModule);
codeGenPasses->add(new DataLayout(*_target->getDataLayout()));
formatted_raw_ostream Out(out);
if (_target->addPassesToEmitFile(*codeGenPasses, Out,
TargetMachine::CGFT_ObjectFile)) {
errMsg = "target file type not supported";
return true;
}
// Run our queue of passes all at once now, efficiently.
passes.run(*mergedModule);
// Run the code generator, and write assembly file
codeGenPasses->doInitialization();
for (Module::iterator
it = mergedModule->begin(), e = mergedModule->end(); it != e; ++it)
if (!it->isDeclaration())
codeGenPasses->run(*it);
codeGenPasses->doFinalization();
delete codeGenPasses;
return false; // success
}
/// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
/// LTO problems.
void LTOCodeGenerator::setCodeGenDebugOptions(const char *options) {
for (std::pair<StringRef, StringRef> o = getToken(options);
!o.first.empty(); o = getToken(o.second)) {
// ParseCommandLineOptions() expects argv[0] to be program name. Lazily add
// that.
if (_codegenOptions.empty())
_codegenOptions.push_back(strdup("libLTO"));
_codegenOptions.push_back(strdup(o.first.str().c_str()));
}
}
<commit_msg>Revert to old behavior until linker can pass export-dynamic option.<commit_after>//===-LTOCodeGenerator.cpp - LLVM Link Time Optimizer ---------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the Link Time Optimization library. This library is
// intended to be used by linker to optimize code at link time.
//
//===----------------------------------------------------------------------===//
#include "LTOCodeGenerator.h"
#include "LTOModule.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Analysis/Passes.h"
#include "llvm/Analysis/Verifier.h"
#include "llvm/Bitcode/ReaderWriter.h"
#include "llvm/Config/config.h"
#include "llvm/Constants.h"
#include "llvm/DataLayout.h"
#include "llvm/DerivedTypes.h"
#include "llvm/LLVMContext.h"
#include "llvm/Linker.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/SubtargetFeature.h"
#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FormattedStream.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/TargetRegistry.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Support/ToolOutputFile.h"
#include "llvm/Support/system_error.h"
#include "llvm/Target/Mangler.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Target/TargetRegisterInfo.h"
#include "llvm/Transforms/IPO.h"
#include "llvm/Transforms/IPO/PassManagerBuilder.h"
using namespace llvm;
static cl::opt<bool>
DisableInline("disable-inlining", cl::init(false),
cl::desc("Do not run the inliner pass"));
static cl::opt<bool>
DisableGVNLoadPRE("disable-gvn-loadpre", cl::init(false),
cl::desc("Do not run the GVN load PRE pass"));
const char* LTOCodeGenerator::getVersionString() {
#ifdef LLVM_VERSION_INFO
return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
#else
return PACKAGE_NAME " version " PACKAGE_VERSION;
#endif
}
LTOCodeGenerator::LTOCodeGenerator()
: _context(getGlobalContext()),
_linker("LinkTimeOptimizer", "ld-temp.o", _context), _target(NULL),
_emitDwarfDebugInfo(false), _scopeRestrictionsDone(false),
_exportDynamic(false), _codeModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC),
_nativeObjectFile(NULL) {
InitializeAllTargets();
InitializeAllTargetMCs();
InitializeAllAsmPrinters();
}
LTOCodeGenerator::~LTOCodeGenerator() {
delete _target;
delete _nativeObjectFile;
for (std::vector<char*>::iterator I = _codegenOptions.begin(),
E = _codegenOptions.end(); I != E; ++I)
free(*I);
}
bool LTOCodeGenerator::addModule(LTOModule* mod, std::string& errMsg) {
bool ret = _linker.LinkInModule(mod->getLLVVMModule(), &errMsg);
const std::vector<const char*> &undefs = mod->getAsmUndefinedRefs();
for (int i = 0, e = undefs.size(); i != e; ++i)
_asmUndefinedRefs[undefs[i]] = 1;
return ret;
}
bool LTOCodeGenerator::setDebugInfo(lto_debug_model debug,
std::string& errMsg) {
switch (debug) {
case LTO_DEBUG_MODEL_NONE:
_emitDwarfDebugInfo = false;
return false;
case LTO_DEBUG_MODEL_DWARF:
_emitDwarfDebugInfo = true;
return false;
}
llvm_unreachable("Unknown debug format!");
}
bool LTOCodeGenerator::setCodePICModel(lto_codegen_model model,
std::string& errMsg) {
switch (model) {
case LTO_CODEGEN_PIC_MODEL_STATIC:
case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
_codeModel = model;
return false;
}
llvm_unreachable("Unknown PIC model!");
}
bool LTOCodeGenerator::writeMergedModules(const char *path,
std::string &errMsg) {
if (determineTarget(errMsg))
return true;
// mark which symbols can not be internalized
applyScopeRestrictions();
// create output file
std::string ErrInfo;
tool_output_file Out(path, ErrInfo,
raw_fd_ostream::F_Binary);
if (!ErrInfo.empty()) {
errMsg = "could not open bitcode file for writing: ";
errMsg += path;
return true;
}
// write bitcode to it
WriteBitcodeToFile(_linker.getModule(), Out.os());
Out.os().close();
if (Out.os().has_error()) {
errMsg = "could not write bitcode file: ";
errMsg += path;
Out.os().clear_error();
return true;
}
Out.keep();
return false;
}
bool LTOCodeGenerator::compile_to_file(const char** name, std::string& errMsg) {
// make unique temp .o file to put generated object file
sys::PathWithStatus uniqueObjPath("lto-llvm.o");
if (uniqueObjPath.createTemporaryFileOnDisk(false, &errMsg)) {
uniqueObjPath.eraseFromDisk();
return true;
}
sys::RemoveFileOnSignal(uniqueObjPath);
// generate object file
bool genResult = false;
tool_output_file objFile(uniqueObjPath.c_str(), errMsg);
if (!errMsg.empty()) {
uniqueObjPath.eraseFromDisk();
return true;
}
genResult = this->generateObjectFile(objFile.os(), errMsg);
objFile.os().close();
if (objFile.os().has_error()) {
objFile.os().clear_error();
uniqueObjPath.eraseFromDisk();
return true;
}
objFile.keep();
if (genResult) {
uniqueObjPath.eraseFromDisk();
return true;
}
_nativeObjectPath = uniqueObjPath.str();
*name = _nativeObjectPath.c_str();
return false;
}
const void* LTOCodeGenerator::compile(size_t* length, std::string& errMsg) {
const char *name;
if (compile_to_file(&name, errMsg))
return NULL;
// remove old buffer if compile() called twice
delete _nativeObjectFile;
// read .o file into memory buffer
OwningPtr<MemoryBuffer> BuffPtr;
if (error_code ec = MemoryBuffer::getFile(name, BuffPtr, -1, false)) {
errMsg = ec.message();
sys::Path(_nativeObjectPath).eraseFromDisk();
return NULL;
}
_nativeObjectFile = BuffPtr.take();
// remove temp files
sys::Path(_nativeObjectPath).eraseFromDisk();
// return buffer, unless error
if (_nativeObjectFile == NULL)
return NULL;
*length = _nativeObjectFile->getBufferSize();
return _nativeObjectFile->getBufferStart();
}
bool LTOCodeGenerator::determineTarget(std::string& errMsg) {
if (_target != NULL)
return false;
std::string TripleStr = _linker.getModule()->getTargetTriple();
if (TripleStr.empty())
TripleStr = sys::getDefaultTargetTriple();
llvm::Triple Triple(TripleStr);
// create target machine from info for merged modules
const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
if (march == NULL)
return true;
// The relocation model is actually a static member of TargetMachine and
// needs to be set before the TargetMachine is instantiated.
Reloc::Model RelocModel = Reloc::Default;
switch (_codeModel) {
case LTO_CODEGEN_PIC_MODEL_STATIC:
RelocModel = Reloc::Static;
break;
case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
RelocModel = Reloc::PIC_;
break;
case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
RelocModel = Reloc::DynamicNoPIC;
break;
}
// construct LTOModule, hand over ownership of module and target
SubtargetFeatures Features;
Features.getDefaultSubtargetFeatures(Triple);
std::string FeatureStr = Features.getString();
// Set a default CPU for Darwin triples.
if (_mCpu.empty() && Triple.isOSDarwin()) {
if (Triple.getArch() == llvm::Triple::x86_64)
_mCpu = "core2";
else if (Triple.getArch() == llvm::Triple::x86)
_mCpu = "yonah";
}
TargetOptions Options;
LTOModule::getTargetOptions(Options);
_target = march->createTargetMachine(TripleStr, _mCpu, FeatureStr, Options,
RelocModel, CodeModel::Default,
CodeGenOpt::Aggressive);
return false;
}
void LTOCodeGenerator::
applyRestriction(GlobalValue &GV,
std::vector<const char*> &mustPreserveList,
SmallPtrSet<GlobalValue*, 8> &asmUsed,
Mangler &mangler) {
SmallString<64> Buffer;
mangler.getNameWithPrefix(Buffer, &GV, false);
if (GV.isDeclaration())
return;
if (_mustPreserveSymbols.count(Buffer))
mustPreserveList.push_back(GV.getName().data());
if (_asmUndefinedRefs.count(Buffer))
asmUsed.insert(&GV);
}
static void findUsedValues(GlobalVariable *LLVMUsed,
SmallPtrSet<GlobalValue*, 8> &UsedValues) {
if (LLVMUsed == 0) return;
ConstantArray *Inits = dyn_cast<ConstantArray>(LLVMUsed->getInitializer());
if (Inits == 0) return;
for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
if (GlobalValue *GV =
dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
UsedValues.insert(GV);
}
void LTOCodeGenerator::applyScopeRestrictions() {
if (_scopeRestrictionsDone) return;
Module *mergedModule = _linker.getModule();
// Start off with a verification pass.
PassManager passes;
passes.add(createVerifierPass());
// mark which symbols can not be internalized
MCContext Context(*_target->getMCAsmInfo(), *_target->getRegisterInfo(),NULL);
Mangler mangler(Context, *_target->getDataLayout());
std::vector<const char*> mustPreserveList;
SmallPtrSet<GlobalValue*, 8> asmUsed;
for (Module::iterator f = mergedModule->begin(),
e = mergedModule->end(); f != e; ++f)
applyRestriction(*f, mustPreserveList, asmUsed, mangler);
for (Module::global_iterator v = mergedModule->global_begin(),
e = mergedModule->global_end(); v != e; ++v)
applyRestriction(*v, mustPreserveList, asmUsed, mangler);
for (Module::alias_iterator a = mergedModule->alias_begin(),
e = mergedModule->alias_end(); a != e; ++a)
applyRestriction(*a, mustPreserveList, asmUsed, mangler);
GlobalVariable *LLVMCompilerUsed =
mergedModule->getGlobalVariable("llvm.compiler.used");
findUsedValues(LLVMCompilerUsed, asmUsed);
if (LLVMCompilerUsed)
LLVMCompilerUsed->eraseFromParent();
llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(_context);
std::vector<Constant*> asmUsed2;
for (SmallPtrSet<GlobalValue*, 16>::const_iterator i = asmUsed.begin(),
e = asmUsed.end(); i !=e; ++i) {
GlobalValue *GV = *i;
Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
asmUsed2.push_back(c);
}
llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
LLVMCompilerUsed =
new llvm::GlobalVariable(*mergedModule, ATy, false,
llvm::GlobalValue::AppendingLinkage,
llvm::ConstantArray::get(ATy, asmUsed2),
"llvm.compiler.used");
LLVMCompilerUsed->setSection("llvm.metadata");
if (!_exportDynamic)
passes.add(createInternalizePass(mustPreserveList));
// apply scope restrictions
passes.run(*mergedModule);
_scopeRestrictionsDone = true;
}
/// Optimize merged modules using various IPO passes
bool LTOCodeGenerator::generateObjectFile(raw_ostream &out,
std::string &errMsg) {
if (this->determineTarget(errMsg))
return true;
Module* mergedModule = _linker.getModule();
// if options were requested, set them
if (!_codegenOptions.empty())
cl::ParseCommandLineOptions(_codegenOptions.size(),
const_cast<char **>(&_codegenOptions[0]));
// mark which symbols can not be internalized
this->applyScopeRestrictions();
// Instantiate the pass manager to organize the passes.
PassManager passes;
// Start off with a verification pass.
passes.add(createVerifierPass());
// Add an appropriate DataLayout instance for this module...
passes.add(new DataLayout(*_target->getDataLayout()));
passes.add(new TargetTransformInfo(_target->getScalarTargetTransformInfo(),
_target->getVectorTargetTransformInfo()));
// Enabling internalize here would use its AllButMain variant. It
// keeps only main if it exists and does nothing for libraries. Instead
// we create the pass ourselves with the symbol list provided by the linker.
PassManagerBuilder().populateLTOPassManager(passes,
/*Internalize=*/
// FIXME: remove 'false' once
// Darwin linker can pass this
// option.
// <rdar://problem/12839986>
false /*!_exportDynamic*/,
!DisableInline,
DisableGVNLoadPRE);
// Make sure everything is still good.
passes.add(createVerifierPass());
FunctionPassManager *codeGenPasses = new FunctionPassManager(mergedModule);
codeGenPasses->add(new DataLayout(*_target->getDataLayout()));
formatted_raw_ostream Out(out);
if (_target->addPassesToEmitFile(*codeGenPasses, Out,
TargetMachine::CGFT_ObjectFile)) {
errMsg = "target file type not supported";
return true;
}
// Run our queue of passes all at once now, efficiently.
passes.run(*mergedModule);
// Run the code generator, and write assembly file
codeGenPasses->doInitialization();
for (Module::iterator
it = mergedModule->begin(), e = mergedModule->end(); it != e; ++it)
if (!it->isDeclaration())
codeGenPasses->run(*it);
codeGenPasses->doFinalization();
delete codeGenPasses;
return false; // success
}
/// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
/// LTO problems.
void LTOCodeGenerator::setCodeGenDebugOptions(const char *options) {
for (std::pair<StringRef, StringRef> o = getToken(options);
!o.first.empty(); o = getToken(o.second)) {
// ParseCommandLineOptions() expects argv[0] to be program name. Lazily add
// that.
if (_codegenOptions.empty())
_codegenOptions.push_back(strdup("libLTO"));
_codegenOptions.push_back(strdup(o.first.str().c_str()));
}
}
<|endoftext|> |
<commit_before>// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License
#ifndef __PROCESS_DEFERRED_HPP__
#define __PROCESS_DEFERRED_HPP__
#include <functional>
#include <process/dispatch.hpp>
#include <process/pid.hpp>
#include <stout/preprocessor.hpp>
namespace process {
// Acts like a function call but runs within an asynchronous execution
// context such as an Executor or a ProcessBase (enforced because only
// an executor or the 'defer' routines are allowed to create them).
template <typename F>
struct Deferred : std::function<F>
{
private:
friend class Executor;
template <typename G> friend struct _Deferred;
// TODO(benh): Consider removing these in favor of having these
// functions return _Deferred.
template <typename T>
friend Deferred<void()>
defer(const PID<T>& pid, void (T::*method)());
template <typename R, typename T>
friend Deferred<Future<R>()>
defer(const PID<T>& pid, Future<R> (T::*method)());
template <typename R, typename T>
friend Deferred<Future<R>()>
defer(const PID<T>& pid, R (T::*method)());
/*implicit*/ Deferred(const std::function<F>& f) : std::function<F>(f) {}
};
// We need an intermediate "deferred" type because when constructing a
// Deferred we won't always know the underlying function type (for
// example, if we're being passed a std::bind or a lambda). A lambda
// won't always implicitly convert to a std::function so instead we
// hold onto the functor type F and let the compiler invoke the
// necessary cast operator (below) when it actually has determined
// what type is needed. This is similar in nature to how std::bind
// works with its intermediate _Bind type (which the pre-C++11
// implementation relied on).
template <typename F>
struct _Deferred
{
// We expect that conversion operators are invoked on rvalues only,
// as _Deferred is supposed to be used directly as a result of defer call.
operator Deferred<void()>() &&
{
// The 'pid' differentiates an already dispatched functor versus
// one which still needs to be dispatched (which is done
// below). We have to delay wrapping the dispatch (for example, in
// defer.hpp) as long as possible because we don't always know
// what type the functor is or is going to be cast to (i.e., a
// std::bind might can be cast to functions that do or do not take
// arguments which will just be dropped when invoking the
// underlying bound function).
if (pid.isNone()) {
return std::function<void()>(std::forward<F>(f));
}
// We need to explicitly copy the members otherwise we'll
// implicitly copy 'this' which might not exist at invocation.
Option<UPID> pid_ = pid;
F&& f_ = std::forward<F>(f);
return std::function<void()>(
[=]() {
dispatch(pid_.get(), f_);
});
}
operator std::function<void()>() &&
{
if (pid.isNone()) {
return std::function<void()>(std::forward<F>(f));
}
Option<UPID> pid_ = pid;
F&& f_ = std::forward<F>(f);
return std::function<void()>(
[=]() {
dispatch(pid_.get(), f_);
});
}
template <typename R>
operator Deferred<R()>() &&
{
if (pid.isNone()) {
return std::function<R()>(std::forward<F>(f));
}
Option<UPID> pid_ = pid;
F&& f_ = std::forward<F>(f);
return std::function<R()>(
[=]() {
return dispatch(pid_.get(), f_);
});
}
template <typename R>
operator std::function<R()>() &&
{
if (pid.isNone()) {
return std::function<R()>(std::forward<F>(f));
}
Option<UPID> pid_ = pid;
F&& f_ = std::forward<F>(f);
return std::function<R()>(
[=]() {
return dispatch(pid_.get(), f_);
});
}
// Due to a bug (http://gcc.gnu.org/bugzilla/show_bug.cgi?id=41933)
// with variadic templates and lambdas, we still need to do
// preprocessor expansions. In addition, due to a bug with clang (or
// libc++) we can't use std::bind with a std::function so we have to
// explicitly use the std::function<R(P...)>::operator() (see
// http://stackoverflow.com/questions/20097616/stdbind-to-a-stdfunction-crashes-with-clang).
#define TEMPLATE(Z, N, DATA) \
template <ENUM_PARAMS(N, typename P)> \
operator Deferred<void(ENUM_PARAMS(N, P))>() && \
{ \
if (pid.isNone()) { \
return std::function<void(ENUM_PARAMS(N, P))>(std::forward<F>(f)); \
} \
\
Option<UPID> pid_ = pid; \
F&& f_ = std::forward<F>(f); \
\
return std::function<void(ENUM_PARAMS(N, P))>( \
[=](ENUM_BINARY_PARAMS(N, P, p)) { \
std::function<void()> f__([=]() { \
f_(ENUM_PARAMS(N, p)); \
}); \
dispatch(pid_.get(), f__); \
}); \
} \
\
template <ENUM_PARAMS(N, typename P)> \
operator std::function<void(ENUM_PARAMS(N, P))>() && \
{ \
if (pid.isNone()) { \
return std::function<void(ENUM_PARAMS(N, P))>(std::forward<F>(f)); \
} \
\
Option<UPID> pid_ = pid; \
F&& f_ = std::forward<F>(f); \
\
return std::function<void(ENUM_PARAMS(N, P))>( \
[=](ENUM_BINARY_PARAMS(N, P, p)) { \
std::function<void()> f__([=]() { \
f_(ENUM_PARAMS(N, p)); \
}); \
dispatch(pid_.get(), f__); \
}); \
}
REPEAT_FROM_TO(1, 13, TEMPLATE, _) // Args A0 -> A11.
#undef TEMPLATE
#define TEMPLATE(Z, N, DATA) \
template <typename R, ENUM_PARAMS(N, typename P)> \
operator Deferred<R(ENUM_PARAMS(N, P))>() && \
{ \
if (pid.isNone()) { \
return std::function<R(ENUM_PARAMS(N, P))>(std::forward<F>(f)); \
} \
\
Option<UPID> pid_ = pid; \
F&& f_ = std::forward<F>(f); \
\
return std::function<R(ENUM_PARAMS(N, P))>( \
[=](ENUM_BINARY_PARAMS(N, P, p)) { \
std::function<R()> f__([=]() { \
return f_(ENUM_PARAMS(N, p)); \
}); \
return dispatch(pid_.get(), f__); \
}); \
} \
\
template <typename R, ENUM_PARAMS(N, typename P)> \
operator std::function<R(ENUM_PARAMS(N, P))>() && \
{ \
if (pid.isNone()) { \
return std::function<R(ENUM_PARAMS(N, P))>(std::forward<F>(f)); \
} \
\
Option<UPID> pid_ = pid; \
F&& f_ = std::forward<F>(f); \
\
return std::function<R(ENUM_PARAMS(N, P))>( \
[=](ENUM_BINARY_PARAMS(N, P, p)) { \
std::function<R()> f__([=]() { \
return f_(ENUM_PARAMS(N, p)); \
}); \
return dispatch(pid_.get(), f__); \
}); \
}
REPEAT_FROM_TO(1, 13, TEMPLATE, _) // Args A0 -> A11.
#undef TEMPLATE
private:
friend class Executor;
template <typename G>
friend _Deferred<G> defer(const UPID& pid, G&& g);
// This assumes type and variable base names are `A` and `a` respectively.
#define FORWARD(Z, N, DATA) std::forward<A ## N>(a ## N)
#define TEMPLATE(Z, N, DATA) \
template <typename T, \
ENUM_PARAMS(N, typename P), \
ENUM_PARAMS(N, typename A)> \
friend auto defer(const PID<T>& pid, \
void (T::*method)(ENUM_PARAMS(N, P)), \
ENUM_BINARY_PARAMS(N, A, &&a)) \
-> _Deferred<decltype( \
lambda::partial( \
&std::function<void(ENUM_PARAMS(N, P))>::operator(), \
std::function<void(ENUM_PARAMS(N, P))>(), \
ENUM(N, FORWARD, _)))>;
REPEAT_FROM_TO(1, 13, TEMPLATE, _) // Args A0 -> A11.
#undef TEMPLATE
#define TEMPLATE(Z, N, DATA) \
template <typename R, \
typename T, \
ENUM_PARAMS(N, typename P), \
ENUM_PARAMS(N, typename A)> \
friend auto defer(const PID<T>& pid, \
Future<R> (T::*method)(ENUM_PARAMS(N, P)), \
ENUM_BINARY_PARAMS(N, A, &&a)) \
-> _Deferred<decltype( \
lambda::partial( \
&std::function<Future<R>(ENUM_PARAMS(N, P))>::operator(), \
std::function<Future<R>(ENUM_PARAMS(N, P))>(), \
ENUM(N, FORWARD, _)))>;
REPEAT_FROM_TO(1, 13, TEMPLATE, _) // Args A0 -> A11.
#undef TEMPLATE
#define TEMPLATE(Z, N, DATA) \
template <typename R, \
typename T, \
ENUM_PARAMS(N, typename P), \
ENUM_PARAMS(N, typename A)> \
friend auto defer(const PID<T>& pid, \
R (T::*method)(ENUM_PARAMS(N, P)), \
ENUM_BINARY_PARAMS(N, A, &&a)) \
-> _Deferred<decltype( \
lambda::partial( \
&std::function<Future<R>(ENUM_PARAMS(N, P))>::operator(), \
std::function<Future<R>(ENUM_PARAMS(N, P))>(), \
ENUM(N, FORWARD, _)))>;
REPEAT_FROM_TO(1, 13, TEMPLATE, _) // Args A0 -> A11.
#undef TEMPLATE
#undef FORWARD
_Deferred(const UPID& pid, F&& f) : pid(pid), f(std::forward<F>(f)) {}
/*implicit*/ _Deferred(F&& f) : f(std::forward<F>(f)) {}
Option<UPID> pid;
F f;
};
} // namespace process {
#endif // __PROCESS_DEFERRED_HPP__
<commit_msg>Reduced # of supported arguments in `_Deferred` conversion operators.<commit_after>// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License
#ifndef __PROCESS_DEFERRED_HPP__
#define __PROCESS_DEFERRED_HPP__
#include <functional>
#include <process/dispatch.hpp>
#include <process/pid.hpp>
#include <stout/preprocessor.hpp>
namespace process {
// Acts like a function call but runs within an asynchronous execution
// context such as an Executor or a ProcessBase (enforced because only
// an executor or the 'defer' routines are allowed to create them).
template <typename F>
struct Deferred : std::function<F>
{
private:
friend class Executor;
template <typename G> friend struct _Deferred;
// TODO(benh): Consider removing these in favor of having these
// functions return _Deferred.
template <typename T>
friend Deferred<void()>
defer(const PID<T>& pid, void (T::*method)());
template <typename R, typename T>
friend Deferred<Future<R>()>
defer(const PID<T>& pid, Future<R> (T::*method)());
template <typename R, typename T>
friend Deferred<Future<R>()>
defer(const PID<T>& pid, R (T::*method)());
/*implicit*/ Deferred(const std::function<F>& f) : std::function<F>(f) {}
};
// We need an intermediate "deferred" type because when constructing a
// Deferred we won't always know the underlying function type (for
// example, if we're being passed a std::bind or a lambda). A lambda
// won't always implicitly convert to a std::function so instead we
// hold onto the functor type F and let the compiler invoke the
// necessary cast operator (below) when it actually has determined
// what type is needed. This is similar in nature to how std::bind
// works with its intermediate _Bind type (which the pre-C++11
// implementation relied on).
template <typename F>
struct _Deferred
{
// We expect that conversion operators are invoked on rvalues only,
// as _Deferred is supposed to be used directly as a result of defer call.
operator Deferred<void()>() &&
{
// The 'pid' differentiates an already dispatched functor versus
// one which still needs to be dispatched (which is done
// below). We have to delay wrapping the dispatch (for example, in
// defer.hpp) as long as possible because we don't always know
// what type the functor is or is going to be cast to (i.e., a
// std::bind might can be cast to functions that do or do not take
// arguments which will just be dropped when invoking the
// underlying bound function).
if (pid.isNone()) {
return std::function<void()>(std::forward<F>(f));
}
// We need to explicitly copy the members otherwise we'll
// implicitly copy 'this' which might not exist at invocation.
Option<UPID> pid_ = pid;
F&& f_ = std::forward<F>(f);
return std::function<void()>(
[=]() {
dispatch(pid_.get(), f_);
});
}
operator std::function<void()>() &&
{
if (pid.isNone()) {
return std::function<void()>(std::forward<F>(f));
}
Option<UPID> pid_ = pid;
F&& f_ = std::forward<F>(f);
return std::function<void()>(
[=]() {
dispatch(pid_.get(), f_);
});
}
template <typename R>
operator Deferred<R()>() &&
{
if (pid.isNone()) {
return std::function<R()>(std::forward<F>(f));
}
Option<UPID> pid_ = pid;
F&& f_ = std::forward<F>(f);
return std::function<R()>(
[=]() {
return dispatch(pid_.get(), f_);
});
}
template <typename R>
operator std::function<R()>() &&
{
if (pid.isNone()) {
return std::function<R()>(std::forward<F>(f));
}
Option<UPID> pid_ = pid;
F&& f_ = std::forward<F>(f);
return std::function<R()>(
[=]() {
return dispatch(pid_.get(), f_);
});
}
// Due to a bug (http://gcc.gnu.org/bugzilla/show_bug.cgi?id=41933)
// with variadic templates and lambdas, we still need to do
// preprocessor expansions. In addition, due to a bug with clang (or
// libc++) we can't use std::bind with a std::function so we have to
// explicitly use the std::function<R(P...)>::operator() (see
// http://stackoverflow.com/questions/20097616/stdbind-to-a-stdfunction-crashes-with-clang).
#define TEMPLATE(Z, N, DATA) \
template <ENUM_PARAMS(N, typename P)> \
operator Deferred<void(ENUM_PARAMS(N, P))>() && \
{ \
if (pid.isNone()) { \
return std::function<void(ENUM_PARAMS(N, P))>(std::forward<F>(f)); \
} \
\
Option<UPID> pid_ = pid; \
F&& f_ = std::forward<F>(f); \
\
return std::function<void(ENUM_PARAMS(N, P))>( \
[=](ENUM_BINARY_PARAMS(N, P, p)) { \
std::function<void()> f__([=]() { \
f_(ENUM_PARAMS(N, p)); \
}); \
dispatch(pid_.get(), f__); \
}); \
} \
\
template <ENUM_PARAMS(N, typename P)> \
operator std::function<void(ENUM_PARAMS(N, P))>() && \
{ \
if (pid.isNone()) { \
return std::function<void(ENUM_PARAMS(N, P))>(std::forward<F>(f)); \
} \
\
Option<UPID> pid_ = pid; \
F&& f_ = std::forward<F>(f); \
\
return std::function<void(ENUM_PARAMS(N, P))>( \
[=](ENUM_BINARY_PARAMS(N, P, p)) { \
std::function<void()> f__([=]() { \
f_(ENUM_PARAMS(N, p)); \
}); \
dispatch(pid_.get(), f__); \
}); \
}
REPEAT_FROM_TO(1, 3, TEMPLATE, _) // Args A0 -> A1.
#undef TEMPLATE
#define TEMPLATE(Z, N, DATA) \
template <typename R, ENUM_PARAMS(N, typename P)> \
operator Deferred<R(ENUM_PARAMS(N, P))>() && \
{ \
if (pid.isNone()) { \
return std::function<R(ENUM_PARAMS(N, P))>(std::forward<F>(f)); \
} \
\
Option<UPID> pid_ = pid; \
F&& f_ = std::forward<F>(f); \
\
return std::function<R(ENUM_PARAMS(N, P))>( \
[=](ENUM_BINARY_PARAMS(N, P, p)) { \
std::function<R()> f__([=]() { \
return f_(ENUM_PARAMS(N, p)); \
}); \
return dispatch(pid_.get(), f__); \
}); \
} \
\
template <typename R, ENUM_PARAMS(N, typename P)> \
operator std::function<R(ENUM_PARAMS(N, P))>() && \
{ \
if (pid.isNone()) { \
return std::function<R(ENUM_PARAMS(N, P))>(std::forward<F>(f)); \
} \
\
Option<UPID> pid_ = pid; \
F&& f_ = std::forward<F>(f); \
\
return std::function<R(ENUM_PARAMS(N, P))>( \
[=](ENUM_BINARY_PARAMS(N, P, p)) { \
std::function<R()> f__([=]() { \
return f_(ENUM_PARAMS(N, p)); \
}); \
return dispatch(pid_.get(), f__); \
}); \
}
REPEAT_FROM_TO(1, 3, TEMPLATE, _) // Args A0 -> A1.
#undef TEMPLATE
private:
friend class Executor;
template <typename G>
friend _Deferred<G> defer(const UPID& pid, G&& g);
// This assumes type and variable base names are `A` and `a` respectively.
#define FORWARD(Z, N, DATA) std::forward<A ## N>(a ## N)
#define TEMPLATE(Z, N, DATA) \
template <typename T, \
ENUM_PARAMS(N, typename P), \
ENUM_PARAMS(N, typename A)> \
friend auto defer(const PID<T>& pid, \
void (T::*method)(ENUM_PARAMS(N, P)), \
ENUM_BINARY_PARAMS(N, A, &&a)) \
-> _Deferred<decltype( \
lambda::partial( \
&std::function<void(ENUM_PARAMS(N, P))>::operator(), \
std::function<void(ENUM_PARAMS(N, P))>(), \
ENUM(N, FORWARD, _)))>;
REPEAT_FROM_TO(1, 13, TEMPLATE, _) // Args A0 -> A11.
#undef TEMPLATE
#define TEMPLATE(Z, N, DATA) \
template <typename R, \
typename T, \
ENUM_PARAMS(N, typename P), \
ENUM_PARAMS(N, typename A)> \
friend auto defer(const PID<T>& pid, \
Future<R> (T::*method)(ENUM_PARAMS(N, P)), \
ENUM_BINARY_PARAMS(N, A, &&a)) \
-> _Deferred<decltype( \
lambda::partial( \
&std::function<Future<R>(ENUM_PARAMS(N, P))>::operator(), \
std::function<Future<R>(ENUM_PARAMS(N, P))>(), \
ENUM(N, FORWARD, _)))>;
REPEAT_FROM_TO(1, 13, TEMPLATE, _) // Args A0 -> A11.
#undef TEMPLATE
#define TEMPLATE(Z, N, DATA) \
template <typename R, \
typename T, \
ENUM_PARAMS(N, typename P), \
ENUM_PARAMS(N, typename A)> \
friend auto defer(const PID<T>& pid, \
R (T::*method)(ENUM_PARAMS(N, P)), \
ENUM_BINARY_PARAMS(N, A, &&a)) \
-> _Deferred<decltype( \
lambda::partial( \
&std::function<Future<R>(ENUM_PARAMS(N, P))>::operator(), \
std::function<Future<R>(ENUM_PARAMS(N, P))>(), \
ENUM(N, FORWARD, _)))>;
REPEAT_FROM_TO(1, 13, TEMPLATE, _) // Args A0 -> A11.
#undef TEMPLATE
#undef FORWARD
_Deferred(const UPID& pid, F&& f) : pid(pid), f(std::forward<F>(f)) {}
/*implicit*/ _Deferred(F&& f) : f(std::forward<F>(f)) {}
Option<UPID> pid;
F f;
};
} // namespace process {
#endif // __PROCESS_DEFERRED_HPP__
<|endoftext|> |
<commit_before>// 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 <stdlib.h>
#include <gmock/gmock.h>
#include <process/defer.hpp>
#include <process/dispatch.hpp>
#include <process/future.hpp>
#include <process/gtest.hpp>
#include <process/gmock.hpp>
#include <process/process.hpp>
#include <process/sequence.hpp>
#include <stout/nothing.hpp>
using process::Clock;
using process::Future;
using process::Process;
using process::Promise;
using process::Sequence;
using testing::_;
using testing::Return;
class TestProcess : public Process<TestProcess>
{
public:
Future<Nothing> foo()
{
return dispatch(self(), &Self::_foo);
}
Future<Nothing> _foo()
{
return dispatch(self(), &Self::__foo);
}
Future<Nothing> __foo()
{
return promise.future();
}
Nothing bar()
{
return Nothing();
}
Promise<Nothing> promise;
};
// The test verifies that callbacks are properly serialized by the
// Sequence object.
TEST(SequenceTest, Serialize)
{
TestProcess process;
spawn(process);
Sequence sequence;
Future<Nothing> bar = FUTURE_DISPATCH(_, &TestProcess::bar);
lambda::function<Future<Nothing>()> f;
f = defer(process, &TestProcess::foo);
sequence.add(f);
f = defer(process, &TestProcess::bar);
sequence.add(f);
// Flush the event queue to make sure that if the method 'bar' could
// have been invoked, the future 'bar' would be satisfied before the
// pending check below.
Clock::pause();
Clock::settle();
Clock::resume();
EXPECT_TRUE(bar.isPending());
process.promise.set(Nothing());
AWAIT_READY(bar);
terminate(process);
wait(process);
}
// Used to verify the discard semantics of Sequence.
class DiscardProcess : public Process<DiscardProcess>
{
public:
Future<Nothing> func0() { return promise.future(); }
MOCK_METHOD0(func1, Nothing());
MOCK_METHOD0(func2, Nothing());
MOCK_METHOD0(func3, Nothing());
Promise<Nothing> promise;
};
// The tests verifies semantics of discarding one returned future.
TEST(SequenceTest, DiscardOne)
{
DiscardProcess process;
spawn(process);
Sequence sequence;
lambda::function<Future<Nothing>()> f;
f = defer(process, &DiscardProcess::func0);
Future<Nothing> f0 = sequence.add(f);
f = defer(process, &DiscardProcess::func1);
Future<Nothing> f1 = sequence.add(f);
f = defer(process, &DiscardProcess::func2);
Future<Nothing> f2 = sequence.add(f);
f = defer(process, &DiscardProcess::func3);
Future<Nothing> f3 = sequence.add(f);
EXPECT_CALL(process, func1())
.WillOnce(Return(Nothing()));
EXPECT_CALL(process, func2())
.Times(0);
EXPECT_CALL(process, func3())
.WillOnce(Return(Nothing()));
// Flush the event queue to make sure that all callbacks have been
// added to the sequence.
Clock::pause();
Clock::settle();
Clock::resume();
f2.discard();
// Start the sequence of calls.
process.promise.set(Nothing());
AWAIT_READY(f3);
terminate(process);
wait(process);
}
// The test verifies the semantics of deleting the Sequence object,
// which will result in all pending callbacks being discarded.
TEST(SequenceTest, DiscardAll)
{
DiscardProcess process;
spawn(process);
Sequence* sequence = new Sequence();
lambda::function<Future<Nothing>()> f;
f = defer(process, &DiscardProcess::func0);
Future<Nothing> f0 = sequence->add(f);
f = defer(process, &DiscardProcess::func1);
Future<Nothing> f1 = sequence->add(f);
f = defer(process, &DiscardProcess::func2);
Future<Nothing> f2 = sequence->add(f);
f = defer(process, &DiscardProcess::func3);
Future<Nothing> f3 = sequence->add(f);
EXPECT_CALL(process, func1())
.Times(0);
EXPECT_CALL(process, func2())
.Times(0);
EXPECT_CALL(process, func3())
.Times(0);
// Flush the event queue to make sure that all callbacks have been
// added to the sequence.
Clock::pause();
Clock::settle();
Clock::resume();
// This should cancel all pending callbacks.
delete sequence;
// Start the sequence of calls.
process.promise.set(Nothing());
AWAIT_READY(f0);
AWAIT_DISCARDED(f1);
AWAIT_DISCARDED(f2);
AWAIT_DISCARDED(f3);
terminate(process);
wait(process);
}
class RandomProcess : public Process<RandomProcess>
{
public:
RandomProcess() : value(0) {}
Nothing verify()
{
EXPECT_EQ(0, value);
return Nothing();
}
Future<Nothing> pulse()
{
value++;
return dispatch(self(), &Self::_pulse);
}
Nothing _pulse()
{
value--;
return Nothing();
}
private:
int value;
};
TEST(SequenceTest, Random)
{
RandomProcess process;
spawn(process);
Sequence sequence;
for (int i = 0; i < 100; i++) {
lambda::function<Future<Nothing>()> f;
// We randomly do 'pulse' and 'verify'. The idea here is that: if
// sequence is not used, a 'verify' may see an intermediate
// result of a 'pulse', in which case the value is not zero.
if (::random() % 2 == 0) {
f = defer(process, &RandomProcess::pulse);
} else {
f = defer(process, &RandomProcess::verify);
}
sequence.add(f);
}
Clock::pause();
Clock::settle();
Clock::resume();
terminate(process);
wait(process);
}
<commit_msg>Windows: [2/3] Libprocess: Used `os::random`.<commit_after>// 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 <stdlib.h>
#include <gmock/gmock.h>
#include <process/defer.hpp>
#include <process/dispatch.hpp>
#include <process/future.hpp>
#include <process/gtest.hpp>
#include <process/gmock.hpp>
#include <process/process.hpp>
#include <process/sequence.hpp>
#include <stout/nothing.hpp>
#include <stout/os.hpp>
using process::Clock;
using process::Future;
using process::Process;
using process::Promise;
using process::Sequence;
using testing::_;
using testing::Return;
class TestProcess : public Process<TestProcess>
{
public:
Future<Nothing> foo()
{
return dispatch(self(), &Self::_foo);
}
Future<Nothing> _foo()
{
return dispatch(self(), &Self::__foo);
}
Future<Nothing> __foo()
{
return promise.future();
}
Nothing bar()
{
return Nothing();
}
Promise<Nothing> promise;
};
// The test verifies that callbacks are properly serialized by the
// Sequence object.
TEST(SequenceTest, Serialize)
{
TestProcess process;
spawn(process);
Sequence sequence;
Future<Nothing> bar = FUTURE_DISPATCH(_, &TestProcess::bar);
lambda::function<Future<Nothing>()> f;
f = defer(process, &TestProcess::foo);
sequence.add(f);
f = defer(process, &TestProcess::bar);
sequence.add(f);
// Flush the event queue to make sure that if the method 'bar' could
// have been invoked, the future 'bar' would be satisfied before the
// pending check below.
Clock::pause();
Clock::settle();
Clock::resume();
EXPECT_TRUE(bar.isPending());
process.promise.set(Nothing());
AWAIT_READY(bar);
terminate(process);
wait(process);
}
// Used to verify the discard semantics of Sequence.
class DiscardProcess : public Process<DiscardProcess>
{
public:
Future<Nothing> func0() { return promise.future(); }
MOCK_METHOD0(func1, Nothing());
MOCK_METHOD0(func2, Nothing());
MOCK_METHOD0(func3, Nothing());
Promise<Nothing> promise;
};
// The tests verifies semantics of discarding one returned future.
TEST(SequenceTest, DiscardOne)
{
DiscardProcess process;
spawn(process);
Sequence sequence;
lambda::function<Future<Nothing>()> f;
f = defer(process, &DiscardProcess::func0);
Future<Nothing> f0 = sequence.add(f);
f = defer(process, &DiscardProcess::func1);
Future<Nothing> f1 = sequence.add(f);
f = defer(process, &DiscardProcess::func2);
Future<Nothing> f2 = sequence.add(f);
f = defer(process, &DiscardProcess::func3);
Future<Nothing> f3 = sequence.add(f);
EXPECT_CALL(process, func1())
.WillOnce(Return(Nothing()));
EXPECT_CALL(process, func2())
.Times(0);
EXPECT_CALL(process, func3())
.WillOnce(Return(Nothing()));
// Flush the event queue to make sure that all callbacks have been
// added to the sequence.
Clock::pause();
Clock::settle();
Clock::resume();
f2.discard();
// Start the sequence of calls.
process.promise.set(Nothing());
AWAIT_READY(f3);
terminate(process);
wait(process);
}
// The test verifies the semantics of deleting the Sequence object,
// which will result in all pending callbacks being discarded.
TEST(SequenceTest, DiscardAll)
{
DiscardProcess process;
spawn(process);
Sequence* sequence = new Sequence();
lambda::function<Future<Nothing>()> f;
f = defer(process, &DiscardProcess::func0);
Future<Nothing> f0 = sequence->add(f);
f = defer(process, &DiscardProcess::func1);
Future<Nothing> f1 = sequence->add(f);
f = defer(process, &DiscardProcess::func2);
Future<Nothing> f2 = sequence->add(f);
f = defer(process, &DiscardProcess::func3);
Future<Nothing> f3 = sequence->add(f);
EXPECT_CALL(process, func1())
.Times(0);
EXPECT_CALL(process, func2())
.Times(0);
EXPECT_CALL(process, func3())
.Times(0);
// Flush the event queue to make sure that all callbacks have been
// added to the sequence.
Clock::pause();
Clock::settle();
Clock::resume();
// This should cancel all pending callbacks.
delete sequence;
// Start the sequence of calls.
process.promise.set(Nothing());
AWAIT_READY(f0);
AWAIT_DISCARDED(f1);
AWAIT_DISCARDED(f2);
AWAIT_DISCARDED(f3);
terminate(process);
wait(process);
}
class RandomProcess : public Process<RandomProcess>
{
public:
RandomProcess() : value(0) {}
Nothing verify()
{
EXPECT_EQ(0, value);
return Nothing();
}
Future<Nothing> pulse()
{
value++;
return dispatch(self(), &Self::_pulse);
}
Nothing _pulse()
{
value--;
return Nothing();
}
private:
int value;
};
TEST(SequenceTest, Random)
{
RandomProcess process;
spawn(process);
Sequence sequence;
for (int i = 0; i < 100; i++) {
lambda::function<Future<Nothing>()> f;
// We randomly do 'pulse' and 'verify'. The idea here is that: if
// sequence is not used, a 'verify' may see an intermediate
// result of a 'pulse', in which case the value is not zero.
if (os::random() % 2 == 0) {
f = defer(process, &RandomProcess::pulse);
} else {
f = defer(process, &RandomProcess::verify);
}
sequence.add(f);
}
Clock::pause();
Clock::settle();
Clock::resume();
terminate(process);
wait(process);
}
<|endoftext|> |
<commit_before>/* -------------------------------------------------------------------------- *
* OpenSim: testJointReactions.cpp *
* -------------------------------------------------------------------------- *
* The OpenSim API is a toolkit for musculoskeletal modeling and simulation. *
* See http://opensim.stanford.edu and the NOTICE file for more information. *
* OpenSim is developed at Stanford University and supported by the US *
* National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA *
* through the Warrior Web program. *
* *
* Copyright (c) 2005-2017 Stanford University and the Authors *
* Author(s): Ayman Habib *
* *
* 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
#include <OpenSim/OpenSim.h>
#include <OpenSim/Auxiliary/auxiliaryTestFunctions.h>
using namespace OpenSim;
using namespace std;
int main()
{
try {
AnalyzeTool analyze("SinglePin_Setup_JointReaction.xml");
analyze.run();
Storage result1("SinglePin_JointReaction_ReactionLoads.sto"), standard1("std_SinglePin_JointReaction_ReactionLoads.sto");
CHECK_STORAGE_AGAINST_STANDARD(result1, standard1,
std::vector<double>(standard1.getSmallestNumberOfStates(), 1e-5), __FILE__, __LINE__,
"SinglePin failed");
cout << "SinglePin passed" << endl;
AnalyzeTool analyze2("DoublePendulum3D_Setup_JointReaction.xml");
analyze2.run();
Storage result2("DoublePendulum3D_JointReaction_ReactionLoads.sto"), standard2("std_DoublePendulum3D_JointReaction_ReactionLoads.sto");
CHECK_STORAGE_AGAINST_STANDARD(result2, standard2,
std::vector<double>(standard2.getSmallestNumberOfStates(), 1e-5), __FILE__, __LINE__,
"DoublePendulum3D failed");
cout << "DoublePendulum3D passed" << endl;
AnalyzeTool analyze3("SinglePin_Setup_JointReaction_FrameKeyword.xml");
analyze.run();
Storage result3("SinglePin_JointReaction_ReactionLoads.sto"), standard3("std_SinglePin_JointReaction_ReactionLoads_FrameKeyword.sto");
CHECK_STORAGE_AGAINST_STANDARD(result3, standard3,
std::vector<double>(standard1.getSmallestNumberOfStates(), 1e-5), __FILE__, __LINE__,
"SinglePin failed");
cout << "SinglePin_FrameKeyword passed" << endl;
AnalyzeTool analyze4("DoublePendulum3D_Setup_JointReaction.xml");
analyze2.run();
Storage result4("DoublePendulum3D_JointReaction_ReactionLoads.sto"), standard4("std_DoublePendulum3D_JointReaction_ReactionLoads_FrameKeyword.sto");
CHECK_STORAGE_AGAINST_STANDARD(result4, standard4,
std::vector<double>(standard2.getSmallestNumberOfStates(), 1e-5), __FILE__, __LINE__,
"DoublePendulum3D failed");
cout << "DoublePendulum3D_FrameKeyword passed" << endl;
}
catch (const Exception& e) {
e.print(cerr);
return 1;
}
cout << "Done" << endl;
return 0;
}
<commit_msg>fix testJointReactions standard checks and messages<commit_after>/* -------------------------------------------------------------------------- *
* OpenSim: testJointReactions.cpp *
* -------------------------------------------------------------------------- *
* The OpenSim API is a toolkit for musculoskeletal modeling and simulation. *
* See http://opensim.stanford.edu and the NOTICE file for more information. *
* OpenSim is developed at Stanford University and supported by the US *
* National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA *
* through the Warrior Web program. *
* *
* Copyright (c) 2005-2017 Stanford University and the Authors *
* Author(s): Ayman Habib *
* *
* 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
#include <OpenSim/OpenSim.h>
#include <OpenSim/Auxiliary/auxiliaryTestFunctions.h>
using namespace OpenSim;
using namespace std;
int main()
{
try {
AnalyzeTool analyze("SinglePin_Setup_JointReaction.xml");
analyze.run();
Storage result1("SinglePin_JointReaction_ReactionLoads.sto"), standard1("std_SinglePin_JointReaction_ReactionLoads.sto");
CHECK_STORAGE_AGAINST_STANDARD(result1, standard1,
std::vector<double>(standard1.getSmallestNumberOfStates(), 1e-5), __FILE__, __LINE__,
"SinglePin failed");
cout << "SinglePin passed" << endl;
AnalyzeTool analyze2("DoublePendulum3D_Setup_JointReaction.xml");
analyze2.run();
Storage result2("DoublePendulum3D_JointReaction_ReactionLoads.sto"), standard2("std_DoublePendulum3D_JointReaction_ReactionLoads.sto");
CHECK_STORAGE_AGAINST_STANDARD(result2, standard2,
std::vector<double>(standard2.getSmallestNumberOfStates(), 1e-5), __FILE__, __LINE__,
"DoublePendulum3D failed");
cout << "DoublePendulum3D passed" << endl;
AnalyzeTool analyze3("SinglePin_Setup_JointReaction_FrameKeyword.xml");
analyze.run();
Storage result3("SinglePin_JointReaction_ReactionLoads.sto"), standard3("std_SinglePin_JointReaction_ReactionLoads_FrameKeyword.sto");
CHECK_STORAGE_AGAINST_STANDARD(result3, standard3,
std::vector<double>(standard3.getSmallestNumberOfStates(), 1e-5), __FILE__, __LINE__,
"SinglePin_FrameKeyword failed");
cout << "SinglePin_FrameKeyword passed" << endl;
AnalyzeTool analyze4("DoublePendulum3D_Setup_JointReaction.xml");
analyze2.run();
Storage result4("DoublePendulum3D_JointReaction_ReactionLoads.sto"), standard4("std_DoublePendulum3D_JointReaction_ReactionLoads_FrameKeyword.sto");
CHECK_STORAGE_AGAINST_STANDARD(result4, standard4,
std::vector<double>(standard4.getSmallestNumberOfStates(), 1e-5), __FILE__, __LINE__,
"DoublePendulum3D_FrameKeyword failed");
cout << "DoublePendulum3D_FrameKeyword passed" << endl;
}
catch (const Exception& e) {
e.print(cerr);
return 1;
}
cout << "Done" << endl;
return 0;
}
<|endoftext|> |
<commit_before>/* $Id$ */
#include <base/quadrature_lib.h>
#include <lac/vector.h>
#include <basic/data_out.h>
#include <grid/tria.h>
#include <grid/dof.h>
#include <grid/dof_accessor.h>
#include <grid/tria_iterator.h>
#include <fe/fe.h>
#include <fe/fe_values.h>
template <int dim>
DataOut_DoFData<dim>::DataEntry::DataEntry (const Vector<double> *data,
const vector<string> &names) :
data(data),
names(names)
{};
template <int dim>
DataOut_DoFData<dim>::DataOut_DoFData () :
dofs(0)
{};
template <int dim>
DataOut_DoFData<dim>::~DataOut_DoFData ()
{
clear ();
};
template <int dim>
void DataOut_DoFData<dim>::attach_dof_handler (const DoFHandler<dim> &d)
{
Assert (dof_data.size() == 0, ExcOldDataStillPresent());
Assert (cell_data.size() == 0, ExcOldDataStillPresent());
if (dofs != 0)
dofs->unsubscribe ();
dofs = &d;
if (dofs != 0)
dofs->subscribe ();
};
template <int dim>
void DataOut_DoFData<dim>::add_data_vector (const Vector<double> &vec,
const vector<string> &names)
{
Assert (dofs != 0, ExcNoDoFHandlerSelected ());
// either cell data and one name,
// or dof data and n_components names
Assert (((vec.size() == dofs->get_tria().n_active_cells()) &&
(names.size() == 1))
||
((vec.size() == dofs->n_dofs()) &&
(names.size() == dofs->get_fe().n_components)),
ExcInvalidNumberOfNames (names.size(), dofs->get_fe().n_components));
for (unsigned int i=0; i<names.size(); ++i)
Assert (names[i].find_first_not_of("abcdefghijklmnopqrstuvwxyz"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"0123456789_<>()") == string::npos,
ExcInvalidCharacter (names[i]));
DataEntry new_entry (&vec, names);
if (vec.size() == dofs->n_dofs())
dof_data.push_back (new_entry);
else
if (vec.size() == dofs->get_tria().n_active_cells())
cell_data.push_back (new_entry);
else
Assert (false,
ExcInvalidVectorSize (vec.size(),
dofs->n_dofs(),
dofs->get_tria().n_active_cells()));
};
template <int dim>
void DataOut_DoFData<dim>::add_data_vector (const Vector<double> &vec,
const string &name)
{
add_data_vector (vec, vector<string>(1,name));
};
template <int dim>
void DataOut_DoFData<dim>::clear ()
{
dof_data.erase (dof_data.begin(), dof_data.end());
cell_data.erase (cell_data.begin(), cell_data.end());
if (dofs != 0)
{
dofs->unsubscribe ();
dofs = 0;
};
// delete patches
vector<DataOutBase::Patch<dim> > dummy;
patches.swap (dummy);
};
template <int dim>
vector<string> DataOut_DoFData<dim>::get_dataset_names () const
{
vector<string> names;
// collect the names of dof
// and cell data
for (vector<DataEntry>::const_iterator d=dof_data.begin(); d!=dof_data.end(); ++d)
for (unsigned int i=0; i<d->names.size(); ++i)
names.push_back (d->names[i]);
for (vector<DataEntry>::const_iterator d=cell_data.begin(); d!=cell_data.end(); ++d)
{
Assert (d->names.size() == 1, ExcInternalError());
names.push_back (d->names[0]);
};
return names;
};
template <int dim>
const vector<typename DataOutBase::Patch<dim> > &
DataOut_DoFData<dim>::get_patches () const
{
return patches;
};
template <int dim>
void DataOut<dim>::build_patches (const unsigned int n_subdivisions)
{
Assert (dofs != 0, ExcNoDoFHandlerSelected());
const unsigned int n_components = dofs->get_fe().n_components;
const unsigned int n_datasets = dof_data.size() * n_components +
cell_data.size();
// clear the patches array
if (true)
{
vector<DataOutBase::Patch<dim> > dummy;
patches.swap (dummy);
};
// first count the cells we want to
// create patches of and make sure
// there is enough memory for that
unsigned int n_patches = 0;
for (DoFHandler<dim>::active_cell_iterator cell=dofs->begin_active();
cell != dofs->end(); ++cell)
++n_patches;
// before we start the loop:
// create a quadrature rule that
// actually has the points on this
// patch, and an object that
// extracts the data on each
// cell to these points
QTrapez<1> q_trapez;
QIterated<dim> patch_points (q_trapez, n_subdivisions);
FEValues<dim> fe_patch_values (dofs->get_fe(),
patch_points,
update_default);
const unsigned int n_q_points = patch_points.n_quadrature_points;
vector<double> patch_values (n_q_points);
vector<Vector<double> > patch_values_system (n_q_points,
Vector<double>(n_components));
DataOutBase::Patch<dim> default_patch;
default_patch.n_subdivisions = n_subdivisions;
default_patch.data.reinit (n_datasets, n_q_points);
patches.insert (patches.end(), n_patches, default_patch);
// now loop over all cells and
// actually create the patches
vector<DataOutBase::Patch<dim> >::iterator patch = patches.begin();
unsigned int cell_number = 0;
for (DoFHandler<dim>::active_cell_iterator cell=dofs->begin_active();
cell != dofs->end(); ++cell, ++patch, ++cell_number)
{
Assert (patch != patches.end(), ExcInternalError());
for (unsigned int vertex=0; vertex<GeometryInfo<dim>::vertices_per_cell; ++vertex)
patch->vertices[vertex] = cell->vertex(vertex);
if (n_datasets > 0)
{
fe_patch_values.reinit (cell);
// first fill dof_data
for (unsigned int dataset=0; dataset<dof_data.size(); ++dataset)
{
if (n_components == 1)
{
fe_patch_values.get_function_values (*dof_data[dataset].data,
patch_values);
for (unsigned int q=0; q<n_q_points; ++q)
patch->data(dataset,q) = patch_values[q];
}
else
// system of components
{
fe_patch_values.get_function_values (*dof_data[dataset].data,
patch_values_system);
for (unsigned int component=0; component<n_components; ++component)
for (unsigned int q=0; q<n_q_points; ++q)
patch->data(dataset*n_components+component,q) = patch_values_system[q](component);
};
};
// then do the cell data
for (unsigned int dataset=0; dataset<cell_data.size(); ++dataset)
{
const double value = (*cell_data[dataset].data)(cell_number);
for (unsigned int q=0; q<n_q_points; ++q)
patch->data(dataset,q) = value;
};
};
};
};
// explicit instantiations
template class DataOut_DoFData<deal_II_dimension>;
template class DataOut<deal_II_dimension>;
<commit_msg>Fix a rather serious bug which was tapered over by my reluctance not to test cell data...<commit_after>/* $Id$ */
#include <base/quadrature_lib.h>
#include <lac/vector.h>
#include <basic/data_out.h>
#include <grid/tria.h>
#include <grid/dof.h>
#include <grid/dof_accessor.h>
#include <grid/tria_iterator.h>
#include <fe/fe.h>
#include <fe/fe_values.h>
template <int dim>
DataOut_DoFData<dim>::DataEntry::DataEntry (const Vector<double> *data,
const vector<string> &names) :
data(data),
names(names)
{};
template <int dim>
DataOut_DoFData<dim>::DataOut_DoFData () :
dofs(0)
{};
template <int dim>
DataOut_DoFData<dim>::~DataOut_DoFData ()
{
clear ();
};
template <int dim>
void DataOut_DoFData<dim>::attach_dof_handler (const DoFHandler<dim> &d)
{
Assert (dof_data.size() == 0, ExcOldDataStillPresent());
Assert (cell_data.size() == 0, ExcOldDataStillPresent());
if (dofs != 0)
dofs->unsubscribe ();
dofs = &d;
if (dofs != 0)
dofs->subscribe ();
};
template <int dim>
void DataOut_DoFData<dim>::add_data_vector (const Vector<double> &vec,
const vector<string> &names)
{
Assert (dofs != 0, ExcNoDoFHandlerSelected ());
// either cell data and one name,
// or dof data and n_components names
Assert (((vec.size() == dofs->get_tria().n_active_cells()) &&
(names.size() == 1))
||
((vec.size() == dofs->n_dofs()) &&
(names.size() == dofs->get_fe().n_components)),
ExcInvalidNumberOfNames (names.size(), dofs->get_fe().n_components));
for (unsigned int i=0; i<names.size(); ++i)
Assert (names[i].find_first_not_of("abcdefghijklmnopqrstuvwxyz"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"0123456789_<>()") == string::npos,
ExcInvalidCharacter (names[i]));
DataEntry new_entry (&vec, names);
if (vec.size() == dofs->n_dofs())
dof_data.push_back (new_entry);
else
if (vec.size() == dofs->get_tria().n_active_cells())
cell_data.push_back (new_entry);
else
Assert (false,
ExcInvalidVectorSize (vec.size(),
dofs->n_dofs(),
dofs->get_tria().n_active_cells()));
};
template <int dim>
void DataOut_DoFData<dim>::add_data_vector (const Vector<double> &vec,
const string &name)
{
add_data_vector (vec, vector<string>(1,name));
};
template <int dim>
void DataOut_DoFData<dim>::clear ()
{
dof_data.erase (dof_data.begin(), dof_data.end());
cell_data.erase (cell_data.begin(), cell_data.end());
if (dofs != 0)
{
dofs->unsubscribe ();
dofs = 0;
};
// delete patches
vector<DataOutBase::Patch<dim> > dummy;
patches.swap (dummy);
};
template <int dim>
vector<string> DataOut_DoFData<dim>::get_dataset_names () const
{
vector<string> names;
// collect the names of dof
// and cell data
for (vector<DataEntry>::const_iterator d=dof_data.begin(); d!=dof_data.end(); ++d)
for (unsigned int i=0; i<d->names.size(); ++i)
names.push_back (d->names[i]);
for (vector<DataEntry>::const_iterator d=cell_data.begin(); d!=cell_data.end(); ++d)
{
Assert (d->names.size() == 1, ExcInternalError());
names.push_back (d->names[0]);
};
return names;
};
template <int dim>
const vector<typename DataOutBase::Patch<dim> > &
DataOut_DoFData<dim>::get_patches () const
{
return patches;
};
template <int dim>
void DataOut<dim>::build_patches (const unsigned int n_subdivisions)
{
Assert (dofs != 0, ExcNoDoFHandlerSelected());
const unsigned int n_components = dofs->get_fe().n_components;
const unsigned int n_datasets = dof_data.size() * n_components +
cell_data.size();
// clear the patches array
if (true)
{
vector<DataOutBase::Patch<dim> > dummy;
patches.swap (dummy);
};
// first count the cells we want to
// create patches of and make sure
// there is enough memory for that
unsigned int n_patches = 0;
for (DoFHandler<dim>::active_cell_iterator cell=dofs->begin_active();
cell != dofs->end(); ++cell)
++n_patches;
// before we start the loop:
// create a quadrature rule that
// actually has the points on this
// patch, and an object that
// extracts the data on each
// cell to these points
QTrapez<1> q_trapez;
QIterated<dim> patch_points (q_trapez, n_subdivisions);
FEValues<dim> fe_patch_values (dofs->get_fe(),
patch_points,
update_default);
const unsigned int n_q_points = patch_points.n_quadrature_points;
vector<double> patch_values (n_q_points);
vector<Vector<double> > patch_values_system (n_q_points,
Vector<double>(n_components));
DataOutBase::Patch<dim> default_patch;
default_patch.n_subdivisions = n_subdivisions;
default_patch.data.reinit (n_datasets, n_q_points);
patches.insert (patches.end(), n_patches, default_patch);
// now loop over all cells and
// actually create the patches
vector<DataOutBase::Patch<dim> >::iterator patch = patches.begin();
unsigned int cell_number = 0;
for (DoFHandler<dim>::active_cell_iterator cell=dofs->begin_active();
cell != dofs->end(); ++cell, ++patch, ++cell_number)
{
Assert (patch != patches.end(), ExcInternalError());
for (unsigned int vertex=0; vertex<GeometryInfo<dim>::vertices_per_cell; ++vertex)
patch->vertices[vertex] = cell->vertex(vertex);
if (n_datasets > 0)
{
fe_patch_values.reinit (cell);
// first fill dof_data
for (unsigned int dataset=0; dataset<dof_data.size(); ++dataset)
{
if (n_components == 1)
{
fe_patch_values.get_function_values (*dof_data[dataset].data,
patch_values);
for (unsigned int q=0; q<n_q_points; ++q)
patch->data(dataset,q) = patch_values[q];
}
else
// system of components
{
fe_patch_values.get_function_values (*dof_data[dataset].data,
patch_values_system);
for (unsigned int component=0; component<n_components; ++component)
for (unsigned int q=0; q<n_q_points; ++q)
patch->data(dataset*n_components+component,q) = patch_values_system[q](component);
};
};
// then do the cell data
for (unsigned int dataset=0; dataset<cell_data.size(); ++dataset)
{
const double value = (*cell_data[dataset].data)(cell_number);
for (unsigned int q=0; q<n_q_points; ++q)
patch->data(dataset+dof_data.size()*n_components,q) = value;
};
};
};
};
// explicit instantiations
template class DataOut_DoFData<deal_II_dimension>;
template class DataOut<deal_II_dimension>;
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2016 Daniel Nicoletti <dantti12@gmail.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "statusmessage.h"
#include <Cutelyst/Application>
#include <Cutelyst/Plugins/Session/session.h>
#include <QtCore/QDateTime>
#include <QtCore/QLoggingCategory>
using namespace Cutelyst;
Q_LOGGING_CATEGORY(C_STATUSMESSAGE, "cutelyst.plugins.statusmessage")
namespace Cutelyst {
class StatusMessagePrivate
{
public:
QString sessionPrefix = QStringLiteral("status_msg");
QString tokenParam = QStringLiteral("mid");
QString statusMsgStashKey = QStringLiteral("status_msg");
QString errorMsgStashKey = QStringLiteral("error_msg");
};
}
StatusMessage::StatusMessage(Application *parent) : Plugin(parent), d_ptr(new StatusMessagePrivate)
{
qsrand(QDateTime::currentMSecsSinceEpoch());
}
StatusMessage::~StatusMessage()
{
delete d_ptr;
}
QString StatusMessage::sessionPrefix() const
{
Q_D(const StatusMessage);
return d->sessionPrefix;
}
void StatusMessage::setSessionPrefix(const QString &sessionPrefix)
{
Q_D(StatusMessage);
d->sessionPrefix = sessionPrefix;
}
QString StatusMessage::tokenParam() const
{
Q_D(const StatusMessage);
return d->tokenParam;
}
void StatusMessage::setTokenParam(const QString &tokenParam)
{
Q_D(StatusMessage);
d->tokenParam = tokenParam;
}
QString StatusMessage::statusMsgStashKey() const
{
Q_D(const StatusMessage);
return d->statusMsgStashKey;
}
void StatusMessage::setStatusMsgStashKey(const QString &statusMsgStashKey)
{
Q_D(StatusMessage);
d->statusMsgStashKey = statusMsgStashKey;
}
QString StatusMessage::errorMgStashKey() const
{
Q_D(const StatusMessage);
return d->errorMsgStashKey;
}
void StatusMessage::setErrorMgStashKey(const QString &errorMgStashKey)
{
Q_D(StatusMessage);
d->errorMsgStashKey = errorMgStashKey;
}
void StatusMessage::load(Context *c)
{
auto sm = c->plugin<StatusMessage*>();
if (!sm) {
qCCritical(C_STATUSMESSAGE, "StatusMessage plugin not registered");
return;
}
const QString token = c->request()->queryParam(sm->d_ptr->tokenParam);
if (token.isEmpty()) {
return;
}
const QString statusKey = sm->d_ptr->sessionPrefix + QLatin1String("status") + token;
const QVariant statusValue = Session::value(c, statusKey);
if (!statusValue.isNull()) {
Session::deleteValue(c, statusKey);
c->setStash(sm->d_ptr->statusMsgStashKey, statusValue);
}
const QString errorKey = sm->d_ptr->sessionPrefix + QLatin1String("error") + token;
const QVariant errorValue = Session::value(c, errorKey);
if (!errorValue.isNull()) {
Session::deleteValue(c, errorKey);
c->setStash(sm->d_ptr->errorMsgStashKey, errorValue);
}
}
QString getSessionMessage(Context *c, const QString &key)
{
const QVariant value = Session::value(c, key);
if (!value.isNull()) {
Session::deleteValue(c, key);
c->setStash(QLatin1String("status_msg"), value);
}
return value.toString();
}
QString createToken()
{
return QString::number(qrand() % 99999999).rightJustified(8, QLatin1Char('0'), true);
}
QString StatusMessage::setError(Context *c, const QString &msg)
{
QString token;
auto sm = c->plugin<StatusMessage*>();
if (!sm) {
qCCritical(C_STATUSMESSAGE, "StatusMessage plugin not registered");
return token;
}
token = createToken();
Session::setValue(c, sm->d_ptr->sessionPrefix + QLatin1String("error") + token, msg);
return token;
}
QString StatusMessage::setStatus(Context *c, const QString &msg)
{
QString token;
auto sm = c->plugin<StatusMessage*>();
if (!sm) {
qCCritical(C_STATUSMESSAGE, "StatusMessage plugin not registered");
return token;
}
token = createToken();
Session::setValue(c, sm->d_ptr->sessionPrefix + QLatin1String("status") + token, msg);
return token;
}
#include "moc_statusmessage.cpp"
<commit_msg>Use thread_local to access StatusMessage object<commit_after>/*
* Copyright (C) 2016 Daniel Nicoletti <dantti12@gmail.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "statusmessage.h"
#include <Cutelyst/Application>
#include <Cutelyst/Plugins/Session/session.h>
#include <QtCore/QDateTime>
#include <QtCore/QLoggingCategory>
using namespace Cutelyst;
Q_LOGGING_CATEGORY(C_STATUSMESSAGE, "cutelyst.plugins.statusmessage")
namespace Cutelyst {
class StatusMessagePrivate
{
public:
QString sessionPrefix = QStringLiteral("status_msg");
QString tokenParam = QStringLiteral("mid");
QString statusMsgStashKey = QStringLiteral("status_msg");
QString errorMsgStashKey = QStringLiteral("error_msg");
};
}
static thread_local StatusMessage *m_instance = nullptr;
StatusMessage::StatusMessage(Application *parent) : Plugin(parent), d_ptr(new StatusMessagePrivate)
{
qsrand(QDateTime::currentMSecsSinceEpoch());
m_instance = this;
}
StatusMessage::~StatusMessage()
{
delete d_ptr;
}
QString StatusMessage::sessionPrefix() const
{
Q_D(const StatusMessage);
return d->sessionPrefix;
}
void StatusMessage::setSessionPrefix(const QString &sessionPrefix)
{
Q_D(StatusMessage);
d->sessionPrefix = sessionPrefix;
}
QString StatusMessage::tokenParam() const
{
Q_D(const StatusMessage);
return d->tokenParam;
}
void StatusMessage::setTokenParam(const QString &tokenParam)
{
Q_D(StatusMessage);
d->tokenParam = tokenParam;
}
QString StatusMessage::statusMsgStashKey() const
{
Q_D(const StatusMessage);
return d->statusMsgStashKey;
}
void StatusMessage::setStatusMsgStashKey(const QString &statusMsgStashKey)
{
Q_D(StatusMessage);
d->statusMsgStashKey = statusMsgStashKey;
}
QString StatusMessage::errorMgStashKey() const
{
Q_D(const StatusMessage);
return d->errorMsgStashKey;
}
void StatusMessage::setErrorMgStashKey(const QString &errorMgStashKey)
{
Q_D(StatusMessage);
d->errorMsgStashKey = errorMgStashKey;
}
void StatusMessage::load(Context *c)
{
if (!m_instance) {
qCCritical(C_STATUSMESSAGE, "StatusMessage plugin not registered");
return;
}
const QString token = c->request()->queryParam(m_instance->d_ptr->tokenParam);
if (token.isEmpty()) {
return;
}
const QString statusKey = m_instance->d_ptr->sessionPrefix + QLatin1String("status") + token;
const QVariant statusValue = Session::value(c, statusKey);
if (!statusValue.isNull()) {
Session::deleteValue(c, statusKey);
c->setStash(m_instance->d_ptr->statusMsgStashKey, statusValue);
}
const QString errorKey = m_instance->d_ptr->sessionPrefix + QLatin1String("error") + token;
const QVariant errorValue = Session::value(c, errorKey);
if (!errorValue.isNull()) {
Session::deleteValue(c, errorKey);
c->setStash(m_instance->d_ptr->errorMsgStashKey, errorValue);
}
}
QString getSessionMessage(Context *c, const QString &key)
{
const QVariant value = Session::value(c, key);
if (!value.isNull()) {
Session::deleteValue(c, key);
c->setStash(QLatin1String("status_msg"), value);
}
return value.toString();
}
QString createToken()
{
return QString::number(qrand() % 99999999).rightJustified(8, QLatin1Char('0'), true);
}
QString StatusMessage::setError(Context *c, const QString &msg)
{
QString token;
if (!m_instance) {
qCCritical(C_STATUSMESSAGE, "StatusMessage plugin not registered");
return token;
}
token = createToken();
Session::setValue(c, m_instance->d_ptr->sessionPrefix + QLatin1String("error") + token, msg);
return token;
}
QString StatusMessage::setStatus(Context *c, const QString &msg)
{
QString token;
if (!m_instance) {
qCCritical(C_STATUSMESSAGE, "StatusMessage plugin not registered");
return token;
}
token = createToken();
Session::setValue(c, m_instance->d_ptr->sessionPrefix + QLatin1String("status") + token, msg);
return token;
}
#include "moc_statusmessage.cpp"
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2017-2018 Matthias Fehring <kontakt@buschmann23.de>
*
* 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 "validatorip_p.h"
#include <QHostAddress>
#include <QRegularExpression>
#include <utility>
using namespace Cutelyst;
ValidatorIp::ValidatorIp(const QString &field, Constraints constraints, const Cutelyst::ValidatorMessages &messages, const QString &defValKey) :
ValidatorRule(*new ValidatorIpPrivate(field, constraints, messages, defValKey))
{
}
ValidatorIp::~ValidatorIp()
{
}
ValidatorReturnType ValidatorIp::validate(Cutelyst::Context *c, const ParamsMultiMap ¶ms) const
{
ValidatorReturnType result;
Q_D(const ValidatorIp);
const QString v = value(params);
if (!v.isEmpty()) {
if (ValidatorIp::validate(v, d->constraints)) {
result.value.setValue<QString>(v);
} else {
result.errorMessage = validationError(c);
qCDebug(C_VALIDATOR, "ValidatorIp: Validation failed for field %s at %s::%s: not a valid IP address within the constraints.", qPrintable(field()), qPrintable(c->controllerName()), qPrintable(c->actionName()));
}
} else {
defaultValue(c, &result, "ValidatorIp");
}
return result;
}
bool ValidatorIp::validate(const QString &value, Constraints constraints)
{
bool valid = true;
// simple check for an IPv4 address with four parts, because QHostAddress also tolerates addresses like 192.168.2 and fills them with 0 somewhere
if (!value.contains(QLatin1Char(':')) && !value.contains(QRegularExpression(QStringLiteral("^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$")))) {
valid = false;
} else {
// private IPv4 subnets
static const std::vector<std::pair<QHostAddress,int>> ipv4Private({
// Used for local communications within a private network
// https://tools.ietf.org/html/rfc1918
{QHostAddress(QStringLiteral("10.0.0.0")), 8},
// Used for link-local addresses between two hosts on a single link when no IP address
// is otherwise specified, such as would have normally been retrieved from a DHCP server
// https://tools.ietf.org/html/rfc3927
{QHostAddress(QStringLiteral("169.254.0.0")), 16},
// Used for local communications within a private network
// https://tools.ietf.org/html/rfc1918
{QHostAddress(QStringLiteral("172.16.0.0")), 12},
// Used for local communications within a private network
// https://tools.ietf.org/html/rfc1918
{QHostAddress(QStringLiteral("192.168.0.0")), 12}
});
// reserved IPv4 subnets
static const std::vector<std::pair<QHostAddress,int>> ipv4Reserved({
// Used for broadcast messages to the current ("this")
// https://tools.ietf.org/html/rfc1700
{QHostAddress(QStringLiteral("0.0.0.0")), 8},
// Used for communications between a service provider and its subscribers when using a carrier-grade NAT
// https://tools.ietf.org/html/rfc6598
{QHostAddress(QStringLiteral("100.64.0.0")), 10},
// Used for loopback addresses to the local host
// https://tools.ietf.org/html/rfc990
{QHostAddress(QStringLiteral("127.0.0.1")), 8},
// Used for the IANA IPv4 Special Purpose Address Registry
// https://tools.ietf.org/html/rfc5736
{QHostAddress(QStringLiteral("192.0.0.0")), 24},
// Assigned as "TEST-NET" for use in documentation and examples. It should not be used publicly.
// https://tools.ietf.org/html/rfc5737
{QHostAddress(QStringLiteral("192.0.2.0")), 24},
// Used by 6to4 anycast relays
// https://tools.ietf.org/html/rfc3068
{QHostAddress(QStringLiteral("192.88.99.0")), 24},
// Used for testing of inter-network communications between two separate subnets
// https://tools.ietf.org/html/rfc2544
{QHostAddress(QStringLiteral("198.18.0.0")), 15},
// Assigned as "TEST-NET-2" for use in documentation and examples. It should not be used publicly.
// https://tools.ietf.org/html/rfc5737
{QHostAddress(QStringLiteral("198.51.100.0")), 24},
// Assigned as "TEST-NET-3" for use in documentation and examples. It should not be used publicly.
// https://tools.ietf.org/html/rfc5737
{QHostAddress(QStringLiteral("203.0.113.0")), 24},
// Reserved for future use
// https://tools.ietf.org/html/rfc6890
{QHostAddress(QStringLiteral("240.0.0.0")), 4},
// Reserved for the "limited broadcast" destination address
// https://tools.ietf.org/html/rfc6890
{QHostAddress(QStringLiteral("255.255.255.255")), 32}
});
// private IPv6 subnets
static const std::vector<std::pair<QHostAddress,int>> ipv6Private({
// unique local address
{QHostAddress(QStringLiteral("fc00::")), 7},
// link-local address
{QHostAddress(QStringLiteral("fe80::")), 10}
});
// reserved IPv6 subnets
static const std::vector<std::pair<QHostAddress,int>> ipv6Reserved({
// unspecified address
{QHostAddress(QStringLiteral("::")), 128},
// loopback address to the loca host
{QHostAddress(QStringLiteral("::1")), 128},
// IPv4 mapped addresses
{QHostAddress(QStringLiteral("::ffff:0:0")), 96},
// discard prefix
// https://tools.ietf.org/html/rfc6666
{QHostAddress(QStringLiteral("100::")), 64},
// IPv4/IPv6 translation
// https://tools.ietf.org/html/rfc6052
{QHostAddress(QStringLiteral("64:ff9b::")), 96},
// Teredo tunneling
{QHostAddress(QStringLiteral("2001::")), 32},
// deprected (previously ORCHID)
{QHostAddress(QStringLiteral("2001:10::")), 28},
// ORCHIDv2
{QHostAddress(QStringLiteral("2001:20::")), 28},
// addresses used in documentation and example source code
{QHostAddress(QStringLiteral("2001:db8::")), 32},
// 6to4
{QHostAddress(QStringLiteral("2002::")), 16}
});
QHostAddress a;
if (a.setAddress(value)) {
if (!constraints.testFlag(NoConstraint)) {
if (a.protocol() == QAbstractSocket::IPv4Protocol) {
if (constraints.testFlag(IPv6Only)) {
valid = false;
}
if (valid && (constraints.testFlag(NoPrivateRange) || constraints.testFlag(PublicOnly))) {
for (const std::pair<QHostAddress,int> &subnet : ipv4Private) {
if (a.isInSubnet(subnet.first, subnet.second)) {
valid = false;
break;
}
}
}
if (valid && (constraints.testFlag(NoReservedRange) || constraints.testFlag(PublicOnly))) {
for (const std::pair<QHostAddress,int> &subnet : ipv4Reserved) {
if (a.isInSubnet(subnet.first, subnet.second)) {
valid = false;
break;
}
}
}
if (valid && (constraints.testFlag(NoMultiCast) || constraints.testFlag(PublicOnly))) {
if (a.isInSubnet(QHostAddress(QStringLiteral("224.0.0.0")), 4)) {
valid = false;
}
}
} else {
if (constraints.testFlag(IPv4Only)) {
valid = false;
}
if (valid && (constraints.testFlag(NoPrivateRange) || constraints.testFlag(PublicOnly))) {
for (const std::pair<QHostAddress,int> &subnet : ipv6Private) {
if (a.isInSubnet(subnet.first, subnet.second)) {
valid = false;
break;
}
}
}
if (valid && (constraints.testFlag(NoReservedRange) || constraints.testFlag(PublicOnly))) {
for (const std::pair<QHostAddress,int> &subnet : ipv6Reserved) {
if (a.isInSubnet(subnet.first, subnet.second)) {
valid = false;
break;
}
}
}
if (valid && (constraints.testFlag(NoMultiCast) || constraints.testFlag(PublicOnly))) {
if (a.isInSubnet(QHostAddress(QStringLiteral("ff00::")), 8)) {
valid = false;
}
}
}
}
} else {
valid = false;
}
}
return valid;
}
QString ValidatorIp::genericValidationError(Context *c, const QVariant &errorData) const
{
QString error;
Q_UNUSED(errorData)
const QString _label = label(c);
if (!_label.isEmpty()) {
error = c->translate("Cutelyst::ValidatorIp", "IP address is invalid or not acceptable.");
} else {
error = c->translate("Cutelyst::ValidatorIp", "The IP address in the “%1” field is invalid or not acceptable.").arg(_label);
}
return error;
}
<commit_msg>Validator plugin: fix returning wrong error string in ValidatorIp<commit_after>/*
* Copyright (C) 2017-2018 Matthias Fehring <kontakt@buschmann23.de>
*
* 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 "validatorip_p.h"
#include <QHostAddress>
#include <QRegularExpression>
#include <utility>
using namespace Cutelyst;
ValidatorIp::ValidatorIp(const QString &field, Constraints constraints, const Cutelyst::ValidatorMessages &messages, const QString &defValKey) :
ValidatorRule(*new ValidatorIpPrivate(field, constraints, messages, defValKey))
{
}
ValidatorIp::~ValidatorIp()
{
}
ValidatorReturnType ValidatorIp::validate(Cutelyst::Context *c, const ParamsMultiMap ¶ms) const
{
ValidatorReturnType result;
Q_D(const ValidatorIp);
const QString v = value(params);
if (!v.isEmpty()) {
if (ValidatorIp::validate(v, d->constraints)) {
result.value.setValue<QString>(v);
} else {
result.errorMessage = validationError(c);
qCDebug(C_VALIDATOR, "ValidatorIp: Validation failed for field %s at %s::%s: not a valid IP address within the constraints.", qPrintable(field()), qPrintable(c->controllerName()), qPrintable(c->actionName()));
}
} else {
defaultValue(c, &result, "ValidatorIp");
}
return result;
}
bool ValidatorIp::validate(const QString &value, Constraints constraints)
{
bool valid = true;
// simple check for an IPv4 address with four parts, because QHostAddress also tolerates addresses like 192.168.2 and fills them with 0 somewhere
if (!value.contains(QLatin1Char(':')) && !value.contains(QRegularExpression(QStringLiteral("^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$")))) {
valid = false;
} else {
// private IPv4 subnets
static const std::vector<std::pair<QHostAddress,int>> ipv4Private({
// Used for local communications within a private network
// https://tools.ietf.org/html/rfc1918
{QHostAddress(QStringLiteral("10.0.0.0")), 8},
// Used for link-local addresses between two hosts on a single link when no IP address
// is otherwise specified, such as would have normally been retrieved from a DHCP server
// https://tools.ietf.org/html/rfc3927
{QHostAddress(QStringLiteral("169.254.0.0")), 16},
// Used for local communications within a private network
// https://tools.ietf.org/html/rfc1918
{QHostAddress(QStringLiteral("172.16.0.0")), 12},
// Used for local communications within a private network
// https://tools.ietf.org/html/rfc1918
{QHostAddress(QStringLiteral("192.168.0.0")), 12}
});
// reserved IPv4 subnets
static const std::vector<std::pair<QHostAddress,int>> ipv4Reserved({
// Used for broadcast messages to the current ("this")
// https://tools.ietf.org/html/rfc1700
{QHostAddress(QStringLiteral("0.0.0.0")), 8},
// Used for communications between a service provider and its subscribers when using a carrier-grade NAT
// https://tools.ietf.org/html/rfc6598
{QHostAddress(QStringLiteral("100.64.0.0")), 10},
// Used for loopback addresses to the local host
// https://tools.ietf.org/html/rfc990
{QHostAddress(QStringLiteral("127.0.0.1")), 8},
// Used for the IANA IPv4 Special Purpose Address Registry
// https://tools.ietf.org/html/rfc5736
{QHostAddress(QStringLiteral("192.0.0.0")), 24},
// Assigned as "TEST-NET" for use in documentation and examples. It should not be used publicly.
// https://tools.ietf.org/html/rfc5737
{QHostAddress(QStringLiteral("192.0.2.0")), 24},
// Used by 6to4 anycast relays
// https://tools.ietf.org/html/rfc3068
{QHostAddress(QStringLiteral("192.88.99.0")), 24},
// Used for testing of inter-network communications between two separate subnets
// https://tools.ietf.org/html/rfc2544
{QHostAddress(QStringLiteral("198.18.0.0")), 15},
// Assigned as "TEST-NET-2" for use in documentation and examples. It should not be used publicly.
// https://tools.ietf.org/html/rfc5737
{QHostAddress(QStringLiteral("198.51.100.0")), 24},
// Assigned as "TEST-NET-3" for use in documentation and examples. It should not be used publicly.
// https://tools.ietf.org/html/rfc5737
{QHostAddress(QStringLiteral("203.0.113.0")), 24},
// Reserved for future use
// https://tools.ietf.org/html/rfc6890
{QHostAddress(QStringLiteral("240.0.0.0")), 4},
// Reserved for the "limited broadcast" destination address
// https://tools.ietf.org/html/rfc6890
{QHostAddress(QStringLiteral("255.255.255.255")), 32}
});
// private IPv6 subnets
static const std::vector<std::pair<QHostAddress,int>> ipv6Private({
// unique local address
{QHostAddress(QStringLiteral("fc00::")), 7},
// link-local address
{QHostAddress(QStringLiteral("fe80::")), 10}
});
// reserved IPv6 subnets
static const std::vector<std::pair<QHostAddress,int>> ipv6Reserved({
// unspecified address
{QHostAddress(QStringLiteral("::")), 128},
// loopback address to the loca host
{QHostAddress(QStringLiteral("::1")), 128},
// IPv4 mapped addresses
{QHostAddress(QStringLiteral("::ffff:0:0")), 96},
// discard prefix
// https://tools.ietf.org/html/rfc6666
{QHostAddress(QStringLiteral("100::")), 64},
// IPv4/IPv6 translation
// https://tools.ietf.org/html/rfc6052
{QHostAddress(QStringLiteral("64:ff9b::")), 96},
// Teredo tunneling
{QHostAddress(QStringLiteral("2001::")), 32},
// deprected (previously ORCHID)
{QHostAddress(QStringLiteral("2001:10::")), 28},
// ORCHIDv2
{QHostAddress(QStringLiteral("2001:20::")), 28},
// addresses used in documentation and example source code
{QHostAddress(QStringLiteral("2001:db8::")), 32},
// 6to4
{QHostAddress(QStringLiteral("2002::")), 16}
});
QHostAddress a;
if (a.setAddress(value)) {
if (!constraints.testFlag(NoConstraint)) {
if (a.protocol() == QAbstractSocket::IPv4Protocol) {
if (constraints.testFlag(IPv6Only)) {
valid = false;
}
if (valid && (constraints.testFlag(NoPrivateRange) || constraints.testFlag(PublicOnly))) {
for (const std::pair<QHostAddress,int> &subnet : ipv4Private) {
if (a.isInSubnet(subnet.first, subnet.second)) {
valid = false;
break;
}
}
}
if (valid && (constraints.testFlag(NoReservedRange) || constraints.testFlag(PublicOnly))) {
for (const std::pair<QHostAddress,int> &subnet : ipv4Reserved) {
if (a.isInSubnet(subnet.first, subnet.second)) {
valid = false;
break;
}
}
}
if (valid && (constraints.testFlag(NoMultiCast) || constraints.testFlag(PublicOnly))) {
if (a.isInSubnet(QHostAddress(QStringLiteral("224.0.0.0")), 4)) {
valid = false;
}
}
} else {
if (constraints.testFlag(IPv4Only)) {
valid = false;
}
if (valid && (constraints.testFlag(NoPrivateRange) || constraints.testFlag(PublicOnly))) {
for (const std::pair<QHostAddress,int> &subnet : ipv6Private) {
if (a.isInSubnet(subnet.first, subnet.second)) {
valid = false;
break;
}
}
}
if (valid && (constraints.testFlag(NoReservedRange) || constraints.testFlag(PublicOnly))) {
for (const std::pair<QHostAddress,int> &subnet : ipv6Reserved) {
if (a.isInSubnet(subnet.first, subnet.second)) {
valid = false;
break;
}
}
}
if (valid && (constraints.testFlag(NoMultiCast) || constraints.testFlag(PublicOnly))) {
if (a.isInSubnet(QHostAddress(QStringLiteral("ff00::")), 8)) {
valid = false;
}
}
}
}
} else {
valid = false;
}
}
return valid;
}
QString ValidatorIp::genericValidationError(Context *c, const QVariant &errorData) const
{
QString error;
Q_UNUSED(errorData)
const QString _label = label(c);
if (_label.isEmpty()) {
error = c->translate("Cutelyst::ValidatorIp", "IP address is invalid or not acceptable.");
} else {
//: %1 will be replaced by the field label
error = c->translate("Cutelyst::ValidatorIp", "The IP address in the “%1” field is invalid or not acceptable.").arg(_label);
}
return error;
}
<|endoftext|> |
<commit_before>#include <mtp/metadata/Library.h>
#include <mtp/ptp/Session.h>
#include <mtp/log.h>
#include <unordered_map>
namespace mtp
{
namespace
{
const std::string UknownArtist ("UknownArtist");
const std::string UknownAlbum ("UknownAlbum");
const std::string VariousArtists ("VariousArtists");
}
Library::NameToObjectIdMap Library::ListAssociations(ObjectId parentId)
{
NameToObjectIdMap list;
auto folders = _session->GetObjectHandles(_storage, mtp::ObjectFormat::Association, parentId);
list.reserve(folders.ObjectHandles.size());
for(auto id : folders.ObjectHandles)
{
auto name = _session->GetObjectStringProperty(id, ObjectProperty::ObjectFilename);
list.insert(std::make_pair(name, id));
}
return list;
}
ObjectId Library::GetOrCreate(ObjectId parentId, const std::string &name)
{
auto objects = _session->GetObjectHandles(_storage, mtp::ObjectFormat::Association, parentId);
for (auto id : objects.ObjectHandles)
{
auto oname = _session->GetObjectStringProperty(id, ObjectProperty::ObjectFilename);
if (name == oname)
return id;
}
return _session->CreateDirectory(name, parentId, _storage).ObjectId;
}
Library::Library(const mtp::SessionPtr & session, ProgressReporter && reporter): _session(session)
{
auto storages = _session->GetStorageIDs();
if (storages.StorageIDs.empty())
throw std::runtime_error("no storages found");
u64 progress = 0, total = 0;
if (reporter)
reporter(State::Initialising, progress, total);
_artistSupported = _session->GetDeviceInfo().Supports(ObjectFormat::Artist);
{
auto propsSupported = _session->GetObjectPropertiesSupported(ObjectFormat::AbstractAudioAlbum);
_albumDateAuthoredSupported = std::find(propsSupported.ObjectPropertyCodes.begin(), propsSupported.ObjectPropertyCodes.end(), ObjectProperty::DateAuthored) != propsSupported.ObjectPropertyCodes.end();
}
_storage = storages.StorageIDs[0]; //picking up first storage.
//zune fails to create artist/album without storage id
{
msg::ObjectHandles rootFolders = _session->GetObjectHandles(Session::AllStorages, mtp::ObjectFormat::Association, Session::Root);
for (auto id : rootFolders.ObjectHandles)
{
auto name = _session->GetObjectStringProperty(id, ObjectProperty::ObjectFilename);
if (name == "Artists")
_artistsFolder = id;
else if (name == "Albums")
_albumsFolder = id;
else if (name == "Music")
_musicFolder = id;
}
}
if (_artistSupported && _artistsFolder == ObjectId())
_artistsFolder = _session->CreateDirectory("Artists", Session::Root, _storage).ObjectId;
if (_albumsFolder == ObjectId())
_albumsFolder = _session->CreateDirectory("Albums", Session::Root, _storage).ObjectId;
if (_musicFolder == ObjectId())
_musicFolder = _session->CreateDirectory("Music", Session::Root, _storage).ObjectId;
debug("artists folder: ", _artistsFolder != ObjectId()? _artistsFolder.Id: 0);
debug("albums folder: ", _albumsFolder.Id);
debug("music folder: ", _musicFolder.Id);
auto musicFolders = ListAssociations(_musicFolder);
using namespace mtp;
msg::ObjectHandles artists, albums;
if (_artistSupported)
{
debug("getting artists...");
if (reporter)
reporter(State::QueryingArtists, progress, total);
artists = _session->GetObjectHandles(Session::AllStorages, ObjectFormat::Artist, Session::Device);
total += artists.ObjectHandles.size();
}
{
debug("getting albums...");
if (reporter)
reporter(State::QueryingAlbums, progress, total);
albums = _session->GetObjectHandles(Session::AllStorages, ObjectFormat::AbstractAudioAlbum, Session::Device);
total += albums.ObjectHandles.size();
}
if (_artistSupported)
{
if (reporter)
reporter(State::LoadingArtists, progress, total);
for (auto id : artists.ObjectHandles)
{
auto name = _session->GetObjectStringProperty(id, ObjectProperty::Name);
debug("artist: ", name, "\t", id.Id);
auto artist = std::make_shared<Artist>();
artist->Id = id;
artist->Name = name;
auto it = musicFolders.find(name);
if (it != musicFolders.end())
artist->MusicFolderId = it->second;
else
artist->MusicFolderId = _session->CreateDirectory(name, _musicFolder, _storage).ObjectId;
_artists.insert(std::make_pair(name, artist));
if (reporter)
reporter(State::LoadingArtists, ++progress, total);
}
}
if (reporter)
reporter(State::LoadingAlbums, progress, total);
std::unordered_map<ArtistPtr, NameToObjectIdMap> albumFolders;
for (auto id : albums.ObjectHandles)
{
auto name = _session->GetObjectStringProperty(id, ObjectProperty::Name);
auto artistName = _session->GetObjectStringProperty(id, ObjectProperty::Artist);
std::string albumDate;
if (_albumDateAuthoredSupported)
albumDate = _session->GetObjectStringProperty(id, ObjectProperty::DateAuthored);
auto artist = GetArtist(artistName);
if (!artist)
artist = CreateArtist(artistName);
debug("album: ", artistName, " -- ", name, "\t", id.Id, "\t", albumDate);
auto album = std::make_shared<Album>();
album->Name = name;
album->Artist = artist;
album->Id = id;
album->Year = !albumDate.empty()? ConvertDateTime(albumDate): 0;
if (albumFolders.find(artist) == albumFolders.end()) {
albumFolders[artist] = ListAssociations(artist->MusicFolderId);
}
auto it = albumFolders.find(artist);
if (it == albumFolders.end())
throw std::runtime_error("no iterator after insert, internal error");
const auto & albums = it->second;
auto alit = albums.find(name);
if (alit != albums.end())
album->MusicFolderId = alit->second;
else
album->MusicFolderId = _session->CreateDirectory(name, artist->MusicFolderId, _storage).ObjectId;
_albums.insert(std::make_pair(std::make_pair(artist, name), album));
if (reporter)
reporter(State::LoadingAlbums, ++progress, total);
}
if (reporter)
reporter(State::Loaded, progress, total);
}
Library::~Library()
{ }
Library::ArtistPtr Library::GetArtist(std::string name)
{
if (name.empty())
name = UknownArtist;
auto it = _artists.find(name);
return it != _artists.end()? it->second: ArtistPtr();
}
Library::ArtistPtr Library::CreateArtist(std::string name)
{
if (name.empty())
name = UknownArtist;
auto artist = std::make_shared<Artist>();
artist->Name = name;
artist->MusicFolderId = GetOrCreate(_musicFolder, name);
if (_artistSupported)
{
ByteArray propList;
OutputStream os(propList);
os.Write32(2); //number of props
os.Write32(0); //object handle
os.Write16(static_cast<u16>(ObjectProperty::Name));
os.Write16(static_cast<u16>(DataTypeCode::String));
os.WriteString(name);
os.Write32(0); //object handle
os.Write16(static_cast<u16>(ObjectProperty::ObjectFilename));
os.Write16(static_cast<u16>(DataTypeCode::String));
os.WriteString(name + ".art");
auto response = _session->SendObjectPropList(_storage, _artistsFolder, ObjectFormat::Artist, 0, propList);
artist->Id = response.ObjectId;
}
_artists.insert(std::make_pair(name, artist));
return artist;
}
Library::AlbumPtr Library::GetAlbum(const ArtistPtr & artist, std::string name)
{
if (name.empty())
name = UknownAlbum;
auto it = _albums.find(std::make_pair(artist, name));
return it != _albums.end()? it->second: AlbumPtr();
}
Library::AlbumPtr Library::CreateAlbum(const ArtistPtr & artist, std::string name, int year)
{
if (!artist)
throw std::runtime_error("artists is required");
if (name.empty())
name = UknownAlbum;
ByteArray propList;
OutputStream os(propList);
bool sendYear = year != 0 && _albumDateAuthoredSupported;
os.Write32(3 + (sendYear? 1: 0)); //number of props
if (_artistSupported)
{
os.Write32(0); //object handle
os.Write16(static_cast<u16>(ObjectProperty::ArtistId));
os.Write16(static_cast<u16>(DataTypeCode::Uint32));
os.Write32(artist->Id.Id);
}
else
{
os.Write32(0); //object handle
os.Write16(static_cast<u16>(ObjectProperty::Artist));
os.Write16(static_cast<u16>(DataTypeCode::String));
os.WriteString(artist->Name);
}
os.Write32(0); //object handle
os.Write16(static_cast<u16>(ObjectProperty::Name));
os.Write16(static_cast<u16>(DataTypeCode::String));
os.WriteString(name);
os.Write32(0); //object handle
os.Write16(static_cast<u16>(ObjectProperty::ObjectFilename));
os.Write16(static_cast<u16>(DataTypeCode::String));
os.WriteString(artist->Name + "--" + name + ".alb");
if (sendYear)
{
os.Write32(0); //object handle
os.Write16(static_cast<u16>(ObjectProperty::DateAuthored));
os.Write16(static_cast<u16>(DataTypeCode::String));
os.WriteString(ConvertYear(year));
}
auto album = std::make_shared<Album>();
album->Artist = artist;
album->Name = name;
album->Year = year;
album->MusicFolderId = GetOrCreate(artist->MusicFolderId, name);
auto response = _session->SendObjectPropList(_storage, _albumsFolder, ObjectFormat::AbstractAudioAlbum, 0, propList);
album->Id = response.ObjectId;
_albums.insert(std::make_pair(std::make_pair(artist, name), album));
return album;
}
bool Library::HasTrack(const AlbumPtr & album, const std::string &name, int trackIndex)
{
if (!album)
return false;
LoadRefs(album);
auto & tracks = album->Tracks;
auto range = tracks.equal_range(name);
for(auto i = range.first; i != range.second; ++i)
{
if (i->second == trackIndex)
return true;
}
return false;
}
Library::NewTrackInfo Library::CreateTrack(const ArtistPtr & artist,
const AlbumPtr & album,
ObjectFormat type,
std::string name, const std::string & genre, int trackIndex,
const std::string &filename, size_t size)
{
ByteArray propList;
OutputStream os(propList);
os.Write32(3 + (!genre.empty()? 1: 0) + (trackIndex? 1: 0)); //number of props
if (_artistSupported)
{
os.Write32(0); //object handle
os.Write16(static_cast<u16>(ObjectProperty::ArtistId));
os.Write16(static_cast<u16>(DataTypeCode::Uint32));
os.Write32(artist->Id.Id);
}
else
{
os.Write32(0); //object handle
os.Write16(static_cast<u16>(ObjectProperty::Artist));
os.Write16(static_cast<u16>(DataTypeCode::String));
os.WriteString(artist->Name);
}
os.Write32(0); //object handle
os.Write16(static_cast<u16>(ObjectProperty::Name));
os.Write16(static_cast<u16>(DataTypeCode::String));
os.WriteString(name);
if (trackIndex)
{
os.Write32(0); //object handle
os.Write16(static_cast<u16>(ObjectProperty::Track));
os.Write16(static_cast<u16>(DataTypeCode::Uint16));
os.Write16(trackIndex);
}
if (!genre.empty())
{
os.Write32(0); //object handle
os.Write16(static_cast<u16>(ObjectProperty::Genre));
os.Write16(static_cast<u16>(DataTypeCode::String));
os.WriteString(genre);
}
os.Write32(0); //object handle
os.Write16(static_cast<u16>(ObjectProperty::ObjectFilename));
os.Write16(static_cast<u16>(DataTypeCode::String));
os.WriteString(filename);
auto response = _session->SendObjectPropList(_storage, album->MusicFolderId, type, size, propList);
NewTrackInfo ti;
ti.Id = response.ObjectId;
ti.Name = name;
ti.Index = trackIndex;
return ti;
}
void Library::LoadRefs(AlbumPtr album)
{
if (!album || album->RefsLoaded)
return;
auto refs = _session->GetObjectReferences(album->Id).ObjectHandles;
std::copy(refs.begin(), refs.end(), std::inserter(album->Refs, album->Refs.begin()));
for(auto trackId : refs)
{
auto name = _session->GetObjectStringProperty(trackId, ObjectProperty::Name);
auto index = _session->GetObjectIntegerProperty(trackId, ObjectProperty::Track);
debug("[", index, "]: ", name);
album->Tracks.insert(std::make_pair(name, index));
}
album->RefsLoaded = true;
}
void Library::AddTrack(AlbumPtr album, const NewTrackInfo & ti)
{
if (!album)
return;
LoadRefs(album);
auto & refs = album->Refs;
auto & tracks = album->Tracks;
msg::ObjectHandles handles;
std::copy(refs.begin(), refs.end(), std::back_inserter(handles.ObjectHandles));
handles.ObjectHandles.push_back(ti.Id);
_session->SetObjectReferences(album->Id, handles);
refs.insert(ti.Id);
tracks.insert(std::make_pair(ti.Name, ti.Index));
}
bool Library::Supported(const mtp::SessionPtr & session)
{
auto & gdi = session->GetDeviceInfo();
return
gdi.Supports(OperationCode::SendObjectPropList) &&
gdi.Supports(OperationCode::SetObjectReferences) &&
gdi.Supports(ObjectFormat::AbstractAudioAlbum);
;
}
}
<commit_msg>use GetObjectPropList to get id/prop more efficient<commit_after>#include <mtp/metadata/Library.h>
#include <mtp/ptp/Session.h>
#include <mtp/ptp/ObjectPropertyListParser.h>
#include <mtp/log.h>
#include <unordered_map>
namespace mtp
{
namespace
{
const std::string UknownArtist ("UknownArtist");
const std::string UknownAlbum ("UknownAlbum");
const std::string VariousArtists ("VariousArtists");
}
Library::NameToObjectIdMap Library::ListAssociations(ObjectId parentId)
{
NameToObjectIdMap list;
ByteArray data = _session->GetObjectPropertyList(parentId, ObjectFormat::Association, ObjectProperty::ObjectFilename, 0, 1);
ObjectPropertyListParser<std::string> parser;
parser.Parse(data, [&](ObjectId id, ObjectProperty property, const std::string &name) {
list.insert(std::make_pair(name, id));
});
return list;
}
ObjectId Library::GetOrCreate(ObjectId parentId, const std::string &name)
{
auto objects = _session->GetObjectHandles(_storage, mtp::ObjectFormat::Association, parentId);
for (auto id : objects.ObjectHandles)
{
auto oname = _session->GetObjectStringProperty(id, ObjectProperty::ObjectFilename);
if (name == oname)
return id;
}
return _session->CreateDirectory(name, parentId, _storage).ObjectId;
}
Library::Library(const mtp::SessionPtr & session, ProgressReporter && reporter): _session(session)
{
auto storages = _session->GetStorageIDs();
if (storages.StorageIDs.empty())
throw std::runtime_error("no storages found");
u64 progress = 0, total = 0;
if (reporter)
reporter(State::Initialising, progress, total);
_artistSupported = _session->GetDeviceInfo().Supports(ObjectFormat::Artist);
{
auto propsSupported = _session->GetObjectPropertiesSupported(ObjectFormat::AbstractAudioAlbum);
_albumDateAuthoredSupported = std::find(propsSupported.ObjectPropertyCodes.begin(), propsSupported.ObjectPropertyCodes.end(), ObjectProperty::DateAuthored) != propsSupported.ObjectPropertyCodes.end();
}
_storage = storages.StorageIDs[0]; //picking up first storage.
//zune fails to create artist/album without storage id
{
ByteArray data = _session->GetObjectPropertyList(Session::Root, ObjectFormat::Association, ObjectProperty::ObjectFilename, 0, 1);
ObjectPropertyListParser<std::string> parser;
parser.Parse(data, [&](ObjectId id, ObjectProperty property, const std::string &name)
{
if (name == "Artists")
_artistsFolder = id;
else if (name == "Albums")
_albumsFolder = id;
else if (name == "Music")
_musicFolder = id;
});
}
if (_artistSupported && _artistsFolder == ObjectId())
_artistsFolder = _session->CreateDirectory("Artists", Session::Root, _storage).ObjectId;
if (_albumsFolder == ObjectId())
_albumsFolder = _session->CreateDirectory("Albums", Session::Root, _storage).ObjectId;
if (_musicFolder == ObjectId())
_musicFolder = _session->CreateDirectory("Music", Session::Root, _storage).ObjectId;
debug("artists folder: ", _artistsFolder != ObjectId()? _artistsFolder.Id: 0);
debug("albums folder: ", _albumsFolder.Id);
debug("music folder: ", _musicFolder.Id);
auto musicFolders = ListAssociations(_musicFolder);
using namespace mtp;
msg::ObjectHandles artists, albums;
if (_artistSupported)
{
debug("getting artists...");
if (reporter)
reporter(State::QueryingArtists, progress, total);
artists = _session->GetObjectHandles(Session::AllStorages, ObjectFormat::Artist, Session::Device);
total += artists.ObjectHandles.size();
}
{
debug("getting albums...");
if (reporter)
reporter(State::QueryingAlbums, progress, total);
albums = _session->GetObjectHandles(Session::AllStorages, ObjectFormat::AbstractAudioAlbum, Session::Device);
total += albums.ObjectHandles.size();
}
if (_artistSupported)
{
if (reporter)
reporter(State::LoadingArtists, progress, total);
for (auto id : artists.ObjectHandles)
{
auto name = _session->GetObjectStringProperty(id, ObjectProperty::Name);
debug("artist: ", name, "\t", id.Id);
auto artist = std::make_shared<Artist>();
artist->Id = id;
artist->Name = name;
auto it = musicFolders.find(name);
if (it != musicFolders.end())
artist->MusicFolderId = it->second;
else
artist->MusicFolderId = _session->CreateDirectory(name, _musicFolder, _storage).ObjectId;
_artists.insert(std::make_pair(name, artist));
if (reporter)
reporter(State::LoadingArtists, ++progress, total);
}
}
if (reporter)
reporter(State::LoadingAlbums, progress, total);
std::unordered_map<ArtistPtr, NameToObjectIdMap> albumFolders;
for (auto id : albums.ObjectHandles)
{
auto name = _session->GetObjectStringProperty(id, ObjectProperty::Name);
auto artistName = _session->GetObjectStringProperty(id, ObjectProperty::Artist);
std::string albumDate;
if (_albumDateAuthoredSupported)
albumDate = _session->GetObjectStringProperty(id, ObjectProperty::DateAuthored);
auto artist = GetArtist(artistName);
if (!artist)
artist = CreateArtist(artistName);
debug("album: ", artistName, " -- ", name, "\t", id.Id, "\t", albumDate);
auto album = std::make_shared<Album>();
album->Name = name;
album->Artist = artist;
album->Id = id;
album->Year = !albumDate.empty()? ConvertDateTime(albumDate): 0;
if (albumFolders.find(artist) == albumFolders.end()) {
albumFolders[artist] = ListAssociations(artist->MusicFolderId);
}
auto it = albumFolders.find(artist);
if (it == albumFolders.end())
throw std::runtime_error("no iterator after insert, internal error");
const auto & albums = it->second;
auto alit = albums.find(name);
if (alit != albums.end())
album->MusicFolderId = alit->second;
else
album->MusicFolderId = _session->CreateDirectory(name, artist->MusicFolderId, _storage).ObjectId;
_albums.insert(std::make_pair(std::make_pair(artist, name), album));
if (reporter)
reporter(State::LoadingAlbums, ++progress, total);
}
if (reporter)
reporter(State::Loaded, progress, total);
}
Library::~Library()
{ }
Library::ArtistPtr Library::GetArtist(std::string name)
{
if (name.empty())
name = UknownArtist;
auto it = _artists.find(name);
return it != _artists.end()? it->second: ArtistPtr();
}
Library::ArtistPtr Library::CreateArtist(std::string name)
{
if (name.empty())
name = UknownArtist;
auto artist = std::make_shared<Artist>();
artist->Name = name;
artist->MusicFolderId = GetOrCreate(_musicFolder, name);
if (_artistSupported)
{
ByteArray propList;
OutputStream os(propList);
os.Write32(2); //number of props
os.Write32(0); //object handle
os.Write16(static_cast<u16>(ObjectProperty::Name));
os.Write16(static_cast<u16>(DataTypeCode::String));
os.WriteString(name);
os.Write32(0); //object handle
os.Write16(static_cast<u16>(ObjectProperty::ObjectFilename));
os.Write16(static_cast<u16>(DataTypeCode::String));
os.WriteString(name + ".art");
auto response = _session->SendObjectPropList(_storage, _artistsFolder, ObjectFormat::Artist, 0, propList);
artist->Id = response.ObjectId;
}
_artists.insert(std::make_pair(name, artist));
return artist;
}
Library::AlbumPtr Library::GetAlbum(const ArtistPtr & artist, std::string name)
{
if (name.empty())
name = UknownAlbum;
auto it = _albums.find(std::make_pair(artist, name));
return it != _albums.end()? it->second: AlbumPtr();
}
Library::AlbumPtr Library::CreateAlbum(const ArtistPtr & artist, std::string name, int year)
{
if (!artist)
throw std::runtime_error("artists is required");
if (name.empty())
name = UknownAlbum;
ByteArray propList;
OutputStream os(propList);
bool sendYear = year != 0 && _albumDateAuthoredSupported;
os.Write32(3 + (sendYear? 1: 0)); //number of props
if (_artistSupported)
{
os.Write32(0); //object handle
os.Write16(static_cast<u16>(ObjectProperty::ArtistId));
os.Write16(static_cast<u16>(DataTypeCode::Uint32));
os.Write32(artist->Id.Id);
}
else
{
os.Write32(0); //object handle
os.Write16(static_cast<u16>(ObjectProperty::Artist));
os.Write16(static_cast<u16>(DataTypeCode::String));
os.WriteString(artist->Name);
}
os.Write32(0); //object handle
os.Write16(static_cast<u16>(ObjectProperty::Name));
os.Write16(static_cast<u16>(DataTypeCode::String));
os.WriteString(name);
os.Write32(0); //object handle
os.Write16(static_cast<u16>(ObjectProperty::ObjectFilename));
os.Write16(static_cast<u16>(DataTypeCode::String));
os.WriteString(artist->Name + "--" + name + ".alb");
if (sendYear)
{
os.Write32(0); //object handle
os.Write16(static_cast<u16>(ObjectProperty::DateAuthored));
os.Write16(static_cast<u16>(DataTypeCode::String));
os.WriteString(ConvertYear(year));
}
auto album = std::make_shared<Album>();
album->Artist = artist;
album->Name = name;
album->Year = year;
album->MusicFolderId = GetOrCreate(artist->MusicFolderId, name);
auto response = _session->SendObjectPropList(_storage, _albumsFolder, ObjectFormat::AbstractAudioAlbum, 0, propList);
album->Id = response.ObjectId;
_albums.insert(std::make_pair(std::make_pair(artist, name), album));
return album;
}
bool Library::HasTrack(const AlbumPtr & album, const std::string &name, int trackIndex)
{
if (!album)
return false;
LoadRefs(album);
auto & tracks = album->Tracks;
auto range = tracks.equal_range(name);
for(auto i = range.first; i != range.second; ++i)
{
if (i->second == trackIndex)
return true;
}
return false;
}
Library::NewTrackInfo Library::CreateTrack(const ArtistPtr & artist,
const AlbumPtr & album,
ObjectFormat type,
std::string name, const std::string & genre, int trackIndex,
const std::string &filename, size_t size)
{
ByteArray propList;
OutputStream os(propList);
os.Write32(3 + (!genre.empty()? 1: 0) + (trackIndex? 1: 0)); //number of props
if (_artistSupported)
{
os.Write32(0); //object handle
os.Write16(static_cast<u16>(ObjectProperty::ArtistId));
os.Write16(static_cast<u16>(DataTypeCode::Uint32));
os.Write32(artist->Id.Id);
}
else
{
os.Write32(0); //object handle
os.Write16(static_cast<u16>(ObjectProperty::Artist));
os.Write16(static_cast<u16>(DataTypeCode::String));
os.WriteString(artist->Name);
}
os.Write32(0); //object handle
os.Write16(static_cast<u16>(ObjectProperty::Name));
os.Write16(static_cast<u16>(DataTypeCode::String));
os.WriteString(name);
if (trackIndex)
{
os.Write32(0); //object handle
os.Write16(static_cast<u16>(ObjectProperty::Track));
os.Write16(static_cast<u16>(DataTypeCode::Uint16));
os.Write16(trackIndex);
}
if (!genre.empty())
{
os.Write32(0); //object handle
os.Write16(static_cast<u16>(ObjectProperty::Genre));
os.Write16(static_cast<u16>(DataTypeCode::String));
os.WriteString(genre);
}
os.Write32(0); //object handle
os.Write16(static_cast<u16>(ObjectProperty::ObjectFilename));
os.Write16(static_cast<u16>(DataTypeCode::String));
os.WriteString(filename);
auto response = _session->SendObjectPropList(_storage, album->MusicFolderId, type, size, propList);
NewTrackInfo ti;
ti.Id = response.ObjectId;
ti.Name = name;
ti.Index = trackIndex;
return ti;
}
void Library::LoadRefs(AlbumPtr album)
{
if (!album || album->RefsLoaded)
return;
auto refs = _session->GetObjectReferences(album->Id).ObjectHandles;
std::copy(refs.begin(), refs.end(), std::inserter(album->Refs, album->Refs.begin()));
for(auto trackId : refs)
{
auto name = _session->GetObjectStringProperty(trackId, ObjectProperty::Name);
auto index = _session->GetObjectIntegerProperty(trackId, ObjectProperty::Track);
debug("[", index, "]: ", name);
album->Tracks.insert(std::make_pair(name, index));
}
album->RefsLoaded = true;
}
void Library::AddTrack(AlbumPtr album, const NewTrackInfo & ti)
{
if (!album)
return;
LoadRefs(album);
auto & refs = album->Refs;
auto & tracks = album->Tracks;
msg::ObjectHandles handles;
std::copy(refs.begin(), refs.end(), std::back_inserter(handles.ObjectHandles));
handles.ObjectHandles.push_back(ti.Id);
_session->SetObjectReferences(album->Id, handles);
refs.insert(ti.Id);
tracks.insert(std::make_pair(ti.Name, ti.Index));
}
bool Library::Supported(const mtp::SessionPtr & session)
{
auto & gdi = session->GetDeviceInfo();
return
gdi.Supports(OperationCode::GetObjectPropList) &&
gdi.Supports(OperationCode::SendObjectPropList) &&
gdi.Supports(OperationCode::SetObjectReferences) &&
gdi.Supports(ObjectFormat::AbstractAudioAlbum);
;
}
}
<|endoftext|> |
<commit_before>#include <mtp/metadata/Library.h>
#include <mtp/ptp/Session.h>
#include <mtp/log.h>
#include <unordered_map>
namespace mtp
{
namespace
{
const std::string UknownArtist ("UknownArtist");
const std::string UknownAlbum ("UknownAlbum");
}
Library::NameToObjectIdMap Library::ListAssociations(ObjectId parentId)
{
NameToObjectIdMap list;
auto folders = _session->GetObjectHandles(_storage, mtp::ObjectFormat::Association, parentId);
list.reserve(folders.ObjectHandles.size());
for(auto id : folders.ObjectHandles)
{
auto name = _session->GetObjectStringProperty(id, ObjectProperty::ObjectFilename);
list.insert(std::make_pair(name, id));
}
return list;
}
ObjectId Library::GetOrCreate(ObjectId parentId, const std::string &name)
{
auto objects = _session->GetObjectHandles(_storage, mtp::ObjectFormat::Association, parentId);
for (auto id : objects.ObjectHandles)
{
auto oname = _session->GetObjectStringProperty(id, ObjectProperty::ObjectFilename);
if (name == oname)
return id;
}
return _session->CreateDirectory(name, parentId, _storage).ObjectId;
}
Library::Library(const mtp::SessionPtr & session): _session(session)
{
auto storages = _session->GetStorageIDs();
if (storages.StorageIDs.empty())
throw std::runtime_error("no storages found");
_artistSupported = _session->GetDeviceInfo().Supports(ObjectFormat::Artist);
{
auto propsSupported = _session->GetObjectPropertiesSupported(ObjectFormat::AbstractAudioAlbum);
_albumDateAuthoredSupported = std::find(propsSupported.ObjectPropertyCodes.begin(), propsSupported.ObjectPropertyCodes.end(), ObjectProperty::DateAuthored) != propsSupported.ObjectPropertyCodes.end();
}
_storage = storages.StorageIDs[0]; //picking up first storage.
//zune fails to create artist/album without storage id
{
msg::ObjectHandles rootFolders = _session->GetObjectHandles(Session::AllStorages, mtp::ObjectFormat::Association, Session::Root);
for (auto id : rootFolders.ObjectHandles)
{
auto name = _session->GetObjectStringProperty(id, ObjectProperty::ObjectFilename);
if (name == "Artists")
_artistsFolder = id;
else if (name == "Albums")
_albumsFolder = id;
else if (name == "Music")
_musicFolder = id;
}
}
if (_artistSupported && _artistsFolder == ObjectId())
_artistsFolder = _session->CreateDirectory("Artists", Session::Root, _storage).ObjectId;
if (_albumsFolder == ObjectId())
_albumsFolder = _session->CreateDirectory("Albums", Session::Root, _storage).ObjectId;
if (_musicFolder == ObjectId())
_musicFolder = _session->CreateDirectory("Music", Session::Root, _storage).ObjectId;
debug("artists folder: ", _artistsFolder != ObjectId()? _artistsFolder.Id: 0);
debug("albums folder: ", _albumsFolder.Id);
debug("music folder: ", _musicFolder.Id);
auto musicFolders = ListAssociations(_musicFolder);
using namespace mtp;
if (_artistSupported)
{
debug("getting artists...");
auto artists = _session->GetObjectHandles(Session::AllStorages, ObjectFormat::Artist, Session::Device);
for (auto id : artists.ObjectHandles)
{
auto name = _session->GetObjectStringProperty(id, ObjectProperty::Name);
debug("artist: ", name, "\t", id.Id);
auto artist = std::make_shared<Artist>();
artist->Id = id;
artist->Name = name;
auto it = musicFolders.find(name);
if (it != musicFolders.end())
artist->MusicFolderId = it->second;
else
artist->MusicFolderId = _session->CreateDirectory(name, _musicFolder, _storage).ObjectId;
_artists.insert(std::make_pair(name, artist));
}
}
std::unordered_map<ArtistPtr, NameToObjectIdMap> albumFolders;
{
debug("getting albums...");
auto albums = _session->GetObjectHandles(Session::AllStorages, ObjectFormat::AbstractAudioAlbum, Session::Device);
for (auto id : albums.ObjectHandles)
{
auto name = _session->GetObjectStringProperty(id, ObjectProperty::Name);
auto artistName = _session->GetObjectStringProperty(id, ObjectProperty::Artist);
std::string albumDate;
if (_albumDateAuthoredSupported)
albumDate = _session->GetObjectStringProperty(id, ObjectProperty::DateAuthored);
auto artist = GetArtist(artistName);
if (!artist)
artist = CreateArtist(artistName);
debug("album: ", artistName, " -- ", name, "\t", id.Id, "\t", albumDate);
auto album = std::make_shared<Album>();
album->Name = name;
album->Artist = artist;
album->Id = id;
album->Year = !albumDate.empty()? ConvertDateTime(albumDate): 0;
if (albumFolders.find(artist) == albumFolders.end()) {
albumFolders[artist] = ListAssociations(artist->MusicFolderId);
}
auto it = albumFolders.find(artist);
if (it == albumFolders.end())
throw std::runtime_error("no iterator after insert, internal error");
{
auto refs = _session->GetObjectReferences(id).ObjectHandles;
std::copy(refs.begin(), refs.end(), std::inserter(album->Refs, album->Refs.begin()));
for(auto trackId : refs)
{
auto name = _session->GetObjectStringProperty(trackId, ObjectProperty::Name);
auto index = _session->GetObjectIntegerProperty(trackId, ObjectProperty::Track);
debug("[", index, "]: ", name);
album->Tracks.insert(std::make_pair(name, index));
}
}
const auto & albums = it->second;
auto alit = albums.find(name);
if (alit != albums.end())
album->MusicFolderId = alit->second;
else
album->MusicFolderId = _session->CreateDirectory(name, artist->MusicFolderId, _storage).ObjectId;
_albums.insert(std::make_pair(std::make_pair(artist, name), album));
}
}
}
Library::~Library()
{ }
Library::ArtistPtr Library::GetArtist(std::string name)
{
if (name.empty())
name = UknownArtist;
auto it = _artists.find(name);
return it != _artists.end()? it->second: ArtistPtr();
}
Library::ArtistPtr Library::CreateArtist(std::string name)
{
if (name.empty())
name = UknownArtist;
auto artist = std::make_shared<Artist>();
artist->Name = name;
artist->MusicFolderId = GetOrCreate(_musicFolder, name);
if (_artistSupported)
{
ByteArray propList;
OutputStream os(propList);
os.Write32(2); //number of props
os.Write32(0); //object handle
os.Write16(static_cast<u16>(ObjectProperty::Name));
os.Write16(static_cast<u16>(DataTypeCode::String));
os.WriteString(name);
os.Write32(0); //object handle
os.Write16(static_cast<u16>(ObjectProperty::ObjectFilename));
os.Write16(static_cast<u16>(DataTypeCode::String));
os.WriteString(name + ".art");
auto response = _session->SendObjectPropList(_storage, _artistsFolder, ObjectFormat::Artist, 0, propList);
artist->Id = response.ObjectId;
}
_artists.insert(std::make_pair(name, artist));
return artist;
}
Library::AlbumPtr Library::GetAlbum(const ArtistPtr & artist, std::string name)
{
if (name.empty())
name = UknownAlbum;
auto it = _albums.find(std::make_pair(artist, name));
return it != _albums.end()? it->second: AlbumPtr();
}
Library::AlbumPtr Library::CreateAlbum(const ArtistPtr & artist, std::string name, int year)
{
if (!artist)
throw std::runtime_error("artists is required");
if (name.empty())
name = UknownAlbum;
ByteArray propList;
OutputStream os(propList);
bool sendYear = year != 0 && _albumDateAuthoredSupported;
os.Write32(3 + (sendYear? 1: 0)); //number of props
if (_artistSupported)
{
os.Write32(0); //object handle
os.Write16(static_cast<u16>(ObjectProperty::ArtistId));
os.Write16(static_cast<u16>(DataTypeCode::Uint32));
os.Write32(artist->Id.Id);
}
else
{
os.Write32(0); //object handle
os.Write16(static_cast<u16>(ObjectProperty::Artist));
os.Write16(static_cast<u16>(DataTypeCode::String));
os.WriteString(artist->Name);
}
os.Write32(0); //object handle
os.Write16(static_cast<u16>(ObjectProperty::Name));
os.Write16(static_cast<u16>(DataTypeCode::String));
os.WriteString(name);
os.Write32(0); //object handle
os.Write16(static_cast<u16>(ObjectProperty::ObjectFilename));
os.Write16(static_cast<u16>(DataTypeCode::String));
os.WriteString(artist->Name + "--" + name + ".alb");
if (sendYear)
{
os.Write32(0); //object handle
os.Write16(static_cast<u16>(ObjectProperty::DateAuthored));
os.Write16(static_cast<u16>(DataTypeCode::String));
os.WriteString(ConvertYear(year));
}
auto album = std::make_shared<Album>();
album->Artist = artist;
album->Name = name;
album->Year = year;
album->MusicFolderId = GetOrCreate(artist->MusicFolderId, name);
auto response = _session->SendObjectPropList(_storage, _albumsFolder, ObjectFormat::AbstractAudioAlbum, 0, propList);
album->Id = response.ObjectId;
_albums.insert(std::make_pair(std::make_pair(artist, name), album));
return album;
}
bool Library::HasTrack(const AlbumPtr & album, const std::string &name, int trackIndex)
{
if (!album)
return false;
auto & tracks = album->Tracks;
auto it = tracks.find(name);
if (it == tracks.end())
return false;
if (trackIndex <= 0 || it->second <= 0)
return true;
return trackIndex == it->second;
}
Library::NewTrackInfo Library::CreateTrack(const ArtistPtr & artist,
const AlbumPtr & album,
ObjectFormat type,
std::string name, const std::string & genre, int trackIndex,
const std::string &filename, size_t size)
{
ByteArray propList;
OutputStream os(propList);
os.Write32(3 + (!genre.empty()? 1: 0) + (trackIndex? 1: 0)); //number of props
if (_artistSupported)
{
os.Write32(0); //object handle
os.Write16(static_cast<u16>(ObjectProperty::ArtistId));
os.Write16(static_cast<u16>(DataTypeCode::Uint32));
os.Write32(artist->Id.Id);
}
else
{
os.Write32(0); //object handle
os.Write16(static_cast<u16>(ObjectProperty::Artist));
os.Write16(static_cast<u16>(DataTypeCode::String));
os.WriteString(artist->Name);
}
os.Write32(0); //object handle
os.Write16(static_cast<u16>(ObjectProperty::Name));
os.Write16(static_cast<u16>(DataTypeCode::String));
os.WriteString(name);
if (trackIndex)
{
os.Write32(0); //object handle
os.Write16(static_cast<u16>(ObjectProperty::Track));
os.Write16(static_cast<u16>(DataTypeCode::Uint16));
os.Write16(trackIndex);
}
if (!genre.empty())
{
os.Write32(0); //object handle
os.Write16(static_cast<u16>(ObjectProperty::Genre));
os.Write16(static_cast<u16>(DataTypeCode::String));
os.WriteString(genre);
}
os.Write32(0); //object handle
os.Write16(static_cast<u16>(ObjectProperty::ObjectFilename));
os.Write16(static_cast<u16>(DataTypeCode::String));
os.WriteString(filename);
auto response = _session->SendObjectPropList(_storage, album->MusicFolderId, type, size, propList);
NewTrackInfo ti;
ti.Id = response.ObjectId;
ti.Name = name;
ti.Index = trackIndex;
return ti;
}
void Library::AddTrack(AlbumPtr album, const NewTrackInfo & ti)
{
if (!album)
return;
auto & refs = album->Refs;
auto & tracks = album->Tracks;
msg::ObjectHandles handles;
std::copy(refs.begin(), refs.end(), std::back_inserter(handles.ObjectHandles));
handles.ObjectHandles.push_back(ti.Id);
_session->SetObjectReferences(album->Id, handles);
refs.insert(ti.Id);
tracks.insert(std::make_pair(ti.Name, ti.Index));
}
bool Library::Supported(const mtp::SessionPtr & session)
{
auto & gdi = session->GetDeviceInfo();
return
gdi.Supports(OperationCode::SendObjectPropList) &&
gdi.Supports(OperationCode::SetObjectReferences) &&
gdi.Supports(ObjectFormat::AbstractAudioAlbum);
;
}
}
<commit_msg>fix HasTrack logic<commit_after>#include <mtp/metadata/Library.h>
#include <mtp/ptp/Session.h>
#include <mtp/log.h>
#include <unordered_map>
namespace mtp
{
namespace
{
const std::string UknownArtist ("UknownArtist");
const std::string UknownAlbum ("UknownAlbum");
}
Library::NameToObjectIdMap Library::ListAssociations(ObjectId parentId)
{
NameToObjectIdMap list;
auto folders = _session->GetObjectHandles(_storage, mtp::ObjectFormat::Association, parentId);
list.reserve(folders.ObjectHandles.size());
for(auto id : folders.ObjectHandles)
{
auto name = _session->GetObjectStringProperty(id, ObjectProperty::ObjectFilename);
list.insert(std::make_pair(name, id));
}
return list;
}
ObjectId Library::GetOrCreate(ObjectId parentId, const std::string &name)
{
auto objects = _session->GetObjectHandles(_storage, mtp::ObjectFormat::Association, parentId);
for (auto id : objects.ObjectHandles)
{
auto oname = _session->GetObjectStringProperty(id, ObjectProperty::ObjectFilename);
if (name == oname)
return id;
}
return _session->CreateDirectory(name, parentId, _storage).ObjectId;
}
Library::Library(const mtp::SessionPtr & session): _session(session)
{
auto storages = _session->GetStorageIDs();
if (storages.StorageIDs.empty())
throw std::runtime_error("no storages found");
_artistSupported = _session->GetDeviceInfo().Supports(ObjectFormat::Artist);
{
auto propsSupported = _session->GetObjectPropertiesSupported(ObjectFormat::AbstractAudioAlbum);
_albumDateAuthoredSupported = std::find(propsSupported.ObjectPropertyCodes.begin(), propsSupported.ObjectPropertyCodes.end(), ObjectProperty::DateAuthored) != propsSupported.ObjectPropertyCodes.end();
}
_storage = storages.StorageIDs[0]; //picking up first storage.
//zune fails to create artist/album without storage id
{
msg::ObjectHandles rootFolders = _session->GetObjectHandles(Session::AllStorages, mtp::ObjectFormat::Association, Session::Root);
for (auto id : rootFolders.ObjectHandles)
{
auto name = _session->GetObjectStringProperty(id, ObjectProperty::ObjectFilename);
if (name == "Artists")
_artistsFolder = id;
else if (name == "Albums")
_albumsFolder = id;
else if (name == "Music")
_musicFolder = id;
}
}
if (_artistSupported && _artistsFolder == ObjectId())
_artistsFolder = _session->CreateDirectory("Artists", Session::Root, _storage).ObjectId;
if (_albumsFolder == ObjectId())
_albumsFolder = _session->CreateDirectory("Albums", Session::Root, _storage).ObjectId;
if (_musicFolder == ObjectId())
_musicFolder = _session->CreateDirectory("Music", Session::Root, _storage).ObjectId;
debug("artists folder: ", _artistsFolder != ObjectId()? _artistsFolder.Id: 0);
debug("albums folder: ", _albumsFolder.Id);
debug("music folder: ", _musicFolder.Id);
auto musicFolders = ListAssociations(_musicFolder);
using namespace mtp;
if (_artistSupported)
{
debug("getting artists...");
auto artists = _session->GetObjectHandles(Session::AllStorages, ObjectFormat::Artist, Session::Device);
for (auto id : artists.ObjectHandles)
{
auto name = _session->GetObjectStringProperty(id, ObjectProperty::Name);
debug("artist: ", name, "\t", id.Id);
auto artist = std::make_shared<Artist>();
artist->Id = id;
artist->Name = name;
auto it = musicFolders.find(name);
if (it != musicFolders.end())
artist->MusicFolderId = it->second;
else
artist->MusicFolderId = _session->CreateDirectory(name, _musicFolder, _storage).ObjectId;
_artists.insert(std::make_pair(name, artist));
}
}
std::unordered_map<ArtistPtr, NameToObjectIdMap> albumFolders;
{
debug("getting albums...");
auto albums = _session->GetObjectHandles(Session::AllStorages, ObjectFormat::AbstractAudioAlbum, Session::Device);
for (auto id : albums.ObjectHandles)
{
auto name = _session->GetObjectStringProperty(id, ObjectProperty::Name);
auto artistName = _session->GetObjectStringProperty(id, ObjectProperty::Artist);
std::string albumDate;
if (_albumDateAuthoredSupported)
albumDate = _session->GetObjectStringProperty(id, ObjectProperty::DateAuthored);
auto artist = GetArtist(artistName);
if (!artist)
artist = CreateArtist(artistName);
debug("album: ", artistName, " -- ", name, "\t", id.Id, "\t", albumDate);
auto album = std::make_shared<Album>();
album->Name = name;
album->Artist = artist;
album->Id = id;
album->Year = !albumDate.empty()? ConvertDateTime(albumDate): 0;
if (albumFolders.find(artist) == albumFolders.end()) {
albumFolders[artist] = ListAssociations(artist->MusicFolderId);
}
auto it = albumFolders.find(artist);
if (it == albumFolders.end())
throw std::runtime_error("no iterator after insert, internal error");
{
auto refs = _session->GetObjectReferences(id).ObjectHandles;
std::copy(refs.begin(), refs.end(), std::inserter(album->Refs, album->Refs.begin()));
for(auto trackId : refs)
{
auto name = _session->GetObjectStringProperty(trackId, ObjectProperty::Name);
auto index = _session->GetObjectIntegerProperty(trackId, ObjectProperty::Track);
debug("[", index, "]: ", name);
album->Tracks.insert(std::make_pair(name, index));
}
}
const auto & albums = it->second;
auto alit = albums.find(name);
if (alit != albums.end())
album->MusicFolderId = alit->second;
else
album->MusicFolderId = _session->CreateDirectory(name, artist->MusicFolderId, _storage).ObjectId;
_albums.insert(std::make_pair(std::make_pair(artist, name), album));
}
}
}
Library::~Library()
{ }
Library::ArtistPtr Library::GetArtist(std::string name)
{
if (name.empty())
name = UknownArtist;
auto it = _artists.find(name);
return it != _artists.end()? it->second: ArtistPtr();
}
Library::ArtistPtr Library::CreateArtist(std::string name)
{
if (name.empty())
name = UknownArtist;
auto artist = std::make_shared<Artist>();
artist->Name = name;
artist->MusicFolderId = GetOrCreate(_musicFolder, name);
if (_artistSupported)
{
ByteArray propList;
OutputStream os(propList);
os.Write32(2); //number of props
os.Write32(0); //object handle
os.Write16(static_cast<u16>(ObjectProperty::Name));
os.Write16(static_cast<u16>(DataTypeCode::String));
os.WriteString(name);
os.Write32(0); //object handle
os.Write16(static_cast<u16>(ObjectProperty::ObjectFilename));
os.Write16(static_cast<u16>(DataTypeCode::String));
os.WriteString(name + ".art");
auto response = _session->SendObjectPropList(_storage, _artistsFolder, ObjectFormat::Artist, 0, propList);
artist->Id = response.ObjectId;
}
_artists.insert(std::make_pair(name, artist));
return artist;
}
Library::AlbumPtr Library::GetAlbum(const ArtistPtr & artist, std::string name)
{
if (name.empty())
name = UknownAlbum;
auto it = _albums.find(std::make_pair(artist, name));
return it != _albums.end()? it->second: AlbumPtr();
}
Library::AlbumPtr Library::CreateAlbum(const ArtistPtr & artist, std::string name, int year)
{
if (!artist)
throw std::runtime_error("artists is required");
if (name.empty())
name = UknownAlbum;
ByteArray propList;
OutputStream os(propList);
bool sendYear = year != 0 && _albumDateAuthoredSupported;
os.Write32(3 + (sendYear? 1: 0)); //number of props
if (_artistSupported)
{
os.Write32(0); //object handle
os.Write16(static_cast<u16>(ObjectProperty::ArtistId));
os.Write16(static_cast<u16>(DataTypeCode::Uint32));
os.Write32(artist->Id.Id);
}
else
{
os.Write32(0); //object handle
os.Write16(static_cast<u16>(ObjectProperty::Artist));
os.Write16(static_cast<u16>(DataTypeCode::String));
os.WriteString(artist->Name);
}
os.Write32(0); //object handle
os.Write16(static_cast<u16>(ObjectProperty::Name));
os.Write16(static_cast<u16>(DataTypeCode::String));
os.WriteString(name);
os.Write32(0); //object handle
os.Write16(static_cast<u16>(ObjectProperty::ObjectFilename));
os.Write16(static_cast<u16>(DataTypeCode::String));
os.WriteString(artist->Name + "--" + name + ".alb");
if (sendYear)
{
os.Write32(0); //object handle
os.Write16(static_cast<u16>(ObjectProperty::DateAuthored));
os.Write16(static_cast<u16>(DataTypeCode::String));
os.WriteString(ConvertYear(year));
}
auto album = std::make_shared<Album>();
album->Artist = artist;
album->Name = name;
album->Year = year;
album->MusicFolderId = GetOrCreate(artist->MusicFolderId, name);
auto response = _session->SendObjectPropList(_storage, _albumsFolder, ObjectFormat::AbstractAudioAlbum, 0, propList);
album->Id = response.ObjectId;
_albums.insert(std::make_pair(std::make_pair(artist, name), album));
return album;
}
bool Library::HasTrack(const AlbumPtr & album, const std::string &name, int trackIndex)
{
if (!album)
return false;
auto & tracks = album->Tracks;
auto range = tracks.equal_range(name);
for(auto i = range.first; i != range.second; ++i)
{
if (i->second == trackIndex)
return true;
}
return false;
}
Library::NewTrackInfo Library::CreateTrack(const ArtistPtr & artist,
const AlbumPtr & album,
ObjectFormat type,
std::string name, const std::string & genre, int trackIndex,
const std::string &filename, size_t size)
{
ByteArray propList;
OutputStream os(propList);
os.Write32(3 + (!genre.empty()? 1: 0) + (trackIndex? 1: 0)); //number of props
if (_artistSupported)
{
os.Write32(0); //object handle
os.Write16(static_cast<u16>(ObjectProperty::ArtistId));
os.Write16(static_cast<u16>(DataTypeCode::Uint32));
os.Write32(artist->Id.Id);
}
else
{
os.Write32(0); //object handle
os.Write16(static_cast<u16>(ObjectProperty::Artist));
os.Write16(static_cast<u16>(DataTypeCode::String));
os.WriteString(artist->Name);
}
os.Write32(0); //object handle
os.Write16(static_cast<u16>(ObjectProperty::Name));
os.Write16(static_cast<u16>(DataTypeCode::String));
os.WriteString(name);
if (trackIndex)
{
os.Write32(0); //object handle
os.Write16(static_cast<u16>(ObjectProperty::Track));
os.Write16(static_cast<u16>(DataTypeCode::Uint16));
os.Write16(trackIndex);
}
if (!genre.empty())
{
os.Write32(0); //object handle
os.Write16(static_cast<u16>(ObjectProperty::Genre));
os.Write16(static_cast<u16>(DataTypeCode::String));
os.WriteString(genre);
}
os.Write32(0); //object handle
os.Write16(static_cast<u16>(ObjectProperty::ObjectFilename));
os.Write16(static_cast<u16>(DataTypeCode::String));
os.WriteString(filename);
auto response = _session->SendObjectPropList(_storage, album->MusicFolderId, type, size, propList);
NewTrackInfo ti;
ti.Id = response.ObjectId;
ti.Name = name;
ti.Index = trackIndex;
return ti;
}
void Library::AddTrack(AlbumPtr album, const NewTrackInfo & ti)
{
if (!album)
return;
auto & refs = album->Refs;
auto & tracks = album->Tracks;
msg::ObjectHandles handles;
std::copy(refs.begin(), refs.end(), std::back_inserter(handles.ObjectHandles));
handles.ObjectHandles.push_back(ti.Id);
_session->SetObjectReferences(album->Id, handles);
refs.insert(ti.Id);
tracks.insert(std::make_pair(ti.Name, ti.Index));
}
bool Library::Supported(const mtp::SessionPtr & session)
{
auto & gdi = session->GetDeviceInfo();
return
gdi.Supports(OperationCode::SendObjectPropList) &&
gdi.Supports(OperationCode::SetObjectReferences) &&
gdi.Supports(ObjectFormat::AbstractAudioAlbum);
;
}
}
<|endoftext|> |
<commit_before>// @(#)root/rint:$Name: $:$Id: TRint.cxx,v 1.4 2001/02/22 13:32:00 rdm Exp $
// Author: Rene Brun 17/02/95
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// Rint //
// //
// Rint is the ROOT Interactive Interface. It allows interactive access //
// to the ROOT system via the CINT C/C++ interpreter. //
// //
//////////////////////////////////////////////////////////////////////////
#include "TROOT.h"
#include "TClass.h"
#include "TVirtualX.h"
#include "Getline.h"
#include "TStyle.h"
#include "TObjectTable.h"
#include "TClassTable.h"
#include "TStopwatch.h"
#include "TCanvas.h"
#include "TBenchmark.h"
#include "TRint.h"
#include "TSystem.h"
#include "TEnv.h"
#include "TSysEvtHandler.h"
#include "TError.h"
#include "TException.h"
#include "TInterpreter.h"
#include "TObjArray.h"
#include "TObjString.h"
#include "TFile.h"
#include "TMapFile.h"
#include "TTabCom.h"
#ifdef R__UNIX
#include <signal.h>
extern "C" {
extern int G__get_security_error();
extern int G__genericerror(char* msg);
}
#endif
//----- Interrupt signal handler -----------------------------------------------
//______________________________________________________________________________
class TInterruptHandler : public TSignalHandler {
public:
TInterruptHandler() : TSignalHandler(kSigInterrupt, kFALSE) { }
Bool_t Notify();
};
//______________________________________________________________________________
Bool_t TInterruptHandler::Notify()
{
// TRint interrupt handler.
if (fDelay) {
fDelay++;
return kTRUE;
}
// make sure we use the sbrk heap (in case of mapped files)
gMmallocDesc = 0;
if (!G__get_security_error())
G__genericerror("\n *** Break *** keyboard interrupt");
else {
Printf("\n *** Break *** keyboard interrupt");
if (TROOT::Initialized()) {
Getlinem(kInit, "Root > ");
gInterpreter->RewindDictionary();
Throw(GetSignal());
}
}
return kTRUE;
}
//----- Terminal Input file handler --------------------------------------------
//______________________________________________________________________________
class TTermInputHandler : public TFileHandler {
public:
TTermInputHandler(int fd) : TFileHandler(fd, 1) { }
Bool_t Notify();
Bool_t ReadNotify() { return Notify(); }
};
//______________________________________________________________________________
Bool_t TTermInputHandler::Notify()
{
gApplication->HandleTermInput();
return kTRUE;
}
ClassImp(TRint)
//______________________________________________________________________________
TRint::TRint(const char *appClassName, int *argc, char **argv, void *options,
int numOptions, Bool_t noLogo)
: TApplication(appClassName, argc, argv, options, numOptions)
{
// Create an application environment. The TRint environment provides an
// interface to the WM manager functionality and eventloop via inheritance
// of TApplication and in addition provides interactive access to
// the CINT C++ interpreter via the command line.
fNcmd = 0;
fDefaultPrompt = "root [%d] ";
fInterrupt = kFALSE;
gBenchmark = new TBenchmark();
if (!noLogo)
PrintLogo();
// Everybody expects iostream to be available, so load it...
#ifndef WIN32
ProcessLine("#include <iostream>");
#endif
// The following libs are also useful to have,
// make sure they are loaded...
gROOT->LoadClass("TGeometry", "Graf3d");
gROOT->LoadClass("TTree", "Tree");
gROOT->LoadClass("TMatrix", "Matrix");
gROOT->LoadClass("TMinuit", "Minuit");
gROOT->LoadClass("TPostScript", "Postscript");
gROOT->LoadClass("TCanvas", "Gpad");
gROOT->LoadClass("THtml", "Html");
// Load user functions
const char *logon;
logon = gEnv->GetValue("Rint.Load", (char*)0);
if (logon) {
char *mac = gSystem->Which(TROOT::GetMacroPath(), logon, kReadPermission);
if (mac)
ProcessLine(Form(".L %s",logon));
delete [] mac;
}
// Execute logon macro
logon = gEnv->GetValue("Rint.Logon", (char*)0);
if (logon && !NoLogOpt()) {
char *mac = gSystem->Which(TROOT::GetMacroPath(), logon, kReadPermission);
if (mac)
ProcessFile(logon);
delete [] mac;
}
gInterpreter->SaveContext();
gInterpreter->SaveGlobalsContext();
// Install interrupt and terminal input handlers
TInterruptHandler *ih = new TInterruptHandler();
ih->Add();
SetSignalHandler(ih);
TTermInputHandler *th = new TTermInputHandler(0);
th->Add();
// Goto into raw terminal input mode
char defhist[128];
#ifndef R__VMS
sprintf(defhist, "%s/.root_hist", gSystem->Getenv("HOME"));
#else
sprintf(defhist, "%s.root_hist", gSystem->Getenv("HOME"));
#endif
logon = gEnv->GetValue("Rint.History", defhist);
Gl_histinit((char *)logon);
Gl_windowchanged();
// Setup for tab completion
gTabCom = new TTabCom;
}
//______________________________________________________________________________
TRint::~TRint()
{
}
//______________________________________________________________________________
void TRint::Run(Bool_t retrn)
{
// Main application eventloop. First process files given on the command
// line and then go into the main application event loop.
Getlinem(kInit, GetPrompt());
// Process shell command line input files
if (InputFiles()) {
TObjString *file;
TIter next(InputFiles());
RETRY {
while ((file = (TObjString *)next())) {
char cmd[256];
if (file->String().EndsWith(".root")) {
const char *rfile = (const char*)file->String();
Printf("\nAttaching file %s...", rfile);
char *base = StrDup(gSystem->BaseName(rfile));
char *s = strchr(base, '.'); *s = 0;
sprintf(cmd, "TFile *%s = TFile::Open(\"%s\")", base, rfile);
delete [] base;
} else {
Printf("\nProcessing %s...", (const char*)file->String());
sprintf(cmd, ".x %s", (const char*)file->String());
}
Getlinem(kCleanUp, 0);
Gl_histadd(cmd);
fNcmd++;
ProcessLine(cmd);
}
} ENDTRY;
if (QuitOpt())
Terminate(0);
ClearInputFiles();
Getlinem(kInit, GetPrompt());
}
TApplication::Run(retrn);
Getlinem(kCleanUp, 0);
}
//______________________________________________________________________________
void TRint::PrintLogo()
{
// Print the ROOT logo on standard output.
Int_t iday,imonth,iyear;
static const char *months[] = {"January","February","March","April","May",
"June","July","August","September","October",
"November","December"};
const char *root_version = gROOT->GetVersion();
Int_t idatqq = gROOT->GetVersionDate();
iday = idatqq%100;
imonth = (idatqq/100)%100;
iyear = (idatqq/10000);
char *root_date = Form("%d %s %4d",iday,months[imonth-1],iyear);
Printf(" *******************************************");
Printf(" * *");
Printf(" * W E L C O M E to R O O T *");
Printf(" * *");
Printf(" * Version%10s %17s *",root_version,root_date);
// Printf(" * Development version *");
Printf(" * *");
Printf(" * You are welcome to visit our Web site *");
Printf(" * http://root.cern.ch *");
Printf(" * *");
Printf(" *******************************************");
#ifdef R__UNIX
if (!strcmp(gVirtualX->GetName(), "X11TTF"))
Printf("\nFreeType Engine v1.x used to render TrueType fonts.");
#endif
#ifdef _REENTRANT
#ifdef R__UNIX
else
#endif
printf("\n");
Printf("Compiled with thread support.");
#endif
gInterpreter->PrintIntro();
#ifdef R__UNIX
// Popdown X logo, only if started with -splash option
for (int i = 0; i < Argc(); i++)
if (!strcmp(Argv(i), "-splash"))
kill(getppid(), SIGUSR1);
#endif
}
//______________________________________________________________________________
char *TRint::GetPrompt()
{
// Get prompt from interpreter. Either "root [n]" or "end with '}'".
char *s = gInterpreter->GetPrompt();
if (s[0])
strcpy(fPrompt, s);
else
sprintf(fPrompt, fDefaultPrompt.Data(), fNcmd);
return fPrompt;
}
//______________________________________________________________________________
const char *TRint::SetPrompt(const char *newPrompt)
{
// Set a new default prompt. It returns the previous prompt.
// The prompt may contain a %d which will be replaced by the commend
// number. The default prompt is "root [%d] ". The maximum length of
// the prompt is 55 characters. To set the prompt in an interactive
// session do:
// root [0] ((TRint*)gROOT->GetApplication())->SetPrompt("aap> ")
// aap>
static TString op = fDefaultPrompt;
if (newPrompt && strlen(newPrompt) <= 55)
fDefaultPrompt = newPrompt;
else
Error("SetPrompt", "newPrompt too long (> 55 characters)");
return op.Data();
}
//______________________________________________________________________________
void TRint::HandleTermInput()
{
// Handle input coming from terminal.
static TStopwatch timer;
char *line;
if ((line = Getlinem(kOneChar, 0))) {
if (line[0] == 0 && Gl_eof())
Terminate(0);
if (gROOT->Timer()) timer.Start();
Gl_histadd(line);
char *s = line;
while (s && *s == ' ') s++; // strip-off leading blanks
s[strlen(s)-1] = '\0'; // strip also '\n' off
fInterrupt = kFALSE;
if (!gInterpreter->GetMore() && strlen(s) != 0) fNcmd++;
ProcessLine(s);
if (strstr(s,".reset") != s)
gInterpreter->EndOfLineAction();
if (gROOT->Timer()) timer.Print();
gTabCom->ClearAll();
Getlinem(kInit, GetPrompt());
}
}
//______________________________________________________________________________
void TRint::Terminate(int status)
{
// Terminate the application. Reset the terminal to sane mode and call
// the logoff macro defined via Rint.Logoff environment variable.
Getlinem(kCleanUp, 0);
if (ReturnFromRun()) {
gSystem->ExitLoop();
} else {
//Execute logoff macro
const char *logoff;
logoff = gEnv->GetValue("Rint.Logoff", (char*)0);
if (logoff && !NoLogOpt()) {
char *mac = gSystem->Which(TROOT::GetMacroPath(), logoff, kReadPermission);
if (mac)
ProcessFile(logoff);
delete [] mac;
}
gSystem->Exit(status);
}
}
<commit_msg>Remove #include "TCanvas.h"<commit_after>// @(#)root/rint:$Name: $:$Id: TRint.cxx,v 1.5 2001/03/05 15:29:51 rdm Exp $
// Author: Rene Brun 17/02/95
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// Rint //
// //
// Rint is the ROOT Interactive Interface. It allows interactive access //
// to the ROOT system via the CINT C/C++ interpreter. //
// //
//////////////////////////////////////////////////////////////////////////
#include "TROOT.h"
#include "TClass.h"
#include "TVirtualX.h"
#include "Getline.h"
#include "TStyle.h"
#include "TObjectTable.h"
#include "TClassTable.h"
#include "TStopwatch.h"
#include "TBenchmark.h"
#include "TRint.h"
#include "TSystem.h"
#include "TEnv.h"
#include "TSysEvtHandler.h"
#include "TError.h"
#include "TException.h"
#include "TInterpreter.h"
#include "TObjArray.h"
#include "TObjString.h"
#include "TFile.h"
#include "TMapFile.h"
#include "TTabCom.h"
#ifdef R__UNIX
#include <signal.h>
extern "C" {
extern int G__get_security_error();
extern int G__genericerror(char* msg);
}
#endif
//----- Interrupt signal handler -----------------------------------------------
//______________________________________________________________________________
class TInterruptHandler : public TSignalHandler {
public:
TInterruptHandler() : TSignalHandler(kSigInterrupt, kFALSE) { }
Bool_t Notify();
};
//______________________________________________________________________________
Bool_t TInterruptHandler::Notify()
{
// TRint interrupt handler.
if (fDelay) {
fDelay++;
return kTRUE;
}
// make sure we use the sbrk heap (in case of mapped files)
gMmallocDesc = 0;
if (!G__get_security_error())
G__genericerror("\n *** Break *** keyboard interrupt");
else {
Printf("\n *** Break *** keyboard interrupt");
if (TROOT::Initialized()) {
Getlinem(kInit, "Root > ");
gInterpreter->RewindDictionary();
Throw(GetSignal());
}
}
return kTRUE;
}
//----- Terminal Input file handler --------------------------------------------
//______________________________________________________________________________
class TTermInputHandler : public TFileHandler {
public:
TTermInputHandler(int fd) : TFileHandler(fd, 1) { }
Bool_t Notify();
Bool_t ReadNotify() { return Notify(); }
};
//______________________________________________________________________________
Bool_t TTermInputHandler::Notify()
{
gApplication->HandleTermInput();
return kTRUE;
}
ClassImp(TRint)
//______________________________________________________________________________
TRint::TRint(const char *appClassName, int *argc, char **argv, void *options,
int numOptions, Bool_t noLogo)
: TApplication(appClassName, argc, argv, options, numOptions)
{
// Create an application environment. The TRint environment provides an
// interface to the WM manager functionality and eventloop via inheritance
// of TApplication and in addition provides interactive access to
// the CINT C++ interpreter via the command line.
fNcmd = 0;
fDefaultPrompt = "root [%d] ";
fInterrupt = kFALSE;
gBenchmark = new TBenchmark();
if (!noLogo)
PrintLogo();
// Everybody expects iostream to be available, so load it...
#ifndef WIN32
ProcessLine("#include <iostream>");
#endif
// The following libs are also useful to have,
// make sure they are loaded...
gROOT->LoadClass("TGeometry", "Graf3d");
gROOT->LoadClass("TTree", "Tree");
gROOT->LoadClass("TMatrix", "Matrix");
gROOT->LoadClass("TMinuit", "Minuit");
gROOT->LoadClass("TPostScript", "Postscript");
gROOT->LoadClass("TCanvas", "Gpad");
gROOT->LoadClass("THtml", "Html");
// Load user functions
const char *logon;
logon = gEnv->GetValue("Rint.Load", (char*)0);
if (logon) {
char *mac = gSystem->Which(TROOT::GetMacroPath(), logon, kReadPermission);
if (mac)
ProcessLine(Form(".L %s",logon));
delete [] mac;
}
// Execute logon macro
logon = gEnv->GetValue("Rint.Logon", (char*)0);
if (logon && !NoLogOpt()) {
char *mac = gSystem->Which(TROOT::GetMacroPath(), logon, kReadPermission);
if (mac)
ProcessFile(logon);
delete [] mac;
}
gInterpreter->SaveContext();
gInterpreter->SaveGlobalsContext();
// Install interrupt and terminal input handlers
TInterruptHandler *ih = new TInterruptHandler();
ih->Add();
SetSignalHandler(ih);
TTermInputHandler *th = new TTermInputHandler(0);
th->Add();
// Goto into raw terminal input mode
char defhist[128];
#ifndef R__VMS
sprintf(defhist, "%s/.root_hist", gSystem->Getenv("HOME"));
#else
sprintf(defhist, "%s.root_hist", gSystem->Getenv("HOME"));
#endif
logon = gEnv->GetValue("Rint.History", defhist);
Gl_histinit((char *)logon);
Gl_windowchanged();
// Setup for tab completion
gTabCom = new TTabCom;
}
//______________________________________________________________________________
TRint::~TRint()
{
}
//______________________________________________________________________________
void TRint::Run(Bool_t retrn)
{
// Main application eventloop. First process files given on the command
// line and then go into the main application event loop.
Getlinem(kInit, GetPrompt());
// Process shell command line input files
if (InputFiles()) {
TObjString *file;
TIter next(InputFiles());
RETRY {
while ((file = (TObjString *)next())) {
char cmd[256];
if (file->String().EndsWith(".root")) {
const char *rfile = (const char*)file->String();
Printf("\nAttaching file %s...", rfile);
char *base = StrDup(gSystem->BaseName(rfile));
char *s = strchr(base, '.'); *s = 0;
sprintf(cmd, "TFile *%s = TFile::Open(\"%s\")", base, rfile);
delete [] base;
} else {
Printf("\nProcessing %s...", (const char*)file->String());
sprintf(cmd, ".x %s", (const char*)file->String());
}
Getlinem(kCleanUp, 0);
Gl_histadd(cmd);
fNcmd++;
ProcessLine(cmd);
}
} ENDTRY;
if (QuitOpt())
Terminate(0);
ClearInputFiles();
Getlinem(kInit, GetPrompt());
}
TApplication::Run(retrn);
Getlinem(kCleanUp, 0);
}
//______________________________________________________________________________
void TRint::PrintLogo()
{
// Print the ROOT logo on standard output.
Int_t iday,imonth,iyear;
static const char *months[] = {"January","February","March","April","May",
"June","July","August","September","October",
"November","December"};
const char *root_version = gROOT->GetVersion();
Int_t idatqq = gROOT->GetVersionDate();
iday = idatqq%100;
imonth = (idatqq/100)%100;
iyear = (idatqq/10000);
char *root_date = Form("%d %s %4d",iday,months[imonth-1],iyear);
Printf(" *******************************************");
Printf(" * *");
Printf(" * W E L C O M E to R O O T *");
Printf(" * *");
Printf(" * Version%10s %17s *",root_version,root_date);
// Printf(" * Development version *");
Printf(" * *");
Printf(" * You are welcome to visit our Web site *");
Printf(" * http://root.cern.ch *");
Printf(" * *");
Printf(" *******************************************");
#ifdef R__UNIX
if (!strcmp(gVirtualX->GetName(), "X11TTF"))
Printf("\nFreeType Engine v1.x used to render TrueType fonts.");
#endif
#ifdef _REENTRANT
#ifdef R__UNIX
else
#endif
printf("\n");
Printf("Compiled with thread support.");
#endif
gInterpreter->PrintIntro();
#ifdef R__UNIX
// Popdown X logo, only if started with -splash option
for (int i = 0; i < Argc(); i++)
if (!strcmp(Argv(i), "-splash"))
kill(getppid(), SIGUSR1);
#endif
}
//______________________________________________________________________________
char *TRint::GetPrompt()
{
// Get prompt from interpreter. Either "root [n]" or "end with '}'".
char *s = gInterpreter->GetPrompt();
if (s[0])
strcpy(fPrompt, s);
else
sprintf(fPrompt, fDefaultPrompt.Data(), fNcmd);
return fPrompt;
}
//______________________________________________________________________________
const char *TRint::SetPrompt(const char *newPrompt)
{
// Set a new default prompt. It returns the previous prompt.
// The prompt may contain a %d which will be replaced by the commend
// number. The default prompt is "root [%d] ". The maximum length of
// the prompt is 55 characters. To set the prompt in an interactive
// session do:
// root [0] ((TRint*)gROOT->GetApplication())->SetPrompt("aap> ")
// aap>
static TString op = fDefaultPrompt;
if (newPrompt && strlen(newPrompt) <= 55)
fDefaultPrompt = newPrompt;
else
Error("SetPrompt", "newPrompt too long (> 55 characters)");
return op.Data();
}
//______________________________________________________________________________
void TRint::HandleTermInput()
{
// Handle input coming from terminal.
static TStopwatch timer;
char *line;
if ((line = Getlinem(kOneChar, 0))) {
if (line[0] == 0 && Gl_eof())
Terminate(0);
if (gROOT->Timer()) timer.Start();
Gl_histadd(line);
char *s = line;
while (s && *s == ' ') s++; // strip-off leading blanks
s[strlen(s)-1] = '\0'; // strip also '\n' off
fInterrupt = kFALSE;
if (!gInterpreter->GetMore() && strlen(s) != 0) fNcmd++;
ProcessLine(s);
if (strstr(s,".reset") != s)
gInterpreter->EndOfLineAction();
if (gROOT->Timer()) timer.Print();
gTabCom->ClearAll();
Getlinem(kInit, GetPrompt());
}
}
//______________________________________________________________________________
void TRint::Terminate(int status)
{
// Terminate the application. Reset the terminal to sane mode and call
// the logoff macro defined via Rint.Logoff environment variable.
Getlinem(kCleanUp, 0);
if (ReturnFromRun()) {
gSystem->ExitLoop();
} else {
//Execute logoff macro
const char *logoff;
logoff = gEnv->GetValue("Rint.Logoff", (char*)0);
if (logoff && !NoLogOpt()) {
char *mac = gSystem->Which(TROOT::GetMacroPath(), logoff, kReadPermission);
if (mac)
ProcessFile(logoff);
delete [] mac;
}
gSystem->Exit(status);
}
}
<|endoftext|> |
<commit_before>/* Copyright 2019 Benjamin Worpitz
*
* This file is part of alpaka.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "mysqrt.hpp"
#include <alpaka/test/MeasureKernelRunTime.hpp>
#include <alpaka/test/acc/TestAccs.hpp>
#include <alpaka/test/queue/Queue.hpp>
#include <catch2/catch.hpp>
#include <iostream>
#include <typeinfo>
//#############################################################################
//! A vector addition kernel.
class SqrtKernel
{
public:
//-----------------------------------------------------------------------------
//! The kernel entry point.
//!
//! \tparam TAcc The accelerator environment to be executed on.
//! \tparam TElem The matrix element type.
//! \param acc The accelerator to be executed on.
//! \param A The first source vector.
//! \param B The second source vector.
//! \param C The destination vector.
//! \param numElements The number of elements.
ALPAKA_NO_HOST_ACC_WARNING
template<
typename TAcc,
typename TElem,
typename TIdx>
ALPAKA_FN_ACC auto operator()(
TAcc const & acc,
TElem const * const A,
TElem const * const B,
TElem * const C,
TIdx const & numElements) const
-> void
{
static_assert(
alpaka::dim::Dim<TAcc>::value == 1,
"The VectorAddKernel expects 1-dimensional indices!");
auto const gridThreadIdx(alpaka::idx::getIdx<alpaka::Grid, alpaka::Threads>(acc)[0u]);
auto const threadElemExtent(alpaka::workdiv::getWorkDiv<alpaka::Thread, alpaka::Elems>(acc)[0u]);
auto const threadFirstElemIdx(gridThreadIdx * threadElemExtent);
if(threadFirstElemIdx < numElements)
{
// Calculate the number of elements to compute in this thread.
// The result is uniform for all but the last thread.
auto const threadLastElemIdx(threadFirstElemIdx+threadElemExtent);
auto const threadLastElemIdxClipped((numElements > threadLastElemIdx) ? threadLastElemIdx : numElements);
for(TIdx i(threadFirstElemIdx); i<threadLastElemIdxClipped; ++i)
{
C[i] = mysqrt(A[i]) + mysqrt(B[i]);
}
}
}
};
using TestAccs = alpaka::test::acc::EnabledAccs<
alpaka::dim::DimInt<1u>,
std::size_t>;
TEMPLATE_LIST_TEST_CASE( "separableCompilation", "[separableCompilation]", TestAccs)
{
using Acc = TestType;
using Idx = alpaka::idx::Idx<Acc>;
using Val = double;
using DevAcc = alpaka::dev::Dev<Acc>;
using PltfAcc = alpaka::pltf::Pltf<DevAcc>;
using QueueAcc = alpaka::test::queue::DefaultQueue<alpaka::dev::Dev<Acc>>;
using PltfHost = alpaka::pltf::PltfCpu;
using DevHost = alpaka::dev::Dev<PltfHost>;
Idx const numElements(32);
// Create the kernel function object.
SqrtKernel kernel;
// Get the host device.
DevHost const devHost(
alpaka::pltf::getDevByIdx<PltfHost>(0u));
// Select a device to execute on.
DevAcc const devAcc(
alpaka::pltf::getDevByIdx<PltfAcc>(0));
// Get a queue on this device.
QueueAcc queueAcc(devAcc);
// The data extent.
alpaka::vec::Vec<alpaka::dim::DimInt<1u>, Idx> const extent(
numElements);
// Let alpaka calculate good block and grid sizes given our full problem extent.
alpaka::workdiv::WorkDivMembers<alpaka::dim::DimInt<1u>, Idx> const workDiv(
alpaka::workdiv::getValidWorkDiv<Acc>(
devAcc,
extent,
static_cast<Idx>(3u),
false,
alpaka::workdiv::GridBlockExtentSubDivRestrictions::Unrestricted));
std::cout
<< typeid(kernel).name() << "("
<< "accelerator: " << alpaka::acc::getAccName<Acc>()
<< ", workDiv: " << workDiv
<< ", numElements:" << numElements
<< ")" << std::endl;
// Allocate host memory buffers.
auto memBufHostA(alpaka::mem::buf::alloc<Val, Idx>(devHost, extent));
auto memBufHostB(alpaka::mem::buf::alloc<Val, Idx>(devHost, extent));
auto memBufHostC(alpaka::mem::buf::alloc<Val, Idx>(devHost, extent));
// Initialize the host input vectors
for (Idx i(0); i < numElements; ++i)
{
alpaka::mem::view::getPtrNative(memBufHostA)[i] = static_cast<Val>(rand()) / static_cast<Val>(RAND_MAX);
alpaka::mem::view::getPtrNative(memBufHostB)[i] = static_cast<Val>(rand()) / static_cast<Val>(RAND_MAX);
}
// Allocate the buffers on the accelerator.
auto memBufAccA(alpaka::mem::buf::alloc<Val, Idx>(devAcc, extent));
auto memBufAccB(alpaka::mem::buf::alloc<Val, Idx>(devAcc, extent));
auto memBufAccC(alpaka::mem::buf::alloc<Val, Idx>(devAcc, extent));
// Copy Host -> Acc.
alpaka::mem::view::copy(queueAcc, memBufAccA, memBufHostA, extent);
alpaka::mem::view::copy(queueAcc, memBufAccB, memBufHostB, extent);
// Create the executor task.
auto const taskKernel(alpaka::kernel::createTaskKernel<Acc>(
workDiv,
kernel,
alpaka::mem::view::getPtrNative(memBufAccA),
alpaka::mem::view::getPtrNative(memBufAccB),
alpaka::mem::view::getPtrNative(memBufAccC),
numElements));
// Profile the kernel execution.
std::cout << "Execution time: "
<< alpaka::test::integ::measureTaskRunTimeMs(
queueAcc,
taskKernel)
<< " ms"
<< std::endl;
// Copy back the result.
alpaka::mem::view::copy(queueAcc, memBufHostC, memBufAccC, extent);
alpaka::wait::wait(queueAcc);
bool resultCorrect(true);
auto const pHostData(alpaka::mem::view::getPtrNative(memBufHostC));
for(Idx i(0u);
i < numElements;
++i)
{
auto const & val(pHostData[i]);
auto const correctResult(std::sqrt(alpaka::mem::view::getPtrNative(memBufHostA)[i]) + std::sqrt(alpaka::mem::view::getPtrNative(memBufHostB)[i]));
auto const absDiff = (val - correctResult);
if( absDiff > std::numeric_limits<Val>::epsilon() )
{
std::cout << "C[" << i << "] == " << val << " != " << correctResult << std::endl;
resultCorrect = false;
}
}
REQUIRE(true == resultCorrect);
}
<commit_msg>omp4: Disable separableCompilation test for OMP4<commit_after>/* Copyright 2019 Benjamin Worpitz
*
* This file is part of alpaka.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "mysqrt.hpp"
#include <alpaka/test/MeasureKernelRunTime.hpp>
#include <alpaka/test/acc/TestAccs.hpp>
#include <alpaka/test/queue/Queue.hpp>
#include <alpaka/meta/Filter.hpp>
#include <catch2/catch.hpp>
#include <iostream>
#include <typeinfo>
//#############################################################################
//! A vector addition kernel.
class SqrtKernel
{
public:
//-----------------------------------------------------------------------------
//! The kernel entry point.
//!
//! \tparam TAcc The accelerator environment to be executed on.
//! \tparam TElem The matrix element type.
//! \param acc The accelerator to be executed on.
//! \param A The first source vector.
//! \param B The second source vector.
//! \param C The destination vector.
//! \param numElements The number of elements.
ALPAKA_NO_HOST_ACC_WARNING
template<
typename TAcc,
typename TElem,
typename TIdx>
ALPAKA_FN_ACC auto operator()(
TAcc const & acc,
TElem const * const A,
TElem const * const B,
TElem * const C,
TIdx const & numElements) const
-> void
{
static_assert(
alpaka::dim::Dim<TAcc>::value == 1,
"The VectorAddKernel expects 1-dimensional indices!");
auto const gridThreadIdx(alpaka::idx::getIdx<alpaka::Grid, alpaka::Threads>(acc)[0u]);
auto const threadElemExtent(alpaka::workdiv::getWorkDiv<alpaka::Thread, alpaka::Elems>(acc)[0u]);
auto const threadFirstElemIdx(gridThreadIdx * threadElemExtent);
if(threadFirstElemIdx < numElements)
{
// Calculate the number of elements to compute in this thread.
// The result is uniform for all but the last thread.
auto const threadLastElemIdx(threadFirstElemIdx+threadElemExtent);
auto const threadLastElemIdxClipped((numElements > threadLastElemIdx) ? threadLastElemIdx : numElements);
for(TIdx i(threadFirstElemIdx); i<threadLastElemIdxClipped; ++i)
{
C[i] = mysqrt(A[i]) + mysqrt(B[i]);
}
}
}
};
template<typename B>
struct not_omp4 : public std::integral_constant<
bool,
!bool(std::is_same<
alpaka::acc::AccCpuOmp4<
alpaka::dim::DimInt<1u>,
std::size_t>,
B>::value
)>
{};
using TestAccs = alpaka::meta::Filter<
alpaka::test::acc::EnabledAccs<
alpaka::dim::DimInt<1u>,
std::size_t>,
not_omp4
>;
TEMPLATE_LIST_TEST_CASE( "separableCompilation", "[separableCompilation]", TestAccs)
{
using Acc = TestType;
using Idx = alpaka::idx::Idx<Acc>;
using Val = double;
using DevAcc = alpaka::dev::Dev<Acc>;
using PltfAcc = alpaka::pltf::Pltf<DevAcc>;
using QueueAcc = alpaka::test::queue::DefaultQueue<alpaka::dev::Dev<Acc>>;
using PltfHost = alpaka::pltf::PltfCpu;
using DevHost = alpaka::dev::Dev<PltfHost>;
Idx const numElements(32);
// Create the kernel function object.
SqrtKernel kernel;
// Get the host device.
DevHost const devHost(
alpaka::pltf::getDevByIdx<PltfHost>(0u));
// Select a device to execute on.
DevAcc const devAcc(
alpaka::pltf::getDevByIdx<PltfAcc>(0));
// Get a queue on this device.
QueueAcc queueAcc(devAcc);
// The data extent.
alpaka::vec::Vec<alpaka::dim::DimInt<1u>, Idx> const extent(
numElements);
// Let alpaka calculate good block and grid sizes given our full problem extent.
alpaka::workdiv::WorkDivMembers<alpaka::dim::DimInt<1u>, Idx> const workDiv(
alpaka::workdiv::getValidWorkDiv<Acc>(
devAcc,
extent,
static_cast<Idx>(3u),
false,
alpaka::workdiv::GridBlockExtentSubDivRestrictions::Unrestricted));
std::cout
<< typeid(kernel).name() << "("
<< "accelerator: " << alpaka::acc::getAccName<Acc>()
<< ", workDiv: " << workDiv
<< ", numElements:" << numElements
<< ")" << std::endl;
// Allocate host memory buffers.
auto memBufHostA(alpaka::mem::buf::alloc<Val, Idx>(devHost, extent));
auto memBufHostB(alpaka::mem::buf::alloc<Val, Idx>(devHost, extent));
auto memBufHostC(alpaka::mem::buf::alloc<Val, Idx>(devHost, extent));
// Initialize the host input vectors
for (Idx i(0); i < numElements; ++i)
{
alpaka::mem::view::getPtrNative(memBufHostA)[i] = static_cast<Val>(rand()) / static_cast<Val>(RAND_MAX);
alpaka::mem::view::getPtrNative(memBufHostB)[i] = static_cast<Val>(rand()) / static_cast<Val>(RAND_MAX);
}
// Allocate the buffers on the accelerator.
auto memBufAccA(alpaka::mem::buf::alloc<Val, Idx>(devAcc, extent));
auto memBufAccB(alpaka::mem::buf::alloc<Val, Idx>(devAcc, extent));
auto memBufAccC(alpaka::mem::buf::alloc<Val, Idx>(devAcc, extent));
// Copy Host -> Acc.
alpaka::mem::view::copy(queueAcc, memBufAccA, memBufHostA, extent);
alpaka::mem::view::copy(queueAcc, memBufAccB, memBufHostB, extent);
// Create the executor task.
auto const taskKernel(alpaka::kernel::createTaskKernel<Acc>(
workDiv,
kernel,
alpaka::mem::view::getPtrNative(memBufAccA),
alpaka::mem::view::getPtrNative(memBufAccB),
alpaka::mem::view::getPtrNative(memBufAccC),
numElements));
// Profile the kernel execution.
std::cout << "Execution time: "
<< alpaka::test::integ::measureTaskRunTimeMs(
queueAcc,
taskKernel)
<< " ms"
<< std::endl;
// Copy back the result.
alpaka::mem::view::copy(queueAcc, memBufHostC, memBufAccC, extent);
alpaka::wait::wait(queueAcc);
bool resultCorrect(true);
auto const pHostData(alpaka::mem::view::getPtrNative(memBufHostC));
for(Idx i(0u);
i < numElements;
++i)
{
auto const & val(pHostData[i]);
auto const correctResult(std::sqrt(alpaka::mem::view::getPtrNative(memBufHostA)[i]) + std::sqrt(alpaka::mem::view::getPtrNative(memBufHostB)[i]));
auto const absDiff = (val - correctResult);
if( absDiff > std::numeric_limits<Val>::epsilon() )
{
std::cout << "C[" << i << "] == " << val << " != " << correctResult << std::endl;
resultCorrect = false;
}
}
REQUIRE(true == resultCorrect);
}
<|endoftext|> |
<commit_before>//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// 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 "platform/platform.h"
#include "shaderGen/HLSL/pixSpecularHLSL.h"
#include "materials/processedMaterial.h"
#include "materials/materialFeatureTypes.h"
#include "shaderGen/shaderOp.h"
#include "shaderGen/shaderGenVars.h"
#include "gfx/gfxStructs.h"
PixelSpecularHLSL::PixelSpecularHLSL()
: mDep( "shaders/common/lighting.hlsl" )
{
addDependency( &mDep );
}
void PixelSpecularHLSL::processVert( Vector<ShaderComponent*> &componentList,
const MaterialFeatureData &fd )
{
AssertFatal( fd.features[MFT_RTLighting],
"PixelSpecularHLSL requires RTLighting to be enabled!" );
// Nothing to do here... MFT_RTLighting should have
// taken care of passing everything to the pixel shader.
}
void PixelSpecularHLSL::processPix( Vector<ShaderComponent*> &componentList,
const MaterialFeatureData &fd )
{
AssertFatal( fd.features[MFT_RTLighting],
"PixelSpecularHLSL requires RTLighting to be enabled!" );
// RTLighting should have spit out the 4 specular
// powers for the 4 potential lights on this pass.
//
// This can sometimes be NULL if RTLighting skips out
// on us for lightmaps or missing normals.
Var *specular = (Var*)LangElement::find( "specular" );
if ( !specular )
return;
MultiLine *meta = new MultiLine;
LangElement *specMul = new GenOp( "@", specular );
LangElement *final = specMul;
// mask out with lightmap if present
if ( fd.features[MFT_LightMap] )
{
LangElement *lmColor = NULL;
// find lightmap color
lmColor = LangElement::find( "lmColor" );
if ( !lmColor )
{
LangElement * lightMap = LangElement::find( "lightMap" );
LangElement * lmCoord = LangElement::find( "texCoord2" );
lmColor = new GenOp( "tex2D(@, @)", lightMap, lmCoord );
}
final = new GenOp( "@ * float4(@.rgb,0)", specMul, lmColor );
}
// If we have a normal map then mask the specular
if ( fd.features[MFT_SpecularMap] )
{
Var *specularColor = (Var*)LangElement::find( "specularColor" );
if (specularColor)
final = new GenOp( "@ * @", final, specularColor );
}
else if ( fd.features[MFT_NormalMap] && !fd.features[MFT_IsDXTnm] )
{
Var *bumpColor = (Var*)LangElement::find( "bumpNormal" );
final = new GenOp( "@ * @.a", final, bumpColor );
}
// Add the specular to the final color.
// search for color var
Var *color = (Var*)LangElement::find( "col" );
meta->addStatement( new GenOp( " @.rgb += ( @ ).rgb;\r\n", color, final ) );
output = meta;
}
ShaderFeature::Resources PixelSpecularHLSL::getResources( const MaterialFeatureData &fd )
{
Resources res;
return res;
}
void SpecularMapHLSL::processPix( Vector<ShaderComponent*> &componentList, const MaterialFeatureData &fd )
{
// Get the texture coord.
Var *texCoord = getInTexCoord( "texCoord", "float2", true, componentList );
// create texture var
Var *specularMap = new Var;
specularMap->setType( "sampler2D" );
specularMap->setName( "specularMap" );
specularMap->uniform = true;
specularMap->sampler = true;
specularMap->constNum = Var::getTexUnitNum();
LangElement *texOp = new GenOp( "tex2D(@, @)", specularMap, texCoord );
Var *specularColor = new Var( "specularColor", "float4" );
output = new GenOp( " @ = @;\r\n", new DecOp( specularColor ), texOp );
}
ShaderFeature::Resources SpecularMapHLSL::getResources( const MaterialFeatureData &fd )
{
Resources res;
res.numTex = 1;
return res;
}
void SpecularMapHLSL::setTexData( Material::StageData &stageDat,
const MaterialFeatureData &fd,
RenderPassData &passData,
U32 &texIndex )
{
GFXTextureObject *tex = stageDat.getTex( MFT_SpecularMap );
if ( tex )
{
passData.mTexType[ texIndex ] = Material::Standard;
passData.mSamplerNames[ texIndex ] = "specularMap";
passData.mTexSlot[ texIndex++ ].texObject = tex;
}
}<commit_msg>fixed also on DirectX<commit_after>//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// 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 "platform/platform.h"
#include "shaderGen/HLSL/pixSpecularHLSL.h"
#include "materials/processedMaterial.h"
#include "materials/materialFeatureTypes.h"
#include "shaderGen/shaderOp.h"
#include "shaderGen/shaderGenVars.h"
#include "gfx/gfxStructs.h"
PixelSpecularHLSL::PixelSpecularHLSL()
: mDep( "shaders/common/lighting.hlsl" )
{
addDependency( &mDep );
}
void PixelSpecularHLSL::processVert( Vector<ShaderComponent*> &componentList,
const MaterialFeatureData &fd )
{
AssertFatal( fd.features[MFT_RTLighting],
"PixelSpecularHLSL requires RTLighting to be enabled!" );
// Nothing to do here... MFT_RTLighting should have
// taken care of passing everything to the pixel shader.
}
void PixelSpecularHLSL::processPix( Vector<ShaderComponent*> &componentList,
const MaterialFeatureData &fd )
{
AssertFatal( fd.features[MFT_RTLighting],
"PixelSpecularHLSL requires RTLighting to be enabled!" );
// RTLighting should have spit out the 4 specular
// powers for the 4 potential lights on this pass.
//
// This can sometimes be NULL if RTLighting skips out
// on us for lightmaps or missing normals.
Var *specular = (Var*)LangElement::find( "specular" );
if ( !specular )
return;
MultiLine *meta = new MultiLine;
LangElement *specMul = new GenOp( "@", specular );
LangElement *final = specMul;
// mask out with lightmap if present
if ( fd.features[MFT_LightMap] )
{
LangElement *lmColor = NULL;
// find lightmap color
lmColor = LangElement::find( "lmColor" );
if ( !lmColor )
{
LangElement * lightMap = LangElement::find( "lightMap" );
LangElement * lmCoord = LangElement::find( "texCoord2" );
lmColor = new GenOp( "tex2D(@, @)", lightMap, lmCoord );
}
final = new GenOp( "@ * float4(@.rgb,0)", specMul, lmColor );
}
// If we have a normal map then mask the specular
if ( fd.features[MFT_SpecularMap] )
{
Var *specularColor = (Var*)LangElement::find( "specularColor" );
if (specularColor)
final = new GenOp( "@ * @", final, specularColor );
}
else if ( fd.features[MFT_NormalMap] && !fd.features[MFT_IsDXTnm] )
{
Var *bumpColor = (Var*)LangElement::find( "bumpNormal" );
final = new GenOp( "@ * @.a", final, bumpColor );
}
// Add the specular to the final color.
// search for color var
Var *color = (Var*)LangElement::find( "col" );
meta->addStatement( new GenOp( " @.rgb += ( @ ).rgb;\r\n", color, final ) );
output = meta;
}
ShaderFeature::Resources PixelSpecularHLSL::getResources( const MaterialFeatureData &fd )
{
Resources res;
return res;
}
void SpecularMapHLSL::processVert(Vector<ShaderComponent*> &componentList, const MaterialFeatureData &fd)
{
MultiLine *meta = new MultiLine;
// Add the texture coords.
getOutTexCoord("texCoord",
"float2",
true,
fd.features[MFT_TexAnim],
meta,
componentList);
output = meta;
}
void SpecularMapHLSL::processPix( Vector<ShaderComponent*> &componentList, const MaterialFeatureData &fd )
{
// Get the texture coord.
Var *texCoord = getInTexCoord( "texCoord", "float2", true, componentList );
// create texture var
Var *specularMap = new Var;
specularMap->setType( "sampler2D" );
specularMap->setName( "specularMap" );
specularMap->uniform = true;
specularMap->sampler = true;
specularMap->constNum = Var::getTexUnitNum();
LangElement *texOp = new GenOp( "tex2D(@, @)", specularMap, texCoord );
Var *specularColor = new Var( "specularColor", "float4" );
output = new GenOp( " @ = @;\r\n", new DecOp( specularColor ), texOp );
}
ShaderFeature::Resources SpecularMapHLSL::getResources( const MaterialFeatureData &fd )
{
Resources res;
res.numTex = 1;
return res;
}
void SpecularMapHLSL::setTexData( Material::StageData &stageDat,
const MaterialFeatureData &fd,
RenderPassData &passData,
U32 &texIndex )
{
GFXTextureObject *tex = stageDat.getTex( MFT_SpecularMap );
if ( tex )
{
passData.mTexType[ texIndex ] = Material::Standard;
passData.mSamplerNames[ texIndex ] = "specularMap";
passData.mTexSlot[ texIndex++ ].texObject = tex;
}
}
<|endoftext|> |
<commit_before> /*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: filcmd.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-09 15:22:50 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _FILCMD_HXX_
#define _FILCMD_HXX_
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_XINTERFACE_HPP_
#include <com/sun/star/uno/XInterface.hpp>
#endif
#ifndef _COM_SUN_STAR_UCB_XCOMMANDINFO_HPP_
#include <com/sun/star/ucb/XCommandInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_UCB_XCONTENTPROVIDER_HPP_
#include <com/sun/star/ucb/XContentProvider.hpp>
#endif
namespace fileaccess {
// forward
class shell;
class XCommandInfo_impl
: public cppu::OWeakObject,
public com::sun::star::ucb::XCommandInfo
{
public:
XCommandInfo_impl( shell* pMyShell, const rtl::OUString& aUnqPath );
virtual ~XCommandInfo_impl();
// XInterface
virtual com::sun::star::uno::Any SAL_CALL
queryInterface(
const com::sun::star::uno::Type& aType )
throw( com::sun::star::uno::RuntimeException);
virtual void SAL_CALL
acquire(
void )
throw();
virtual void SAL_CALL
release(
void )
throw();
// XCommandInfo
virtual com::sun::star::uno::Sequence< com::sun::star::ucb::CommandInfo > SAL_CALL
getCommands(
void )
throw( com::sun::star::uno::RuntimeException);
virtual com::sun::star::ucb::CommandInfo SAL_CALL
getCommandInfoByName(
const rtl::OUString& Name )
throw( com::sun::star::ucb::UnsupportedCommandException,
com::sun::star::uno::RuntimeException);
virtual com::sun::star::ucb::CommandInfo SAL_CALL
getCommandInfoByHandle(
sal_Int32 Handle )
throw( com::sun::star::ucb::UnsupportedCommandException,
com::sun::star::uno::RuntimeException );
virtual sal_Bool SAL_CALL
hasCommandByName(
const rtl::OUString& Name )
throw( com::sun::star::uno::RuntimeException );
virtual sal_Bool SAL_CALL
hasCommandByHandle(
sal_Int32 Handle )
throw( com::sun::star::uno::RuntimeException );
private:
shell* m_pMyShell;
com::sun::star::uno::Reference< com::sun::star::ucb::XContentProvider > m_xProvider;
};
}
#endif
<commit_msg>INTEGRATION: CWS warnings01 (1.4.10); FILE MERGED 2005/11/09 21:01:52 sb 1.4.10.1: #i53898# Made code warning-free.<commit_after> /*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: filcmd.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: hr $ $Date: 2006-06-20 05:19:31 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _FILCMD_HXX_
#define _FILCMD_HXX_
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_XINTERFACE_HPP_
#include <com/sun/star/uno/XInterface.hpp>
#endif
#ifndef _COM_SUN_STAR_UCB_XCOMMANDINFO_HPP_
#include <com/sun/star/ucb/XCommandInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_UCB_XCONTENTPROVIDER_HPP_
#include <com/sun/star/ucb/XContentProvider.hpp>
#endif
namespace fileaccess {
// forward
class shell;
class XCommandInfo_impl
: public cppu::OWeakObject,
public com::sun::star::ucb::XCommandInfo
{
public:
XCommandInfo_impl( shell* pMyShell );
virtual ~XCommandInfo_impl();
// XInterface
virtual com::sun::star::uno::Any SAL_CALL
queryInterface(
const com::sun::star::uno::Type& aType )
throw( com::sun::star::uno::RuntimeException);
virtual void SAL_CALL
acquire(
void )
throw();
virtual void SAL_CALL
release(
void )
throw();
// XCommandInfo
virtual com::sun::star::uno::Sequence< com::sun::star::ucb::CommandInfo > SAL_CALL
getCommands(
void )
throw( com::sun::star::uno::RuntimeException);
virtual com::sun::star::ucb::CommandInfo SAL_CALL
getCommandInfoByName(
const rtl::OUString& Name )
throw( com::sun::star::ucb::UnsupportedCommandException,
com::sun::star::uno::RuntimeException);
virtual com::sun::star::ucb::CommandInfo SAL_CALL
getCommandInfoByHandle(
sal_Int32 Handle )
throw( com::sun::star::ucb::UnsupportedCommandException,
com::sun::star::uno::RuntimeException );
virtual sal_Bool SAL_CALL
hasCommandByName(
const rtl::OUString& Name )
throw( com::sun::star::uno::RuntimeException );
virtual sal_Bool SAL_CALL
hasCommandByHandle(
sal_Int32 Handle )
throw( com::sun::star::uno::RuntimeException );
private:
shell* m_pMyShell;
com::sun::star::uno::Reference< com::sun::star::ucb::XContentProvider > m_xProvider;
};
}
#endif
<|endoftext|> |
<commit_before>
#include "tablemodelpairsassigned.h"
#include "column.h"
#include <QMimeData>
#include <QTimer>
#include <QDebug>
using namespace std;
TableModelPairsAssigned::TableModelPairsAssigned(QObject *parent)
: TableModel(parent)
{
_boundTo = NULL;
_source = NULL;
_variableTypesAllowed = 0;
_variableTypesSuggested = Column::ColumnTypeNominal | Column::ColumnTypeOrdinal | Column::ColumnTypeScale;
}
void TableModelPairsAssigned::bindTo(Option *option)
{
_boundTo = dynamic_cast<OptionVariablesGroups *>(option);
if (_boundTo == NULL)
{
qDebug() << "TableModelPairsAssigned::bindTo(); Could not bind to option";
return;
}
if (_source == NULL)
{
qDebug() << "TableModelPairsAssigned::bindTo(); source not set";
return;
}
beginResetModel();
Terms terms = _boundTo->value();
_values = terms.asQListOfQLists();
endResetModel();
}
void TableModelPairsAssigned::setSource(TableModelVariablesAvailable *source)
{
_source = source;
this->setInfoProvider(source);
}
int TableModelPairsAssigned::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return _values.size();
}
int TableModelPairsAssigned::columnCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return 2;
}
QVariant TableModelPairsAssigned::data(const QModelIndex &index, int role) const
{
if ( ! index.isValid())
return QVariant();
if (role == Qt::DisplayRole)
{
const QStringList &row = _values.at(index.row());
return row.at(index.column());
}
return QVariant();
}
Qt::ItemFlags TableModelPairsAssigned::flags(const QModelIndex &index) const
{
if (index.isValid())
return Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled;
else
return Qt::ItemIsEnabled | Qt::ItemIsDropEnabled;
}
Qt::DropActions TableModelPairsAssigned::supportedDropActions() const
{
return Qt::CopyAction;
}
Qt::DropActions TableModelPairsAssigned::supportedDragActions() const
{
return Qt::MoveAction;
}
QStringList TableModelPairsAssigned::mimeTypes() const
{
QStringList types;
types << "application/vnd.list.variable";
return types;
}
QMimeData *TableModelPairsAssigned::mimeData(const QModelIndexList &indexes) const
{
Q_UNUSED(indexes);
QMimeData *mimeData = new QMimeData();
QByteArray encodedData;
QDataStream dataStream(&encodedData, QIODevice::WriteOnly);
dataStream << 0;
mimeData->setData("application/vnd.list.variable", encodedData);
return mimeData;
}
bool TableModelPairsAssigned::dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent)
{
if (action == Qt::IgnoreAction)
return true;
if ( ! canDropMimeData(data, action, row, column, parent))
return false;
if (mimeTypes().contains("application/vnd.list.variable"))
{
QByteArray encodedData = data->data("application/vnd.list.variable");
QDataStream stream(&encodedData, QIODevice::ReadOnly);
Terms terms;
terms.set(encodedData);
if (parent.isValid()) // drop into cell
{
QStringList row = _values.at(parent.row());
row.replace(parent.column(), terms.at(0).asQString());
_values.replace(parent.row(), row);
emit dataChanged(parent, parent);
}
else if (row == -1 && _values.size() > 0 && _values.last().last() == "")
{
int row = _values.length() - 1;
int column = _values.at(row).length() - 1;
_values.last().last() = terms.at(0).asQString();
emit dataChanged(index(row, column), index(row, column));
}
else
{
int beginRow;
if (row != -1)
beginRow = row;
else
beginRow = rowCount(QModelIndex());
beginInsertRows(QModelIndex(), beginRow, beginRow);
if (terms.size() == 1)
{
QList<QString> newRow;
newRow.append(terms.at(0).asQString());
newRow.append("");
_values.insert(beginRow, newRow);
}
else
{
QList<QString> newRow;
newRow.append(terms.at(0).asQString());
newRow.append(terms.at(1).asQString());
_values.insert(beginRow, newRow);
}
endInsertRows();
}
assignToOption();
return true;
}
return false;
}
bool TableModelPairsAssigned::canDropMimeData(const QMimeData *data, Qt::DropAction, int row, int column, const QModelIndex &parent) const
{
Q_UNUSED(parent);
Q_UNUSED(row);
Q_UNUSED(column);
if (mimeTypes().contains("application/vnd.list.variable"))
{
QByteArray encodedData = data->data("application/vnd.list.variable");
Terms variables;
variables.set(encodedData);
foreach (const Term &variable, variables)
{
if ( ! isAllowed(variable))
return false;
}
return true;
}
else
{
return false;
}
}
bool TableModelPairsAssigned::isAllowed(const Term &term) const
{
QVariant v = requestInfo(term, VariableInfo::VariableType);
int variableType = v.toInt();
return variableType == 0 || variableType & _variableTypesAllowed;
}
bool TableModelPairsAssigned::insertRows(int row, int count, const QModelIndex &parent)
{
beginInsertRows(parent, row, row + count - 1);
for (int i = 0; i < count; i++)
{
QList<QString> newRow;
newRow.append("");
newRow.append("");
_values.insert(row, newRow);
}
endInsertRows();
return true;
}
void TableModelPairsAssigned::mimeDataMoved(const QModelIndexList &indexes)
{
beginResetModel();
QModelIndexList sorted = indexes;
int lastRowDeleted = -1;
qSort(sorted.begin(), sorted.end(), qGreater<QModelIndex>());
foreach (const QModelIndex &index, sorted)
{
int row = index.row();
if (row != lastRowDeleted)
_values.removeAt(row);
lastRowDeleted = row;
}
endResetModel();
assignToOption();
}
void TableModelPairsAssigned::assignToOption()
{
if (_boundTo != NULL)
_boundTo->setValue(Terms(_values).asVectorOfVectors());
}
void TableModelPairsAssigned::setVariableTypesSuggested(int variableTypesSuggested)
{
_variableTypesSuggested = variableTypesSuggested;
}
int TableModelPairsAssigned::variableTypesSuggested() const
{
return _variableTypesSuggested;
}
void TableModelPairsAssigned::setVariableTypesAllowed(int variableTypesAllowed)
{
_variableTypesAllowed = variableTypesAllowed;
}
int TableModelPairsAssigned::variableTypesAllowed() const
{
return _variableTypesAllowed;
}
<commit_msg>PS T-Tests: Fix to not all pairs always appearing<commit_after>
#include "tablemodelpairsassigned.h"
#include "column.h"
#include <QMimeData>
#include <QTimer>
#include <QDebug>
using namespace std;
TableModelPairsAssigned::TableModelPairsAssigned(QObject *parent)
: TableModel(parent)
{
_boundTo = NULL;
_source = NULL;
_variableTypesAllowed = 0;
_variableTypesSuggested = Column::ColumnTypeNominal | Column::ColumnTypeOrdinal | Column::ColumnTypeScale;
}
void TableModelPairsAssigned::bindTo(Option *option)
{
_boundTo = dynamic_cast<OptionVariablesGroups *>(option);
if (_boundTo == NULL)
{
qDebug() << "TableModelPairsAssigned::bindTo(); Could not bind to option";
return;
}
if (_source == NULL)
{
qDebug() << "TableModelPairsAssigned::bindTo(); source not set";
return;
}
beginResetModel();
Terms terms = _boundTo->value();
_values = terms.asQListOfQLists();
endResetModel();
}
void TableModelPairsAssigned::setSource(TableModelVariablesAvailable *source)
{
_source = source;
this->setInfoProvider(source);
}
int TableModelPairsAssigned::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return _values.size();
}
int TableModelPairsAssigned::columnCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return 2;
}
QVariant TableModelPairsAssigned::data(const QModelIndex &index, int role) const
{
if ( ! index.isValid())
return QVariant();
if (role == Qt::DisplayRole)
{
const QStringList &row = _values.at(index.row());
return row.at(index.column());
}
return QVariant();
}
Qt::ItemFlags TableModelPairsAssigned::flags(const QModelIndex &index) const
{
if (index.isValid())
return Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled;
else
return Qt::ItemIsEnabled | Qt::ItemIsDropEnabled;
}
Qt::DropActions TableModelPairsAssigned::supportedDropActions() const
{
return Qt::CopyAction;
}
Qt::DropActions TableModelPairsAssigned::supportedDragActions() const
{
return Qt::MoveAction;
}
QStringList TableModelPairsAssigned::mimeTypes() const
{
QStringList types;
types << "application/vnd.list.variable";
return types;
}
QMimeData *TableModelPairsAssigned::mimeData(const QModelIndexList &indexes) const
{
Q_UNUSED(indexes);
QMimeData *mimeData = new QMimeData();
QByteArray encodedData;
QDataStream dataStream(&encodedData, QIODevice::WriteOnly);
dataStream << 0;
mimeData->setData("application/vnd.list.variable", encodedData);
return mimeData;
}
bool TableModelPairsAssigned::dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent)
{
if (action == Qt::IgnoreAction)
return true;
if ( ! canDropMimeData(data, action, row, column, parent))
return false;
if (mimeTypes().contains("application/vnd.list.variable"))
{
QByteArray encodedData = data->data("application/vnd.list.variable");
QDataStream stream(&encodedData, QIODevice::ReadOnly);
Terms terms;
terms.set(encodedData);
if (parent.isValid()) // drop into cell
{
QStringList row = _values.at(parent.row());
row.replace(parent.column(), terms.at(0).asQString());
_values.replace(parent.row(), row);
emit dataChanged(parent, parent);
}
else if (row == -1 && _values.size() > 0 && _values.last().last() == "")
{
int row = _values.length() - 1;
int column = _values.at(row).length() - 1;
_values.last().last() = terms.at(0).asQString();
emit dataChanged(index(row, column), index(row, column));
}
else
{
int beginRow;
if (row != -1)
beginRow = row;
else
beginRow = rowCount(QModelIndex());
beginInsertRows(QModelIndex(), beginRow, beginRow);
if (terms.size() == 1)
{
QList<QString> newRow;
newRow.append(terms.at(0).asQString());
newRow.append("");
_values.insert(beginRow, newRow);
}
else
{
QList<QString> newRow;
newRow.append(terms.at(0).asQString());
newRow.append(terms.at(1).asQString());
_values.insert(beginRow, newRow);
}
endInsertRows();
}
assignToOption();
return true;
}
return false;
}
bool TableModelPairsAssigned::canDropMimeData(const QMimeData *data, Qt::DropAction, int row, int column, const QModelIndex &parent) const
{
Q_UNUSED(parent);
Q_UNUSED(row);
Q_UNUSED(column);
if (mimeTypes().contains("application/vnd.list.variable"))
{
QByteArray encodedData = data->data("application/vnd.list.variable");
Terms variables;
variables.set(encodedData);
foreach (const Term &variable, variables)
{
if ( ! isAllowed(variable))
return false;
}
return true;
}
else
{
return false;
}
}
bool TableModelPairsAssigned::isAllowed(const Term &term) const
{
QVariant v = requestInfo(term, VariableInfo::VariableType);
int variableType = v.toInt();
return variableType == 0 || variableType & _variableTypesAllowed;
}
bool TableModelPairsAssigned::insertRows(int row, int count, const QModelIndex &parent)
{
beginInsertRows(parent, row, row + count - 1);
for (int i = 0; i < count; i++)
{
QList<QString> newRow;
newRow.append("");
newRow.append("");
_values.insert(row, newRow);
}
endInsertRows();
return true;
}
void TableModelPairsAssigned::mimeDataMoved(const QModelIndexList &indexes)
{
beginResetModel();
QModelIndexList sorted = indexes;
int lastRowDeleted = -1;
qSort(sorted.begin(), sorted.end(), qGreater<QModelIndex>());
foreach (const QModelIndex &index, sorted)
{
int row = index.row();
if (row != lastRowDeleted)
_values.removeAt(row);
lastRowDeleted = row;
}
endResetModel();
assignToOption();
}
void TableModelPairsAssigned::assignToOption()
{
if (_boundTo != NULL)
{
vector<vector<string> > pairs;
foreach (const QStringList &qPair, _values)
{
vector<string> pair;
pair.push_back(qPair.first().toStdString());
pair.push_back(qPair.at(1).toStdString());
pairs.push_back(pair);
}
_boundTo->setValue(pairs);
}
}
void TableModelPairsAssigned::setVariableTypesSuggested(int variableTypesSuggested)
{
_variableTypesSuggested = variableTypesSuggested;
}
int TableModelPairsAssigned::variableTypesSuggested() const
{
return _variableTypesSuggested;
}
void TableModelPairsAssigned::setVariableTypesAllowed(int variableTypesAllowed)
{
_variableTypesAllowed = variableTypesAllowed;
}
int TableModelPairsAssigned::variableTypesAllowed() const
{
return _variableTypesAllowed;
}
<|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 "mitkDispatcher.h"
#include "mitkInteractionEvent.h"
#include "mitkInternalEvent.h"
// MicroServices
#include "usGetModuleContext.h"
#include "mitkInteractionEventObserver.h"
mitk::Dispatcher::Dispatcher( const std::string& rendererName )
: m_ProcessingMode(REGULAR)
{
// LDAP filter string to find all listeners specific for the renderer
// corresponding to this dispatcher
std::string specificRenderer = "(rendererName=" + rendererName +")";
// LDAP filter string to find all listeners that are not specific
// to any renderer
std::string anyRenderer = "(!(rendererName=*))";
// LDAP filter string to find only instances of InteractionEventObserver
std::string classInteractionEventObserver = "(" + us::ServiceConstants::OBJECTCLASS() + "=" + us_service_interface_iid<InteractionEventObserver>() + ")";
// Configure the LDAP filter to find all instances of InteractionEventObserver
// that are specific to this dispatcher or unspecific to any dispatchers (real global listener)
us::LDAPFilter filter( "(&(|"+ specificRenderer + anyRenderer + ")"+classInteractionEventObserver+")" );
// Give the filter to the ObserverTracker
m_EventObserverTracker = new us::ServiceTracker<InteractionEventObserver>(us::GetModuleContext(), filter);
m_EventObserverTracker->Open();
}
void mitk::Dispatcher::AddDataInteractor(const DataNode* dataNode)
{
RemoveDataInteractor(dataNode);
RemoveOrphanedInteractors();
DataInteractor::Pointer dataInteractor = dataNode->GetDataInteractor();
if (dataInteractor.IsNotNull())
{
m_Interactors.push_back(dataInteractor);
}
}
/*
* Note: One DataInteractor can only have one DataNode and vice versa,
* BUT the m_Interactors list may contain another DataInteractor that is still connected to this DataNode,
* in this case we have to remove >1 DataInteractor. (Some special case of switching DataNodes between DataInteractors and registering a
* DataNode to a DataStorage after assigning it to an DataInteractor)
*/
void mitk::Dispatcher::RemoveDataInteractor(const DataNode* dataNode)
{
for (ListInteractorType::iterator it = m_Interactors.begin(); it != m_Interactors.end();)
{
if ((*it)->GetDataNode() == dataNode)
{
it = m_Interactors.erase(it);
}
else
{
++it;
}
}
}
size_t mitk::Dispatcher::GetNumberOfInteractors()
{
return m_Interactors.size();
}
mitk::Dispatcher::~Dispatcher()
{
m_EventObserverTracker->Close();
delete m_EventObserverTracker;
m_Interactors.clear();
}
bool mitk::Dispatcher::ProcessEvent(InteractionEvent* event)
{
InteractionEvent::Pointer p = event;
bool eventIsHandled = false;
/* Filter out and handle Internal Events separately */
InternalEvent* internalEvent = dynamic_cast<InternalEvent*>(event);
if (internalEvent != NULL)
{
eventIsHandled = HandleInternalEvent(internalEvent);
// InternalEvents that are handled are not sent to the listeners
if (eventIsHandled)
{
return true;
}
}
switch (m_ProcessingMode)
{
case CONNECTEDMOUSEACTION:
// finished connected mouse action
if (std::strcmp(p->GetNameOfClass(), "MouseReleaseEvent") == 0)
{
m_ProcessingMode = REGULAR;
eventIsHandled = m_SelectedInteractor->HandleEvent(event, m_SelectedInteractor->GetDataNode());
// delete reference to interactor as soon as connected action is finished
m_SelectedInteractor = NULL;
}
// give event to selected interactor
if (eventIsHandled == false && m_SelectedInteractor.IsNotNull())
{
eventIsHandled = m_SelectedInteractor->HandleEvent(event, m_SelectedInteractor->GetDataNode());
}
break;
case GRABINPUT:
eventIsHandled = m_SelectedInteractor->HandleEvent(event, m_SelectedInteractor->GetDataNode());
SetEventProcessingMode(m_SelectedInteractor);
break;
case PREFERINPUT:
if (m_SelectedInteractor->HandleEvent(event, m_SelectedInteractor->GetDataNode()) == true)
{
SetEventProcessingMode(m_SelectedInteractor);
eventIsHandled = true;
}
break;
case REGULAR:
break;
}
// Standard behavior. Is executed in STANDARD mode and PREFERINPUT mode, if preferred interactor rejects event.
if (m_ProcessingMode == REGULAR || (m_ProcessingMode == PREFERINPUT && eventIsHandled == false))
{
if (std::strcmp(p->GetNameOfClass(), "MousePressEvent") == 0)
event->GetSender()->GetRenderingManager()->SetRenderWindowFocus(event->GetSender()->GetRenderWindow());
m_Interactors.sort(cmp()); // sorts interactors by layer (descending);
// copy the list to prevent iterator invalidation as executing actions
// in HandleEvent() can cause the m_Interactors list to be updated
const std::list<DataInteractor::Pointer> tmpInteractorList( m_Interactors );
std::list<DataInteractor::Pointer>::const_iterator it;
for ( it=tmpInteractorList.cbegin(); it!=tmpInteractorList.cend(); ++it )
{
DataInteractor::Pointer dataInteractor = *it;
if ( (*it)->HandleEvent(event, dataInteractor->GetDataNode()) )
{ // if an event is handled several properties are checked, in order to determine the processing mode of the dispatcher
SetEventProcessingMode(dataInteractor);
if (std::strcmp(p->GetNameOfClass(), "MousePressEvent") == 0 && m_ProcessingMode == REGULAR)
{
m_SelectedInteractor = dataInteractor;
m_ProcessingMode = CONNECTEDMOUSEACTION;
}
eventIsHandled = true;
break;
}
}
}
/* Notify InteractionEventObserver */
const std::vector<us::ServiceReference<InteractionEventObserver> > listEventObserver =
m_EventObserverTracker->GetServiceReferences();
for (std::vector<us::ServiceReference<InteractionEventObserver> >::const_iterator it = listEventObserver.cbegin();
it != listEventObserver.cend(); ++it)
{
InteractionEventObserver* interactionEventObserver = m_EventObserverTracker->GetService(*it);
if (interactionEventObserver != NULL)
{
if (interactionEventObserver->IsEnabled())
{
interactionEventObserver->Notify(event, eventIsHandled);
}
}
}
// Process event queue
if (!m_QueuedEvents.empty())
{
InteractionEvent::Pointer e = m_QueuedEvents.front();
m_QueuedEvents.pop_front();
ProcessEvent(e);
}
return eventIsHandled;
}
/*
* Checks if DataNodes associated with DataInteractors point back to them.
* If not remove the DataInteractors. (This can happen when s.o. tries to set DataNodes to multiple DataInteractors)
*/
void mitk::Dispatcher::RemoveOrphanedInteractors()
{
for (ListInteractorType::iterator it = m_Interactors.begin(); it != m_Interactors.end();)
{
DataNode::Pointer dn = (*it)->GetDataNode();
if (dn.IsNull())
{
it = m_Interactors.erase(it);
}
else
{
DataInteractor::Pointer interactor = dn->GetDataInteractor();
if (interactor != it->GetPointer())
{
it = m_Interactors.erase(it);
}
else
{
++it;
}
}
}
}
void mitk::Dispatcher::QueueEvent(InteractionEvent* event)
{
m_QueuedEvents.push_back(event);
}
void mitk::Dispatcher::SetEventProcessingMode(DataInteractor::Pointer dataInteractor)
{
m_ProcessingMode = dataInteractor->GetMode();
if (dataInteractor->GetMode() != REGULAR)
{
m_SelectedInteractor = dataInteractor;
}
}
bool mitk::Dispatcher::HandleInternalEvent(InternalEvent* internalEvent)
{
if (internalEvent->GetSignalName() == DataInteractor::IntDeactivateMe &&
internalEvent->GetTargetInteractor() != NULL)
{
internalEvent->GetTargetInteractor()->GetDataNode()->SetDataInteractor(NULL);
internalEvent->GetTargetInteractor()->SetDataNode(NULL);
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
return true;
}
return false;
}
<commit_msg>Dispatcher will also remove all DataInteractor with no valid DataNode<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 "mitkDispatcher.h"
#include "mitkInteractionEvent.h"
#include "mitkInternalEvent.h"
// MicroServices
#include "usGetModuleContext.h"
#include "mitkInteractionEventObserver.h"
mitk::Dispatcher::Dispatcher( const std::string& rendererName )
: m_ProcessingMode(REGULAR)
{
// LDAP filter string to find all listeners specific for the renderer
// corresponding to this dispatcher
std::string specificRenderer = "(rendererName=" + rendererName +")";
// LDAP filter string to find all listeners that are not specific
// to any renderer
std::string anyRenderer = "(!(rendererName=*))";
// LDAP filter string to find only instances of InteractionEventObserver
std::string classInteractionEventObserver = "(" + us::ServiceConstants::OBJECTCLASS() + "=" + us_service_interface_iid<InteractionEventObserver>() + ")";
// Configure the LDAP filter to find all instances of InteractionEventObserver
// that are specific to this dispatcher or unspecific to any dispatchers (real global listener)
us::LDAPFilter filter( "(&(|"+ specificRenderer + anyRenderer + ")"+classInteractionEventObserver+")" );
// Give the filter to the ObserverTracker
m_EventObserverTracker = new us::ServiceTracker<InteractionEventObserver>(us::GetModuleContext(), filter);
m_EventObserverTracker->Open();
}
void mitk::Dispatcher::AddDataInteractor(const DataNode* dataNode)
{
RemoveDataInteractor(dataNode);
RemoveOrphanedInteractors();
DataInteractor::Pointer dataInteractor = dataNode->GetDataInteractor();
if (dataInteractor.IsNotNull())
{
m_Interactors.push_back(dataInteractor);
}
}
/*
* Note: One DataInteractor can only have one DataNode and vice versa,
* BUT the m_Interactors list may contain another DataInteractor that is still connected to this DataNode,
* in this case we have to remove >1 DataInteractor. (Some special case of switching DataNodes between DataInteractors and registering a
* DataNode to a DataStorage after assigning it to an DataInteractor)
*/
void mitk::Dispatcher::RemoveDataInteractor(const DataNode* dataNode)
{
for (ListInteractorType::iterator it = m_Interactors.begin(); it != m_Interactors.end();)
{
if ((*it)->GetDataNode() == dataNode)
{
it = m_Interactors.erase(it);
}
else if ((*it)->GetDataNode() == nullptr)
{
it = m_Interactors.erase(it);
}
else
{
++it;
}
}
}
size_t mitk::Dispatcher::GetNumberOfInteractors()
{
return m_Interactors.size();
}
mitk::Dispatcher::~Dispatcher()
{
m_EventObserverTracker->Close();
delete m_EventObserverTracker;
m_Interactors.clear();
}
bool mitk::Dispatcher::ProcessEvent(InteractionEvent* event)
{
InteractionEvent::Pointer p = event;
bool eventIsHandled = false;
/* Filter out and handle Internal Events separately */
InternalEvent* internalEvent = dynamic_cast<InternalEvent*>(event);
if (internalEvent != NULL)
{
eventIsHandled = HandleInternalEvent(internalEvent);
// InternalEvents that are handled are not sent to the listeners
if (eventIsHandled)
{
return true;
}
}
switch (m_ProcessingMode)
{
case CONNECTEDMOUSEACTION:
// finished connected mouse action
if (std::strcmp(p->GetNameOfClass(), "MouseReleaseEvent") == 0)
{
m_ProcessingMode = REGULAR;
eventIsHandled = m_SelectedInteractor->HandleEvent(event, m_SelectedInteractor->GetDataNode());
// delete reference to interactor as soon as connected action is finished
m_SelectedInteractor = NULL;
}
// give event to selected interactor
if (eventIsHandled == false && m_SelectedInteractor.IsNotNull())
{
eventIsHandled = m_SelectedInteractor->HandleEvent(event, m_SelectedInteractor->GetDataNode());
}
break;
case GRABINPUT:
eventIsHandled = m_SelectedInteractor->HandleEvent(event, m_SelectedInteractor->GetDataNode());
SetEventProcessingMode(m_SelectedInteractor);
break;
case PREFERINPUT:
if (m_SelectedInteractor->HandleEvent(event, m_SelectedInteractor->GetDataNode()) == true)
{
SetEventProcessingMode(m_SelectedInteractor);
eventIsHandled = true;
}
break;
case REGULAR:
break;
}
// Standard behavior. Is executed in STANDARD mode and PREFERINPUT mode, if preferred interactor rejects event.
if (m_ProcessingMode == REGULAR || (m_ProcessingMode == PREFERINPUT && eventIsHandled == false))
{
if (std::strcmp(p->GetNameOfClass(), "MousePressEvent") == 0)
event->GetSender()->GetRenderingManager()->SetRenderWindowFocus(event->GetSender()->GetRenderWindow());
m_Interactors.sort(cmp()); // sorts interactors by layer (descending);
// copy the list to prevent iterator invalidation as executing actions
// in HandleEvent() can cause the m_Interactors list to be updated
const std::list<DataInteractor::Pointer> tmpInteractorList( m_Interactors );
std::list<DataInteractor::Pointer>::const_iterator it;
for ( it=tmpInteractorList.cbegin(); it!=tmpInteractorList.cend(); ++it )
{
DataInteractor::Pointer dataInteractor = *it;
if ( (*it)->HandleEvent(event, dataInteractor->GetDataNode()) )
{ // if an event is handled several properties are checked, in order to determine the processing mode of the dispatcher
SetEventProcessingMode(dataInteractor);
if (std::strcmp(p->GetNameOfClass(), "MousePressEvent") == 0 && m_ProcessingMode == REGULAR)
{
m_SelectedInteractor = dataInteractor;
m_ProcessingMode = CONNECTEDMOUSEACTION;
}
eventIsHandled = true;
break;
}
}
}
/* Notify InteractionEventObserver */
const std::vector<us::ServiceReference<InteractionEventObserver> > listEventObserver =
m_EventObserverTracker->GetServiceReferences();
for (std::vector<us::ServiceReference<InteractionEventObserver> >::const_iterator it = listEventObserver.cbegin();
it != listEventObserver.cend(); ++it)
{
InteractionEventObserver* interactionEventObserver = m_EventObserverTracker->GetService(*it);
if (interactionEventObserver != NULL)
{
if (interactionEventObserver->IsEnabled())
{
interactionEventObserver->Notify(event, eventIsHandled);
}
}
}
// Process event queue
if (!m_QueuedEvents.empty())
{
InteractionEvent::Pointer e = m_QueuedEvents.front();
m_QueuedEvents.pop_front();
ProcessEvent(e);
}
return eventIsHandled;
}
/*
* Checks if DataNodes associated with DataInteractors point back to them.
* If not remove the DataInteractors. (This can happen when s.o. tries to set DataNodes to multiple DataInteractors)
*/
void mitk::Dispatcher::RemoveOrphanedInteractors()
{
for (ListInteractorType::iterator it = m_Interactors.begin(); it != m_Interactors.end();)
{
DataNode::Pointer dn = (*it)->GetDataNode();
if (dn.IsNull())
{
it = m_Interactors.erase(it);
}
else
{
DataInteractor::Pointer interactor = dn->GetDataInteractor();
if (interactor != it->GetPointer())
{
it = m_Interactors.erase(it);
}
else
{
++it;
}
}
}
}
void mitk::Dispatcher::QueueEvent(InteractionEvent* event)
{
m_QueuedEvents.push_back(event);
}
void mitk::Dispatcher::SetEventProcessingMode(DataInteractor::Pointer dataInteractor)
{
m_ProcessingMode = dataInteractor->GetMode();
if (dataInteractor->GetMode() != REGULAR)
{
m_SelectedInteractor = dataInteractor;
}
}
bool mitk::Dispatcher::HandleInternalEvent(InternalEvent* internalEvent)
{
if (internalEvent->GetSignalName() == DataInteractor::IntDeactivateMe &&
internalEvent->GetTargetInteractor() != NULL)
{
internalEvent->GetTargetInteractor()->GetDataNode()->SetDataInteractor(NULL);
internalEvent->GetTargetInteractor()->SetDataNode(NULL);
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
return true;
}
return false;
}
<|endoftext|> |
<commit_before>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
//______________________________________________________________________________
// Analysis task for jT Analysis
// author: B.K Kim, D.J. Kim, T. Snellman
// ALICE Group University of Jyvaskyla
// Finland
// Fill the analysis containers for ESD or AOD
// Adapted for AliAnalysisTaskSE and AOD objects
//////////////////////////////////////////////////////////////////////////////
#include "AliAODEvent.h"
#include "AliInputEventHandler.h"
#include "AliAnalysisTaskSE.h"
#include "AliAODHandler.h"
#include "AliParticleContainer.h"
#include "AliMultSelection.h"
#include "AliAnalysisManager.h"
#include "AliJHistManager.h"
#include "AliLog.h"
#include "AliJMCTrack.h"
#include "AliJJetJtTask.h"
#include "AliJCard.h"
#include "AliJetContainer.h"
#include "AliJEfficiency.h"
//______________________________________________________________________________
AliJJetJtTask::AliJJetJtTask() :
AliAnalysisTaskSE("AliJJetJtTaskTask"),
fJetTask(NULL),
fMCJetTask(NULL),
fJetTaskName(""),
fMCJetTaskName(""),
fJJetJtAnalysis(0x0),
fOutput(NULL),
fCard(NULL),
fFirstEvent(kTRUE),
cBin(-1),
zBin(-1),
fDoMC(0),
fSide(0),
fDoLog(0),
NRandom(1),
moveJet(0),
fCentCut(100),
zVert(-999),
fAnaUtils(NULL),
fRunTable(NULL),
fJMCTracks(NULL),
fEventHist()
{
DefineOutput (1, TDirectory::Class());
}
//______________________________________________________________________________
AliJJetJtTask::AliJJetJtTask(const char *name, TString inputformat):
AliAnalysisTaskSE(name),
fJetTask(NULL),
fMCJetTask(NULL),
fJetTaskName(""),
fMCJetTaskName(""),
fJJetJtAnalysis(0x0),
fOutput(NULL),
fCard(NULL),
fFirstEvent(kTRUE),
cBin(-1),
zBin(-1),
fDoMC(0),
fSide(0),
fDoLog(0),
NRandom(1),
moveJet(0),
fCentCut(100),
zVert(-999),
fAnaUtils(NULL),
fRunTable(NULL),
fJMCTracks(NULL),
fEventHist()
{
// Constructor
AliInfo("---- AliJJetJtTask Constructor ----");
JUNUSED(inputformat);
DefineOutput (1, TDirectory::Class());
}
//____________________________________________________________________________
AliJJetJtTask::AliJJetJtTask(const AliJJetJtTask& ap) :
AliAnalysisTaskSE(ap.GetName()),
fJetTask(ap.fJetTask),
fJetTaskName(ap.fJetTaskName),
fMCJetTask(ap.fMCJetTask),
fMCJetTaskName(ap.fMCJetTaskName),
fJJetJtAnalysis( ap.fJJetJtAnalysis ),
fOutput( ap.fOutput ),
fCard(ap.fCard),
fFirstEvent(ap.fFirstEvent),
cBin(ap.cBin),
zBin(ap.zBin),
fSide(ap.fSide),
NRandom(ap.NRandom),
moveJet(ap.moveJet),
fCentCut(ap.fCentCut),
zVert(ap.zVert),
fJMCTracks(ap.fJMCTracks),
fAnaUtils(ap.fAnaUtils),
fRunTable(ap.fRunTable),
fEventHist(ap.fEventHist)
{
AliInfo("----DEBUG AliJJetJtTask COPY ----");
}
//_____________________________________________________________________________
AliJJetJtTask& AliJJetJtTask::operator = (const AliJJetJtTask& ap)
{
// assignment operator
AliInfo("----DEBUG AliJJetJtTask operator= ----");
this->~AliJJetJtTask();
new(this) AliJJetJtTask(ap);
return *this;
}
//______________________________________________________________________________
AliJJetJtTask::~AliJJetJtTask()
{
// destructor
delete fJJetJtAnalysis;
delete fAnaUtils;
}
//________________________________________________________________________
void AliJJetJtTask::UserCreateOutputObjects()
{
//=== create the jcorran outputs objects
if(fDebug > 1) printf("AliJJetJtTask::UserCreateOutPutData() \n");
fAnaUtils = new AliAnalysisUtils();
fAnaUtils->SetUseOutOfBunchPileUp(kTRUE);
//=== Get AnalysisManager
AliAnalysisManager *man = AliAnalysisManager::GetAnalysisManager();
//OpenFile(1);
//if(!man->GetOutputEventHandler()) {
// Fatal("UserCreateOutputObjects", "This task needs an AOD handler");
// return;
//}
OpenFile(1);
fOutput = gDirectory;//->mkdir("JDiHadronCorr");
fOutput->cd();
fJetTask = (AliJJetTask*)(man->GetTask( fJetTaskName));
fJJetJtAnalysis = new AliJJetJtAnalysis(fCard);
fJJetJtAnalysis->SetJetFinderName(fJetTask->GetJetFinderString());
fJJetJtAnalysis->SetNumberOfJetFinders(fJetTask->GetNumberOfJetCollections());
fJJetJtAnalysis->SetNrandom(NRandom);
fJJetJtAnalysis->SetMoveJet(moveJet);
fJJetJtAnalysis->SetMC(fDoMC);
if(fDoLog) fJJetJtAnalysis->SetLog(fDoLog);
fJJetJtAnalysis->SetLeadingJets(fLeadingJets);
fJJetJtAnalysis->SetSide(fSide);
fJJetJtAnalysis->SetnR(fJetTask->GetnR());
fJJetJtAnalysis->Setnkt(fJetTask->Getnkt());
fJJetJtAnalysis->UserCreateOutputObjects();
fCard->WriteCard(gDirectory);
fEventHist << TH1D("EventHist","event numbers",10,0,10) << "END";
PostData( 1, fOutput );
for( int ij=0;ij< fJetTask->GetNumberOfJetCollections();ij++ ){
fJJetJtAnalysis->AddJets( fJetTask->GetAliJJetList( ij ),fJetTask->GetTrackOrMCParticle(ij), fJetTask->GetConeSize(ij));
}
fJJetJtAnalysis->SetJTracks(fJetTask->GetJTracks());
if(fDoMC){
fJMCTracks = fJetTask->GetMCJTracks();
fJJetJtAnalysis->SetMCJTracks(fJetTask->GetMCJTracks());
}
fFirstEvent = kTRUE;
}
//______________________________________________________________________________
/// Primary loop
void AliJJetJtTask::UserExec(Option_t* /*option*/)
{
// Processing of one event
if( fJetTask->GetTaskEntry() != fEntry ) return;
fJJetJtAnalysis->ClearBeforeEvent();
// Called for each event
AliVEvent *event = InputEvent();
if(!event) return;
//---------------------------------------------------------------
// check if the event was triggered or not and vertex
AliAODEvent* aodEvent = dynamic_cast<AliAODEvent*>(event);
if(!aodEvent) return;
if( fFirstEvent ) {
fRunTable = & AliJRunTable::GetSpecialInstance();
fRunTable->SetRunNumber( aodEvent->GetRunNumber() );
fJJetJtAnalysis->GetAliJEfficiency()->SetRunNumber( aodEvent->GetRunNumber() );
fJJetJtAnalysis->GetAliJEfficiency()->Load();
fFirstEvent = kFALSE;
}
if(!IsGoodEvent( event )) return; // zBin is set there
// centrality
float fcent = -999;
if(fRunTable->IsHeavyIon() || fRunTable->IsPA()){
if(fDebug > 6) cout << fRunTable->GetPeriodName() << endl;
if(fRunTable->IsPA() && !(fRunTable->GetPeriodName().BeginsWith("LHC3"))){
sel = (AliMultSelection*) InputEvent() -> FindListObject("MultSelection");
if (sel) {
fcent = sel->GetMultiplicityPercentile("V0C");
}
else{
if(fDebug > 2) cout << "Sel not found" << endl;
}
}
AliCentrality *cent = event->GetCentrality();
if( ! cent ) return;
if(fRunTable->GetPeriodName().BeginsWith("LHC3")){
fcent = cent->GetCentralityPercentile("V0C");
}else{
fcent = cent->GetCentralityPercentile("V0M");
}
} else {
fcent = -1;
}
if(fcent > fCentCut){
if(fDebug > 2) cout << "Skip event, Centrality was " << fcent << " and cut is " << fCentCut << endl;
return;
}
cBin = fCard->GetBin(kCentrType, fcent);;
//if(cBin<0) return; //TODO CHECK
fJJetJtAnalysis->SetCentralityBin( cBin );
fJJetJtAnalysis->SetCentrality( fcent );
fJJetJtAnalysis->SetZVertexBin( zBin );
fJJetJtAnalysis->SetZVertex( zVert );
if(fDoMC){
AliMCParticleContainer * mcTracksCont = fJetTask->GetMCParticleContainer("mcparticles");
if(mcTracksCont){
TClonesArray * jets = new TClonesArray("AliJJet",1000); // just alias for AliJJet array
for(int itrack = 0; itrack<mcTracksCont->GetNParticles(); itrack++){
AliAODMCParticle *track = static_cast<AliAODMCParticle*>(mcTracksCont->GetParticle(itrack));
if(TMath::Abs(track->Eta()) > 1.0) continue;
if(track->Pt() > 5){
if(track->GetNDaughters() > 1){
/*cout << "Mother: " << endl;
cout << "Track " << itrack << " Px: " << track->Px() << " Py: " << track->Py() << " Pz: " << track->Pz() << " charge: " << track->Charge() << endl;
cout << "pT " << track->Pt() << " eta: " << track->Eta() << endl;
track->Print();
cout << "Daughters: " << endl;*/
AliJJet *jet = new AliJJet(track->Px(),track->Py(),track->Pz(), track->E(),track->GetLabel(),0,0);
FindDaughters(jet,track,mcTracksCont);
//cout << "Jet pT: " << jet->Pt() << " Eta: " << jet->Eta() << " Phi: " << jet->Phi() << " Constituents: " << jet->GetNConstituents() << endl;
}
// If .... new (jets[iJet]) AliJJet(jet->Px(),jet->Py(), jet->Pz(), jet->E(), jet->GetLabel(),0,0);
}
}
}
}
fJJetJtAnalysis->UserExec();
PostData(1, fOutput );
//PostData(1, fJJetJtAnalysis->GetHistogramsDirectory());
if(fDebug > 5) cout << "\t------- End UserExec "<<endl;
}
/// Obsolete?
/// Find daughters of given track
/// If daughters are primary tracks, add them as constituents to the original jet
/// If they are not primary then keep searching for daughters
/// \param jet Pointer to jet, i.e. the original track
/// \param track Find daughters of this track
/// \param mcTracksCont Monte carlo track container
///
void AliJJetJtTask::FindDaughters(AliJJet *jet, AliAODMCParticle *track, AliMCParticleContainer *mcTracksCont){
for(int id = track->GetFirstDaughter(); id <= track->GetLastDaughter() ; id++){
AliAODMCParticle *daughter = static_cast<AliAODMCParticle*>(mcTracksCont->GetParticle(id));
if(daughter->GetNDaughters() > 0){
FindDaughters(jet,daughter,mcTracksCont);
}
if(daughter->IsPrimary() && daughter->Charge() != 0){
/*cout << "Add constituent" << endl;
cout << "Track " << id << " Px: " << daughter->Px() << " Py: " << daughter->Py() << " Pz: " << daughter->Pz() << " charge: " << daughter->Charge() << endl;
cout << "pT " << daughter->Pt() << " eta: " << daughter->Eta() << endl;
daughter->Print();*/
AliJMCTrack * particle = (AliJMCTrack*)fJMCTracks->At(id);
//cout << "Add Constituent: " << id << " pT: " << particle->Pt() << " Eta: " << particle->Eta() << " Phi: " << particle->Phi() << endl;
//jet->AddConstituent(&fJetTask->GetMCJTracks()[id]);
jet->AddConstituent(particle);
}
}
}
//______________________________________________________________________________
/// Function to initialize the parameters
void AliJJetJtTask::Init()
{
// Intialisation of parameters
AliInfo("Doing initialization") ;
//fJJetJtAnalysis->Init();
}
void AliJJetJtTask::FinishTaskOutput(){
//TFile::Open("a.root","recreate");
OpenFile(1);
fJJetJtAnalysis->WriteHistograms();
}
//________________________________________________________________________
bool AliJJetJtTask::IsGoodEvent(AliVEvent *event) {
if(fRunTable->IsPP() && fAnaUtils->IsPileUpEvent(event)) {
return kFALSE;
} else {
Bool_t triggeredEventMB = kFALSE; //init
fEventHist->Fill( 0 );
Bool_t triggerkMB = ((AliInputEventHandler*)(AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler()))->IsEventSelected() & ( AliVEvent::kMB );
// Make sure if V0OR or whayt
if( triggerkMB ){
triggeredEventMB = kTRUE; //event triggered as minimum bias
fEventHist->Fill( 1 );
}
//--------------------------------------------------------------
// check reconstructed vertex
int ncontributors = 0;
Bool_t goodRecVertex = kFALSE;
const AliVVertex *vtx = event->GetPrimaryVertex();
if(vtx){
ncontributors = vtx->GetNContributors();
if(ncontributors > 0){
zVert = vtx->GetZ();
//cout<<zVert<<endl;
fEventHist->Fill( 2 );
if(fCard->VertInZRange(zVert)) {
goodRecVertex = kTRUE;
fEventHist->Fill( 3 );
zBin = fCard->GetBin(kZVertType, zVert);
}
}
}
return goodRecVertex;
}
//---------------------------------
}
//______________________________________________________________________________
void AliJJetJtTask::Terminate(Option_t *)
{
//fJJetJtAnalysis->WriteHistograms();
}
<commit_msg>Fix bug from commit 9344cda<commit_after>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
//______________________________________________________________________________
// Analysis task for jT Analysis
// author: B.K Kim, D.J. Kim, T. Snellman
// ALICE Group University of Jyvaskyla
// Finland
// Fill the analysis containers for ESD or AOD
// Adapted for AliAnalysisTaskSE and AOD objects
//////////////////////////////////////////////////////////////////////////////
#include "AliAODEvent.h"
#include "AliInputEventHandler.h"
#include "AliAnalysisTaskSE.h"
#include "AliAODHandler.h"
#include "AliParticleContainer.h"
#include "AliMultSelection.h"
#include "AliAnalysisManager.h"
#include "AliJHistManager.h"
#include "AliLog.h"
#include "AliJMCTrack.h"
#include "AliJJetJtTask.h"
#include "AliJCard.h"
#include "AliJetContainer.h"
#include "AliJEfficiency.h"
//______________________________________________________________________________
AliJJetJtTask::AliJJetJtTask() :
AliAnalysisTaskSE("AliJJetJtTaskTask"),
fJetTask(NULL),
fMCJetTask(NULL),
fJetTaskName(""),
fMCJetTaskName(""),
fJJetJtAnalysis(0x0),
fOutput(NULL),
fCard(NULL),
fFirstEvent(kTRUE),
cBin(-1),
zBin(-1),
fDoMC(0),
fSide(0),
fDoLog(0),
NRandom(1),
moveJet(0),
fCentCut(100),
zVert(-999),
fAnaUtils(NULL),
fRunTable(NULL),
fJMCTracks(NULL),
fEventHist()
{
DefineOutput (1, TDirectory::Class());
}
//______________________________________________________________________________
AliJJetJtTask::AliJJetJtTask(const char *name, TString inputformat):
AliAnalysisTaskSE(name),
fJetTask(NULL),
fMCJetTask(NULL),
fJetTaskName(""),
fMCJetTaskName(""),
fJJetJtAnalysis(0x0),
fOutput(NULL),
fCard(NULL),
fFirstEvent(kTRUE),
cBin(-1),
zBin(-1),
fDoMC(0),
fSide(0),
fDoLog(0),
NRandom(1),
moveJet(0),
fCentCut(100),
zVert(-999),
fAnaUtils(NULL),
fRunTable(NULL),
fJMCTracks(NULL),
fEventHist()
{
// Constructor
AliInfo("---- AliJJetJtTask Constructor ----");
JUNUSED(inputformat);
DefineOutput (1, TDirectory::Class());
}
//____________________________________________________________________________
AliJJetJtTask::AliJJetJtTask(const AliJJetJtTask& ap) :
AliAnalysisTaskSE(ap.GetName()),
fJetTask(ap.fJetTask),
fJetTaskName(ap.fJetTaskName),
fMCJetTask(ap.fMCJetTask),
fMCJetTaskName(ap.fMCJetTaskName),
fJJetJtAnalysis( ap.fJJetJtAnalysis ),
fOutput( ap.fOutput ),
fCard(ap.fCard),
fFirstEvent(ap.fFirstEvent),
cBin(ap.cBin),
zBin(ap.zBin),
fSide(ap.fSide),
NRandom(ap.NRandom),
moveJet(ap.moveJet),
fCentCut(ap.fCentCut),
zVert(ap.zVert),
fJMCTracks(ap.fJMCTracks),
fAnaUtils(ap.fAnaUtils),
fRunTable(ap.fRunTable),
fEventHist(ap.fEventHist)
{
AliInfo("----DEBUG AliJJetJtTask COPY ----");
}
//_____________________________________________________________________________
AliJJetJtTask& AliJJetJtTask::operator = (const AliJJetJtTask& ap)
{
// assignment operator
AliInfo("----DEBUG AliJJetJtTask operator= ----");
this->~AliJJetJtTask();
new(this) AliJJetJtTask(ap);
return *this;
}
//______________________________________________________________________________
AliJJetJtTask::~AliJJetJtTask()
{
// destructor
delete fJJetJtAnalysis;
delete fAnaUtils;
}
//________________________________________________________________________
void AliJJetJtTask::UserCreateOutputObjects()
{
//=== create the jcorran outputs objects
if(fDebug > 1) printf("AliJJetJtTask::UserCreateOutPutData() \n");
fAnaUtils = new AliAnalysisUtils();
fAnaUtils->SetUseOutOfBunchPileUp(kTRUE);
//=== Get AnalysisManager
AliAnalysisManager *man = AliAnalysisManager::GetAnalysisManager();
//OpenFile(1);
//if(!man->GetOutputEventHandler()) {
// Fatal("UserCreateOutputObjects", "This task needs an AOD handler");
// return;
//}
OpenFile(1);
fOutput = gDirectory;//->mkdir("JDiHadronCorr");
fOutput->cd();
fJetTask = (AliJJetTask*)(man->GetTask( fJetTaskName));
fJJetJtAnalysis = new AliJJetJtAnalysis(fCard);
fJJetJtAnalysis->SetJetFinderName(fJetTask->GetJetFinderString());
fJJetJtAnalysis->SetNumberOfJetFinders(fJetTask->GetNumberOfJetCollections());
fJJetJtAnalysis->SetNrandom(NRandom);
fJJetJtAnalysis->SetMoveJet(moveJet);
fJJetJtAnalysis->SetMC(fDoMC);
if(fDoLog) fJJetJtAnalysis->SetLog(fDoLog);
fJJetJtAnalysis->SetLeadingJets(fLeadingJets);
fJJetJtAnalysis->SetSide(fSide);
fJJetJtAnalysis->SetnR(fJetTask->GetnR());
fJJetJtAnalysis->Setnkt(fJetTask->Getnkt());
fJJetJtAnalysis->UserCreateOutputObjects();
fCard->WriteCard(gDirectory);
fEventHist << TH1D("EventHist","event numbers",10,0,10) << "END";
PostData( 1, fOutput );
for( int ij=0;ij< fJetTask->GetNumberOfJetCollections();ij++ ){
fJJetJtAnalysis->AddJets( fJetTask->GetAliJJetList( ij ),fJetTask->GetTrackOrMCParticle(ij), fJetTask->GetConeSize(ij));
}
fJJetJtAnalysis->SetJTracks(fJetTask->GetJTracks());
if(fDoMC){
fJMCTracks = fJetTask->GetMCJTracks();
fJJetJtAnalysis->SetMCJTracks(fJetTask->GetMCJTracks());
}
fFirstEvent = kTRUE;
}
//______________________________________________________________________________
/// Primary loop
void AliJJetJtTask::UserExec(Option_t* /*option*/)
{
// Processing of one event
if( fJetTask->GetTaskEntry() != fEntry ) return;
fJJetJtAnalysis->ClearBeforeEvent();
// Called for each event
AliVEvent *event = InputEvent();
if(!event) return;
//---------------------------------------------------------------
// check if the event was triggered or not and vertex
AliAODEvent* aodEvent = dynamic_cast<AliAODEvent*>(event);
if(!aodEvent) return;
if( fFirstEvent ) {
fRunTable = & AliJRunTable::GetSpecialInstance();
fRunTable->SetRunNumber( aodEvent->GetRunNumber() );
fJJetJtAnalysis->GetAliJEfficiency()->SetRunNumber( aodEvent->GetRunNumber() );
fJJetJtAnalysis->GetAliJEfficiency()->Load();
fFirstEvent = kFALSE;
}
if(!IsGoodEvent( event )) return; // zBin is set there
// centrality
float fcent = -999;
if(fRunTable->IsHeavyIon() || fRunTable->IsPA()){
if(fDebug > 6) cout << fRunTable->GetPeriodName() << endl;
if(fRunTable->IsPA() && !(fRunTable->GetPeriodName().BeginsWith("LHC13"))){
sel = (AliMultSelection*) InputEvent() -> FindListObject("MultSelection");
if (sel) {
fcent = sel->GetMultiplicityPercentile("V0C");
}
else{
if(fDebug > 2) cout << "Sel not found" << endl;
}
}else{
AliCentrality *cent = event->GetCentrality();
if( ! cent ) return;
if(fRunTable->GetPeriodName().BeginsWith("LHC13")){
fcent = cent->GetCentralityPercentile("V0C");
}else{
fcent = cent->GetCentralityPercentile("V0M");
}
}
} else {
fcent = -1;
}
if(fcent > fCentCut){
if(fDebug > 2) cout << "Skip event, Centrality was " << fcent << " and cut is " << fCentCut << endl;
return;
}
cBin = fCard->GetBin(kCentrType, fcent);;
//if(cBin<0) return; //TODO CHECK
fJJetJtAnalysis->SetCentralityBin( cBin );
fJJetJtAnalysis->SetCentrality( fcent );
fJJetJtAnalysis->SetZVertexBin( zBin );
fJJetJtAnalysis->SetZVertex( zVert );
if(fDoMC){
AliMCParticleContainer * mcTracksCont = fJetTask->GetMCParticleContainer("mcparticles");
if(mcTracksCont){
TClonesArray * jets = new TClonesArray("AliJJet",1000); // just alias for AliJJet array
for(int itrack = 0; itrack<mcTracksCont->GetNParticles(); itrack++){
AliAODMCParticle *track = static_cast<AliAODMCParticle*>(mcTracksCont->GetParticle(itrack));
if(TMath::Abs(track->Eta()) > 1.0) continue;
if(track->Pt() > 5){
if(track->GetNDaughters() > 1){
/*cout << "Mother: " << endl;
cout << "Track " << itrack << " Px: " << track->Px() << " Py: " << track->Py() << " Pz: " << track->Pz() << " charge: " << track->Charge() << endl;
cout << "pT " << track->Pt() << " eta: " << track->Eta() << endl;
track->Print();
cout << "Daughters: " << endl;*/
AliJJet *jet = new AliJJet(track->Px(),track->Py(),track->Pz(), track->E(),track->GetLabel(),0,0);
FindDaughters(jet,track,mcTracksCont);
//cout << "Jet pT: " << jet->Pt() << " Eta: " << jet->Eta() << " Phi: " << jet->Phi() << " Constituents: " << jet->GetNConstituents() << endl;
}
// If .... new (jets[iJet]) AliJJet(jet->Px(),jet->Py(), jet->Pz(), jet->E(), jet->GetLabel(),0,0);
}
}
}
}
fJJetJtAnalysis->UserExec();
PostData(1, fOutput );
//PostData(1, fJJetJtAnalysis->GetHistogramsDirectory());
if(fDebug > 5) cout << "\t------- End UserExec "<<endl;
}
/// Obsolete?
/// Find daughters of given track
/// If daughters are primary tracks, add them as constituents to the original jet
/// If they are not primary then keep searching for daughters
/// \param jet Pointer to jet, i.e. the original track
/// \param track Find daughters of this track
/// \param mcTracksCont Monte carlo track container
///
void AliJJetJtTask::FindDaughters(AliJJet *jet, AliAODMCParticle *track, AliMCParticleContainer *mcTracksCont){
for(int id = track->GetFirstDaughter(); id <= track->GetLastDaughter() ; id++){
AliAODMCParticle *daughter = static_cast<AliAODMCParticle*>(mcTracksCont->GetParticle(id));
if(daughter->GetNDaughters() > 0){
FindDaughters(jet,daughter,mcTracksCont);
}
if(daughter->IsPrimary() && daughter->Charge() != 0){
/*cout << "Add constituent" << endl;
cout << "Track " << id << " Px: " << daughter->Px() << " Py: " << daughter->Py() << " Pz: " << daughter->Pz() << " charge: " << daughter->Charge() << endl;
cout << "pT " << daughter->Pt() << " eta: " << daughter->Eta() << endl;
daughter->Print();*/
AliJMCTrack * particle = (AliJMCTrack*)fJMCTracks->At(id);
//cout << "Add Constituent: " << id << " pT: " << particle->Pt() << " Eta: " << particle->Eta() << " Phi: " << particle->Phi() << endl;
//jet->AddConstituent(&fJetTask->GetMCJTracks()[id]);
jet->AddConstituent(particle);
}
}
}
//______________________________________________________________________________
/// Function to initialize the parameters
void AliJJetJtTask::Init()
{
// Intialisation of parameters
AliInfo("Doing initialization") ;
//fJJetJtAnalysis->Init();
}
void AliJJetJtTask::FinishTaskOutput(){
//TFile::Open("a.root","recreate");
OpenFile(1);
fJJetJtAnalysis->WriteHistograms();
}
//________________________________________________________________________
bool AliJJetJtTask::IsGoodEvent(AliVEvent *event) {
if(fRunTable->IsPP() && fAnaUtils->IsPileUpEvent(event)) {
return kFALSE;
} else {
Bool_t triggeredEventMB = kFALSE; //init
fEventHist->Fill( 0 );
Bool_t triggerkMB = ((AliInputEventHandler*)(AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler()))->IsEventSelected() & ( AliVEvent::kMB );
// Make sure if V0OR or whayt
if( triggerkMB ){
triggeredEventMB = kTRUE; //event triggered as minimum bias
fEventHist->Fill( 1 );
}
//--------------------------------------------------------------
// check reconstructed vertex
int ncontributors = 0;
Bool_t goodRecVertex = kFALSE;
const AliVVertex *vtx = event->GetPrimaryVertex();
if(vtx){
ncontributors = vtx->GetNContributors();
if(ncontributors > 0){
zVert = vtx->GetZ();
//cout<<zVert<<endl;
fEventHist->Fill( 2 );
if(fCard->VertInZRange(zVert)) {
goodRecVertex = kTRUE;
fEventHist->Fill( 3 );
zBin = fCard->GetBin(kZVertType, zVert);
}
}
}
return goodRecVertex;
}
//---------------------------------
}
//______________________________________________________________________________
void AliJJetJtTask::Terminate(Option_t *)
{
//fJJetJtAnalysis->WriteHistograms();
}
<|endoftext|> |
<commit_before>// $Id$
//
// Calculation of rho from a collection of jets.
// If scale function is given the scaled rho will be exported
// with the name as "fOutRhoName".apppend("_Scaled").
//
// Authors: R.Reed, S.Aiola, M.Connors
#include "AliAnalysisTaskRhoSparse.h"
#include <TClonesArray.h>
#include <TMath.h>
#include "AliAnalysisManager.h"
#include <AliVEventHandler.h>
#include "AliEmcalJet.h"
#include "AliLog.h"
#include "AliRhoParameter.h"
#include "AliJetContainer.h"
ClassImp(AliAnalysisTaskRhoSparse)
//________________________________________________________________________
AliAnalysisTaskRhoSparse::AliAnalysisTaskRhoSparse() :
AliAnalysisTaskRhoBase("AliAnalysisTaskRhoSparse"),
fNExclLeadJets(0),
fExcludeOverlaps(0),
fRhoCMS(0),
fUseTPCArea(0),
fExcludeAreaExcludedJets(0),
fHistOccCorrvsCent(0)
{
// Constructor.
}
//________________________________________________________________________
AliAnalysisTaskRhoSparse::AliAnalysisTaskRhoSparse(const char *name, Bool_t histo) :
AliAnalysisTaskRhoBase(name, histo),
fNExclLeadJets(0),
fExcludeOverlaps(0),
fRhoCMS(0),
fUseTPCArea(0),
fExcludeAreaExcludedJets(0),
fHistOccCorrvsCent(0)
{
// Constructor.
}
//________________________________________________________________________
void AliAnalysisTaskRhoSparse::UserCreateOutputObjects()
{
if (!fCreateHisto) return;
AliAnalysisTaskRhoBase::UserCreateOutputObjects();
fHistOccCorrvsCent = new TH2F("OccCorrvsCent", "OccCorrvsCent", 101, -1, 100, 2000, 0 , 2);
fOutput->Add(fHistOccCorrvsCent);
}
//________________________________________________________________________
Bool_t AliAnalysisTaskRhoSparse::IsJetOverlapping(AliEmcalJet* jet1, AliEmcalJet* jet2)
{
for (Int_t i = 0; i < jet1->GetNumberOfTracks(); ++i)
{
Int_t jet1Track = jet1->TrackAt(i);
for (Int_t j = 0; j < jet2->GetNumberOfTracks(); ++j)
{
Int_t jet2Track = jet2->TrackAt(j);
if (jet1Track == jet2Track)
return kTRUE;
}
}
return kFALSE;
}
//________________________________________________________________________
Bool_t AliAnalysisTaskRhoSparse::IsJetSignal(AliEmcalJet* jet)
{
if(jet->Pt()>5){
return kTRUE;
}else{
return kFALSE;
}
}
//________________________________________________________________________
Bool_t AliAnalysisTaskRhoSparse::Run()
{
// Run the analysis.
fOutRho->SetVal(0);
if (fOutRhoScaled)
fOutRhoScaled->SetVal(0);
if (!fJets)
return kFALSE;
const Int_t Njets = fJets->GetEntries();
AliJetContainer *sigjets = static_cast<AliJetContainer*>(fJetCollArray.At(1));
Int_t NjetsSig = 0;
if (sigjets) NjetsSig = sigjets->GetNJets();
Int_t maxJetIds[] = {-1, -1};
Float_t maxJetPts[] = { 0, 0};
if (fNExclLeadJets > 0) {
for (Int_t ij = 0; ij < Njets; ++ij) {
AliEmcalJet *jet = static_cast<AliEmcalJet*>(fJets->At(ij));
if (!jet) {
AliError(Form("%s: Could not receive jet %d", GetName(), ij));
continue;
}
if (!AcceptJet(jet))
continue;
//Search the two leading KT jets
if (jet->Pt() > maxJetPts[0]) {
maxJetPts[1] = maxJetPts[0];
maxJetIds[1] = maxJetIds[0];
maxJetPts[0] = jet->Pt();
maxJetIds[0] = ij;
} else if (jet->Pt() > maxJetPts[1]) {
maxJetPts[1] = jet->Pt();
maxJetIds[1] = ij;
}
}
if (fNExclLeadJets < 2) {
maxJetIds[1] = -1;
maxJetPts[1] = 0;
}
}
static Double_t rhovec[999];
Int_t NjetAcc = 0;
Double_t TotaljetAreaPhys=0;
Double_t TotalAreaCovered=0;
Double_t TotalTPCArea=2*TMath::Pi()*0.9;
// push all jets within selected acceptance into stack
for (Int_t iJets = 0; iJets < Njets; ++iJets) {
AliEmcalJet *jet = static_cast<AliEmcalJet*>(fJets->At(iJets));
if (!jet) {
AliError(Form("%s: Could not receive jet %d", GetName(), iJets));
continue;
}
// Take into account the area of real jets (no pure ghost jets)
// and also the area of later excluded jets.
// Some of these jets do not contribute to the rho calculation
// but to the factor with which this rho is scaled down
if (fExcludeAreaExcludedJets==0 && jet->GetNumberOfTracks()>0)
{
TotaljetAreaPhys+=jet->Area();
// Total area of all found jets ghost+phyical jets. This is a proxy
// for the available detector area in which the rho could have been calculated
TotalAreaCovered+=jet->Area();
}
// Exclude leading background jets (could be signal)
if (iJets == maxJetIds[0] || iJets == maxJetIds[1])
continue;
// Exclude background jets that do not fullfill basic cuts defined in AliJetContainer
if (!AcceptJet(jet))
continue;
// Search for overlap with signal jets
Bool_t isOverlapping = kFALSE;
if (sigjets) {
for(Int_t j=0;j<NjetsSig;j++)
{
AliEmcalJet* signalJet = sigjets->GetAcceptJet(j);
if(!signalJet)
continue;
if(!IsJetSignal(signalJet))
continue;
if(IsJetOverlapping(signalJet, jet))
{
isOverlapping = kTRUE;
break;
}
}
}
// Exclude background jets that overlap with anti-kT signal jets
if(fExcludeOverlaps && isOverlapping)
continue;
// Take into account only real jets (no pure ghost jets) that also
// contribute to the rho calculation
if (fExcludeAreaExcludedJets==1 && jet->GetNumberOfTracks()>0)
{
TotaljetAreaPhys+=jet->Area();
// Total area of all found jets ghost+phyical jets. This is a proxy
// for the available detector area in which the rho could have been calculated
TotalAreaCovered+=jet->Area();
}
// Exclude pure ghost jets from the rho calculation.
// Use only jets that fulfill your background jet selection
// for the rho calculation.
// Eg. real signal jets should not bias the background rho
if(jet->GetNumberOfTracks()>0)
{
rhovec[NjetAcc] = jet->Pt() / jet->Area();
++NjetAcc;
}
}
Double_t OccCorr=1;
//Use the total TPC area in which rho is calculated as denominater
if(fUseTPCArea)
{
OccCorr = TotaljetAreaPhys/TotalTPCArea;
}
//Use the total area covered by all ghost+physical jets that pass the selection in the detector as denominator
else if (TotalAreaCovered>0)
{
OccCorr = TotaljetAreaPhys/TotalAreaCovered;
}
if (fCreateHisto)
fHistOccCorrvsCent->Fill(fCent, OccCorr);
if (NjetAcc > 0) {
//find median value
Double_t rho = TMath::Median(NjetAcc, rhovec);
if(fRhoCMS){
rho = rho * OccCorr;
}
fOutRho->SetVal(rho);
if (fOutRhoScaled) {
Double_t rhoScaled = rho * GetScaleFactor(fCent);
fOutRhoScaled->SetVal(rhoScaled);
}
}
return kTRUE;
}
/**
* Rho Sparse AddTask.
*/
AliAnalysisTaskRhoSparse* AliAnalysisTaskRhoSparse::AddTaskRhoSparse(
const char *nTracks,
const char *nClusters,
const char *nRho,
Double_t jetradius,
UInt_t acceptance,
AliJetContainer::EJetType_t jetType,
AliJetContainer::ERecoScheme_t rscheme,
const Bool_t histo,
const char *nJetsSig,
const char *cutType,
Double_t jetptcut,
Double_t jetareacut,
Double_t emcareacut,
const char *suffix
)
{
// Get the pointer to the existing analysis manager via the static access method.
//==============================================================================
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr)
{
::Error("AddTaskRhoSparse", "No analysis manager to connect to.");
return NULL;
}
// Check the analysis type using the event handlers connected to the analysis manager.
//==============================================================================
AliVEventHandler* handler = mgr->GetInputEventHandler();
if (!handler)
{
::Error("AddTaskEmcalJetPerformance", "This task requires an input event handler");
return 0;
}
enum EDataType_t {
kUnknown,
kESD,
kAOD
};
EDataType_t dataType = kUnknown;
if (handler->InheritsFrom("AliESDInputHandler")) {
dataType = kESD;
}
else if (handler->InheritsFrom("AliAODInputHandler")) {
dataType = kAOD;
}
//-------------------------------------------------------
// Init the task and do settings
//-------------------------------------------------------
TString trackName(nTracks);
TString clusName(nClusters);
if (trackName == "usedefault") {
if (dataType == kESD) {
trackName = "Tracks";
}
else if (dataType == kAOD) {
trackName = "tracks";
}
else {
trackName = "";
}
}
if (clusName == "usedefault") {
if (dataType == kESD) {
clusName = "CaloClusters";
}
else if (dataType == kAOD) {
clusName = "caloClusters";
}
else {
clusName = "";
}
}
TString name("AliAnalysisTaskRhoSparse");
if (strcmp(suffix,"") != 0) {
name += "_";
name += suffix;
}
AliAnalysisTaskRhoSparse* mgrTask = (AliAnalysisTaskRhoSparse*)(mgr->GetTask(name.Data()));
if (mgrTask) return mgrTask;
AliAnalysisTaskRhoSparse *rhotask = new AliAnalysisTaskRhoSparse(name, histo);
rhotask->SetHistoBins(1000,-0.1,9.9);
rhotask->SetRhoCMS(1);
rhotask->SetSmallSystem(1);
rhotask->SetOutRhoName(nRho);
AliTrackContainer* trackCont;
AliParticleContainer* partCont;
if (trackName == "mcparticles") {
AliMCParticleContainer* mcpartCont = rhotask->AddMCParticleContainer(trackName);
mcpartCont->SelectPhysicalPrimaries(kTRUE);
}
else if (trackName == "tracks" || trackName == "Tracks") {
trackCont = rhotask->AddTrackContainer(trackName);
}
else if (!trackName.IsNull()) {
rhotask->AddParticleContainer(trackName);
}
partCont = rhotask->GetParticleContainer(0);
AliClusterContainer *clusterCont = rhotask->AddClusterContainer(clusName);
if (clusterCont) {
clusterCont->SetClusECut(0.);
clusterCont->SetClusPtCut(0.);
clusterCont->SetClusHadCorrEnergyCut(0.3);
clusterCont->SetDefaultClusterEnergy(AliVCluster::kHadCorr);
}
//
AliJetContainer *bkgJetCont = rhotask->AddJetContainer(jetType, AliJetContainer::kt_algorithm, rscheme, jetradius, acceptance, partCont, clusterCont);
if (bkgJetCont) {
//why?? bkgJetCont->SetJetAreaCut(jetareacut);
//why?? bkgJetCont->SetAreaEmcCut(emcareacut);
bkgJetCont->SetJetPtCut(0.);
}
//This is only for excluding overlaps with signal jets in case signal jets are provided
AliJetContainer *sigJetCont;
if(nJetsSig!=0)
{
sigJetCont = rhotask->AddJetContainer(nJetsSig,cutType,jetradius);
if (sigJetCont)
{
sigJetCont->SetJetAreaCut(jetareacut);
sigJetCont->SetAreaEmcCut(emcareacut);
sigJetCont->SetJetPtCut(jetptcut);
sigJetCont->ConnectParticleContainer(trackCont);
sigJetCont->ConnectClusterContainer(clusterCont);
}
}
//-------------------------------------------------------
// Final settings, pass to manager and set the containers
//-------------------------------------------------------
mgr->AddTask(rhotask);
// Create containers for input/output
mgr->ConnectInput(rhotask, 0, mgr->GetCommonInputContainer());
if (histo) {
TString contname(name);
contname += "_histos";
AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(contname.Data(),
TList::Class(),AliAnalysisManager::kOutputContainer,
Form("%s", AliAnalysisManager::GetCommonFileName()));
mgr->ConnectOutput(rhotask, 1, coutput1);
}
return rhotask;
}
<commit_msg>Fix error in TotalAreaCovered calculation<commit_after>// $Id$
//
// Calculation of rho from a collection of jets.
// If scale function is given the scaled rho will be exported
// with the name as "fOutRhoName".apppend("_Scaled").
//
// Authors: R.Reed, S.Aiola, M.Connors
#include "AliAnalysisTaskRhoSparse.h"
#include <TClonesArray.h>
#include <TMath.h>
#include "AliAnalysisManager.h"
#include <AliVEventHandler.h>
#include "AliEmcalJet.h"
#include "AliLog.h"
#include "AliRhoParameter.h"
#include "AliJetContainer.h"
ClassImp(AliAnalysisTaskRhoSparse)
//________________________________________________________________________
AliAnalysisTaskRhoSparse::AliAnalysisTaskRhoSparse() :
AliAnalysisTaskRhoBase("AliAnalysisTaskRhoSparse"),
fNExclLeadJets(0),
fExcludeOverlaps(0),
fRhoCMS(0),
fUseTPCArea(0),
fExcludeAreaExcludedJets(0),
fHistOccCorrvsCent(0)
{
// Constructor.
}
//________________________________________________________________________
AliAnalysisTaskRhoSparse::AliAnalysisTaskRhoSparse(const char *name, Bool_t histo) :
AliAnalysisTaskRhoBase(name, histo),
fNExclLeadJets(0),
fExcludeOverlaps(0),
fRhoCMS(0),
fUseTPCArea(0),
fExcludeAreaExcludedJets(0),
fHistOccCorrvsCent(0)
{
// Constructor.
}
//________________________________________________________________________
void AliAnalysisTaskRhoSparse::UserCreateOutputObjects()
{
if (!fCreateHisto) return;
AliAnalysisTaskRhoBase::UserCreateOutputObjects();
fHistOccCorrvsCent = new TH2F("OccCorrvsCent", "OccCorrvsCent", 101, -1, 100, 2000, 0 , 2);
fOutput->Add(fHistOccCorrvsCent);
}
//________________________________________________________________________
Bool_t AliAnalysisTaskRhoSparse::IsJetOverlapping(AliEmcalJet* jet1, AliEmcalJet* jet2)
{
for (Int_t i = 0; i < jet1->GetNumberOfTracks(); ++i)
{
Int_t jet1Track = jet1->TrackAt(i);
for (Int_t j = 0; j < jet2->GetNumberOfTracks(); ++j)
{
Int_t jet2Track = jet2->TrackAt(j);
if (jet1Track == jet2Track)
return kTRUE;
}
}
return kFALSE;
}
//________________________________________________________________________
Bool_t AliAnalysisTaskRhoSparse::IsJetSignal(AliEmcalJet* jet)
{
if(jet->Pt()>5){
return kTRUE;
}else{
return kFALSE;
}
}
//________________________________________________________________________
Bool_t AliAnalysisTaskRhoSparse::Run()
{
// Run the analysis.
fOutRho->SetVal(0);
if (fOutRhoScaled)
fOutRhoScaled->SetVal(0);
if (!fJets)
return kFALSE;
const Int_t Njets = fJets->GetEntries();
AliJetContainer *sigjets = static_cast<AliJetContainer*>(fJetCollArray.At(1));
Int_t NjetsSig = 0;
if (sigjets) NjetsSig = sigjets->GetNJets();
Int_t maxJetIds[] = {-1, -1};
Float_t maxJetPts[] = { 0, 0};
if (fNExclLeadJets > 0) {
for (Int_t ij = 0; ij < Njets; ++ij) {
AliEmcalJet *jet = static_cast<AliEmcalJet*>(fJets->At(ij));
if (!jet) {
AliError(Form("%s: Could not receive jet %d", GetName(), ij));
continue;
}
if (!AcceptJet(jet))
continue;
//Search the two leading KT jets
if (jet->Pt() > maxJetPts[0]) {
maxJetPts[1] = maxJetPts[0];
maxJetIds[1] = maxJetIds[0];
maxJetPts[0] = jet->Pt();
maxJetIds[0] = ij;
} else if (jet->Pt() > maxJetPts[1]) {
maxJetPts[1] = jet->Pt();
maxJetIds[1] = ij;
}
}
if (fNExclLeadJets < 2) {
maxJetIds[1] = -1;
maxJetPts[1] = 0;
}
}
static Double_t rhovec[999];
Int_t NjetAcc = 0;
Double_t TotaljetAreaPhys=0;
Double_t TotalAreaCovered=0;
Double_t TotalTPCArea=2*TMath::Pi()*0.9;
// push all jets within selected acceptance into stack
for (Int_t iJets = 0; iJets < Njets; ++iJets) {
AliEmcalJet *jet = static_cast<AliEmcalJet*>(fJets->At(iJets));
if (!jet) {
AliError(Form("%s: Could not receive jet %d", GetName(), iJets));
continue;
}
// Take into account the area of real jets (no pure ghost jets)
// and also the area of later excluded jets.
// Some of these jets do not contribute to the rho calculation
// but to the factor with which this rho is scaled down
if (fExcludeAreaExcludedJets==0)
{
// Total area of physical jets that are used for the rho calculation
if(jet->GetNumberOfTracks()>0)
{
TotaljetAreaPhys+=jet->Area();
}
// Total area of all found jets ghost+phyical jets. This is a proxy
// for the available detector area in which the rho could have been calculated
TotalAreaCovered+=jet->Area();
}
// Exclude leading background jets (could be signal)
if (iJets == maxJetIds[0] || iJets == maxJetIds[1])
continue;
// Exclude background jets that do not fullfill basic cuts defined in AliJetContainer
if (!AcceptJet(jet))
continue;
// Search for overlap with signal jets
Bool_t isOverlapping = kFALSE;
if (sigjets) {
for(Int_t j=0;j<NjetsSig;j++)
{
AliEmcalJet* signalJet = sigjets->GetAcceptJet(j);
if(!signalJet)
continue;
if(!IsJetSignal(signalJet))
continue;
if(IsJetOverlapping(signalJet, jet))
{
isOverlapping = kTRUE;
break;
}
}
}
// Exclude background jets that overlap with anti-kT signal jets
if(fExcludeOverlaps && isOverlapping)
continue;
// Take into account only real jets (no pure ghost jets) that also
// contribute to the rho calculation
if (fExcludeAreaExcludedJets==1)
{
// Total area of physical jets that are used for the rho calculation
if(jet->GetNumberOfTracks()>0)
{
TotaljetAreaPhys+=jet->Area();
}
// Total area of all found jets ghost+phyical jets. This is a proxy
// for the available detector area in which the rho could have been calculated
TotalAreaCovered+=jet->Area();
}
// Exclude pure ghost jets from the rho calculation.
// Use only jets that fulfill your background jet selection
// for the rho calculation.
// Eg. real signal jets should not bias the background rho
if(jet->GetNumberOfTracks()>0)
{
rhovec[NjetAcc] = jet->Pt() / jet->Area();
++NjetAcc;
}
}
Double_t OccCorr=1;
//Use the total TPC area in which rho is calculated as denominater
if(fUseTPCArea)
{
OccCorr = TotaljetAreaPhys/TotalTPCArea;
}
//Use the total area covered by all ghost+physical jets that pass the selection in the detector as denominator
else if (TotalAreaCovered>0)
{
OccCorr = TotaljetAreaPhys/TotalAreaCovered;
}
if (fCreateHisto)
fHistOccCorrvsCent->Fill(fCent, OccCorr);
if (NjetAcc > 0) {
//find median value
Double_t rho = TMath::Median(NjetAcc, rhovec);
if(fRhoCMS){
rho = rho * OccCorr;
}
fOutRho->SetVal(rho);
if (fOutRhoScaled) {
Double_t rhoScaled = rho * GetScaleFactor(fCent);
fOutRhoScaled->SetVal(rhoScaled);
}
}
return kTRUE;
}
/**
* Rho Sparse AddTask.
*/
AliAnalysisTaskRhoSparse* AliAnalysisTaskRhoSparse::AddTaskRhoSparse(
const char *nTracks,
const char *nClusters,
const char *nRho,
Double_t jetradius,
UInt_t acceptance,
AliJetContainer::EJetType_t jetType,
AliJetContainer::ERecoScheme_t rscheme,
const Bool_t histo,
const char *nJetsSig,
const char *cutType,
Double_t jetptcut,
Double_t jetareacut,
Double_t emcareacut,
const char *suffix
)
{
// Get the pointer to the existing analysis manager via the static access method.
//==============================================================================
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr)
{
::Error("AddTaskRhoSparse", "No analysis manager to connect to.");
return NULL;
}
// Check the analysis type using the event handlers connected to the analysis manager.
//==============================================================================
AliVEventHandler* handler = mgr->GetInputEventHandler();
if (!handler)
{
::Error("AddTaskEmcalJetPerformance", "This task requires an input event handler");
return 0;
}
enum EDataType_t {
kUnknown,
kESD,
kAOD
};
EDataType_t dataType = kUnknown;
if (handler->InheritsFrom("AliESDInputHandler")) {
dataType = kESD;
}
else if (handler->InheritsFrom("AliAODInputHandler")) {
dataType = kAOD;
}
//-------------------------------------------------------
// Init the task and do settings
//-------------------------------------------------------
TString trackName(nTracks);
TString clusName(nClusters);
if (trackName == "usedefault") {
if (dataType == kESD) {
trackName = "Tracks";
}
else if (dataType == kAOD) {
trackName = "tracks";
}
else {
trackName = "";
}
}
if (clusName == "usedefault") {
if (dataType == kESD) {
clusName = "CaloClusters";
}
else if (dataType == kAOD) {
clusName = "caloClusters";
}
else {
clusName = "";
}
}
TString name("AliAnalysisTaskRhoSparse");
if (strcmp(suffix,"") != 0) {
name += "_";
name += suffix;
}
AliAnalysisTaskRhoSparse* mgrTask = (AliAnalysisTaskRhoSparse*)(mgr->GetTask(name.Data()));
if (mgrTask) return mgrTask;
AliAnalysisTaskRhoSparse *rhotask = new AliAnalysisTaskRhoSparse(name, histo);
rhotask->SetHistoBins(1000,-0.1,9.9);
rhotask->SetRhoCMS(1);
rhotask->SetSmallSystem(1);
rhotask->SetOutRhoName(nRho);
AliTrackContainer* trackCont;
AliParticleContainer* partCont;
if (trackName == "mcparticles") {
AliMCParticleContainer* mcpartCont = rhotask->AddMCParticleContainer(trackName);
mcpartCont->SelectPhysicalPrimaries(kTRUE);
}
else if (trackName == "tracks" || trackName == "Tracks") {
trackCont = rhotask->AddTrackContainer(trackName);
}
else if (!trackName.IsNull()) {
rhotask->AddParticleContainer(trackName);
}
partCont = rhotask->GetParticleContainer(0);
AliClusterContainer *clusterCont = rhotask->AddClusterContainer(clusName);
if (clusterCont) {
clusterCont->SetClusECut(0.);
clusterCont->SetClusPtCut(0.);
clusterCont->SetClusHadCorrEnergyCut(0.3);
clusterCont->SetDefaultClusterEnergy(AliVCluster::kHadCorr);
}
//
AliJetContainer *bkgJetCont = rhotask->AddJetContainer(jetType, AliJetContainer::kt_algorithm, rscheme, jetradius, acceptance, partCont, clusterCont);
if (bkgJetCont) {
//why?? bkgJetCont->SetJetAreaCut(jetareacut);
//why?? bkgJetCont->SetAreaEmcCut(emcareacut);
bkgJetCont->SetJetPtCut(0.);
}
//This is only for excluding overlaps with signal jets in case signal jets are provided
AliJetContainer *sigJetCont;
if(nJetsSig!=0)
{
sigJetCont = rhotask->AddJetContainer(nJetsSig,cutType,jetradius);
if (sigJetCont)
{
sigJetCont->SetJetAreaCut(jetareacut);
sigJetCont->SetAreaEmcCut(emcareacut);
sigJetCont->SetJetPtCut(jetptcut);
sigJetCont->ConnectParticleContainer(trackCont);
sigJetCont->ConnectClusterContainer(clusterCont);
}
}
//-------------------------------------------------------
// Final settings, pass to manager and set the containers
//-------------------------------------------------------
mgr->AddTask(rhotask);
// Create containers for input/output
mgr->ConnectInput(rhotask, 0, mgr->GetCommonInputContainer());
if (histo) {
TString contname(name);
contname += "_histos";
AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(contname.Data(),
TList::Class(),AliAnalysisManager::kOutputContainer,
Form("%s", AliAnalysisManager::GetCommonFileName()));
mgr->ConnectOutput(rhotask, 1, coutput1);
}
return rhotask;
}
<|endoftext|> |
<commit_before><commit_msg>process HelpId option entry<commit_after><|endoftext|> |
<commit_before>/*
* Copyright 2008-2013 NVIDIA Corporation
*
* 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 <thrust/detail/config.h>
#include <thrust/detail/allocator/allocator_traits.h>
#include <thrust/detail/type_traits/is_call_possible.h>
#include <thrust/detail/integer_traits.h>
#include <new>
namespace thrust
{
namespace detail
{
namespace allocator_traits_detail
{
__THRUST_DEFINE_IS_CALL_POSSIBLE(has_member_allocate_with_hint_impl, allocate)
template<typename Alloc>
class has_member_allocate_with_hint
{
typedef typename allocator_traits<Alloc>::pointer pointer;
typedef typename allocator_traits<Alloc>::size_type size_type;
typedef typename allocator_traits<Alloc>::const_void_pointer const_void_pointer;
public:
typedef typename has_member_allocate_with_hint_impl<Alloc, pointer(size_type,const_void_pointer)>::type type;
static const bool value = type::value;
};
template<typename Alloc>
__host__ __device__
typename enable_if<
has_member_allocate_with_hint<Alloc>::value,
typename allocator_traits<Alloc>::pointer
>::type
allocate(Alloc &a, typename allocator_traits<Alloc>::size_type n, typename allocator_traits<Alloc>::const_void_pointer hint)
{
return a.allocate(n,hint);
}
template<typename Alloc>
__host__ __device__
typename disable_if<
has_member_allocate_with_hint<Alloc>::value,
typename allocator_traits<Alloc>::pointer
>::type
allocate(Alloc &a, typename allocator_traits<Alloc>::size_type n, typename allocator_traits<Alloc>::const_void_pointer)
{
return a.allocate(n);
}
__THRUST_DEFINE_IS_CALL_POSSIBLE(has_member_construct1_impl, construct)
template<typename Alloc, typename T>
struct has_member_construct1
: has_member_construct1_impl<Alloc, void(T*)>
{};
__thrust_exec_check_disable__
template<typename Alloc, typename T>
inline __host__ __device__
typename enable_if<
has_member_construct1<Alloc,T>::value
>::type
construct(Alloc &a, T *p)
{
a.construct(p);
}
template<typename Alloc, typename T>
inline __host__ __device__
typename disable_if<
has_member_construct1<Alloc,T>::value
>::type
construct(Alloc &a, T *p)
{
::new(static_cast<void*>(p)) T();
}
__THRUST_DEFINE_IS_CALL_POSSIBLE(has_member_construct2_impl, construct)
template<typename Alloc, typename T, typename Arg1>
struct has_member_construct2
: has_member_construct2_impl<Alloc, void(T*,const Arg1 &)>
{};
template<typename Alloc, typename T, typename Arg1>
inline __host__ __device__
typename enable_if<
has_member_construct2<Alloc,T,Arg1>::value
>::type
construct(Alloc &a, T *p, const Arg1 &arg1)
{
a.construct(p,arg1);
}
template<typename Alloc, typename T, typename Arg1>
inline __host__ __device__
typename disable_if<
has_member_construct2<Alloc,T,Arg1>::value
>::type
construct(Alloc &, T *p, const Arg1 &arg1)
{
::new(static_cast<void*>(p)) T(arg1);
}
__THRUST_DEFINE_IS_CALL_POSSIBLE(has_member_destroy_impl, destroy)
template<typename Alloc, typename T>
struct has_member_destroy
: has_member_destroy_impl<Alloc, void(T*)>
{};
template<typename Alloc, typename T>
inline __host__ __device__
typename enable_if<
has_member_destroy<Alloc,T>::value
>::type
destroy(Alloc &a, T *p)
{
a.destroy(p);
}
template<typename Alloc, typename T>
inline __host__ __device__
typename disable_if<
has_member_destroy<Alloc,T>::value
>::type
destroy(Alloc &, T *p)
{
p->~T();
}
__THRUST_DEFINE_IS_CALL_POSSIBLE(has_member_max_size_impl, max_size)
template<typename Alloc>
class has_member_max_size
{
typedef typename allocator_traits<Alloc>::size_type size_type;
public:
typedef typename has_member_max_size_impl<Alloc, size_type(void)>::type type;
static const bool value = type::value;
};
template<typename Alloc>
__host__ __device__
typename enable_if<
has_member_max_size<Alloc>::value,
typename allocator_traits<Alloc>::size_type
>::type
max_size(const Alloc &a)
{
return a.max_size();
}
template<typename Alloc>
__host__ __device__
typename disable_if<
has_member_max_size<Alloc>::value,
typename allocator_traits<Alloc>::size_type
>::type
max_size(const Alloc &)
{
typedef typename allocator_traits<Alloc>::size_type size_type;
return thrust::detail::integer_traits<size_type>::const_max;
}
template<typename Alloc>
__host__ __device__
typename enable_if<
has_member_system<Alloc>::value,
typename allocator_system<Alloc>::type &
>::type
system(Alloc &a)
{
// return the allocator's system
return a.system();
}
template<typename Alloc>
__host__ __device__
typename disable_if<
has_member_system<Alloc>::value,
typename allocator_system<Alloc>::type
>::type
system(Alloc &)
{
// return a copy of a default-constructed system
typename allocator_system<Alloc>::type result;
return result;
}
} // end allocator_traits_detail
template<typename Alloc>
__host__ __device__
typename allocator_traits<Alloc>::pointer
allocator_traits<Alloc>
::allocate(Alloc &a, typename allocator_traits<Alloc>::size_type n)
{
struct workaround_warnings
{
__thrust_exec_check_disable__
static __host__ __device__
typename allocator_traits<Alloc>::pointer
allocate(Alloc &a, typename allocator_traits<Alloc>::size_type n)
{
return a.allocate(n);
}
};
return workaround_warnings::allocate(a, n);
}
template<typename Alloc>
__host__ __device__
typename allocator_traits<Alloc>::pointer
allocator_traits<Alloc>
::allocate(Alloc &a, typename allocator_traits<Alloc>::size_type n, typename allocator_traits<Alloc>::const_void_pointer hint)
{
return allocator_traits_detail::allocate(a, n, hint);
}
template<typename Alloc>
__host__ __device__
void allocator_traits<Alloc>
::deallocate(Alloc &a, typename allocator_traits<Alloc>::pointer p, typename allocator_traits<Alloc>::size_type n)
{
struct workaround_warnings
{
__thrust_exec_check_disable__
static __host__ __device__
void deallocate(Alloc &a, typename allocator_traits<Alloc>::pointer p, typename allocator_traits<Alloc>::size_type n)
{
return a.deallocate(p,n);
}
};
return workaround_warnings::deallocate(a,p,n);
}
template<typename Alloc>
template<typename T>
__host__ __device__
void allocator_traits<Alloc>
::construct(allocator_type &a, T *p)
{
return allocator_traits_detail::construct(a,p);
}
template<typename Alloc>
template<typename T, typename Arg1>
__host__ __device__
void allocator_traits<Alloc>
::construct(allocator_type &a, T *p, const Arg1 &arg1)
{
return allocator_traits_detail::construct(a,p,arg1);
}
template<typename Alloc>
template<typename T>
__host__ __device__
void allocator_traits<Alloc>
::destroy(allocator_type &a, T *p)
{
return allocator_traits_detail::destroy(a,p);
}
template<typename Alloc>
__host__ __device__
typename allocator_traits<Alloc>::size_type
allocator_traits<Alloc>
::max_size(const allocator_type &a)
{
return allocator_traits_detail::max_size(a);
}
template<typename Alloc>
__host__ __device__
typename allocator_system<Alloc>::get_result_type
allocator_system<Alloc>
::get(Alloc &a)
{
return allocator_traits_detail::system(a);
}
} // end detail
} // end thrust
<commit_msg>thrust_exec_check_disable<commit_after>/*
* Copyright 2008-2013 NVIDIA Corporation
*
* 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 <thrust/detail/config.h>
#include <thrust/detail/allocator/allocator_traits.h>
#include <thrust/detail/type_traits/is_call_possible.h>
#include <thrust/detail/integer_traits.h>
#include <new>
namespace thrust
{
namespace detail
{
namespace allocator_traits_detail
{
__THRUST_DEFINE_IS_CALL_POSSIBLE(has_member_allocate_with_hint_impl, allocate)
template<typename Alloc>
class has_member_allocate_with_hint
{
typedef typename allocator_traits<Alloc>::pointer pointer;
typedef typename allocator_traits<Alloc>::size_type size_type;
typedef typename allocator_traits<Alloc>::const_void_pointer const_void_pointer;
public:
typedef typename has_member_allocate_with_hint_impl<Alloc, pointer(size_type,const_void_pointer)>::type type;
static const bool value = type::value;
};
template<typename Alloc>
__host__ __device__
typename enable_if<
has_member_allocate_with_hint<Alloc>::value,
typename allocator_traits<Alloc>::pointer
>::type
allocate(Alloc &a, typename allocator_traits<Alloc>::size_type n, typename allocator_traits<Alloc>::const_void_pointer hint)
{
return a.allocate(n,hint);
}
template<typename Alloc>
__host__ __device__
typename disable_if<
has_member_allocate_with_hint<Alloc>::value,
typename allocator_traits<Alloc>::pointer
>::type
allocate(Alloc &a, typename allocator_traits<Alloc>::size_type n, typename allocator_traits<Alloc>::const_void_pointer)
{
return a.allocate(n);
}
__THRUST_DEFINE_IS_CALL_POSSIBLE(has_member_construct1_impl, construct)
template<typename Alloc, typename T>
struct has_member_construct1
: has_member_construct1_impl<Alloc, void(T*)>
{};
__thrust_exec_check_disable__
template<typename Alloc, typename T>
inline __host__ __device__
typename enable_if<
has_member_construct1<Alloc,T>::value
>::type
construct(Alloc &a, T *p)
{
a.construct(p);
}
template<typename Alloc, typename T>
inline __host__ __device__
typename disable_if<
has_member_construct1<Alloc,T>::value
>::type
construct(Alloc &a, T *p)
{
::new(static_cast<void*>(p)) T();
}
__THRUST_DEFINE_IS_CALL_POSSIBLE(has_member_construct2_impl, construct)
template<typename Alloc, typename T, typename Arg1>
struct has_member_construct2
: has_member_construct2_impl<Alloc, void(T*,const Arg1 &)>
{};
__thrust_exec_check_disable__
template<typename Alloc, typename T, typename Arg1>
inline __host__ __device__
typename enable_if<
has_member_construct2<Alloc,T,Arg1>::value
>::type
construct(Alloc &a, T *p, const Arg1 &arg1)
{
a.construct(p,arg1);
}
template<typename Alloc, typename T, typename Arg1>
inline __host__ __device__
typename disable_if<
has_member_construct2<Alloc,T,Arg1>::value
>::type
construct(Alloc &, T *p, const Arg1 &arg1)
{
::new(static_cast<void*>(p)) T(arg1);
}
__THRUST_DEFINE_IS_CALL_POSSIBLE(has_member_destroy_impl, destroy)
template<typename Alloc, typename T>
struct has_member_destroy
: has_member_destroy_impl<Alloc, void(T*)>
{};
template<typename Alloc, typename T>
inline __host__ __device__
typename enable_if<
has_member_destroy<Alloc,T>::value
>::type
destroy(Alloc &a, T *p)
{
a.destroy(p);
}
template<typename Alloc, typename T>
inline __host__ __device__
typename disable_if<
has_member_destroy<Alloc,T>::value
>::type
destroy(Alloc &, T *p)
{
p->~T();
}
__THRUST_DEFINE_IS_CALL_POSSIBLE(has_member_max_size_impl, max_size)
template<typename Alloc>
class has_member_max_size
{
typedef typename allocator_traits<Alloc>::size_type size_type;
public:
typedef typename has_member_max_size_impl<Alloc, size_type(void)>::type type;
static const bool value = type::value;
};
template<typename Alloc>
__host__ __device__
typename enable_if<
has_member_max_size<Alloc>::value,
typename allocator_traits<Alloc>::size_type
>::type
max_size(const Alloc &a)
{
return a.max_size();
}
template<typename Alloc>
__host__ __device__
typename disable_if<
has_member_max_size<Alloc>::value,
typename allocator_traits<Alloc>::size_type
>::type
max_size(const Alloc &)
{
typedef typename allocator_traits<Alloc>::size_type size_type;
return thrust::detail::integer_traits<size_type>::const_max;
}
template<typename Alloc>
__host__ __device__
typename enable_if<
has_member_system<Alloc>::value,
typename allocator_system<Alloc>::type &
>::type
system(Alloc &a)
{
// return the allocator's system
return a.system();
}
template<typename Alloc>
__host__ __device__
typename disable_if<
has_member_system<Alloc>::value,
typename allocator_system<Alloc>::type
>::type
system(Alloc &)
{
// return a copy of a default-constructed system
typename allocator_system<Alloc>::type result;
return result;
}
} // end allocator_traits_detail
template<typename Alloc>
__host__ __device__
typename allocator_traits<Alloc>::pointer
allocator_traits<Alloc>
::allocate(Alloc &a, typename allocator_traits<Alloc>::size_type n)
{
struct workaround_warnings
{
__thrust_exec_check_disable__
static __host__ __device__
typename allocator_traits<Alloc>::pointer
allocate(Alloc &a, typename allocator_traits<Alloc>::size_type n)
{
return a.allocate(n);
}
};
return workaround_warnings::allocate(a, n);
}
template<typename Alloc>
__host__ __device__
typename allocator_traits<Alloc>::pointer
allocator_traits<Alloc>
::allocate(Alloc &a, typename allocator_traits<Alloc>::size_type n, typename allocator_traits<Alloc>::const_void_pointer hint)
{
return allocator_traits_detail::allocate(a, n, hint);
}
template<typename Alloc>
__host__ __device__
void allocator_traits<Alloc>
::deallocate(Alloc &a, typename allocator_traits<Alloc>::pointer p, typename allocator_traits<Alloc>::size_type n)
{
struct workaround_warnings
{
__thrust_exec_check_disable__
static __host__ __device__
void deallocate(Alloc &a, typename allocator_traits<Alloc>::pointer p, typename allocator_traits<Alloc>::size_type n)
{
return a.deallocate(p,n);
}
};
return workaround_warnings::deallocate(a,p,n);
}
template<typename Alloc>
template<typename T>
__host__ __device__
void allocator_traits<Alloc>
::construct(allocator_type &a, T *p)
{
return allocator_traits_detail::construct(a,p);
}
template<typename Alloc>
template<typename T, typename Arg1>
__host__ __device__
void allocator_traits<Alloc>
::construct(allocator_type &a, T *p, const Arg1 &arg1)
{
return allocator_traits_detail::construct(a,p,arg1);
}
template<typename Alloc>
template<typename T>
__host__ __device__
void allocator_traits<Alloc>
::destroy(allocator_type &a, T *p)
{
return allocator_traits_detail::destroy(a,p);
}
template<typename Alloc>
__host__ __device__
typename allocator_traits<Alloc>::size_type
allocator_traits<Alloc>
::max_size(const allocator_type &a)
{
return allocator_traits_detail::max_size(a);
}
template<typename Alloc>
__host__ __device__
typename allocator_system<Alloc>::get_result_type
allocator_system<Alloc>
::get(Alloc &a)
{
return allocator_traits_detail::system(a);
}
} // end detail
} // end thrust
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: salinst.cxx,v $
*
* $Revision: 1.17 $
*
* last change: $Author: kz $ $Date: 2003-08-25 13:55:53 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#define _SV_SALINST_CXX
// -=-= #includes =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <salunx.h>
#ifndef _VOS_MUTEX_HXX
#include <vos/mutex.hxx>
#endif
#ifndef _SV_SALDATA_HXX
#include <saldata.hxx>
#endif
#ifndef _SV_SALDISP_HXX
#include <saldisp.hxx>
#endif
#ifndef _SV_SALINST_HXX
#include <salinst.hxx>
#endif
#ifndef _SV_SALFRAME_HXX
#include <salframe.hxx>
#endif
#ifndef _SV_SALWTYPE_HXX
#include <salwtype.hxx>
#endif
#ifndef _SV_SALATYPE_HXX
#include <salatype.hxx>
#endif
#ifndef _SV_DTINT_HXX
#include <dtint.hxx>
#endif
#if !defined(_USE_PRINT_EXTENSION_)
#ifndef _SV_SALPRN_H
#include <salprn.h>
#endif
#endif
#ifndef _VCL_SM_HXX
#include <sm.hxx>
#endif
// -=-= C++ globals =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
void SalAbort( const XubString& rErrorText )
{
if( !rErrorText.Len() )
fprintf( stderr, "Application Error" );
else
fprintf( stderr, ByteString( rErrorText, gsl_getSystemTextEncoding() ).GetBuffer() );
abort();
}
// -------------------------------------------------------------------------
//
// SalYieldMutex
//
// -------------------------------------------------------------------------
SalYieldMutex::SalYieldMutex()
{
mnCount = 0;
mnThreadId = 0;
}
void SalYieldMutex::acquire()
{
OMutex::acquire();
mnThreadId = NAMESPACE_VOS(OThread)::getCurrentIdentifier();
mnCount++;
}
void SalYieldMutex::release()
{
if ( mnThreadId == NAMESPACE_VOS(OThread)::getCurrentIdentifier() )
{
if ( mnCount == 1 )
mnThreadId = 0;
mnCount--;
}
OMutex::release();
}
sal_Bool SalYieldMutex::tryToAcquire()
{
if ( OMutex::tryToAcquire() )
{
mnThreadId = NAMESPACE_VOS(OThread)::getCurrentIdentifier();
mnCount++;
return True;
}
else
return False;
}
//----------------------------------------------------------------------------
void InitSalData()
{
SalData *pSalData = new SalData;
SetSalData( pSalData );
}
void DeInitSalData()
{
SalData *pSalData = GetSalData();
delete pSalData;
SetSalData( NULL );
}
void InitSalMain()
{
if (GetSalData())
{
int argc = 0;
GetSalData()->Init( &argc, 0 );
}
}
void DeInitSalMain()
{
}
void SetFilterCallback( void* pCallback, void* pInst )
{
SalData* pSalData = GetSalData();
pSalData->pFirstInstance_->maInstData.mpFilterCallback = pCallback;
pSalData->pFirstInstance_->maInstData.mpFilterInst = pInst;
}
SalInstance *CreateSalInstance()
{
SalData *pSalData = GetSalData();
SalInstance *pInst = new SalInstance;
// init instance (only one instance in this version !!!)
pSalData->pFirstInstance_ = pInst;
return pInst;
}
void DestroySalInstance( SalInstance *pInst )
{
SessionManagerClient::close();
SalData *pSalData = GetSalData();
// dispose SalDisplay list from SalData
// would be done in a static destructor else which is
// a little late
pSalData->DeleteDisplays();
// reset instance (only one instance in this version !!!)
if( pSalData->pFirstInstance_ == pInst )
pSalData->pFirstInstance_ = NULL;
delete pInst;
}
// -=-= SalInstance =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
SalInstance::SalInstance()
{
maInstData.mpFilterCallback = NULL;
maInstData.mpFilterInst = NULL;
maInstData.mpEventInst = NULL;
maInstData.mpEventCallback = NULL;
maInstData.mpErrorEventInst = NULL;
maInstData.mpErrorEventCallback = NULL;
maInstData.mpSalYieldMutex = new SalYieldMutex;
maInstData.mpSalYieldMutex->acquire();
maInstData.mbPrinterInit = false;
}
SalInstance::~SalInstance()
{
// #75711# - java is running
maInstData.mpSalYieldMutex->release();
delete maInstData.mpSalYieldMutex;
}
// --------------------------------------------------------
// AnyInput from sv/mow/source/app/svapp.cxx
struct PredicateReturn
{
USHORT nType;
BOOL bRet;
};
Bool ImplPredicateEvent( Display *, XEvent *pEvent, char *pData )
{
PredicateReturn *pPre = (PredicateReturn *)pData;
if ( pPre->bRet )
return False;
USHORT nType;
switch( pEvent->type )
{
case ButtonPress:
case ButtonRelease:
case MotionNotify:
case EnterNotify:
case LeaveNotify:
nType = INPUT_MOUSE;
break;
case XLIB_KeyPress:
//case KeyRelease:
nType = INPUT_KEYBOARD;
break;
case Expose:
case GraphicsExpose:
case NoExpose:
nType = INPUT_PAINT;
break;
default:
nType = 0;
}
if ( nType & pPre->nType || ( ! nType && pPre->nType & INPUT_OTHER ) )
pPre->bRet = TRUE;
return False;
}
BOOL SalInstance::AnyInput(USHORT nType)
{
SalData *pSalData = GetSalData();
Display *pDisplay = pSalData->GetDefDisp()->GetDisplay();
BOOL bRet = FALSE;
if( (nType & INPUT_TIMER) &&
pSalData->GetDefDisp()->GetXLib()->CheckTimeout( false ) )
{
bRet = TRUE;
}
else if (XPending(pDisplay) )
{
PredicateReturn aInput;
XEvent aEvent;
aInput.bRet = FALSE;
aInput.nType = nType;
XCheckIfEvent(pDisplay, &aEvent, ImplPredicateEvent,
(char *)&aInput );
bRet = aInput.bRet;
}
return bRet;
}
#ifdef _VOS_NO_NAMESPACE
IMutex* SalInstance::GetYieldMutex()
#else
vos::IMutex* SalInstance::GetYieldMutex()
#endif
{
return maInstData.mpSalYieldMutex;
}
// -----------------------------------------------------------------------
ULONG SalInstance::ReleaseYieldMutex()
{
SalYieldMutex* pYieldMutex = maInstData.mpSalYieldMutex;
if ( pYieldMutex->GetThreadId() ==
NAMESPACE_VOS(OThread)::getCurrentIdentifier() )
{
ULONG nCount = pYieldMutex->GetAcquireCount();
ULONG n = nCount;
while ( n )
{
pYieldMutex->release();
n--;
}
return nCount;
}
else
return 0;
}
// -----------------------------------------------------------------------
void SalInstance::AcquireYieldMutex( ULONG nCount )
{
SalYieldMutex* pYieldMutex = maInstData.mpSalYieldMutex;
while ( nCount )
{
pYieldMutex->acquire();
nCount--;
}
}
void SalInstance::Yield( BOOL bWait )
{ GetSalData()->GetLib()->Yield( bWait ); }
void SalInstance::SetEventCallback( void* pInstance, bool(*pCallback)(void*,void*,int) )
{
maInstData.mpEventInst = pInstance;
maInstData.mpEventCallback = pCallback;
}
void SalInstance::SetErrorEventCallback( void* pInstance, bool(*pCallback)(void*,void*,int) )
{
maInstData.mpErrorEventInst = pInstance;
maInstData.mpErrorEventCallback = pCallback;
}
void* SalInstance::GetConnectionIdentifier( ConnectionIdentifierType& rReturnedType, int& rReturnedBytes )
{
static const char* pDisplay = getenv( "DISPLAY" );
rReturnedType = AsciiCString;
rReturnedBytes = pDisplay ? strlen( pDisplay )+1 : 1;
return pDisplay ? (void*)pDisplay : (void*)"";
}
<commit_msg>INTEGRATION: CWS vclplug (1.17.38); FILE MERGED 2003/10/21 15:53:52 pl 1.17.38.1: #i21232# first round of virtualizing the Sal classes, Unix works, Windows to come<commit_after>/*************************************************************************
*
* $RCSfile: salinst.cxx,v $
*
* $Revision: 1.18 $
*
* last change: $Author: kz $ $Date: 2003-11-18 14:42:20 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#define _SV_SALINST_CXX
// -=-= #includes =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <salunx.h>
#ifndef _VOS_MUTEX_HXX
#include <vos/mutex.hxx>
#endif
#ifndef _SV_SALDATA_HXX
#include <saldata.hxx>
#endif
#ifndef _SV_SALDISP_HXX
#include <saldisp.hxx>
#endif
#ifndef _SV_SALINST_H
#include <salinst.h>
#endif
#ifndef _SV_SALFRAME_H
#include <salframe.h>
#endif
#ifndef _SV_SALWTYPE_HXX
#include <salwtype.hxx>
#endif
#ifndef _SV_SALATYPE_HXX
#include <salatype.hxx>
#endif
#ifndef _SV_DTINT_HXX
#include <dtint.hxx>
#endif
#ifndef _SV_SALPRN_H
#include <salprn.h>
#endif
#ifndef _VCL_SM_HXX
#include <sm.hxx>
#endif
#ifndef _SV_SALOGL_H
#include <salogl.h>
#endif
// -------------------------------------------------------------------------
//
// SalYieldMutex
//
// -------------------------------------------------------------------------
SalYieldMutex::SalYieldMutex()
{
mnCount = 0;
mnThreadId = 0;
}
void SalYieldMutex::acquire()
{
OMutex::acquire();
mnThreadId = NAMESPACE_VOS(OThread)::getCurrentIdentifier();
mnCount++;
}
void SalYieldMutex::release()
{
if ( mnThreadId == NAMESPACE_VOS(OThread)::getCurrentIdentifier() )
{
if ( mnCount == 1 )
mnThreadId = 0;
mnCount--;
}
OMutex::release();
}
sal_Bool SalYieldMutex::tryToAcquire()
{
if ( OMutex::tryToAcquire() )
{
mnThreadId = NAMESPACE_VOS(OThread)::getCurrentIdentifier();
mnCount++;
return True;
}
else
return False;
}
//----------------------------------------------------------------------------
// -=-= SalInstance =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// plugin factory function
extern "C"
{
SalInstance* create_SalInstance()
{
return new X11SalInstance();
}
}
X11SalInstance::X11SalInstance()
{
mpSalYieldMutex = new SalYieldMutex;
mpSalYieldMutex->acquire();
mbPrinterInit = false;
// initialize SalData
SalData *pSalData = new SalData;
SetSalData( pSalData );
pSalData->pInstance_ = this;
pSalData->Init();
}
X11SalInstance::~X11SalInstance()
{
// eventually free OpenGL lib
X11SalOpenGL::Release();
// close session management
SessionManagerClient::close();
// dispose SalDisplay list from SalData
// would be done in a static destructor else which is
// a little late
SalData *pSalData = GetSalData();
delete pSalData;
SetSalData( NULL );
mpSalYieldMutex->release();
delete mpSalYieldMutex;
}
// --------------------------------------------------------
// AnyInput from sv/mow/source/app/svapp.cxx
struct PredicateReturn
{
USHORT nType;
BOOL bRet;
};
Bool ImplPredicateEvent( Display *, XEvent *pEvent, char *pData )
{
PredicateReturn *pPre = (PredicateReturn *)pData;
if ( pPre->bRet )
return False;
USHORT nType;
switch( pEvent->type )
{
case ButtonPress:
case ButtonRelease:
case MotionNotify:
case EnterNotify:
case LeaveNotify:
nType = INPUT_MOUSE;
break;
case XLIB_KeyPress:
//case KeyRelease:
nType = INPUT_KEYBOARD;
break;
case Expose:
case GraphicsExpose:
case NoExpose:
nType = INPUT_PAINT;
break;
default:
nType = 0;
}
if ( nType & pPre->nType || ( ! nType && pPre->nType & INPUT_OTHER ) )
pPre->bRet = TRUE;
return False;
}
bool X11SalInstance::AnyInput(USHORT nType)
{
SalData *pSalData = GetSalData();
Display *pDisplay = pSalData->GetDefDisp()->GetDisplay();
BOOL bRet = FALSE;
if( (nType & INPUT_TIMER) &&
pSalData->GetDefDisp()->GetXLib()->CheckTimeout( false ) )
{
bRet = TRUE;
}
else if (XPending(pDisplay) )
{
PredicateReturn aInput;
XEvent aEvent;
aInput.bRet = FALSE;
aInput.nType = nType;
XCheckIfEvent(pDisplay, &aEvent, ImplPredicateEvent,
(char *)&aInput );
bRet = aInput.bRet;
}
return bRet;
}
vos::IMutex* X11SalInstance::GetYieldMutex()
{
return mpSalYieldMutex;
}
// -----------------------------------------------------------------------
ULONG X11SalInstance::ReleaseYieldMutex()
{
SalYieldMutex* pYieldMutex = mpSalYieldMutex;
if ( pYieldMutex->GetThreadId() ==
NAMESPACE_VOS(OThread)::getCurrentIdentifier() )
{
ULONG nCount = pYieldMutex->GetAcquireCount();
ULONG n = nCount;
while ( n )
{
pYieldMutex->release();
n--;
}
return nCount;
}
else
return 0;
}
// -----------------------------------------------------------------------
void X11SalInstance::AcquireYieldMutex( ULONG nCount )
{
SalYieldMutex* pYieldMutex = mpSalYieldMutex;
while ( nCount )
{
pYieldMutex->acquire();
nCount--;
}
}
void X11SalInstance::Yield( BOOL bWait )
{ GetSalData()->GetLib()->Yield( bWait ); }
void* X11SalInstance::GetConnectionIdentifier( ConnectionIdentifierType& rReturnedType, int& rReturnedBytes )
{
static const char* pDisplay = getenv( "DISPLAY" );
rReturnedType = AsciiCString;
rReturnedBytes = pDisplay ? strlen( pDisplay )+1 : 1;
return pDisplay ? (void*)pDisplay : (void*)"";
}
SalFrame *X11SalInstance::CreateFrame( SalFrame *pParent, ULONG nSalFrameStyle )
{
SalFrame *pFrame = new X11SalFrame( pParent, nSalFrameStyle );
return pFrame;
}
SalFrame* X11SalInstance::CreateChildFrame( SystemParentData* pParentData, ULONG nStyle )
{
SalFrame* pFrame = new X11SalFrame( NULL, nStyle, pParentData );
return pFrame;
}
void X11SalInstance::DestroyFrame( SalFrame* pFrame )
{
delete pFrame;
}
SalOpenGL* X11SalInstance::CreateSalOpenGL( SalGraphics* pGraphics )
{
return new X11SalOpenGL( pGraphics );
}
<|endoftext|> |
<commit_before>#include "USRFindingAction.h"
#include "gtest/gtest.h"
#include "clang/Tooling/Tooling.h"
#include <stdio.h>
#include <set>
#include <map>
#include <vector>
namespace clang {
namespace rename {
namespace test {
// Determines if the symbol group invariants hold. To recap, those invariants
// are:
// (1) All symbols in the same symbol group share the same USR.
// (2) Two symbols from two different groups do not share the same USR.
static void testOffsetGroups(const char *Code,
const std::vector<std::vector<unsigned>> Groups) {
std::set<std::string> AllUSRs, CurrUSR;
for (const auto &Group : Groups) {
// Groups the invariants do not hold then the value of USR is also invalid,
// but at that point the test has already failed and USR ceases to be
// useful.
std::string USR;
for (const auto &Offset : Group) {
USRFindingAction Action(Offset);
auto Factory = tooling::newFrontendActionFactory(&Action);
EXPECT_TRUE(tooling::runToolOnCode(Factory->create(), Code));
const auto &USRs = Action.getUSRs();
EXPECT_EQ(1u, USRs.size());
USR = USRs[0];
CurrUSR.insert(USR);
}
EXPECT_EQ(1u, CurrUSR.size());
CurrUSR.clear();
AllUSRs.insert(USR);
}
EXPECT_EQ(Groups.size(), AllUSRs.size());
}
TEST(USRLocFinding, FindsVarUSR) {
const char VarTest[] = "\n\
namespace A {\n\
int foo;\n\
}\n\
int foo;\n\
int bar = foo;\n\
int baz = A::foo;\n\
void fun1() {\n\
struct {\n\
int foo;\n\
} b = { 100 };\n\
int foo = 100;\n\
baz = foo;\n\
{\n\
extern int foo;\n\
baz = foo;\n\
foo = A::foo + baz;\n\
A::foo = b.foo;\n\
}\n\
foo = b.foo;\n\
}\n";
std::vector<std::vector<unsigned>> VarTestOffsets = {
{ 19, 63, 205, 223 },
{ 30, 45, 172, 187 },
{ 129, 148, 242 },
};
testOffsetGroups(VarTest, VarTestOffsets);
}
}
}
}
<commit_msg>Suppress ClangRenameTests/USRLocFinding.FindsVarUSR on msc17 for now. Will fix later.<commit_after>#include "USRFindingAction.h"
#include "gtest/gtest.h"
#include "clang/Tooling/Tooling.h"
#include <stdio.h>
#include <set>
#include <map>
#include <vector>
namespace clang {
namespace rename {
namespace test {
// Determines if the symbol group invariants hold. To recap, those invariants
// are:
// (1) All symbols in the same symbol group share the same USR.
// (2) Two symbols from two different groups do not share the same USR.
static void testOffsetGroups(const char *Code,
const std::vector<std::vector<unsigned>> Groups) {
std::set<std::string> AllUSRs, CurrUSR;
for (const auto &Group : Groups) {
// Groups the invariants do not hold then the value of USR is also invalid,
// but at that point the test has already failed and USR ceases to be
// useful.
std::string USR;
for (const auto &Offset : Group) {
USRFindingAction Action(Offset);
auto Factory = tooling::newFrontendActionFactory(&Action);
EXPECT_TRUE(tooling::runToolOnCode(Factory->create(), Code));
const auto &USRs = Action.getUSRs();
EXPECT_EQ(1u, USRs.size());
USR = USRs[0];
CurrUSR.insert(USR);
}
EXPECT_EQ(1u, CurrUSR.size());
CurrUSR.clear();
AllUSRs.insert(USR);
}
EXPECT_EQ(Groups.size(), AllUSRs.size());
}
#if !(defined(_MSC_VER) && _MSC_VER < 1800)
TEST(USRLocFinding, FindsVarUSR) {
const char VarTest[] = "\n\
namespace A {\n\
int foo;\n\
}\n\
int foo;\n\
int bar = foo;\n\
int baz = A::foo;\n\
void fun1() {\n\
struct {\n\
int foo;\n\
} b = { 100 };\n\
int foo = 100;\n\
baz = foo;\n\
{\n\
extern int foo;\n\
baz = foo;\n\
foo = A::foo + baz;\n\
A::foo = b.foo;\n\
}\n\
foo = b.foo;\n\
}\n";
std::vector<std::vector<unsigned>> VarTestOffsets = {
{ 19, 63, 205, 223 },
{ 30, 45, 172, 187 },
{ 129, 148, 242 },
};
testOffsetGroups(VarTest, VarTestOffsets);
}
#endif
}
}
}
<|endoftext|> |
<commit_before>/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2011, 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.
*
* Author: Nico Blodow (blodow@cs.tum.edu)
*/
#include <pcl/io/kinect_grabber.h>
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <boost/shared_ptr.hpp>
#include <pcl/visualization/cloud_viewer.h>
#include <iostream>
//pcl_visualization::CloudViewer viewer ("Simple Kinect Viewer");
class SimpleKinectViewer
{
public:
SimpleKinectViewer () : viewer ("KinectGrabber"), init_(false) {}
void cloud_cb_ (const pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr &cloud)
{
//boost::mutex::scoped_lock (mutex_);
//cloud_ = cloud;
if (!viewer.wasStopped())
viewer.showCloud (*cloud);
}
void viz_cb (pcl_visualization::PCLVisualizer& viz)
{
if (!init_)
{
viz.setBackgroundColor (1,1,1);
init_ = true;
}
else
viz.removePointCloud ("KinectCloud");
boost::mutex::scoped_lock (mutex_);
if (cloud_)
viz.addPointCloud (*cloud_, "KinectCloud");
}
void run ()
{
pcl::Grabber* interface = new pcl::OpenNIGrabber();
boost::function<void (const pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr&)> f = boost::bind (&SimpleKinectViewer::cloud_cb_, this, _1);
boost::signals2::connection c = interface->registerCallback (f);
boost::function1<void, pcl_visualization::PCLVisualizer&> fn = boost::bind (&SimpleKinectViewer::viz_cb, this, _1);
//viewer.runOnVisualizationThread (fn, "viz_cb");
interface->start ();
while (!viewer.wasStopped())
{
}
interface->stop ();
}
pcl_visualization::CloudViewer viewer;
boost::mutex mutex_;
pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr cloud_;
bool init_;
};
int main ()
{
SimpleKinectViewer v;
v.run ();
return 0;
}
<commit_msg>"..."<commit_after>/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2011, 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.
*
* Author: Nico Blodow (blodow@cs.tum.edu)
*/
#include <pcl/io/kinect_grabber.h>
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <boost/shared_ptr.hpp>
#include <pcl/visualization/cloud_viewer.h>
#include <iostream>
//pcl_visualization::CloudViewer viewer ("Simple Kinect Viewer");
class SimpleKinectViewer
{
public:
SimpleKinectViewer () : viewer ("KinectGrabber"), init_(false) {}
void cloud_cb_ (const pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr &cloud)
{
//boost::mutex::scoped_lock lock(mutex_);
//cloud_ = cloud;
if (!viewer.wasStopped())
viewer.showCloud (*cloud);
}
void viz_cb (pcl_visualization::PCLVisualizer& viz)
{
if (!init_)
{
viz.setBackgroundColor (1,1,1);
init_ = true;
}
else
viz.removePointCloud ("KinectCloud");
boost::mutex::scoped_lock lock(mutex_);
if (cloud_)
viz.addPointCloud (*cloud_, "KinectCloud");
}
void run ()
{
pcl::Grabber* interface = new pcl::OpenNIGrabber();
boost::function<void (const pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr&)> f = boost::bind (&SimpleKinectViewer::cloud_cb_, this, _1);
boost::signals2::connection c = interface->registerCallback (f);
boost::function1<void, pcl_visualization::PCLVisualizer&> fn = boost::bind (&SimpleKinectViewer::viz_cb, this, _1);
//viewer.runOnVisualizationThread (fn, "viz_cb");
interface->start ();
while (!viewer.wasStopped())
{
}
interface->stop ();
}
pcl_visualization::CloudViewer viewer;
boost::mutex mutex_;
pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr cloud_;
bool init_;
};
int main ()
{
SimpleKinectViewer v;
v.run ();
return 0;
}
<|endoftext|> |
<commit_before>/**************************************************************************
*
* Copyright 2014 Lunarg, Inc.
* All Rights Reserved.
*
* 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 <stdio.h>
#include <string>
#include "vktrace_common.h"
#include "vktrace_tracelog.h"
#include "vktrace_filelike.h"
#include "vktrace_trace_packet_utils.h"
#include "vkreplay_main.h"
#include "vkreplay_factory.h"
#include "vkreplay_seq.h"
#include "vkreplay_window.h"
vkreplayer_settings replaySettings = { NULL, 1, -1, -1, NULL };
vktrace_SettingInfo g_settings_info[] =
{
{ "t", "TraceFile", VKTRACE_SETTING_STRING, &replaySettings.pTraceFilePath, &replaySettings.pTraceFilePath, TRUE, "The trace file to replay."},
{ "l", "NumLoops", VKTRACE_SETTING_UINT, &replaySettings.numLoops, &replaySettings.numLoops, TRUE, "The number of times to replay the trace file or loop range." },
{ "lsf", "LoopStartFrame", VKTRACE_SETTING_UINT, &replaySettings.loopStartFrame, &replaySettings.loopStartFrame, TRUE, "The start frame number of the loop range." },
{ "lef", "LoopEndFrame", VKTRACE_SETTING_UINT, &replaySettings.loopEndFrame, &replaySettings.loopEndFrame, TRUE, "The end frame number of the loop range." },
{ "s", "Screenshot", VKTRACE_SETTING_STRING, &replaySettings.screenshotList, &replaySettings.screenshotList, TRUE, "Comma separated list of frames to take a take snapshots of"},
};
vktrace_SettingGroup g_replaySettingGroup =
{
"vkreplay",
sizeof(g_settings_info) / sizeof(g_settings_info[0]),
&g_settings_info[0]
};
namespace vktrace_replay {
int main_loop(Sequencer &seq, vktrace_trace_packet_replay_library *replayerArray[], vkreplayer_settings settings)
{
int err = 0;
vktrace_trace_packet_header *packet;
unsigned int res;
vktrace_trace_packet_replay_library *replayer;
vktrace_trace_packet_message* msgPacket;
struct seqBookmark startingPacket;
bool trace_running = true;
int prevFrameNumber = -1;
while (settings.numLoops > 0)
{
while ((packet = seq.get_next_packet()) != NULL && trace_running)
{
switch (packet->packet_id) {
case VKTRACE_TPI_MESSAGE:
msgPacket = vktrace_interpret_body_as_trace_packet_message(packet);
vktrace_LogAlways("Packet %lu: Traced Message (%s): %s", packet->global_packet_index, vktrace_LogLevelToShortString(msgPacket->type), msgPacket->message);
break;
case VKTRACE_TPI_MARKER_CHECKPOINT:
break;
case VKTRACE_TPI_MARKER_API_BOUNDARY:
break;
case VKTRACE_TPI_MARKER_API_GROUP_BEGIN:
break;
case VKTRACE_TPI_MARKER_API_GROUP_END:
break;
case VKTRACE_TPI_MARKER_TERMINATE_PROCESS:
break;
//TODO processing code for all the above cases
default:
{
if (packet->tracer_id >= VKTRACE_MAX_TRACER_ID_ARRAY_SIZE || packet->tracer_id == VKTRACE_TID_RESERVED) {
vktrace_LogError("Tracer_id from packet num packet %d invalid.", packet->packet_id);
continue;
}
replayer = replayerArray[packet->tracer_id];
if (replayer == NULL) {
vktrace_LogWarning("Tracer_id %d has no valid replayer.", packet->tracer_id);
continue;
}
if (packet->packet_id >= VKTRACE_TPI_BEGIN_API_HERE)
{
// replay the API packet
res = replayer->Replay(replayer->Interpret(packet));
if (res != VKTRACE_REPLAY_SUCCESS)
{
vktrace_LogError("Failed to replay packet_id %d.",packet->packet_id);
return -1;
}
// frame control logic
int frameNumber = replayer->GetFrameNumber();
printf("frame: %d\n", frameNumber);
if (prevFrameNumber != frameNumber)
{
prevFrameNumber = frameNumber;
if (settings.loopStartFrame == -1 || frameNumber == settings.loopStartFrame)
{
// record the location of looping start packet
seq.record_bookmark();
seq.get_bookmark(startingPacket);
}
if (frameNumber == settings.loopEndFrame)
{
trace_running = false;
}
}
} else {
vktrace_LogError("Bad packet type id=%d, index=%d.", packet->packet_id, packet->global_packet_index);
return -1;
}
}
}
}
settings.numLoops--;
seq.set_bookmark(startingPacket);
trace_running = true;
if (replayer != NULL)
{
replayer->ResetFrameNumber();
}
}
return err;
}
} // namespace vktrace_replay
using namespace vktrace_replay;
void loggingCallback(VktraceLogLevel level, const char* pMessage)
{
switch(level)
{
case VKTRACE_LOG_ALWAYS: printf("%s\n", pMessage); break;
case VKTRACE_LOG_DEBUG: printf("Debug: %s\n", pMessage); break;
case VKTRACE_LOG_ERROR: printf("Error: %s\n", pMessage); break;
case VKTRACE_LOG_WARNING: printf("Warning: %s\n", pMessage); break;
case VKTRACE_LOG_VERBOSE: printf("Verbose: %s\n", pMessage); break;
default:
printf("%s\n", pMessage); break;
}
#if defined(_DEBUG)
#if defined(WIN32)
OutputDebugString(pMessage);
#endif
#endif
}
extern "C"
int main(int argc, char **argv)
{
int err = 0;
vktrace_SettingGroup* pAllSettings = NULL;
unsigned int numAllSettings = 0;
vktrace_LogSetCallback(loggingCallback);
vktrace_LogSetLevel(VKTRACE_LOG_LEVEL_MAXIMUM);
// apply settings from cmd-line args
if (vktrace_SettingGroup_init_from_cmdline(&g_replaySettingGroup, argc, argv, &replaySettings.pTraceFilePath) != 0)
{
// invalid options specified
if (pAllSettings != NULL)
{
vktrace_SettingGroup_Delete_Loaded(&pAllSettings, &numAllSettings);
}
return err;
}
// merge settings so that new settings will get written into the settings file
vktrace_SettingGroup_merge(&g_replaySettingGroup, &pAllSettings, &numAllSettings);
// Set up environment for screenshot
if (replaySettings.screenshotList != NULL)
{
// Set env var that communicates list to ScreenShot layer
vktrace_set_global_var("_VK_SCREENSHOT", replaySettings.screenshotList);
}
else
{
vktrace_set_global_var("_VK_SCREENSHOT","");
}
// open trace file and read in header
char* pTraceFile = replaySettings.pTraceFilePath;
vktrace_trace_file_header fileHeader;
FILE *tracefp;
if (pTraceFile != NULL && strlen(pTraceFile) > 0)
{
tracefp = fopen(pTraceFile, "rb");
if (tracefp == NULL)
{
vktrace_LogError("Cannot open trace file: '%s'.", pTraceFile);
return 1;
}
}
else
{
vktrace_LogError("No trace file specified.");
vktrace_SettingGroup_print(&g_replaySettingGroup);
if (pAllSettings != NULL)
{
vktrace_SettingGroup_Delete_Loaded(&pAllSettings, &numAllSettings);
}
return 1;
}
FileLike* traceFile = vktrace_FileLike_create_file(tracefp);
if (vktrace_FileLike_ReadRaw(traceFile, &fileHeader, sizeof(fileHeader)) == false)
{
vktrace_LogError("Unable to read header from file.");
if (pAllSettings != NULL)
{
vktrace_SettingGroup_Delete_Loaded(&pAllSettings, &numAllSettings);
}
VKTRACE_DELETE(traceFile);
return 1;
}
// Make sure trace file version is supported
if (fileHeader.trace_file_version < VKTRACE_TRACE_FILE_VERSION_MINIMUM_COMPATIBLE)
{
vktrace_LogError("Trace file version %u is older than minimum compatible version (%u).\nYou'll need to make a new trace file, or use an older replayer.", fileHeader.trace_file_version, VKTRACE_TRACE_FILE_VERSION_MINIMUM_COMPATIBLE);
}
// load any API specific driver libraries and init replayer objects
uint8_t tidApi = VKTRACE_TID_RESERVED;
vktrace_trace_packet_replay_library* replayer[VKTRACE_MAX_TRACER_ID_ARRAY_SIZE];
ReplayFactory makeReplayer;
Display disp(1024, 768, 0, false);
for (int i = 0; i < VKTRACE_MAX_TRACER_ID_ARRAY_SIZE; i++)
{
replayer[i] = NULL;
}
for (int i = 0; i < fileHeader.tracer_count; i++)
{
uint8_t tracerId = fileHeader.tracer_id_array[i].id;
tidApi = tracerId;
const VKTRACE_TRACER_REPLAYER_INFO* pReplayerInfo = &(gs_tracerReplayerInfo[tracerId]);
if (pReplayerInfo->tracerId != tracerId)
{
vktrace_LogError("Replayer info for TracerId (%d) failed consistency check.", tracerId);
assert(!"TracerId in VKTRACE_TRACER_REPLAYER_INFO does not match the requested tracerId. The array needs to be corrected.");
}
else if (pReplayerInfo->needsReplayer == TRUE)
{
// Have our factory create the necessary replayer
replayer[tracerId] = makeReplayer.Create(tracerId);
if (replayer[tracerId] == NULL)
{
// replayer failed to be created
if (pAllSettings != NULL)
{
vktrace_SettingGroup_Delete_Loaded(&pAllSettings, &numAllSettings);
}
return err;
}
// merge the replayer's settings into the list of all settings so that we can output a comprehensive settings file later on.
vktrace_SettingGroup_merge(replayer[tracerId]->GetSettings(), &pAllSettings, &numAllSettings);
// update the replayer with the loaded settings
replayer[tracerId]->UpdateFromSettings(pAllSettings, numAllSettings);
replayer[tracerId]->SetLogCallback(loggingCallback);
replayer[tracerId]->SetLogLevel(VKTRACE_LOG_LEVEL_MAXIMUM);
// Initialize the replayer
err = replayer[tracerId]->Initialize(&disp, &replaySettings);
if (err) {
vktrace_LogError("Couldn't Initialize replayer for TracerId %d.", tracerId);
if (pAllSettings != NULL)
{
vktrace_SettingGroup_Delete_Loaded(&pAllSettings, &numAllSettings);
}
return err;
}
}
}
if (tidApi == VKTRACE_TID_RESERVED) {
vktrace_LogError("No API specified in tracefile for replaying.");
if (pAllSettings != NULL)
{
vktrace_SettingGroup_Delete_Loaded(&pAllSettings, &numAllSettings);
}
return -1;
}
// main loop
Sequencer sequencer(traceFile);
err = vktrace_replay::main_loop(sequencer, replayer, replaySettings);
for (int i = 0; i < VKTRACE_MAX_TRACER_ID_ARRAY_SIZE; i++)
{
if (replayer[i] != NULL)
{
replayer[i]->Deinitialize();
makeReplayer.Destroy(&replayer[i]);
}
}
if (pAllSettings != NULL)
{
vktrace_SettingGroup_Delete_Loaded(&pAllSettings, &numAllSettings);
}
return err;
}
<commit_msg>Remove printf. Change type of new options from UINT to INT.<commit_after>/**************************************************************************
*
* Copyright 2014 Lunarg, Inc.
* All Rights Reserved.
*
* 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 <stdio.h>
#include <string>
#include "vktrace_common.h"
#include "vktrace_tracelog.h"
#include "vktrace_filelike.h"
#include "vktrace_trace_packet_utils.h"
#include "vkreplay_main.h"
#include "vkreplay_factory.h"
#include "vkreplay_seq.h"
#include "vkreplay_window.h"
vkreplayer_settings replaySettings = { NULL, 1, -1, -1, NULL };
vktrace_SettingInfo g_settings_info[] =
{
{ "t", "TraceFile", VKTRACE_SETTING_STRING, &replaySettings.pTraceFilePath, &replaySettings.pTraceFilePath, TRUE, "The trace file to replay."},
{ "l", "NumLoops", VKTRACE_SETTING_UINT, &replaySettings.numLoops, &replaySettings.numLoops, TRUE, "The number of times to replay the trace file or loop range." },
{ "lsf", "LoopStartFrame", VKTRACE_SETTING_INT, &replaySettings.loopStartFrame, &replaySettings.loopStartFrame, TRUE, "The start frame number of the loop range." },
{ "lef", "LoopEndFrame", VKTRACE_SETTING_INT, &replaySettings.loopEndFrame, &replaySettings.loopEndFrame, TRUE, "The end frame number of the loop range." },
{ "s", "Screenshot", VKTRACE_SETTING_STRING, &replaySettings.screenshotList, &replaySettings.screenshotList, TRUE, "Comma separated list of frames to take a take snapshots of"},
};
vktrace_SettingGroup g_replaySettingGroup =
{
"vkreplay",
sizeof(g_settings_info) / sizeof(g_settings_info[0]),
&g_settings_info[0]
};
namespace vktrace_replay {
int main_loop(Sequencer &seq, vktrace_trace_packet_replay_library *replayerArray[], vkreplayer_settings settings)
{
int err = 0;
vktrace_trace_packet_header *packet;
unsigned int res;
vktrace_trace_packet_replay_library *replayer;
vktrace_trace_packet_message* msgPacket;
struct seqBookmark startingPacket;
bool trace_running = true;
int prevFrameNumber = -1;
while (settings.numLoops > 0)
{
while ((packet = seq.get_next_packet()) != NULL && trace_running)
{
switch (packet->packet_id) {
case VKTRACE_TPI_MESSAGE:
msgPacket = vktrace_interpret_body_as_trace_packet_message(packet);
vktrace_LogAlways("Packet %lu: Traced Message (%s): %s", packet->global_packet_index, vktrace_LogLevelToShortString(msgPacket->type), msgPacket->message);
break;
case VKTRACE_TPI_MARKER_CHECKPOINT:
break;
case VKTRACE_TPI_MARKER_API_BOUNDARY:
break;
case VKTRACE_TPI_MARKER_API_GROUP_BEGIN:
break;
case VKTRACE_TPI_MARKER_API_GROUP_END:
break;
case VKTRACE_TPI_MARKER_TERMINATE_PROCESS:
break;
//TODO processing code for all the above cases
default:
{
if (packet->tracer_id >= VKTRACE_MAX_TRACER_ID_ARRAY_SIZE || packet->tracer_id == VKTRACE_TID_RESERVED) {
vktrace_LogError("Tracer_id from packet num packet %d invalid.", packet->packet_id);
continue;
}
replayer = replayerArray[packet->tracer_id];
if (replayer == NULL) {
vktrace_LogWarning("Tracer_id %d has no valid replayer.", packet->tracer_id);
continue;
}
if (packet->packet_id >= VKTRACE_TPI_BEGIN_API_HERE)
{
// replay the API packet
res = replayer->Replay(replayer->Interpret(packet));
if (res != VKTRACE_REPLAY_SUCCESS)
{
vktrace_LogError("Failed to replay packet_id %d.",packet->packet_id);
return -1;
}
// frame control logic
int frameNumber = replayer->GetFrameNumber();
if (prevFrameNumber != frameNumber)
{
prevFrameNumber = frameNumber;
if (settings.loopStartFrame == -1 || frameNumber == settings.loopStartFrame)
{
// record the location of looping start packet
seq.record_bookmark();
seq.get_bookmark(startingPacket);
}
if (frameNumber == settings.loopEndFrame)
{
trace_running = false;
}
}
} else {
vktrace_LogError("Bad packet type id=%d, index=%d.", packet->packet_id, packet->global_packet_index);
return -1;
}
}
}
}
settings.numLoops--;
seq.set_bookmark(startingPacket);
trace_running = true;
if (replayer != NULL)
{
replayer->ResetFrameNumber();
}
}
return err;
}
} // namespace vktrace_replay
using namespace vktrace_replay;
void loggingCallback(VktraceLogLevel level, const char* pMessage)
{
switch(level)
{
case VKTRACE_LOG_ALWAYS: printf("%s\n", pMessage); break;
case VKTRACE_LOG_DEBUG: printf("Debug: %s\n", pMessage); break;
case VKTRACE_LOG_ERROR: printf("Error: %s\n", pMessage); break;
case VKTRACE_LOG_WARNING: printf("Warning: %s\n", pMessage); break;
case VKTRACE_LOG_VERBOSE: printf("Verbose: %s\n", pMessage); break;
default:
printf("%s\n", pMessage); break;
}
#if defined(_DEBUG)
#if defined(WIN32)
OutputDebugString(pMessage);
#endif
#endif
}
extern "C"
int main(int argc, char **argv)
{
int err = 0;
vktrace_SettingGroup* pAllSettings = NULL;
unsigned int numAllSettings = 0;
vktrace_LogSetCallback(loggingCallback);
vktrace_LogSetLevel(VKTRACE_LOG_LEVEL_MAXIMUM);
// apply settings from cmd-line args
if (vktrace_SettingGroup_init_from_cmdline(&g_replaySettingGroup, argc, argv, &replaySettings.pTraceFilePath) != 0)
{
// invalid options specified
if (pAllSettings != NULL)
{
vktrace_SettingGroup_Delete_Loaded(&pAllSettings, &numAllSettings);
}
return err;
}
// merge settings so that new settings will get written into the settings file
vktrace_SettingGroup_merge(&g_replaySettingGroup, &pAllSettings, &numAllSettings);
// Set up environment for screenshot
if (replaySettings.screenshotList != NULL)
{
// Set env var that communicates list to ScreenShot layer
vktrace_set_global_var("_VK_SCREENSHOT", replaySettings.screenshotList);
}
else
{
vktrace_set_global_var("_VK_SCREENSHOT","");
}
// open trace file and read in header
char* pTraceFile = replaySettings.pTraceFilePath;
vktrace_trace_file_header fileHeader;
FILE *tracefp;
if (pTraceFile != NULL && strlen(pTraceFile) > 0)
{
tracefp = fopen(pTraceFile, "rb");
if (tracefp == NULL)
{
vktrace_LogError("Cannot open trace file: '%s'.", pTraceFile);
return 1;
}
}
else
{
vktrace_LogError("No trace file specified.");
vktrace_SettingGroup_print(&g_replaySettingGroup);
if (pAllSettings != NULL)
{
vktrace_SettingGroup_Delete_Loaded(&pAllSettings, &numAllSettings);
}
return 1;
}
FileLike* traceFile = vktrace_FileLike_create_file(tracefp);
if (vktrace_FileLike_ReadRaw(traceFile, &fileHeader, sizeof(fileHeader)) == false)
{
vktrace_LogError("Unable to read header from file.");
if (pAllSettings != NULL)
{
vktrace_SettingGroup_Delete_Loaded(&pAllSettings, &numAllSettings);
}
VKTRACE_DELETE(traceFile);
return 1;
}
// Make sure trace file version is supported
if (fileHeader.trace_file_version < VKTRACE_TRACE_FILE_VERSION_MINIMUM_COMPATIBLE)
{
vktrace_LogError("Trace file version %u is older than minimum compatible version (%u).\nYou'll need to make a new trace file, or use an older replayer.", fileHeader.trace_file_version, VKTRACE_TRACE_FILE_VERSION_MINIMUM_COMPATIBLE);
}
// load any API specific driver libraries and init replayer objects
uint8_t tidApi = VKTRACE_TID_RESERVED;
vktrace_trace_packet_replay_library* replayer[VKTRACE_MAX_TRACER_ID_ARRAY_SIZE];
ReplayFactory makeReplayer;
Display disp(1024, 768, 0, false);
for (int i = 0; i < VKTRACE_MAX_TRACER_ID_ARRAY_SIZE; i++)
{
replayer[i] = NULL;
}
for (int i = 0; i < fileHeader.tracer_count; i++)
{
uint8_t tracerId = fileHeader.tracer_id_array[i].id;
tidApi = tracerId;
const VKTRACE_TRACER_REPLAYER_INFO* pReplayerInfo = &(gs_tracerReplayerInfo[tracerId]);
if (pReplayerInfo->tracerId != tracerId)
{
vktrace_LogError("Replayer info for TracerId (%d) failed consistency check.", tracerId);
assert(!"TracerId in VKTRACE_TRACER_REPLAYER_INFO does not match the requested tracerId. The array needs to be corrected.");
}
else if (pReplayerInfo->needsReplayer == TRUE)
{
// Have our factory create the necessary replayer
replayer[tracerId] = makeReplayer.Create(tracerId);
if (replayer[tracerId] == NULL)
{
// replayer failed to be created
if (pAllSettings != NULL)
{
vktrace_SettingGroup_Delete_Loaded(&pAllSettings, &numAllSettings);
}
return err;
}
// merge the replayer's settings into the list of all settings so that we can output a comprehensive settings file later on.
vktrace_SettingGroup_merge(replayer[tracerId]->GetSettings(), &pAllSettings, &numAllSettings);
// update the replayer with the loaded settings
replayer[tracerId]->UpdateFromSettings(pAllSettings, numAllSettings);
replayer[tracerId]->SetLogCallback(loggingCallback);
replayer[tracerId]->SetLogLevel(VKTRACE_LOG_LEVEL_MAXIMUM);
// Initialize the replayer
err = replayer[tracerId]->Initialize(&disp, &replaySettings);
if (err) {
vktrace_LogError("Couldn't Initialize replayer for TracerId %d.", tracerId);
if (pAllSettings != NULL)
{
vktrace_SettingGroup_Delete_Loaded(&pAllSettings, &numAllSettings);
}
return err;
}
}
}
if (tidApi == VKTRACE_TID_RESERVED) {
vktrace_LogError("No API specified in tracefile for replaying.");
if (pAllSettings != NULL)
{
vktrace_SettingGroup_Delete_Loaded(&pAllSettings, &numAllSettings);
}
return -1;
}
// main loop
Sequencer sequencer(traceFile);
err = vktrace_replay::main_loop(sequencer, replayer, replaySettings);
for (int i = 0; i < VKTRACE_MAX_TRACER_ID_ARRAY_SIZE; i++)
{
if (replayer[i] != NULL)
{
replayer[i]->Deinitialize();
makeReplayer.Destroy(&replayer[i]);
}
}
if (pAllSettings != NULL)
{
vktrace_SettingGroup_Delete_Loaded(&pAllSettings, &numAllSettings);
}
return err;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: EventOOoTContext.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2004-07-13 08:49:19 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _XMLOFF_EVENTOOOTCONTEXT_HXX
#define _XMLOFF_EVENTOOOTCONTEXT_HXX
#ifndef _XMLOFF_PERSATTRLISTTCONTEXT_HXX
#include "PersAttrListTContext.hxx"
#endif
class XMLTransformerOOoEventMap_Impl;
class XMLEventOOoTransformerContext : public XMLPersAttrListTContext
{
sal_Bool m_bPersistent;
public:
TYPEINFO();
XMLEventOOoTransformerContext( XMLTransformerBase& rTransformer,
const ::rtl::OUString& rQName,
sal_Bool bPersistent = sal_False );
virtual ~XMLEventOOoTransformerContext();
static XMLTransformerOOoEventMap_Impl *CreateEventMap();
static void FlushEventMap( XMLTransformerOOoEventMap_Impl *p );
static sal_uInt16 GetEventName( const ::rtl::OUString& rName,
::rtl::OUString& rNewName,
XMLTransformerOOoEventMap_Impl& rMap );
virtual void StartElement( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList );
virtual void EndElement();
virtual sal_Bool IsPersistent() const;
};
#endif // _XMLOFF_EVENTOOOTCONTEXT_HXX
<commit_msg>INTEGRATION: CWS ooo19126 (1.2.298); FILE MERGED 2005/09/05 14:40:21 rt 1.2.298.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: EventOOoTContext.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-09 15:43:15 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _XMLOFF_EVENTOOOTCONTEXT_HXX
#define _XMLOFF_EVENTOOOTCONTEXT_HXX
#ifndef _XMLOFF_PERSATTRLISTTCONTEXT_HXX
#include "PersAttrListTContext.hxx"
#endif
class XMLTransformerOOoEventMap_Impl;
class XMLEventOOoTransformerContext : public XMLPersAttrListTContext
{
sal_Bool m_bPersistent;
public:
TYPEINFO();
XMLEventOOoTransformerContext( XMLTransformerBase& rTransformer,
const ::rtl::OUString& rQName,
sal_Bool bPersistent = sal_False );
virtual ~XMLEventOOoTransformerContext();
static XMLTransformerOOoEventMap_Impl *CreateEventMap();
static void FlushEventMap( XMLTransformerOOoEventMap_Impl *p );
static sal_uInt16 GetEventName( const ::rtl::OUString& rName,
::rtl::OUString& rNewName,
XMLTransformerOOoEventMap_Impl& rMap );
virtual void StartElement( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList );
virtual void EndElement();
virtual sal_Bool IsPersistent() const;
};
#endif // _XMLOFF_EVENTOOOTCONTEXT_HXX
<|endoftext|> |
<commit_before>#include <v8.h>
#include <node.h>
#include <string.h>
#include <unistd.h>
#include <node_object_wrap.h>
#include <kstat.h>
#include <errno.h>
#include <string>
#include <vector>
#include <sys/varargs.h>
using namespace v8;
using std::string;
using std::vector;
class KStatReader : node::ObjectWrap {
public:
static void Initialize(Handle<Object> target);
protected:
static Persistent<FunctionTemplate> templ;
KStatReader(string *module, string *classname,
string *name, int instance);
void close();
Handle<Value> error(const char *fmt, ...);
Handle<Value> read(kstat_t *);
bool matches(kstat_t *, string *, string *, string *, int64_t);
int update();
~KStatReader();
static Handle<Value> Close(const Arguments& args);
static Handle<Value> New(const Arguments& args);
static Handle<Value> Read(const Arguments& args);
private:
static string *stringMember(Local<Value>, char *, char *);
static int64_t intMember(Local<Value>, char *, int64_t);
Handle<Object> data_named(kstat_t *);
Handle<Object> data_io(kstat_t *);
string *ksr_module;
string *ksr_class;
string *ksr_name;
int ksr_instance;
kid_t ksr_kid;
kstat_ctl_t *ksr_ctl;
vector<kstat_t *> ksr_kstats;
};
Persistent<FunctionTemplate> KStatReader::templ;
KStatReader::KStatReader(string *module, string *classname,
string *name, int instance)
: node::ObjectWrap(), ksr_module(module), ksr_class(classname),
ksr_name(name), ksr_instance(instance), ksr_kid(-1)
{
if ((ksr_ctl = kstat_open()) == NULL)
throw "could not open kstat";
};
KStatReader::~KStatReader()
{
delete ksr_module;
delete ksr_class;
delete ksr_name;
if (ksr_ctl != NULL)
this->close();
}
void
KStatReader::close()
{
kstat_close(ksr_ctl);
ksr_ctl = NULL;
}
bool
KStatReader::matches(kstat_t *ksp, string* fmodule, string* fclass,
string* fname, int64_t finstance)
{
if (!fmodule->empty() && fmodule->compare(ksp->ks_module) != 0)
return (false);
if (!fclass->empty() && fclass->compare(ksp->ks_class) != 0)
return (false);
if (!fname->empty() && fname->compare(ksp->ks_name) != 0)
return (false);
return (finstance == -1 || ksp->ks_instance == finstance);
}
int
KStatReader::update()
{
kstat_t *ksp;
kid_t kid;
if ((kid = kstat_chain_update(ksr_ctl)) == 0 && ksr_kid != -1)
return (0);
if (kid == -1)
return (-1);
ksr_kid = kid;
ksr_kstats.clear();
for (ksp = ksr_ctl->kc_chain; ksp != NULL; ksp = ksp->ks_next) {
if (!this->matches(ksp,
ksr_module, ksr_class, ksr_name, ksr_instance))
continue;
ksr_kstats.push_back(ksp);
}
return (0);
}
void
KStatReader::Initialize(Handle<Object> target)
{
HandleScope scope;
Local<FunctionTemplate> k = FunctionTemplate::New(KStatReader::New);
templ = Persistent<FunctionTemplate>::New(k);
templ->InstanceTemplate()->SetInternalFieldCount(1);
templ->SetClassName(String::NewSymbol("Reader"));
NODE_SET_PROTOTYPE_METHOD(templ, "read", KStatReader::Read);
NODE_SET_PROTOTYPE_METHOD(templ, "close", KStatReader::Close);
target->Set(String::NewSymbol("Reader"), templ->GetFunction());
}
string *
KStatReader::stringMember(Local<Value> value, char *member, char *deflt)
{
if (!value->IsObject())
return (new string (deflt));
Local<Object> o = Local<Object>::Cast(value);
Local<Value> v = o->Get(String::New(member));
if (!v->IsString())
return (new string (deflt));
String::AsciiValue val(v);
return (new string(*val));
}
int64_t
KStatReader::intMember(Local<Value> value, char *member, int64_t deflt)
{
int64_t rval = deflt;
if (!value->IsObject())
return (rval);
Local<Object> o = Local<Object>::Cast(value);
value = o->Get(String::New(member));
if (!value->IsNumber())
return (rval);
Local<Integer> i = Local<Integer>::Cast(value);
return (i->Value());
}
Handle<Value>
KStatReader::New(const Arguments& args)
{
HandleScope scope;
KStatReader *k = new KStatReader(stringMember(args[0], "module", ""),
stringMember(args[0], "class", ""),
stringMember(args[0], "name", ""),
intMember(args[0], "instance", -1));
k->Wrap(args.Holder());
return (args.This());
}
Handle<Value>
KStatReader::error(const char *fmt, ...)
{
char buf[1024], buf2[1024];
char *err = buf;
va_list ap;
va_start(ap, fmt);
(void) vsnprintf(buf, sizeof (buf), fmt, ap);
if (buf[strlen(buf) - 1] != '\n') {
/*
* If our error doesn't end in a new-line, we'll append the
* strerror of errno.
*/
(void) snprintf(err = buf2, sizeof (buf2),
"%s: %s", buf, strerror(errno));
} else {
buf[strlen(buf) - 1] = '\0';
}
return (ThrowException(Exception::Error(String::New(err))));
}
Handle<Object>
KStatReader::data_named(kstat_t *ksp)
{
Handle<Object> data = Object::New();
kstat_named_t *nm = KSTAT_NAMED_PTR(ksp);
int i;
assert(ksp->ks_type == KSTAT_TYPE_NAMED);
for (i = 0; i < ksp->ks_ndata; i++, nm++) {
Handle<Value> val;
switch (nm->data_type) {
case KSTAT_DATA_CHAR:
val = Number::New(nm->value.c[0]);
break;
case KSTAT_DATA_INT32:
val = Number::New(nm->value.i32);
break;
case KSTAT_DATA_UINT32:
val = Number::New(nm->value.ui32);
break;
case KSTAT_DATA_INT64:
val = Number::New(nm->value.i64);
break;
case KSTAT_DATA_UINT64:
val = Number::New(nm->value.ui64);
break;
case KSTAT_DATA_STRING:
val = String::New(KSTAT_NAMED_STR_PTR(nm));
break;
default:
throw (error("unrecognized data type %d for member "
"\"%s\" in instance %d of stat \"%s\" (module "
"\"%s\", class \"%s\")\n", nm->data_type,
nm->name, ksp->ks_instance, ksp->ks_name,
ksp->ks_module, ksp->ks_class));
}
data->Set(String::New(nm->name), val);
}
return (data);
}
Handle<Object>
KStatReader::data_io(kstat_t *ksp)
{
Handle<Object> data = Object::New();
kstat_io_t *io = KSTAT_IO_PTR(ksp);
assert(ksp->ks_type == KSTAT_TYPE_IO);
data->Set(String::New("nread"), Number::New(io->nread));
data->Set(String::New("nwritten"), Number::New(io->nwritten));
data->Set(String::New("reads"), Integer::New(io->reads));
data->Set(String::New("writes"), Integer::New(io->writes));
data->Set(String::New("wtime"), Number::New(io->wtime));
data->Set(String::New("wlentime"), Number::New(io->wlentime));
data->Set(String::New("wlastupdate"), Number::New(io->wlastupdate));
data->Set(String::New("rtime"), Number::New(io->rtime));
data->Set(String::New("rlentime"), Number::New(io->rlentime));
data->Set(String::New("rlastupdate"), Number::New(io->rlastupdate));
data->Set(String::New("wcnt"), Integer::New(io->wcnt));
data->Set(String::New("rcnt"), Integer::New(io->rcnt));
return (data);
}
Handle<Value>
KStatReader::read(kstat_t *ksp)
{
Handle<Object> rval = Object::New();
Handle<Object> data;
rval->Set(String::New("class"), String::New(ksp->ks_class));
rval->Set(String::New("module"), String::New(ksp->ks_module));
rval->Set(String::New("name"), String::New(ksp->ks_name));
rval->Set(String::New("instance"), Integer::New(ksp->ks_instance));
if (kstat_read(ksr_ctl, ksp, NULL) == -1) {
/*
* It is deeply annoying, but some kstats can return errors
* under otherwise routine conditions. (ACPI is one
* offender; there are surely others.) To prevent these
* fouled kstats from completely ruining our day, we assign
* an "error" member to the return value that consists of
* the strerror().
*/
rval->Set(String::New("error"), String::New(strerror(errno)));
return (rval);
}
rval->Set(String::New("instance"), Integer::New(ksp->ks_instance));
rval->Set(String::New("snaptime"), Number::New(ksp->ks_snaptime));
rval->Set(String::New("crtime"), Number::New(ksp->ks_crtime));
if (ksp->ks_type == KSTAT_TYPE_NAMED) {
data = data_named(ksp);
} else if (ksp->ks_type == KSTAT_TYPE_IO) {
data = data_io(ksp);
} else {
return (rval);
}
rval->Set(String::New("data"), data);
return (rval);
}
Handle<Value>
KStatReader::Close(const Arguments& args)
{
KStatReader *k = ObjectWrap::Unwrap<KStatReader>(args.Holder());
HandleScope scope;
if (k->ksr_ctl == NULL)
return (k->error("kstat reader has already been closed\n"));
k->close();
return (Undefined());
}
Handle<Value>
KStatReader::Read(const Arguments& args)
{
KStatReader *k = ObjectWrap::Unwrap<KStatReader>(args.Holder());
Handle<Array> rval;
HandleScope scope;
int i, j;
if (k->ksr_ctl == NULL)
return (k->error("kstat reader has already been closed\n"));
if (k->update() == -1)
return (k->error("failed to update kstat chain"));
string *rmodule = stringMember(args[0], "module", "");
string *rclass = stringMember(args[0], "class", "");
string *rname = stringMember(args[0], "name", "");
int64_t rinstance = intMember(args[0], "instance", -1);
rval = Array::New();
try {
for (i = 0, j = 0; i < k->ksr_kstats.size(); i++) {
if (!k->matches(k->ksr_kstats[i],
rmodule, rclass, rname, rinstance))
continue;
rval->Set(j++, k->read(k->ksr_kstats[i]));
}
} catch (Handle<Value> err) {
delete rmodule;
delete rclass;
delete rname;
return (err);
}
delete rmodule;
delete rclass;
delete rname;
return (rval);
}
extern "C" void
init (Handle<Object> target)
{
KStatReader::Initialize(target);
}
<commit_msg>Make kstat build/work on node 0.10<commit_after>#include <v8.h>
#include <node.h>
#include <string.h>
#include <unistd.h>
#include <node_object_wrap.h>
#include <kstat.h>
#include <errno.h>
#include <string>
#include <vector>
#include <sys/varargs.h>
using namespace v8;
using std::string;
using std::vector;
class KStatReader : node::ObjectWrap {
public:
static void Initialize(Handle<Object> target);
protected:
static Persistent<FunctionTemplate> templ;
KStatReader(string *module, string *classname,
string *name, int instance);
void close();
Handle<Value> error(const char *fmt, ...);
Handle<Value> read(kstat_t *);
bool matches(kstat_t *, string *, string *, string *, int64_t);
int update();
~KStatReader();
static Handle<Value> Close(const Arguments& args);
static Handle<Value> New(const Arguments& args);
static Handle<Value> Read(const Arguments& args);
private:
static string *stringMember(Local<Value>, char *, char *);
static int64_t intMember(Local<Value>, char *, int64_t);
Handle<Object> data_named(kstat_t *);
Handle<Object> data_io(kstat_t *);
string *ksr_module;
string *ksr_class;
string *ksr_name;
int ksr_instance;
kid_t ksr_kid;
kstat_ctl_t *ksr_ctl;
vector<kstat_t *> ksr_kstats;
};
Persistent<FunctionTemplate> KStatReader::templ;
KStatReader::KStatReader(string *module, string *classname,
string *name, int instance)
: node::ObjectWrap(), ksr_module(module), ksr_class(classname),
ksr_name(name), ksr_instance(instance), ksr_kid(-1)
{
if ((ksr_ctl = kstat_open()) == NULL)
throw "could not open kstat";
};
KStatReader::~KStatReader()
{
delete ksr_module;
delete ksr_class;
delete ksr_name;
if (ksr_ctl != NULL)
this->close();
}
void
KStatReader::close()
{
kstat_close(ksr_ctl);
ksr_ctl = NULL;
}
bool
KStatReader::matches(kstat_t *ksp, string* fmodule, string* fclass,
string* fname, int64_t finstance)
{
if (!fmodule->empty() && fmodule->compare(ksp->ks_module) != 0)
return (false);
if (!fclass->empty() && fclass->compare(ksp->ks_class) != 0)
return (false);
if (!fname->empty() && fname->compare(ksp->ks_name) != 0)
return (false);
return (finstance == -1 || ksp->ks_instance == finstance);
}
int
KStatReader::update()
{
kstat_t *ksp;
kid_t kid;
if ((kid = kstat_chain_update(ksr_ctl)) == 0 && ksr_kid != -1)
return (0);
if (kid == -1)
return (-1);
ksr_kid = kid;
ksr_kstats.clear();
for (ksp = ksr_ctl->kc_chain; ksp != NULL; ksp = ksp->ks_next) {
if (!this->matches(ksp,
ksr_module, ksr_class, ksr_name, ksr_instance))
continue;
ksr_kstats.push_back(ksp);
}
return (0);
}
void
KStatReader::Initialize(Handle<Object> target)
{
HandleScope scope;
Local<FunctionTemplate> k = FunctionTemplate::New(KStatReader::New);
templ = Persistent<FunctionTemplate>::New(k);
templ->InstanceTemplate()->SetInternalFieldCount(1);
templ->SetClassName(String::NewSymbol("Reader"));
NODE_SET_PROTOTYPE_METHOD(templ, "read", KStatReader::Read);
NODE_SET_PROTOTYPE_METHOD(templ, "close", KStatReader::Close);
target->Set(String::NewSymbol("Reader"), templ->GetFunction());
}
string *
KStatReader::stringMember(Local<Value> value, char *member, char *deflt)
{
if (!value->IsObject())
return (new string (deflt));
Local<Object> o = Local<Object>::Cast(value);
Local<Value> v = o->Get(String::New(member));
if (!v->IsString())
return (new string (deflt));
String::AsciiValue val(v);
return (new string(*val));
}
int64_t
KStatReader::intMember(Local<Value> value, char *member, int64_t deflt)
{
int64_t rval = deflt;
if (!value->IsObject())
return (rval);
Local<Object> o = Local<Object>::Cast(value);
value = o->Get(String::New(member));
if (!value->IsNumber())
return (rval);
Local<Integer> i = Local<Integer>::Cast(value);
return (i->Value());
}
Handle<Value>
KStatReader::New(const Arguments& args)
{
HandleScope scope;
KStatReader *k = new KStatReader(stringMember(args[0], "module", ""),
stringMember(args[0], "class", ""),
stringMember(args[0], "name", ""),
intMember(args[0], "instance", -1));
k->Wrap(args.Holder());
return (args.This());
}
Handle<Value>
KStatReader::error(const char *fmt, ...)
{
char buf[1024], buf2[1024];
char *err = buf;
va_list ap;
va_start(ap, fmt);
(void) vsnprintf(buf, sizeof (buf), fmt, ap);
if (buf[strlen(buf) - 1] != '\n') {
/*
* If our error doesn't end in a new-line, we'll append the
* strerror of errno.
*/
(void) snprintf(err = buf2, sizeof (buf2),
"%s: %s", buf, strerror(errno));
} else {
buf[strlen(buf) - 1] = '\0';
}
return (ThrowException(Exception::Error(String::New(err))));
}
Handle<Object>
KStatReader::data_named(kstat_t *ksp)
{
Handle<Object> data = Object::New();
kstat_named_t *nm = KSTAT_NAMED_PTR(ksp);
int i;
assert(ksp->ks_type == KSTAT_TYPE_NAMED);
for (i = 0; i < ksp->ks_ndata; i++, nm++) {
Handle<Value> val;
switch (nm->data_type) {
case KSTAT_DATA_CHAR:
val = Number::New(nm->value.c[0]);
break;
case KSTAT_DATA_INT32:
val = Number::New(nm->value.i32);
break;
case KSTAT_DATA_UINT32:
val = Number::New(nm->value.ui32);
break;
case KSTAT_DATA_INT64:
val = Number::New(nm->value.i64);
break;
case KSTAT_DATA_UINT64:
val = Number::New(nm->value.ui64);
break;
case KSTAT_DATA_STRING:
val = String::New(KSTAT_NAMED_STR_PTR(nm));
break;
default:
throw (error("unrecognized data type %d for member "
"\"%s\" in instance %d of stat \"%s\" (module "
"\"%s\", class \"%s\")\n", nm->data_type,
nm->name, ksp->ks_instance, ksp->ks_name,
ksp->ks_module, ksp->ks_class));
}
data->Set(String::New(nm->name), val);
}
return (data);
}
Handle<Object>
KStatReader::data_io(kstat_t *ksp)
{
Handle<Object> data = Object::New();
kstat_io_t *io = KSTAT_IO_PTR(ksp);
assert(ksp->ks_type == KSTAT_TYPE_IO);
data->Set(String::New("nread"), Number::New(io->nread));
data->Set(String::New("nwritten"), Number::New(io->nwritten));
data->Set(String::New("reads"), Integer::New(io->reads));
data->Set(String::New("writes"), Integer::New(io->writes));
data->Set(String::New("wtime"), Number::New(io->wtime));
data->Set(String::New("wlentime"), Number::New(io->wlentime));
data->Set(String::New("wlastupdate"), Number::New(io->wlastupdate));
data->Set(String::New("rtime"), Number::New(io->rtime));
data->Set(String::New("rlentime"), Number::New(io->rlentime));
data->Set(String::New("rlastupdate"), Number::New(io->rlastupdate));
data->Set(String::New("wcnt"), Integer::New(io->wcnt));
data->Set(String::New("rcnt"), Integer::New(io->rcnt));
return (data);
}
Handle<Value>
KStatReader::read(kstat_t *ksp)
{
Handle<Object> rval = Object::New();
Handle<Object> data;
rval->Set(String::New("class"), String::New(ksp->ks_class));
rval->Set(String::New("module"), String::New(ksp->ks_module));
rval->Set(String::New("name"), String::New(ksp->ks_name));
rval->Set(String::New("instance"), Integer::New(ksp->ks_instance));
if (kstat_read(ksr_ctl, ksp, NULL) == -1) {
/*
* It is deeply annoying, but some kstats can return errors
* under otherwise routine conditions. (ACPI is one
* offender; there are surely others.) To prevent these
* fouled kstats from completely ruining our day, we assign
* an "error" member to the return value that consists of
* the strerror().
*/
rval->Set(String::New("error"), String::New(strerror(errno)));
return (rval);
}
rval->Set(String::New("instance"), Integer::New(ksp->ks_instance));
rval->Set(String::New("snaptime"), Number::New(ksp->ks_snaptime));
rval->Set(String::New("crtime"), Number::New(ksp->ks_crtime));
if (ksp->ks_type == KSTAT_TYPE_NAMED) {
data = data_named(ksp);
} else if (ksp->ks_type == KSTAT_TYPE_IO) {
data = data_io(ksp);
} else {
return (rval);
}
rval->Set(String::New("data"), data);
return (rval);
}
Handle<Value>
KStatReader::Close(const Arguments& args)
{
KStatReader *k = ObjectWrap::Unwrap<KStatReader>(args.Holder());
HandleScope scope;
if (k->ksr_ctl == NULL)
return (k->error("kstat reader has already been closed\n"));
k->close();
return (Undefined());
}
Handle<Value>
KStatReader::Read(const Arguments& args)
{
KStatReader *k = ObjectWrap::Unwrap<KStatReader>(args.Holder());
Handle<Array> rval;
HandleScope scope;
int i, j;
if (k->ksr_ctl == NULL)
return (k->error("kstat reader has already been closed\n"));
if (k->update() == -1)
return (k->error("failed to update kstat chain"));
string *rmodule = stringMember(args[0], "module", "");
string *rclass = stringMember(args[0], "class", "");
string *rname = stringMember(args[0], "name", "");
int64_t rinstance = intMember(args[0], "instance", -1);
rval = Array::New();
try {
for (i = 0, j = 0; i < k->ksr_kstats.size(); i++) {
if (!k->matches(k->ksr_kstats[i],
rmodule, rclass, rname, rinstance))
continue;
rval->Set(j++, k->read(k->ksr_kstats[i]));
}
} catch (Handle<Value> err) {
delete rmodule;
delete rclass;
delete rname;
return (err);
}
delete rmodule;
delete rclass;
delete rname;
return (rval);
}
extern "C" void
init (Handle<Object> target)
{
KStatReader::Initialize(target);
}
NODE_MODULE(kstat, init);
<|endoftext|> |
<commit_before>8fd04904-2d14-11e5-af21-0401358ea401<commit_msg>8fd04905-2d14-11e5-af21-0401358ea401<commit_after>8fd04905-2d14-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>2f53a998-5216-11e5-a24d-6c40088e03e4<commit_msg>2f5a39d4-5216-11e5-a19f-6c40088e03e4<commit_after>2f5a39d4-5216-11e5-a19f-6c40088e03e4<|endoftext|> |
<commit_before>#include "main.h"
Server1 server;
void setup() {
server.begin(115200);
}
void loop() {
char *cmd;
if ((cmd = server.getCmd()) != 0) {
switch(cmd[0]) {
case 'v':
server.sendMsg("v1.0 Duino");
break;
}
}
}
<commit_msg>Define VERSION_STR<commit_after>#include "main.h"
Server1 server;
#define VERSION_STR "v1.0 Duino"
void setup() {
server.begin(115200);
server.sendMsg(VERSION_STR);
}
void loop() {
char *cmd;
if ((cmd = server.getCmd()) != 0) {
switch(cmd[0]) {
case 'v':
server.sendMsg(VERSION_STR);
break;
}
}
}
<|endoftext|> |
<commit_before>2642d845-2748-11e6-a7c8-e0f84713e7b8<commit_msg>Now it no longer crashes if X<commit_after>264d03dc-2748-11e6-9e6d-e0f84713e7b8<|endoftext|> |
<commit_before>/*
* =====================================================================================
*
* Filename: main.cpp
*
* Description:
*
* Version: 1.0
* Created: 09/26/2015 18:25:55
* Revision: none
* Compiler: gcc
*
* Author: Il Jae Lee (iljae), iljae@umich.edu
* Organization: University of Michigan
*
* =====================================================================================
*/
#include "train.hpp"
#include "video.hpp"
#include "nnet.hpp"
#include "hog.hpp"
#include <iostream>
namespace maav {
class FeatureExtractMethod {
public:
FeatureExtractMethod(
ExtractInterface & extract_interface,
std::vector<Features> & features_collection
) :
extract_interface_(extract_interface),
features_collection_(features_collection) {}
void operator() (const cv::Mat & image) const {
Features features((features_collection_.size()==0?
0:features_collection_.front().size()));
extract_interface_.compute(image, features);
features_collection_.push_back(features);
}
private:
ExtractInterface & extract_interface_;
std::vector<Features> & features_collection_;
};
class NegativeMiningMethod {
public:
NegativeMiningMethod(
ExtractInterface & extract_interface,
LearnInterface & learn_interface,
std::vector<Features> & negative_features_collection
) :
extract_interface_(extract_interface),
learn_interface_(learn_interface),
negative_features_collection_(negative_features_collection) {}
void operator() (const cv::Mat & image) {
Features features((negative_features_collection_.size()==0?
0:negative_features_collection_.front().size()));
extract_interface_.compute(image, features);
if(learn_interface_.test(features)) negative_features_collection_.push_back(features);
}
private:
ExtractInterface & extract_interface_;
LearnInterface & learn_interface_;
std::vector<Features> & negative_features_collection_;
};
}
int main() {
const cv::Size window_size=cv::Size(128,72);
maav::HOGExtractor extractor(window_size);
maav::NeuralNet learner(3, 3, 5000000);
std::vector<maav::Features> features_collection;
std::vector<unsigned int> divider;
maav::FeatureExtractMethod extract_method(extractor, features_collection);
boost::function<void (const cv::Mat &)> f=boost::ref(extract_method);
maav::LoadEachFrameFromFile("pos1.mov", f);
for(unsigned int i=0;i<(features_collection.size()-divider.size());i++) {
divider.push_back(0);
}
extractor.scale_=false;
maav::LoadEachFrameFromFile("neg.mov", f);
learner.train(features_collection, divider);
learner.save("trained.dat");
}
<commit_msg>Include cereal!<commit_after>/*
* =====================================================================================
*
* Filename: main.cpp
*
* Description:
*
* Version: 1.0
* Created: 09/26/2015 18:25:55
* Revision: none
* Compiler: gcc
*
* Author: Il Jae Lee (iljae), iljae@umich.edu
* Organization: University of Michigan
*
* =====================================================================================
*/
#include "train.hpp"
#include "video.hpp"
#include "nnet.hpp"
#include "hog.hpp"
#include "cereal/archives/binary.hpp"
#include <iostream>
#include <fstream>
namespace maav {
class FeatureExtractMethod {
public:
FeatureExtractMethod(
ExtractInterface & extract_interface,
std::vector<Features> & features_collection
) :
extract_interface_(extract_interface),
features_collection_(features_collection) {}
void operator() (const cv::Mat & image) const {
std::cout << "Extracted features " << features_collection_.size() << "..." << std::endl;
Features features((features_collection_.size()==0?
0:features_collection_.front().size()));
extract_interface_.compute(image, features);
features_collection_.push_back(features);
}
private:
ExtractInterface & extract_interface_;
std::vector<Features> & features_collection_;
};
class NegativeMiningMethod {
public:
NegativeMiningMethod(
ExtractInterface & extract_interface,
LearnInterface & learn_interface,
std::vector<Features> & negative_features_collection
) :
extract_interface_(extract_interface),
learn_interface_(learn_interface),
negative_features_collection_(negative_features_collection) {}
void operator() (const cv::Mat & image) {
Features features((negative_features_collection_.size()==0?
0:negative_features_collection_.front().size()));
extract_interface_.compute(image, features);
if(learn_interface_.test(features)) negative_features_collection_.push_back(features);
}
private:
ExtractInterface & extract_interface_;
LearnInterface & learn_interface_;
std::vector<Features> & negative_features_collection_;
};
}
int main() {
const cv::Size window_size=cv::Size(128,72);
maav::HOGExtractor extractor(window_size);
maav::NeuralNet learner(3, 3, 5000000);
std::vector<maav::Features> features_collection;
std::vector<unsigned int> divider;
maav::FeatureExtractMethod extract_method(extractor, features_collection);
boost::function<void (const cv::Mat &)> f=boost::ref(extract_method);
maav::LoadEachFrameFromFile("/Users/iljae/Development/MHackers/data/positive.MOV", f);
for(unsigned int i=0;i<(features_collection.size()-divider.size());i++) {
divider.push_back(0);
}
std::cout << "Positive extraction is done!" << std::endl;
{
std::ofstream file_dump("/Users/iljae/Development/MHackers/data/features.dump", std::ofstream::binary);
cereal::BinaryOutputArchive oarchive(file_dump);
oarchive(features_collection, divider);
}
extractor.scale_=false;
maav::LoadEachFrameFromFile("/Users/iljae/Development/MHackers/data/negative.MOV", f);
learner.train(features_collection, divider);
learner.save("/Users/iljae/Development/MHackers/data/trained");
}
<|endoftext|> |
<commit_before>8e9fac46-2d14-11e5-af21-0401358ea401<commit_msg>8e9fac47-2d14-11e5-af21-0401358ea401<commit_after>8e9fac47-2d14-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>8e9fac04-2d14-11e5-af21-0401358ea401<commit_msg>8e9fac05-2d14-11e5-af21-0401358ea401<commit_after>8e9fac05-2d14-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>44f86b1c-5216-11e5-a651-6c40088e03e4<commit_msg>45034078-5216-11e5-a256-6c40088e03e4<commit_after>45034078-5216-11e5-a256-6c40088e03e4<|endoftext|> |
<commit_before>9a5fcc0c-35ca-11e5-9366-6c40088e03e4<commit_msg>9a678348-35ca-11e5-8794-6c40088e03e4<commit_after>9a678348-35ca-11e5-8794-6c40088e03e4<|endoftext|> |
<commit_before>836b8bb0-2e4f-11e5-a25a-28cfe91dbc4b<commit_msg>8372592e-2e4f-11e5-97e7-28cfe91dbc4b<commit_after>8372592e-2e4f-11e5-97e7-28cfe91dbc4b<|endoftext|> |
<commit_before>c73aa268-35ca-11e5-a644-6c40088e03e4<commit_msg>c7413df0-35ca-11e5-bfa5-6c40088e03e4<commit_after>c7413df0-35ca-11e5-bfa5-6c40088e03e4<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.