text
stringlengths 54
60.6k
|
---|
<commit_before>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
// $Id: molecularFileDialog.C,v 1.14 2003/03/20 16:26:44 anhi Exp $
#include <BALL/MOLVIEW/GUI/DIALOGS/molecularFileDialog.h>
#include <BALL/FORMAT/PDBFile.h>
#include <BALL/FORMAT/HINFile.h>
#include <BALL/FORMAT/MOLFile.h>
#include <BALL/FORMAT/MOL2File.h>
#include <BALL/VIEW/GUI/PRIMITIV/glsimpleBox.h>
#include <BALL/MATHS/box3.h>
#include <BALL/KERNEL/system.h>
using namespace BALL::VIEW;
namespace BALL
{
namespace MOLVIEW
{
MolecularFileDialog::MolecularFileDialog(QWidget *parent)
throw()
: QWidget(parent),
ModularWidget()
{
// register the widget with the MainControl
registerWidget(this);
hide();
}
MolecularFileDialog::~MolecularFileDialog()
throw()
{
#ifdef BALL_MOLVIEW_DEBUG
Log.error() << "Destructing object " << (void *)this
<< " of class MolecularFileDialog" << std::endl;
#endif
destroy();
}
void MolecularFileDialog::destroy()
throw()
{
}
void MolecularFileDialog::initializeWidget(MainControl& main_control)
throw()
{
main_control.insertMenuEntry(MainControl::FILE, "&Open...", (QObject *)this,
SLOT(readFile()), QFileDialog::CTRL+QFileDialog::Key_R);
main_control.insertMenuEntry(MainControl::FILE, "&Save As...", (QObject *)this,
SLOT(writeFile()), QFileDialog::CTRL+QFileDialog::Key_W);
}
void MolecularFileDialog::finalizeWidget(MainControl& main_control)
throw()
{
main_control.removeMenuEntry(MainControl::FILE, "&Read System", (QObject *)this,
SLOT(readFile()), QFileDialog::CTRL+QFileDialog::Key_R);
main_control.removeMenuEntry(MainControl::FILE, "&Write System", (QObject *)this,
SLOT(writeFile()), QFileDialog::CTRL+QFileDialog::Key_W);
}
void MolecularFileDialog::readFile()
{
// no throw specifier because of that #$%@* moc
if (MainControl::getMainControl(this) == 0) throw VIEW::MainControlMissing(__FILE__, __LINE__);
QFileDialog *fd = new QFileDialog(MainControl::getMainControl((QObject *)this), "Molecular File Dialog", true);
fd->setMode(QFileDialog::ExistingFile);
fd->setFilter("PDB Files (*.pdb *.brk *.ent)");
fd->addFilter("HIN Files (*.hin)");
fd->addFilter("MOL Files (*.mol)");
fd->addFilter("MOL2 Files (*.mol2)");
fd->setSelectedFilter(0);
fd->setCaption("Select a molecular file");
fd->setViewMode(QFileDialog::Detail);
fd->exec();
String filename(fd->selectedFile().latin1());
String filter(fd->selectedFilter().latin1());
bool ok = false;
try
{
if (File::isReadable(filename)) ok = true;
}
catch(...)
{}
if (!ok || filename == "/" || filename == "\\") return;
// construct a name for the system(the filename without the dir path)
QString qfilename = fd->selectedFile();
qfilename.remove(0, fd->dirPath().length() + 1);
if (qfilename.find('.') != -1)
{
qfilename = qfilename.left(qfilename.find('.'));
}
if (filter.hasSubstring("PDB"))
{
readPDBFile(filename, String(qfilename.latin1()));
}
else if (filter.hasSubstring("HIN"))
{
readHINFile(filename, String(qfilename.latin1()));
}
else if (filter.hasSubstring("MOL2"))
{
readMOL2File(filename, String(qfilename.latin1()));
}
else if (filter.hasSubstring("MOL"))
{
readMOLFile(filename, String(qfilename.latin1()));
}
}
bool MolecularFileDialog::writeFile()
{
// no throw specifier because of that #$%@* moc
if (MainControl::getMainControl(this) == 0) throw VIEW::MainControlMissing(__FILE__, __LINE__);
List<Composite*>& selection = MainControl::getMainControl(this)->getControlSelection();
if (selection.size() == 0 || !RTTI::isKindOf<System> (**selection.begin()))
{
Log.error() << "Not a single system selected! Aborting writing..." << std::endl;
return false;
}
setStatusbarText("writing PDB file...");
QFileDialog *fd = new QFileDialog(MainControl::getMainControl((QObject *)this), "Molecular File Dialog", true);
fd->setMode(QFileDialog::AnyFile);
fd->setFilter("PDB Files (*.pdb)");
fd->addFilter("HIN Files (*.hin)");
fd->addFilter("MOL Files (*.mol)");
fd->addFilter("MOL2 Files (*.mol2)");
fd->setSelectedFilter(0);
fd->setCaption("Select a filename for writing the system");
fd->setViewMode(QFileDialog::Detail);
fd->exec();
String filename(fd->selectedFile().latin1());
String filter(fd->selectedFilter().latin1());
if (filename == "/" || filename == "\\")
{
setStatusbarText("");
return false;
}
const System& system = *(const System*) (*selection.begin());
bool result = false;
if (filter.hasSubstring("PDB"))
{
result = writePDBFile(filename, system);
}
else if (filter.hasSubstring("HIN"))
{
result = writeHINFile(filename, system);
}
else if (filter.hasSubstring("MOL"))
{
result = writeMOLFile(filename, system);
}
else if (filter.hasSubstring("MOL2"))
{
result = writeMOL2File(filename, system);
}
if (!result)
{
return false;
}
Log.info() << "> " << system.countAtoms() << " atoms written to file \"" << filename << "\"" << std::endl;
setStatusbarText("");
return true;
}
bool MolecularFileDialog::writePDBFile(String filename, const System& system)
throw()
{
try
{
PDBFile file(filename, std::ios::out);
file << system;
file.close();
}
catch(...)
{
Log.info() << "> write PDB file failed." << std::endl;
return false;
}
return true;
}
bool MolecularFileDialog::writeHINFile(String filename, const System& system)
throw()
{
try
{
HINFile file(filename, std::ios::out);
file << system;
file.close();
}
catch(...)
{
Log.info() << "> write HIN file failed." << std::endl;
return false;
}
return true;
}
bool MolecularFileDialog::writeMOLFile(String filename, const System& system)
throw()
{
try
{
MOLFile file(filename, std::ios::out);
file << system;
file.close();
}
catch(...)
{
Log.info() << "> write MOL file failed." << std::endl;
return false;
}
return true;
}
bool MolecularFileDialog::writeMOL2File(String filename, const System& system)
throw()
{
try
{
MOL2File file(filename, std::ios::out);
file << system;
file.close();
}
catch(...)
{
Log.info() << "> write MOL2 file failed." << std::endl;
return false;
}
return true;
}
bool MolecularFileDialog::readPDBFile(String filename, String system_name)
throw()
{
setStatusbarText("reading PDB file...");
System* system = new System();
try
{
PDBFile pdb_file(filename);
pdb_file >> *system;
pdb_file.close();
}
catch(...)
{
Log.info() << "> read PDB file failed." << std::endl;
delete system;
return false;
}
return finish_(filename, system_name, system);
}
bool MolecularFileDialog::readHINFile(String filename, String system_name)
throw()
{
bool has_periodic_boundary = false;
Box3 bounding_box;
setStatusbarText("reading HIN file...");
System* system = new System();
try
{
HINFile hin_file(filename);
hin_file >> *system;
has_periodic_boundary = hin_file.hasPeriodicBoundary();
bounding_box = hin_file.getPeriodicBoundary();
hin_file.close();
}
catch(...)
{
Log.info() << "> read HIN file failed." << std::endl;
delete system;
return false;
}
// generating bounding box if exists
if (has_periodic_boundary)
{
GLSimpleBox* simple_box = new GLSimpleBox;
Vector3 first, second;
bounding_box.get(first.x, first.y, first.z, second.x, second.y, second.z);
Log.info() << "> creating bounding box (" << first << ", " << second << ")" << std::endl;
simple_box->setVertex1(first);
simple_box->setVertex2(second);
simple_box->setColor("ff0000a0");
simple_box->setName("BoundingBox");
simple_box->setProperty(BALL::VIEW::GeometricObject::PROPERTY__OBJECT_TRANSPARENT);
system->Composite::appendChild(*simple_box);
}
return finish_(filename, system_name, system);
}
bool MolecularFileDialog::readMOLFile(String filename, String system_name)
throw()
{
setStatusbarText("reading MOL file...");
System* system = new System();
try
{
MOLFile mol_file(filename);
mol_file >> *system;
mol_file.close();
}
catch(...)
{
Log.info() << "> read MOL file failed." << std::endl;
delete system;
return false;
}
return finish_(filename, system_name, system);
}
bool MolecularFileDialog::readMOL2File(String filename, String system_name)
throw()
{
setStatusbarText("reading MOL2 file...");
System* system = new System();
try
{
MOL2File mol2_file(filename);
mol2_file >> *system;
mol2_file.close();
}
catch(...)
{
Log.info() << "> read MOL2 file failed." << std::endl;
delete system;
return false;
}
return finish_(filename, system_name, system);
}
bool MolecularFileDialog::finish_(const String& filename, const String& system_name, System* system)
throw()
{
// writing info to log
Log.info() << "> read " << system->countAtoms() << " atoms from file \"" << filename<< "\"" << std::endl;
if (system->getName() == "")
{
system->setName(system_name);
}
// notify tree of a new composite
NewCompositeMessage* new_message = new NewCompositeMessage;
new_message->setDeletable(true);
new_message->setComposite(system);
new_message->setCompositeName(system_name);
notify_(new_message);
setStatusbarText("");
return true;
}
}
}
<commit_msg>Fixed MOL2 write<commit_after>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
// $Id: molecularFileDialog.C,v 1.15 2003/03/20 16:27:39 anhi Exp $
#include <BALL/MOLVIEW/GUI/DIALOGS/molecularFileDialog.h>
#include <BALL/FORMAT/PDBFile.h>
#include <BALL/FORMAT/HINFile.h>
#include <BALL/FORMAT/MOLFile.h>
#include <BALL/FORMAT/MOL2File.h>
#include <BALL/VIEW/GUI/PRIMITIV/glsimpleBox.h>
#include <BALL/MATHS/box3.h>
#include <BALL/KERNEL/system.h>
using namespace BALL::VIEW;
namespace BALL
{
namespace MOLVIEW
{
MolecularFileDialog::MolecularFileDialog(QWidget *parent)
throw()
: QWidget(parent),
ModularWidget()
{
// register the widget with the MainControl
registerWidget(this);
hide();
}
MolecularFileDialog::~MolecularFileDialog()
throw()
{
#ifdef BALL_MOLVIEW_DEBUG
Log.error() << "Destructing object " << (void *)this
<< " of class MolecularFileDialog" << std::endl;
#endif
destroy();
}
void MolecularFileDialog::destroy()
throw()
{
}
void MolecularFileDialog::initializeWidget(MainControl& main_control)
throw()
{
main_control.insertMenuEntry(MainControl::FILE, "&Open...", (QObject *)this,
SLOT(readFile()), QFileDialog::CTRL+QFileDialog::Key_R);
main_control.insertMenuEntry(MainControl::FILE, "&Save As...", (QObject *)this,
SLOT(writeFile()), QFileDialog::CTRL+QFileDialog::Key_W);
}
void MolecularFileDialog::finalizeWidget(MainControl& main_control)
throw()
{
main_control.removeMenuEntry(MainControl::FILE, "&Read System", (QObject *)this,
SLOT(readFile()), QFileDialog::CTRL+QFileDialog::Key_R);
main_control.removeMenuEntry(MainControl::FILE, "&Write System", (QObject *)this,
SLOT(writeFile()), QFileDialog::CTRL+QFileDialog::Key_W);
}
void MolecularFileDialog::readFile()
{
// no throw specifier because of that #$%@* moc
if (MainControl::getMainControl(this) == 0) throw VIEW::MainControlMissing(__FILE__, __LINE__);
QFileDialog *fd = new QFileDialog(MainControl::getMainControl((QObject *)this), "Molecular File Dialog", true);
fd->setMode(QFileDialog::ExistingFile);
fd->setFilter("PDB Files (*.pdb *.brk *.ent)");
fd->addFilter("HIN Files (*.hin)");
fd->addFilter("MOL Files (*.mol)");
fd->addFilter("MOL2 Files (*.mol2)");
fd->setSelectedFilter(0);
fd->setCaption("Select a molecular file");
fd->setViewMode(QFileDialog::Detail);
fd->exec();
String filename(fd->selectedFile().latin1());
String filter(fd->selectedFilter().latin1());
bool ok = false;
try
{
if (File::isReadable(filename)) ok = true;
}
catch(...)
{}
if (!ok || filename == "/" || filename == "\\") return;
// construct a name for the system(the filename without the dir path)
QString qfilename = fd->selectedFile();
qfilename.remove(0, fd->dirPath().length() + 1);
if (qfilename.find('.') != -1)
{
qfilename = qfilename.left(qfilename.find('.'));
}
if (filter.hasSubstring("PDB"))
{
readPDBFile(filename, String(qfilename.latin1()));
}
else if (filter.hasSubstring("HIN"))
{
readHINFile(filename, String(qfilename.latin1()));
}
else if (filter.hasSubstring("MOL2"))
{
readMOL2File(filename, String(qfilename.latin1()));
}
else if (filter.hasSubstring("MOL"))
{
readMOLFile(filename, String(qfilename.latin1()));
}
}
bool MolecularFileDialog::writeFile()
{
// no throw specifier because of that #$%@* moc
if (MainControl::getMainControl(this) == 0) throw VIEW::MainControlMissing(__FILE__, __LINE__);
List<Composite*>& selection = MainControl::getMainControl(this)->getControlSelection();
if (selection.size() == 0 || !RTTI::isKindOf<System> (**selection.begin()))
{
Log.error() << "Not a single system selected! Aborting writing..." << std::endl;
return false;
}
setStatusbarText("writing PDB file...");
QFileDialog *fd = new QFileDialog(MainControl::getMainControl((QObject *)this), "Molecular File Dialog", true);
fd->setMode(QFileDialog::AnyFile);
fd->setFilter("PDB Files (*.pdb)");
fd->addFilter("HIN Files (*.hin)");
fd->addFilter("MOL Files (*.mol)");
fd->addFilter("MOL2 Files (*.mol2)");
fd->setSelectedFilter(0);
fd->setCaption("Select a filename for writing the system");
fd->setViewMode(QFileDialog::Detail);
fd->exec();
String filename(fd->selectedFile().latin1());
String filter(fd->selectedFilter().latin1());
if (filename == "/" || filename == "\\")
{
setStatusbarText("");
return false;
}
const System& system = *(const System*) (*selection.begin());
bool result = false;
if (filter.hasSubstring("PDB"))
{
result = writePDBFile(filename, system);
}
else if (filter.hasSubstring("HIN"))
{
result = writeHINFile(filename, system);
}
else if (filter.hasSubstring("MOL2"))
{
result = writeMOL2File(filename, system);
}
else if (filter.hasSubstring("MOL"))
{
result = writeMOLFile(filename, system);
}
if (!result)
{
return false;
}
Log.info() << "> " << system.countAtoms() << " atoms written to file \"" << filename << "\"" << std::endl;
setStatusbarText("");
return true;
}
bool MolecularFileDialog::writePDBFile(String filename, const System& system)
throw()
{
try
{
PDBFile file(filename, std::ios::out);
file << system;
file.close();
}
catch(...)
{
Log.info() << "> write PDB file failed." << std::endl;
return false;
}
return true;
}
bool MolecularFileDialog::writeHINFile(String filename, const System& system)
throw()
{
try
{
HINFile file(filename, std::ios::out);
file << system;
file.close();
}
catch(...)
{
Log.info() << "> write HIN file failed." << std::endl;
return false;
}
return true;
}
bool MolecularFileDialog::writeMOLFile(String filename, const System& system)
throw()
{
try
{
MOLFile file(filename, std::ios::out);
file << system;
file.close();
}
catch(...)
{
Log.info() << "> write MOL file failed." << std::endl;
return false;
}
return true;
}
bool MolecularFileDialog::writeMOL2File(String filename, const System& system)
throw()
{
try
{
MOL2File file(filename, std::ios::out);
file << system;
file.close();
}
catch(...)
{
Log.info() << "> write MOL2 file failed." << std::endl;
return false;
}
return true;
}
bool MolecularFileDialog::readPDBFile(String filename, String system_name)
throw()
{
setStatusbarText("reading PDB file...");
System* system = new System();
try
{
PDBFile pdb_file(filename);
pdb_file >> *system;
pdb_file.close();
}
catch(...)
{
Log.info() << "> read PDB file failed." << std::endl;
delete system;
return false;
}
return finish_(filename, system_name, system);
}
bool MolecularFileDialog::readHINFile(String filename, String system_name)
throw()
{
bool has_periodic_boundary = false;
Box3 bounding_box;
setStatusbarText("reading HIN file...");
System* system = new System();
try
{
HINFile hin_file(filename);
hin_file >> *system;
has_periodic_boundary = hin_file.hasPeriodicBoundary();
bounding_box = hin_file.getPeriodicBoundary();
hin_file.close();
}
catch(...)
{
Log.info() << "> read HIN file failed." << std::endl;
delete system;
return false;
}
// generating bounding box if exists
if (has_periodic_boundary)
{
GLSimpleBox* simple_box = new GLSimpleBox;
Vector3 first, second;
bounding_box.get(first.x, first.y, first.z, second.x, second.y, second.z);
Log.info() << "> creating bounding box (" << first << ", " << second << ")" << std::endl;
simple_box->setVertex1(first);
simple_box->setVertex2(second);
simple_box->setColor("ff0000a0");
simple_box->setName("BoundingBox");
simple_box->setProperty(BALL::VIEW::GeometricObject::PROPERTY__OBJECT_TRANSPARENT);
system->Composite::appendChild(*simple_box);
}
return finish_(filename, system_name, system);
}
bool MolecularFileDialog::readMOLFile(String filename, String system_name)
throw()
{
setStatusbarText("reading MOL file...");
System* system = new System();
try
{
MOLFile mol_file(filename);
mol_file >> *system;
mol_file.close();
}
catch(...)
{
Log.info() << "> read MOL file failed." << std::endl;
delete system;
return false;
}
return finish_(filename, system_name, system);
}
bool MolecularFileDialog::readMOL2File(String filename, String system_name)
throw()
{
setStatusbarText("reading MOL2 file...");
System* system = new System();
try
{
MOL2File mol2_file(filename);
mol2_file >> *system;
mol2_file.close();
}
catch(...)
{
Log.info() << "> read MOL2 file failed." << std::endl;
delete system;
return false;
}
return finish_(filename, system_name, system);
}
bool MolecularFileDialog::finish_(const String& filename, const String& system_name, System* system)
throw()
{
// writing info to log
Log.info() << "> read " << system->countAtoms() << " atoms from file \"" << filename<< "\"" << std::endl;
if (system->getName() == "")
{
system->setName(system_name);
}
// notify tree of a new composite
NewCompositeMessage* new_message = new NewCompositeMessage;
new_message->setDeletable(true);
new_message->setComposite(system);
new_message->setCompositeName(system_name);
notify_(new_message);
setStatusbarText("");
return true;
}
}
}
<|endoftext|>
|
<commit_before>/***************************************************************************
filter_pmail.cxx - Pegasus-Mail import
-------------------
begin : Sat Jan 6 2001
copyright : (C) 2001 by Holger Schurig
email : [email protected]
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include <config.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <dirent.h>
#include <klocale.h>
#include <kfiledialog.h>
#include <kdirlister.h>
#include <qregexp.h>
#include "filter_pmail.hxx"
filter_pmail::filter_pmail() :
filter(i18n("Import folders from Pegasus-Mail (*.CNM, *.PMM, *.MBX)"),"Holger Schurig")
{
CAP=i18n("Import Pegasus-Mail");
}
filter_pmail::~filter_pmail()
{
}
void filter_pmail::import(filterInfo *info)
{
QString choosen;
QString msg;
if (!kmailStart(info)) { return; }
inf = info;
par = info->parent();
msg = i18n("Select the Pegasus-Mail directory on your system.\n\n"
"This import filter will import your folders, but not\n"
"the folder structure. But you'll probably only do\n"
"this one time ;-).\n\n"
"NOTE: Kmailcvt creates folders with the prefix 'pmail-'.\n"
"If this causes trouble to you (you've got kmail folders\n"
"with that prefix) cancel this import function (next dialog\n"
"will let you do that) and rename the existing kmail\n"
"folders."
);
info->alert(CAP,msg);
// Select directory from where I have to import files
sprintf(dir,getenv("HOME")); //lukas: noooooo! this breaks i18n, no sprintf please! use QDir instead
choosen=KFileDialog::getExistingDirectory(dir,par);
if (choosen.length()==0) { return; } // No directory choosen here!
strcpy(dir,choosen.latin1());
// Count total number of files to be processed
info->log(i18n("Counting files ..."));
totalFiles = countFiles(".cnm");
totalFiles += countFiles(".pmm");
totalFiles += countFiles(".mbx");
//msg=i18n("Searching for distribution lists ('.pml') ...");
//info->log(msg);
//totalFiles += countFiles(dir, "*.pml");
if (!kmailStart(info))
return;
info->log(i18n("Importing new mail files ('.cnm') ..."));
processFiles(".cnm", &importNewMessage);
info->log(i18n("Importing mail folders ('.pmm') ..."));
processFiles(".pmm", &importMailFolder);
info->log(i18n("Importing 'unix' mail folders ('.mbx') ..."));
processFiles(".mbx", &importUnixMailFolder);
kmailStop(info);
}
/** counts all files with mask (e.g. '*.cnm') in
in a directory */
int filter_pmail::countFiles(const char *mask)
{
DIR *d;
struct dirent *entry;
d = opendir(dir);
int n = 0;
entry=readdir(d);
while (entry!=NULL) {
char *file=entry->d_name;
if (strlen(file)>4 && strcasecmp(&file[strlen(file)-4],mask)==0)
n++;
entry=readdir(d);
}
closedir(d);
return n;
}
/** updates currentFile and the progress bar */
void filter_pmail::nextFile()
{
float perc;
currentFile++;
perc=(((float) currentFile)/((float) totalFiles))*100.0;
inf->overall(perc);
}
/** this looks for all files with the filemask 'mask' and calls the 'workFunc' on each of them */
void filter_pmail::processFiles(const char *mask, void(filter_pmail::* workFunc)(const char*) )
{
DIR *d;
struct dirent *entry;
d = opendir(dir);
entry=readdir(d);
while (entry!=NULL) {
char *file=entry->d_name;
if (strlen(file)>4 && strcasecmp(&file[strlen(file)-4],mask)==0) {
// Notify current file
QString msg;
msg = i18n("From: %1").arg(file);
inf->from(msg);
// Clear the other fields
msg = "";
inf->to(msg);
inf->current(msg);
inf->current(-1);
// combine dir and filename into a path
QString path = dir;
path.append("/");
path.append(file);
// call worker function, increase progressbar
(this->*workFunc)(path.latin1()); //lukas: noooooo! no .latin1() in paths!!!
nextFile();
}
entry=readdir(d);
}
closedir(d);
}
/** this function imports one *.CNM message */
void filter_pmail::importNewMessage(const char *file)
{
unsigned long added;
const char* destFolder = "PMail-New Messages";
QString msg;
msg = i18n("To: %1").arg(destFolder);
inf->to(msg);
kmailMessage((filterInfo *) inf, (char *)destFolder, (char *)file, added);
}
/** this function imports one mail folder file (*.PMM) */
void filter_pmail::importMailFolder(const char *file)
{
struct {
char folder[86];
char id[42];
} pmm_head;
FILE *f;
QString msg;
QString folder;
int ch = 0;
int state = 0;
int n = 0;
FILE *temp = NULL;
char tempname[128];
unsigned long added;
// Format of a PMM file:
// First comes a header with 128 bytes. At the beginning is the name of
// the folder. Then there are some unknown bytes (strings). At offset 128
// the first message starts.
//
// Each message is terminated by a 0x1A byte. The next message follows
// immediately.
//
// The last message is followed by a 0x1A, too.
//
// 000000 6d 61 69 6c 73 65 72 76 65 72 2d 70 72 6f 6a 65 mailserver-proje
// 000010 63 74 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ct..............
// 000020 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
// 000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
// 000040 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
// 000050 00 00 00 00 00 00 36 30 34 37 35 37 32 45 3a 36 ......6047572E:6
// 000060 46 34 39 3a 46 4f 4c 30 31 33 35 35 00 00 00 00 F49:FOL01355....
// 000070 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
// 000080 52 65 74 75 72 6e 2d 50 61 74 68 3a 20 3c 75 72 Return-Path: <ur
// ...
// 000cb0 2d 2d 2d 2d 2d 2d 2d 2d 2d 2b 0d 0a 1a 52 65 74 ---------+...Ret
// 000cc0 75 72 6e 2d 50 61 74 68 3a 20 3c 62 6f 75 6e 63 urn-Path: <bounc
// ...
// 04dc50 46 30 33 38 44 2e 36 31 35 44 37 34 44 30 2d 2d F038D.615D74D0--
// 04dc60 0d 0a 1a
// open the message
f = fopen(file, "rb");
// Get folder name
fread(&pmm_head, sizeof(pmm_head), 1, f);
folder = "PMail-";
folder.append(pmm_head.folder);
msg = i18n("To")+": "+folder;
inf->to(msg);
// The folder name might contain weird characters ...
folder.replace(QRegExp("[^a-zA-Z0-9:.-]"), ":");
// State machine to read the data in. The fgetc usage is probably terribly slow ...
while ((ch = fgetc(f)) >= 0) {
switch (state) {
// new message state
case 0:
// open temp output file
// XXX this is UGLY. Some people have the stuff in /var/tmp ...
// However, KTempFile is also ugly, because it does not return
// the full path of the created file (and creates it in the
// current directory) :-(
snprintf(tempname, sizeof(tempname), "/tmp/pmail_pmm.%d",getpid());
temp = fopen(tempname,"wb");
state = 1;
n++;
msg.sprintf("Message %d", n);
inf->current(msg);
// fall throught
// inside a message state
case 1:
if (ch == 0x1a) {
// close file, send it
fclose(temp);
kmailMessage((filterInfo *) inf, (char *)folder.latin1(), tempname, added);
unlink(tempname);
state = 0;
break;
}
if (ch == 0x0d) {
break;
}
fputc(ch, temp);
break;
}
}
// did Folder end without 0x1a at the end?
if (state != 0) {
fclose(temp);
kmailMessage((filterInfo *) inf, (char *)folder.latin1(), tempname, added);
unlink(tempname);
}
fclose(f);
}
/** imports a 'unix' format mail folder (*.MBX) */
void filter_pmail::importUnixMailFolder(const char *file)
{
#define MAX_LINE 4096
#define MSG_SEPERATOR_START "From "
#define MSG_SEPERATOR_REGEX "^From .*..:...*$"
static short msgSepLen = strlen(MSG_SEPERATOR_START);
struct {
char folder[58];
} pmg_head;
FILE *f;
QString s(file);
QString folder;
char line[MAX_LINE];
FILE *temp = NULL;
char tempname[128];
int n = 0;
QRegExp regexp(MSG_SEPERATOR_REGEX);
unsigned long added;
// Get folder name
s.replace( QRegExp("mbx$"), "pmg");
s.replace( QRegExp("MBX$"), "PMG");
f = fopen(s.latin1(), "rb"); //lukas: noooooo! no fopen nor .latin1() for files!!!
fread(&pmg_head, sizeof(pmg_head), 1, f);
fclose(f);
folder = "PMail-";
folder.append(pmg_head.folder);
inf->to(i18n("To")+": "+folder);
// The folder name might contain weird characters ...
folder.replace(QRegExp("[^a-zA-Z0-9:.-]"), ":");
// Read in the folder
//
// Messages are separated by "From " lines. We use a logic similar
// to KMail's kmfolder.cpp to find the boundaries.
snprintf(tempname, sizeof(tempname), "/tmp/pmail_mbx.%d",getpid());
f = fopen(file, "rb");
while (fgets(line, MAX_LINE, f)) {
// Look for separator
if (temp && // when we wrote to outfile
(strncmp(line,MSG_SEPERATOR_START, msgSepLen)==0 && // quick compar
regexp.match(line) >= 0)) // slower regexp
{
fclose(temp);
kmailMessage((filterInfo *) inf, (char *)folder.latin1(), tempname, added);
unlink(tempname);
temp = NULL;
}
// Do we need to open/reopen output file?
if (!temp) {
// XXX again, direct usage of '/tmp' is ugly, but again KTempFile is not good
// enought for us -- as of early Januar 2001
temp = fopen(tempname,"w");
// Notify progress
n++;
s.sprintf("Message %d", n);
inf->current(s);
}
fputs(line, temp);
}
if (temp) {
fclose(temp);
kmailMessage((filterInfo *) inf, (char *)folder.latin1(), tempname, added);
unlink(tempname);
}
fclose(f);
}
<commit_msg>filter_pmail.cxx:85: ISO C++ forbids taking the address of an unqualified non-static member function to form a pointer to member function. Say `&filter_pmail::importNewMessage'<commit_after>/***************************************************************************
filter_pmail.cxx - Pegasus-Mail import
-------------------
begin : Sat Jan 6 2001
copyright : (C) 2001 by Holger Schurig
email : [email protected]
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include <config.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <dirent.h>
#include <klocale.h>
#include <kfiledialog.h>
#include <kdirlister.h>
#include <qregexp.h>
#include "filter_pmail.hxx"
filter_pmail::filter_pmail() :
filter(i18n("Import folders from Pegasus-Mail (*.CNM, *.PMM, *.MBX)"),"Holger Schurig")
{
CAP=i18n("Import Pegasus-Mail");
}
filter_pmail::~filter_pmail()
{
}
void filter_pmail::import(filterInfo *info)
{
QString choosen;
QString msg;
if (!kmailStart(info)) { return; }
inf = info;
par = info->parent();
msg = i18n("Select the Pegasus-Mail directory on your system.\n\n"
"This import filter will import your folders, but not\n"
"the folder structure. But you'll probably only do\n"
"this one time ;-).\n\n"
"NOTE: Kmailcvt creates folders with the prefix 'pmail-'.\n"
"If this causes trouble to you (you've got kmail folders\n"
"with that prefix) cancel this import function (next dialog\n"
"will let you do that) and rename the existing kmail\n"
"folders."
);
info->alert(CAP,msg);
// Select directory from where I have to import files
sprintf(dir,getenv("HOME")); //lukas: noooooo! this breaks i18n, no sprintf please! use QDir instead
choosen=KFileDialog::getExistingDirectory(dir,par);
if (choosen.length()==0) { return; } // No directory choosen here!
strcpy(dir,choosen.latin1());
// Count total number of files to be processed
info->log(i18n("Counting files ..."));
totalFiles = countFiles(".cnm");
totalFiles += countFiles(".pmm");
totalFiles += countFiles(".mbx");
//msg=i18n("Searching for distribution lists ('.pml') ...");
//info->log(msg);
//totalFiles += countFiles(dir, "*.pml");
if (!kmailStart(info))
return;
info->log(i18n("Importing new mail files ('.cnm') ..."));
processFiles(".cnm", &filter_pmail::importNewMessage);
info->log(i18n("Importing mail folders ('.pmm') ..."));
processFiles(".pmm", &filter_pmail::importMailFolder);
info->log(i18n("Importing 'unix' mail folders ('.mbx') ..."));
processFiles(".mbx", &filter_pmail::importUnixMailFolder);
kmailStop(info);
}
/** counts all files with mask (e.g. '*.cnm') in
in a directory */
int filter_pmail::countFiles(const char *mask)
{
DIR *d;
struct dirent *entry;
d = opendir(dir);
int n = 0;
entry=readdir(d);
while (entry!=NULL) {
char *file=entry->d_name;
if (strlen(file)>4 && strcasecmp(&file[strlen(file)-4],mask)==0)
n++;
entry=readdir(d);
}
closedir(d);
return n;
}
/** updates currentFile and the progress bar */
void filter_pmail::nextFile()
{
float perc;
currentFile++;
perc=(((float) currentFile)/((float) totalFiles))*100.0;
inf->overall(perc);
}
/** this looks for all files with the filemask 'mask' and calls the 'workFunc' on each of them */
void filter_pmail::processFiles(const char *mask, void(filter_pmail::* workFunc)(const char*) )
{
DIR *d;
struct dirent *entry;
d = opendir(dir);
entry=readdir(d);
while (entry!=NULL) {
char *file=entry->d_name;
if (strlen(file)>4 && strcasecmp(&file[strlen(file)-4],mask)==0) {
// Notify current file
QString msg;
msg = i18n("From: %1").arg(file);
inf->from(msg);
// Clear the other fields
msg = "";
inf->to(msg);
inf->current(msg);
inf->current(-1);
// combine dir and filename into a path
QString path = dir;
path.append("/");
path.append(file);
// call worker function, increase progressbar
(this->*workFunc)(path.latin1()); //lukas: noooooo! no .latin1() in paths!!!
nextFile();
}
entry=readdir(d);
}
closedir(d);
}
/** this function imports one *.CNM message */
void filter_pmail::importNewMessage(const char *file)
{
unsigned long added;
const char* destFolder = "PMail-New Messages";
QString msg;
msg = i18n("To: %1").arg(destFolder);
inf->to(msg);
kmailMessage((filterInfo *) inf, (char *)destFolder, (char *)file, added);
}
/** this function imports one mail folder file (*.PMM) */
void filter_pmail::importMailFolder(const char *file)
{
struct {
char folder[86];
char id[42];
} pmm_head;
FILE *f;
QString msg;
QString folder;
int ch = 0;
int state = 0;
int n = 0;
FILE *temp = NULL;
char tempname[128];
unsigned long added;
// Format of a PMM file:
// First comes a header with 128 bytes. At the beginning is the name of
// the folder. Then there are some unknown bytes (strings). At offset 128
// the first message starts.
//
// Each message is terminated by a 0x1A byte. The next message follows
// immediately.
//
// The last message is followed by a 0x1A, too.
//
// 000000 6d 61 69 6c 73 65 72 76 65 72 2d 70 72 6f 6a 65 mailserver-proje
// 000010 63 74 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ct..............
// 000020 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
// 000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
// 000040 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
// 000050 00 00 00 00 00 00 36 30 34 37 35 37 32 45 3a 36 ......6047572E:6
// 000060 46 34 39 3a 46 4f 4c 30 31 33 35 35 00 00 00 00 F49:FOL01355....
// 000070 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
// 000080 52 65 74 75 72 6e 2d 50 61 74 68 3a 20 3c 75 72 Return-Path: <ur
// ...
// 000cb0 2d 2d 2d 2d 2d 2d 2d 2d 2d 2b 0d 0a 1a 52 65 74 ---------+...Ret
// 000cc0 75 72 6e 2d 50 61 74 68 3a 20 3c 62 6f 75 6e 63 urn-Path: <bounc
// ...
// 04dc50 46 30 33 38 44 2e 36 31 35 44 37 34 44 30 2d 2d F038D.615D74D0--
// 04dc60 0d 0a 1a
// open the message
f = fopen(file, "rb");
// Get folder name
fread(&pmm_head, sizeof(pmm_head), 1, f);
folder = "PMail-";
folder.append(pmm_head.folder);
msg = i18n("To")+": "+folder;
inf->to(msg);
// The folder name might contain weird characters ...
folder.replace(QRegExp("[^a-zA-Z0-9:.-]"), ":");
// State machine to read the data in. The fgetc usage is probably terribly slow ...
while ((ch = fgetc(f)) >= 0) {
switch (state) {
// new message state
case 0:
// open temp output file
// XXX this is UGLY. Some people have the stuff in /var/tmp ...
// However, KTempFile is also ugly, because it does not return
// the full path of the created file (and creates it in the
// current directory) :-(
snprintf(tempname, sizeof(tempname), "/tmp/pmail_pmm.%d",getpid());
temp = fopen(tempname,"wb");
state = 1;
n++;
msg.sprintf("Message %d", n);
inf->current(msg);
// fall throught
// inside a message state
case 1:
if (ch == 0x1a) {
// close file, send it
fclose(temp);
kmailMessage((filterInfo *) inf, (char *)folder.latin1(), tempname, added);
unlink(tempname);
state = 0;
break;
}
if (ch == 0x0d) {
break;
}
fputc(ch, temp);
break;
}
}
// did Folder end without 0x1a at the end?
if (state != 0) {
fclose(temp);
kmailMessage((filterInfo *) inf, (char *)folder.latin1(), tempname, added);
unlink(tempname);
}
fclose(f);
}
/** imports a 'unix' format mail folder (*.MBX) */
void filter_pmail::importUnixMailFolder(const char *file)
{
#define MAX_LINE 4096
#define MSG_SEPERATOR_START "From "
#define MSG_SEPERATOR_REGEX "^From .*..:...*$"
static short msgSepLen = strlen(MSG_SEPERATOR_START);
struct {
char folder[58];
} pmg_head;
FILE *f;
QString s(file);
QString folder;
char line[MAX_LINE];
FILE *temp = NULL;
char tempname[128];
int n = 0;
QRegExp regexp(MSG_SEPERATOR_REGEX);
unsigned long added;
// Get folder name
s.replace( QRegExp("mbx$"), "pmg");
s.replace( QRegExp("MBX$"), "PMG");
f = fopen(s.latin1(), "rb"); //lukas: noooooo! no fopen nor .latin1() for files!!!
fread(&pmg_head, sizeof(pmg_head), 1, f);
fclose(f);
folder = "PMail-";
folder.append(pmg_head.folder);
inf->to(i18n("To")+": "+folder);
// The folder name might contain weird characters ...
folder.replace(QRegExp("[^a-zA-Z0-9:.-]"), ":");
// Read in the folder
//
// Messages are separated by "From " lines. We use a logic similar
// to KMail's kmfolder.cpp to find the boundaries.
snprintf(tempname, sizeof(tempname), "/tmp/pmail_mbx.%d",getpid());
f = fopen(file, "rb");
while (fgets(line, MAX_LINE, f)) {
// Look for separator
if (temp && // when we wrote to outfile
(strncmp(line,MSG_SEPERATOR_START, msgSepLen)==0 && // quick compar
regexp.match(line) >= 0)) // slower regexp
{
fclose(temp);
kmailMessage((filterInfo *) inf, (char *)folder.latin1(), tempname, added);
unlink(tempname);
temp = NULL;
}
// Do we need to open/reopen output file?
if (!temp) {
// XXX again, direct usage of '/tmp' is ugly, but again KTempFile is not good
// enought for us -- as of early Januar 2001
temp = fopen(tempname,"w");
// Notify progress
n++;
s.sprintf("Message %d", n);
inf->current(s);
}
fputs(line, temp);
}
if (temp) {
fclose(temp);
kmailMessage((filterInfo *) inf, (char *)folder.latin1(), tempname, added);
unlink(tempname);
}
fclose(f);
}
<|endoftext|>
|
<commit_before>#include "player.h"
#include <cmath>
const double PI = 3.14159265358979323846264338329750288419716939937510582;
const double CROUCH_OFFSET = 0.30;
const double CRAWL_OFFSET = 0.70;
Player::Player() : Speed(0), Moving(false), Crouching(false), Crawling(false), Name("Untitled"), StandingOn(NULL), GravitySpeed(0.f), SurfaceZ(0.f), Entity(Vector3(0,0,0), Vector3(0,0,0), Vector3(0,0,0)) {};
Player::Player(float initspeed, Vector3 initrot, Vector3 initpos, std::string Name) : Speed(initspeed), Moving(false), Crouching(false), Crawling(false), Name(Name), StandingOn(NULL), GravitySpeed(0.f), SurfaceZ(0.f), Entity(initpos, initrot, Vector3(1, 1, 2)) {};
void Player::Forward(float amount)
{
Moving = true;
float xStep = Speed * sin((PI * Rotation.Z) / 180) * amount;
float yStep = Speed * cos((PI * Rotation.Z) / 180) * amount;
//float zStep = -Speed * sin((PI * Rotation.Y) / 180) * amount;
Pos.X += (xStep);// * cos((PI * Rotation.Y) / 180));
Pos.Y += (yStep);// * cos((PI * Rotation.Y) / 180));
//Z += zStep;
}
void Player::Strafe(float amount)
{
float yStep = Speed * sin((PI * Rotation.Z) / 180) * amount;
float xStep = Speed * cos((PI * Rotation.Z) / 180) * amount;
if(Moving == true)
{
xStep *= 0.707106;
yStep *= 0.707106;
}
Pos.X -= xStep;
Pos.Y += yStep;
}
void Player::ChangeRotation(float deltaYRotation, float deltaZRotation)
{
Rotation.Y += deltaYRotation;
Rotation.Z += deltaZRotation;
if(Rotation.Z >= 360)
Rotation.Z -= 360;
else if (Rotation.Z < 0)
Rotation.Z += 360;
if(Rotation.Y < -90)
Rotation.Y = -90;
else if(Rotation.Y >= 90)
Rotation.Y = 90;
}
void Player::Jump()
{
if (StandingOn) {
GravitySpeed = 5.f;
StandingOn = NULL;
Crouching = false;
}
}
void Player::Stand()
{
Crouching = false;
Crawling = false;
}
void Player::Crouch()
{
Crouching = true;
}
bool Player::toggleCrouch()
{
Crouching = !Crouching;
return Crouching;
}
void Player::Crawl()
{
Crawling = true;
}
bool Player::toggleCrawl()
{
Crawling = !Crawling;
return Crawling;
}
void Player::DoStep(float amount)
{
Moving = false;
if (!StandingOn)
{
GravitySpeed -= 9.8f * amount;
if (Pos.Z < 0) GravitySpeed = -GravitySpeed;
Pos.Z += GravitySpeed * amount;
}
else
{
GravitySpeed = 0.f;
Pos.Z = SurfaceZ;
Hitbox.Z = 2;
if (Crawling) {
Pos.Z -= CRAWL_OFFSET;
Hitbox.Z -= CRAWL_OFFSET;
} else if (Crouching) {
Pos.Z -= CROUCH_OFFSET;
Hitbox.Z -= CROUCH_OFFSET;
}
}
}
void Player::Render()
{
//TODO: Write me
}
<commit_msg>Improved crawling/crouching a bit<commit_after>#include "player.h"
#include <cmath>
const double PI = 3.14159265358979323846264338329750288419716939937510582;
const double CROUCH_OFFSET = 0.30;
const double CRAWL_OFFSET = 0.70;
Player::Player() : Speed(0), Moving(false), Crouching(false), Crawling(false), Name("Untitled"), StandingOn(NULL), GravitySpeed(0.f), SurfaceZ(0.f), Entity(Vector3(0,0,0), Vector3(0,0,0), Vector3(0,0,0)) {};
Player::Player(float initspeed, Vector3 initrot, Vector3 initpos, std::string Name) : Speed(initspeed), Moving(false), Crouching(false), Crawling(false), Name(Name), StandingOn(NULL), GravitySpeed(0.f), SurfaceZ(0.f), Entity(initpos, initrot, Vector3(1, 1, 2)) {};
void Player::Forward(float amount)
{
Moving = true;
float xStep = Speed * sin((PI * Rotation.Z) / 180) * amount;
float yStep = Speed * cos((PI * Rotation.Z) / 180) * amount;
//float zStep = -Speed * sin((PI * Rotation.Y) / 180) * amount;
Pos.X += (xStep);// * cos((PI * Rotation.Y) / 180));
Pos.Y += (yStep);// * cos((PI * Rotation.Y) / 180));
//Z += zStep;
}
void Player::Strafe(float amount)
{
float yStep = Speed * sin((PI * Rotation.Z) / 180) * amount;
float xStep = Speed * cos((PI * Rotation.Z) / 180) * amount;
if(Moving == true)
{
xStep *= 0.707106;
yStep *= 0.707106;
}
Pos.X -= xStep;
Pos.Y += yStep;
}
void Player::ChangeRotation(float deltaYRotation, float deltaZRotation)
{
Rotation.Y += deltaYRotation;
Rotation.Z += deltaZRotation;
if(Rotation.Z >= 360)
Rotation.Z -= 360;
else if (Rotation.Z < 0)
Rotation.Z += 360;
if(Rotation.Y < -90)
Rotation.Y = -90;
else if(Rotation.Y >= 90)
Rotation.Y = 90;
}
void Player::Jump()
{
if (StandingOn) {
GravitySpeed = 5.f;
StandingOn = NULL;
Crouching = false;
}
}
void Player::Stand()
{
Crouching = false;
Crawling = false;
}
void Player::Crouch()
{
Crouching = true;
Crawling = false;
}
bool Player::toggleCrouch()
{
if(Crouching)
Stand();
else
Crouch();
return Crouching;
}
void Player::Crawl()
{
Crouching = false;
Crawling = true;
}
bool Player::toggleCrawl()
{
if(Crawling)
Stand();
else
Crawl();
return Crawling;
}
void Player::DoStep(float amount)
{
Moving = false;
if (!StandingOn)
{
GravitySpeed -= 9.8f * amount;
if (Pos.Z < 0) GravitySpeed = -GravitySpeed;
Pos.Z += GravitySpeed * amount;
}
else
{
GravitySpeed = 0.f;
Pos.Z = SurfaceZ;
Hitbox.Z = 2;
if (Crawling) {
Pos.Z -= CRAWL_OFFSET;
Hitbox.Z -= CRAWL_OFFSET;
} else if (Crouching) {
Pos.Z -= CROUCH_OFFSET;
Hitbox.Z -= CROUCH_OFFSET;
}
}
}
void Player::Render()
{
//TODO: Write me
}
<|endoftext|>
|
<commit_before>#include "player.h"
#include "gamestate.h"
#include "datastructures.h"
#include "mccree.h"
Player::Player(Gamestate *state) : character(0)
{
;
}
Player::~Player()
{
;
}
void Player::midstep(Gamestate *state, double frametime)
{
;
}
void Player::clone(Gamestate *oldstate, Gamestate *newstate)
{
PlayerPtr p = newstate->make_player();
newstate->get(p)->character = character;
}
void Player::spawn(Gamestate *state, double x, double y)
{
if (character != 0)
{
// We already have a character, error and respawn
fprintf(stderr, "\nERROR: Tried to spawn character that was already alive.");
}
character = state->make_entity<Mccree>(state, PlayerPtr(id));
Character *c = static_cast<Character*>(state->get(character));
c->x = x;
c->y = y;
}
<commit_msg>Removed forgotten clone method.<commit_after>#include "player.h"
#include "gamestate.h"
#include "datastructures.h"
#include "mccree.h"
Player::Player(Gamestate *state) : character(0)
{
;
}
Player::~Player()
{
;
}
void Player::midstep(Gamestate *state, double frametime)
{
;
}
void Player::spawn(Gamestate *state, double x, double y)
{
if (character != 0)
{
// We already have a character, error and respawn
fprintf(stderr, "\nERROR: Tried to spawn character that was already alive.");
}
character = state->make_entity<Mccree>(state, PlayerPtr(id));
Character *c = static_cast<Character*>(state->get(character));
c->x = x;
c->y = y;
}
<|endoftext|>
|
<commit_before>//===- DeadStoreElimination.cpp - Dead Store Elimination ------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by Owen Anderson and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements a trivial dead store elimination that only considers
// basic-block local redundant stores.
//
// FIXME: This should eventually be extended to be a post-dominator tree
// traversal. Doing so would be pretty trivial.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "fdse"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Function.h"
#include "llvm/Instructions.h"
#include "llvm/Pass.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/Analysis/MemoryDependenceAnalysis.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Transforms/Utils/Local.h"
#include "llvm/Support/Compiler.h"
using namespace llvm;
STATISTIC(NumFastStores, "Number of stores deleted");
STATISTIC(NumFastOther , "Number of other instrs removed");
namespace {
struct VISIBILITY_HIDDEN FDSE : public FunctionPass {
static char ID; // Pass identification, replacement for typeid
FDSE() : FunctionPass((intptr_t)&ID) {}
virtual bool runOnFunction(Function &F) {
bool Changed = false;
for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
Changed |= runOnBasicBlock(*I);
return Changed;
}
bool runOnBasicBlock(BasicBlock &BB);
bool handleFreeWithNonTrivialDependency(FreeInst* F, StoreInst* dependency,
SetVector<Instruction*>& possiblyDead);
bool handleEndBlock(BasicBlock& BB, SetVector<Instruction*>& possiblyDead);
void DeleteDeadInstructionChains(Instruction *I,
SetVector<Instruction*> &DeadInsts);
// getAnalysisUsage - We require post dominance frontiers (aka Control
// Dependence Graph)
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesCFG();
AU.addRequired<TargetData>();
AU.addRequired<AliasAnalysis>();
AU.addRequired<MemoryDependenceAnalysis>();
AU.addPreserved<AliasAnalysis>();
AU.addPreserved<MemoryDependenceAnalysis>();
}
};
char FDSE::ID = 0;
RegisterPass<FDSE> X("fdse", "Fast Dead Store Elimination");
}
FunctionPass *llvm::createFastDeadStoreEliminationPass() { return new FDSE(); }
bool FDSE::runOnBasicBlock(BasicBlock &BB) {
MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
// Record the last-seen store to this pointer
DenseMap<Value*, StoreInst*> lastStore;
// Record instructions possibly made dead by deleting a store
SetVector<Instruction*> possiblyDead;
bool MadeChange = false;
// Do a top-down walk on the BB
for (BasicBlock::iterator BBI = BB.begin(), BBE = BB.end(); BBI != BBE; ++BBI) {
// If we find a store or a free...
if (isa<StoreInst>(BBI) || isa<FreeInst>(BBI)) {
Value* pointer = 0;
if (StoreInst* S = dyn_cast<StoreInst>(BBI))
pointer = S->getPointerOperand();
else if (FreeInst* F = dyn_cast<FreeInst>(BBI))
pointer = F->getPointerOperand();
assert(pointer && "Not a free or a store?");
StoreInst*& last = lastStore[pointer];
// ... to a pointer that has been stored to before...
if (last) {
// ... and no other memory dependencies are between them....
if (MD.getDependency(BBI) == last) {
// Remove it!
MD.removeInstruction(last);
// DCE instructions only used to calculate that store
if (Instruction* D = dyn_cast<Instruction>(last->getOperand(0)))
possiblyDead.insert(D);
last->eraseFromParent();
NumFastStores++;
MadeChange = true;
// If this is a free, check for a non-trivial dependency
} else if (FreeInst* F = dyn_cast<FreeInst>(BBI))
MadeChange |= handleFreeWithNonTrivialDependency(F, last, possiblyDead);
}
// Update our most-recent-store map
if (StoreInst* S = dyn_cast<StoreInst>(BBI))
last = S;
else
last = 0;
}
}
// Do a trivial DCE
while (!possiblyDead.empty()) {
Instruction *I = possiblyDead.back();
possiblyDead.pop_back();
DeleteDeadInstructionChains(I, possiblyDead);
}
return MadeChange;
}
/// handleFreeWithNonTrivialDependency - Handle frees of entire structures whose
/// dependency is a store to a field of that structure
bool FDSE::handleFreeWithNonTrivialDependency(FreeInst* F, StoreInst* dependency,
SetVector<Instruction*>& possiblyDead) {
TargetData &TD = getAnalysis<TargetData>();
AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
Value* depPointer = dependency->getPointerOperand();
unsigned depPointerSize = TD.getTypeSize(dependency->getOperand(0)->getType());
// Check for aliasing
AliasAnalysis::AliasResult A = AA.alias(F->getPointerOperand(), ~0UL,
depPointer, depPointerSize);
if (A == AliasAnalysis::MustAlias) {
// Remove it!
MD.removeInstruction(dependency);
// DCE instructions only used to calculate that store
if (Instruction* D = dyn_cast<Instruction>(dependency->getOperand(0)))
possiblyDead.insert(D);
dependency->eraseFromParent();
NumFastStores++;
return true;
}
return false;
}
void FDSE::DeleteDeadInstructionChains(Instruction *I,
SetVector<Instruction*> &DeadInsts) {
// Instruction must be dead.
if (!I->use_empty() || !isInstructionTriviallyDead(I)) return;
// Let the memory dependence know
getAnalysis<MemoryDependenceAnalysis>().removeInstruction(I);
// See if this made any operands dead. We do it this way in case the
// instruction uses the same operand twice. We don't want to delete a
// value then reference it.
for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
if (I->getOperand(i)->hasOneUse())
if (Instruction* Op = dyn_cast<Instruction>(I->getOperand(i)))
DeadInsts.insert(Op); // Attempt to nuke it later.
I->setOperand(i, 0); // Drop from the operand list.
}
I->eraseFromParent();
++NumFastOther;
}
<commit_msg>Make the condition-checking for free with non-trivial dependencies more correct.<commit_after>//===- DeadStoreElimination.cpp - Dead Store Elimination ------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by Owen Anderson and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements a trivial dead store elimination that only considers
// basic-block local redundant stores.
//
// FIXME: This should eventually be extended to be a post-dominator tree
// traversal. Doing so would be pretty trivial.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "fdse"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Function.h"
#include "llvm/Instructions.h"
#include "llvm/Pass.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/Analysis/MemoryDependenceAnalysis.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Transforms/Utils/Local.h"
#include "llvm/Support/Compiler.h"
using namespace llvm;
STATISTIC(NumFastStores, "Number of stores deleted");
STATISTIC(NumFastOther , "Number of other instrs removed");
namespace {
struct VISIBILITY_HIDDEN FDSE : public FunctionPass {
static char ID; // Pass identification, replacement for typeid
FDSE() : FunctionPass((intptr_t)&ID) {}
virtual bool runOnFunction(Function &F) {
bool Changed = false;
for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
Changed |= runOnBasicBlock(*I);
return Changed;
}
bool runOnBasicBlock(BasicBlock &BB);
bool handleFreeWithNonTrivialDependency(FreeInst* F, Instruction* dependency,
SetVector<Instruction*>& possiblyDead);
void DeleteDeadInstructionChains(Instruction *I,
SetVector<Instruction*> &DeadInsts);
// getAnalysisUsage - We require post dominance frontiers (aka Control
// Dependence Graph)
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesCFG();
AU.addRequired<TargetData>();
AU.addRequired<AliasAnalysis>();
AU.addRequired<MemoryDependenceAnalysis>();
AU.addPreserved<AliasAnalysis>();
AU.addPreserved<MemoryDependenceAnalysis>();
}
};
char FDSE::ID = 0;
RegisterPass<FDSE> X("fdse", "Fast Dead Store Elimination");
}
FunctionPass *llvm::createFastDeadStoreEliminationPass() { return new FDSE(); }
bool FDSE::runOnBasicBlock(BasicBlock &BB) {
MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
// Record the last-seen store to this pointer
DenseMap<Value*, StoreInst*> lastStore;
// Record instructions possibly made dead by deleting a store
SetVector<Instruction*> possiblyDead;
bool MadeChange = false;
// Do a top-down walk on the BB
for (BasicBlock::iterator BBI = BB.begin(), BBE = BB.end(); BBI != BBE; ++BBI) {
// If we find a store or a free...
if (isa<StoreInst>(BBI) || isa<FreeInst>(BBI)) {
Value* pointer = 0;
if (StoreInst* S = dyn_cast<StoreInst>(BBI))
pointer = S->getPointerOperand();
else if (FreeInst* F = dyn_cast<FreeInst>(BBI))
pointer = F->getPointerOperand();
assert(pointer && "Not a free or a store?");
StoreInst*& last = lastStore[pointer];
bool deletedStore = false;
// ... to a pointer that has been stored to before...
if (last) {
// ... and no other memory dependencies are between them....
if (MD.getDependency(BBI) == last) {
// Remove it!
MD.removeInstruction(last);
// DCE instructions only used to calculate that store
if (Instruction* D = dyn_cast<Instruction>(last->getOperand(0)))
possiblyDead.insert(D);
last->eraseFromParent();
NumFastStores++;
deletedStore = true;
MadeChange = true;
}
}
// Handle frees whose dependencies are non-trivial
if (FreeInst* F = dyn_cast<FreeInst>(BBI))
if (!deletedStore)
MadeChange |= handleFreeWithNonTrivialDependency(F, MD.getDependency(F),
possiblyDead);
// Update our most-recent-store map
if (StoreInst* S = dyn_cast<StoreInst>(BBI))
last = S;
else
last = 0;
}
}
// Do a trivial DCE
while (!possiblyDead.empty()) {
Instruction *I = possiblyDead.back();
possiblyDead.pop_back();
DeleteDeadInstructionChains(I, possiblyDead);
}
return MadeChange;
}
/// handleFreeWithNonTrivialDependency - Handle frees of entire structures whose
/// dependency is a store to a field of that structure
bool FDSE::handleFreeWithNonTrivialDependency(FreeInst* F, Instruction* dep,
SetVector<Instruction*>& possiblyDead) {
TargetData &TD = getAnalysis<TargetData>();
AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
if (dep == MemoryDependenceAnalysis::None ||
dep == MemoryDependenceAnalysis::NonLocal)
return false;
StoreInst* dependency = dyn_cast<StoreInst>(dep);
if (!dependency)
return false;
Value* depPointer = dependency->getPointerOperand();
unsigned depPointerSize = TD.getTypeSize(dependency->getOperand(0)->getType());
// Check for aliasing
AliasAnalysis::AliasResult A = AA.alias(F->getPointerOperand(), ~0UL,
depPointer, depPointerSize);
if (A == AliasAnalysis::MustAlias) {
// Remove it!
MD.removeInstruction(dependency);
// DCE instructions only used to calculate that store
if (Instruction* D = dyn_cast<Instruction>(dependency->getOperand(0)))
possiblyDead.insert(D);
dependency->eraseFromParent();
NumFastStores++;
return true;
}
return false;
}
void FDSE::DeleteDeadInstructionChains(Instruction *I,
SetVector<Instruction*> &DeadInsts) {
// Instruction must be dead.
if (!I->use_empty() || !isInstructionTriviallyDead(I)) return;
// Let the memory dependence know
getAnalysis<MemoryDependenceAnalysis>().removeInstruction(I);
// See if this made any operands dead. We do it this way in case the
// instruction uses the same operand twice. We don't want to delete a
// value then reference it.
for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
if (I->getOperand(i)->hasOneUse())
if (Instruction* Op = dyn_cast<Instruction>(I->getOperand(i)))
DeadInsts.insert(Op); // Attempt to nuke it later.
I->setOperand(i, 0); // Drop from the operand list.
}
I->eraseFromParent();
++NumFastOther;
}
<|endoftext|>
|
<commit_before>// SA:MP Profiler plugin
//
// Copyright (c) 2011 Zeex
//
// 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 <algorithm>
#include <cerrno>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iterator>
#include <list>
#include <map>
#include <sstream>
#include <string>
#include <vector>
#include "amx_name.h"
#include "config_reader.h"
#include "debug_info.h"
#include "html_printer.h"
#include "jump_x86.h"
#include "plugin.h"
#include "profiler.h"
#include "text_printer.h"
#include "version.h"
#include "xml_printer.h"
#include "amx/amx.h"
using namespace samp_profiler;
extern void *pAMXFunctions;
namespace {
typedef void (*logprintf_t)(const char *format, ...);
logprintf_t logprintf;
// Symbolic info, used for getting function names
std::map<AMX*, DebugInfo> debugInfos;
// x86 is Little Endian...
void *AMXAPI DummyAmxAlign(void *v) { return v; }
JumpX86 ExecHook;
JumpX86 CallbackHook;
int AMXAPI Exec(AMX *amx, cell *retval, int index) {
ExecHook.Remove();
CallbackHook.Install(); // P-code may call natives
// Return code
int error = AMX_ERR_NONE;
// Check if this script has a profiler attached to it
Profiler *prof = Profiler::Get(amx);
if (prof != 0) {
error = prof->Exec(retval, index);
} else {
error = amx_Exec(amx, retval, index);
}
CallbackHook.Remove();
ExecHook.Install();
return error;
}
int AMXAPI Callback(AMX *amx, cell index, cell *result, cell *params) {
CallbackHook.Remove();
ExecHook.Install(); // Natives may call amx_Exec()
// The default AMX callback (amx_Callback) can replace SYSREQ.C opcodes
// with SYSREQ.D for better performance.
amx->sysreq_d = 0;
// Return code
int error = AMX_ERR_NONE;
// Check if this script has a profiler attached to it
Profiler *prof = Profiler::Get(amx);
if (prof != 0) {
error = prof->Callback(index, result, params);
} else {
error = amx_Callback(amx, index, result, params);
}
ExecHook.Remove();
CallbackHook.Install();
return error;
}
// Replaces back slashes with forward slashes
std::string ToPortablePath(const std::string &path) {
std::string fsPath = path;
std::replace(fsPath.begin(), fsPath.end(), '\\', '/');
return fsPath;
}
bool IsGameMode(const std::string &amxName) {
return ToPortablePath(amxName).find("gamemodes/") != std::string::npos;
}
bool IsFilterScript(const std::string &amxName) {
return ToPortablePath(amxName).find("filterscripts/") != std::string::npos;
}
// Returns true if the .amx should be profiled
bool WantsProfiler(const std::string &amxName) {
std::string goodAmxName = ToPortablePath(amxName);
// This only works if they place their gamemodes and filterscripts in default directories.
// Someting like ../my_scripts/awesome_script.amx obviously won't work.
ConfigReader server_cfg("server.cfg");
if (IsGameMode(amxName)) {
// This is a gamemode
if (server_cfg.GetOption("profile_gamemode", false)) {
return true;
}
} else if (IsFilterScript(amxName)) {
std::string fsList = server_cfg.GetOption("profile_filterscripts", std::string(""));
std::stringstream fsStream(fsList);
do {
std::string fsName;
fsStream >> fsName;
if (goodAmxName == "filterscripts/" + fsName + ".amx"
|| goodAmxName == "filterscripts/" + fsName) {
return true;
}
} while (!fsStream.eof());
}
return false;
}
} // namespace
PLUGIN_EXPORT unsigned int PLUGIN_CALL Supports() {
return SUPPORTS_VERSION | SUPPORTS_AMX_NATIVES;
}
PLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppData) {
pAMXFunctions = ppData[PLUGIN_DATA_AMX_EXPORTS];
logprintf = (logprintf_t)ppData[PLUGIN_DATA_LOGPRINTF];
// The server does not export amx_Align* for some reason.
// They are used in amxdbg.c and amxaux.c, so they must be callable.
((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Align16] = (void*)DummyAmxAlign; // amx_Align16
((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Align32] = (void*)DummyAmxAlign; // amx_Align32
((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Align64] = (void*)DummyAmxAlign; // amx_Align64
ExecHook.Install(
((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Exec],
(void*)::Exec);
CallbackHook.Install(
((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Callback],
(void*)::Callback);
logprintf(" Profiler plugin "VERSION_STRING" is OK.");
return true;
}
PLUGIN_EXPORT void PLUGIN_CALL Unload() {
return;
}
PLUGIN_EXPORT int PLUGIN_CALL AmxLoad(AMX *amx) {
std::string filename = GetAmxName(amx);
if (filename.empty()) {
logprintf("Profiler: Failed to detect .amx name, prifiling will not be done");
return AMX_ERR_NONE;
}
if (!Profiler::IsScriptProfilable(amx)) {
logprintf("Profiler: Can't profile script %s (are you using -d0?)", filename.c_str());
return AMX_ERR_NONE;
}
if (WantsProfiler(filename)) {
if (DebugInfo::HasDebugInfo(amx)) {
DebugInfo debugInfo;
debugInfo.Load(filename);
if (debugInfo.IsLoaded()) {
logprintf("Profiler: Loaded debug info from %s", filename.c_str());
::debugInfos[amx] = debugInfo;
Profiler::Attach(amx, debugInfo);
logprintf("Profiler: Attached profiler instance to %s", filename.c_str());
return AMX_ERR_NONE;
} else {
logprintf("Profiler: Error loading debug info from %s", filename.c_str());
}
}
Profiler::Attach(amx);
logprintf("Profiler: Attached profiler instance to %s (no debug symbols)", filename.c_str());
}
return AMX_ERR_NONE;
}
PLUGIN_EXPORT int PLUGIN_CALL AmxUnload(AMX *amx) {
// Get an instance of Profiler attached to the unloading AMX
Profiler *prof = Profiler::Get(amx);
// Detach profiler
if (prof != 0) {
std::string amx_path = GetAmxName(amx);
std::string amx_name = std::string(amx_path, 0, amx_path.find_last_of("."));
// Output stats depending on currently set output_format
ConfigReader server_cfg("server.cfg");
std::string format =
server_cfg.GetOption("profile_format", std::string("html"));
std::ofstream ostream;
AbstractPrinter *printer = 0;
if (format == "html") {
ostream.open(amx_name + "-profile.html");
printer = new HtmlPrinter;
} else if (format == "text") {
ostream.open(amx_name + "-profile.txt");
printer = new TextPrinter;
} else if (format == "xml") {
ostream.open(amx_name + "-profile.xml");
printer = new XmlPrinter;
} else {
logprintf("Profiler: Unknown output format '%s'", format.c_str());
}
prof->PrintStats(ostream, printer);
delete printer;
Profiler::Detach(amx);
}
// Free debug info
std::map<AMX*, DebugInfo>::iterator it = ::debugInfos.find(amx);
if (it != ::debugInfos.end()) {
it->second.Free();
::debugInfos.erase(it);
}
return AMX_ERR_NONE;
}
<commit_msg>Fix "no matching function to call" error on ofstream.open()<commit_after>// SA:MP Profiler plugin
//
// Copyright (c) 2011 Zeex
//
// 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 <algorithm>
#include <cerrno>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iterator>
#include <list>
#include <map>
#include <sstream>
#include <string>
#include <vector>
#include "amx_name.h"
#include "config_reader.h"
#include "debug_info.h"
#include "html_printer.h"
#include "jump_x86.h"
#include "plugin.h"
#include "profiler.h"
#include "text_printer.h"
#include "version.h"
#include "xml_printer.h"
#include "amx/amx.h"
using namespace samp_profiler;
extern void *pAMXFunctions;
namespace {
typedef void (*logprintf_t)(const char *format, ...);
logprintf_t logprintf;
// Symbolic info, used for getting function names
std::map<AMX*, DebugInfo> debugInfos;
// x86 is Little Endian...
void *AMXAPI DummyAmxAlign(void *v) { return v; }
JumpX86 ExecHook;
JumpX86 CallbackHook;
int AMXAPI Exec(AMX *amx, cell *retval, int index) {
ExecHook.Remove();
CallbackHook.Install(); // P-code may call natives
// Return code
int error = AMX_ERR_NONE;
// Check if this script has a profiler attached to it
Profiler *prof = Profiler::Get(amx);
if (prof != 0) {
error = prof->Exec(retval, index);
} else {
error = amx_Exec(amx, retval, index);
}
CallbackHook.Remove();
ExecHook.Install();
return error;
}
int AMXAPI Callback(AMX *amx, cell index, cell *result, cell *params) {
CallbackHook.Remove();
ExecHook.Install(); // Natives may call amx_Exec()
// The default AMX callback (amx_Callback) can replace SYSREQ.C opcodes
// with SYSREQ.D for better performance.
amx->sysreq_d = 0;
// Return code
int error = AMX_ERR_NONE;
// Check if this script has a profiler attached to it
Profiler *prof = Profiler::Get(amx);
if (prof != 0) {
error = prof->Callback(index, result, params);
} else {
error = amx_Callback(amx, index, result, params);
}
ExecHook.Remove();
CallbackHook.Install();
return error;
}
// Replaces back slashes with forward slashes
std::string ToPortablePath(const std::string &path) {
std::string fsPath = path;
std::replace(fsPath.begin(), fsPath.end(), '\\', '/');
return fsPath;
}
bool IsGameMode(const std::string &amxName) {
return ToPortablePath(amxName).find("gamemodes/") != std::string::npos;
}
bool IsFilterScript(const std::string &amxName) {
return ToPortablePath(amxName).find("filterscripts/") != std::string::npos;
}
// Returns true if the .amx should be profiled
bool WantsProfiler(const std::string &amxName) {
std::string goodAmxName = ToPortablePath(amxName);
// This only works if they place their gamemodes and filterscripts in default directories.
// Someting like ../my_scripts/awesome_script.amx obviously won't work.
ConfigReader server_cfg("server.cfg");
if (IsGameMode(amxName)) {
// This is a gamemode
if (server_cfg.GetOption("profile_gamemode", false)) {
return true;
}
} else if (IsFilterScript(amxName)) {
std::string fsList = server_cfg.GetOption("profile_filterscripts", std::string(""));
std::stringstream fsStream(fsList);
do {
std::string fsName;
fsStream >> fsName;
if (goodAmxName == "filterscripts/" + fsName + ".amx"
|| goodAmxName == "filterscripts/" + fsName) {
return true;
}
} while (!fsStream.eof());
}
return false;
}
} // namespace
PLUGIN_EXPORT unsigned int PLUGIN_CALL Supports() {
return SUPPORTS_VERSION | SUPPORTS_AMX_NATIVES;
}
PLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppData) {
pAMXFunctions = ppData[PLUGIN_DATA_AMX_EXPORTS];
logprintf = (logprintf_t)ppData[PLUGIN_DATA_LOGPRINTF];
// The server does not export amx_Align* for some reason.
// They are used in amxdbg.c and amxaux.c, so they must be callable.
((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Align16] = (void*)DummyAmxAlign; // amx_Align16
((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Align32] = (void*)DummyAmxAlign; // amx_Align32
((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Align64] = (void*)DummyAmxAlign; // amx_Align64
ExecHook.Install(
((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Exec],
(void*)::Exec);
CallbackHook.Install(
((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Callback],
(void*)::Callback);
logprintf(" Profiler plugin "VERSION_STRING" is OK.");
return true;
}
PLUGIN_EXPORT void PLUGIN_CALL Unload() {
return;
}
PLUGIN_EXPORT int PLUGIN_CALL AmxLoad(AMX *amx) {
std::string filename = GetAmxName(amx);
if (filename.empty()) {
logprintf("Profiler: Failed to detect .amx name, prifiling will not be done");
return AMX_ERR_NONE;
}
if (!Profiler::IsScriptProfilable(amx)) {
logprintf("Profiler: Can't profile script %s (are you using -d0?)", filename.c_str());
return AMX_ERR_NONE;
}
if (WantsProfiler(filename)) {
if (DebugInfo::HasDebugInfo(amx)) {
DebugInfo debugInfo;
debugInfo.Load(filename);
if (debugInfo.IsLoaded()) {
logprintf("Profiler: Loaded debug info from %s", filename.c_str());
::debugInfos[amx] = debugInfo;
Profiler::Attach(amx, debugInfo);
logprintf("Profiler: Attached profiler instance to %s", filename.c_str());
return AMX_ERR_NONE;
} else {
logprintf("Profiler: Error loading debug info from %s", filename.c_str());
}
}
Profiler::Attach(amx);
logprintf("Profiler: Attached profiler instance to %s (no debug symbols)", filename.c_str());
}
return AMX_ERR_NONE;
}
PLUGIN_EXPORT int PLUGIN_CALL AmxUnload(AMX *amx) {
// Get an instance of Profiler attached to the unloading AMX
Profiler *prof = Profiler::Get(amx);
// Detach profiler
if (prof != 0) {
std::string amx_path = GetAmxName(amx);
std::string amx_name = std::string(amx_path, 0, amx_path.find_last_of("."));
// Output stats depending on currently set output_format
ConfigReader server_cfg("server.cfg");
std::string format =
server_cfg.GetOption("profile_format", std::string("html"));
std::string filename;
AbstractPrinter *printer = 0;
if (format == "html") {
filename = amx_name + "-profile.html";
printer = new HtmlPrinter;
} else if (format == "text") {
filename = amx_name + "-profile.txt";
printer = new TextPrinter;
} else if (format == "xml") {
filename = amx_name + "-profile.xml";
printer = new XmlPrinter;
} else {
logprintf("Profiler: Unknown output format '%s'", format.c_str());
}
std::ofstream ostream(filename.c_str());
prof->PrintStats(ostream, printer);
delete printer;
Profiler::Detach(amx);
}
// Free debug info
std::map<AMX*, DebugInfo>::iterator it = ::debugInfos.find(amx);
if (it != ::debugInfos.end()) {
it->second.Free();
::debugInfos.erase(it);
}
return AMX_ERR_NONE;
}
<|endoftext|>
|
<commit_before>//===- Reg2Mem.cpp - Convert registers to allocas -------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file demotes all registers to memory references. It is intented to be
// the inverse of PromoteMemoryToRegister. By converting to loads, the only
// values live accross basic blocks are allocas and loads before phi nodes.
// It is intended that this should make CFG hacking much easier.
// To make later hacking easier, the entry block is split into two, such that
// all introduced allocas and nothing else are in the entry block.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "reg2mem"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Utils/Local.h"
#include "llvm/Pass.h"
#include "llvm/Function.h"
#include "llvm/LLVMContext.h"
#include "llvm/Module.h"
#include "llvm/BasicBlock.h"
#include "llvm/Instructions.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Support/CFG.h"
#include <list>
using namespace llvm;
STATISTIC(NumRegsDemoted, "Number of registers demoted");
STATISTIC(NumPhisDemoted, "Number of phi-nodes demoted");
namespace {
struct RegToMem : public FunctionPass {
static char ID; // Pass identification, replacement for typeid
RegToMem() : FunctionPass(&ID) {}
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequiredID(BreakCriticalEdgesID);
AU.addPreservedID(BreakCriticalEdgesID);
}
bool valueEscapes(Instruction* i) {
BasicBlock* bb = i->getParent();
for (Value::use_iterator ii = i->use_begin(), ie = i->use_end();
ii != ie; ++ii)
if (cast<Instruction>(*ii)->getParent() != bb ||
isa<PHINode>(*ii))
return true;
return false;
}
virtual bool runOnFunction(Function &F) {
if (!F.isDeclaration()) {
// Insert all new allocas into entry block.
BasicBlock* BBEntry = &F.getEntryBlock();
assert(pred_begin(BBEntry) == pred_end(BBEntry) &&
"Entry block to function must not have predecessors!");
// Find first non-alloca instruction and create insertion point. This is
// safe if block is well-formed: it always have terminator, otherwise
// we'll get and assertion.
BasicBlock::iterator I = BBEntry->begin();
while (isa<AllocaInst>(I)) ++I;
CastInst *AllocaInsertionPoint =
CastInst::Create(Instruction::BitCast,
Constant::getNullValue(Type::getInt32Ty(F.getContext())),
Type::getInt32Ty(F.getContext()),
"reg2mem alloca point", I);
// Find the escaped instructions. But don't create stack slots for
// allocas in entry block.
std::list<Instruction*> worklist;
for (Function::iterator ibb = F.begin(), ibe = F.end();
ibb != ibe; ++ibb)
for (BasicBlock::iterator iib = ibb->begin(), iie = ibb->end();
iib != iie; ++iib) {
if (!(isa<AllocaInst>(iib) && iib->getParent() == BBEntry) &&
valueEscapes(iib)) {
worklist.push_front(&*iib);
}
}
// Demote escaped instructions
NumRegsDemoted += worklist.size();
for (std::list<Instruction*>::iterator ilb = worklist.begin(),
ile = worklist.end(); ilb != ile; ++ilb)
DemoteRegToStack(**ilb, false, AllocaInsertionPoint);
worklist.clear();
// Find all phi's
for (Function::iterator ibb = F.begin(), ibe = F.end();
ibb != ibe; ++ibb)
for (BasicBlock::iterator iib = ibb->begin(), iie = ibb->end();
iib != iie; ++iib)
if (isa<PHINode>(iib))
worklist.push_front(&*iib);
// Demote phi nodes
NumPhisDemoted += worklist.size();
for (std::list<Instruction*>::iterator ilb = worklist.begin(),
ile = worklist.end(); ilb != ile; ++ilb)
DemotePHIToStack(cast<PHINode>(*ilb), AllocaInsertionPoint);
return true;
}
return false;
}
};
}
char RegToMem::ID = 0;
static RegisterPass<RegToMem>
X("reg2mem", "Demote all values to stack slots");
// createDemoteRegisterToMemory - Provide an entry point to create this pass.
//
const PassInfo *const llvm::DemoteRegisterToMemoryID = &X;
FunctionPass *llvm::createDemoteRegisterToMemoryPass() {
return new RegToMem();
}
<commit_msg>clean up this code a bit.<commit_after>//===- Reg2Mem.cpp - Convert registers to allocas -------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file demotes all registers to memory references. It is intented to be
// the inverse of PromoteMemoryToRegister. By converting to loads, the only
// values live accross basic blocks are allocas and loads before phi nodes.
// It is intended that this should make CFG hacking much easier.
// To make later hacking easier, the entry block is split into two, such that
// all introduced allocas and nothing else are in the entry block.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "reg2mem"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Utils/Local.h"
#include "llvm/Pass.h"
#include "llvm/Function.h"
#include "llvm/LLVMContext.h"
#include "llvm/Module.h"
#include "llvm/BasicBlock.h"
#include "llvm/Instructions.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Support/CFG.h"
#include <list>
using namespace llvm;
STATISTIC(NumRegsDemoted, "Number of registers demoted");
STATISTIC(NumPhisDemoted, "Number of phi-nodes demoted");
namespace {
struct RegToMem : public FunctionPass {
static char ID; // Pass identification, replacement for typeid
RegToMem() : FunctionPass(&ID) {}
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequiredID(BreakCriticalEdgesID);
AU.addPreservedID(BreakCriticalEdgesID);
}
bool valueEscapes(const Instruction *Inst) const {
const BasicBlock *BB = Inst->getParent();
for (Value::use_const_iterator UI = Inst->use_begin(),E = Inst->use_end();
UI != E; ++UI)
if (cast<Instruction>(*UI)->getParent() != BB ||
isa<PHINode>(*UI))
return true;
return false;
}
virtual bool runOnFunction(Function &F);
};
}
char RegToMem::ID = 0;
static RegisterPass<RegToMem>
X("reg2mem", "Demote all values to stack slots");
bool RegToMem::runOnFunction(Function &F) {
if (F.isDeclaration())
return false;
// Insert all new allocas into entry block.
BasicBlock *BBEntry = &F.getEntryBlock();
assert(pred_begin(BBEntry) == pred_end(BBEntry) &&
"Entry block to function must not have predecessors!");
// Find first non-alloca instruction and create insertion point. This is
// safe if block is well-formed: it always have terminator, otherwise
// we'll get and assertion.
BasicBlock::iterator I = BBEntry->begin();
while (isa<AllocaInst>(I)) ++I;
CastInst *AllocaInsertionPoint =
new BitCastInst(Constant::getNullValue(Type::getInt32Ty(F.getContext())),
Type::getInt32Ty(F.getContext()),
"reg2mem alloca point", I);
// Find the escaped instructions. But don't create stack slots for
// allocas in entry block.
std::list<Instruction*> WorkList;
for (Function::iterator ibb = F.begin(), ibe = F.end();
ibb != ibe; ++ibb)
for (BasicBlock::iterator iib = ibb->begin(), iie = ibb->end();
iib != iie; ++iib) {
if (!(isa<AllocaInst>(iib) && iib->getParent() == BBEntry) &&
valueEscapes(iib)) {
WorkList.push_front(&*iib);
}
}
// Demote escaped instructions
NumRegsDemoted += WorkList.size();
for (std::list<Instruction*>::iterator ilb = WorkList.begin(),
ile = WorkList.end(); ilb != ile; ++ilb)
DemoteRegToStack(**ilb, false, AllocaInsertionPoint);
WorkList.clear();
// Find all phi's
for (Function::iterator ibb = F.begin(), ibe = F.end();
ibb != ibe; ++ibb)
for (BasicBlock::iterator iib = ibb->begin(), iie = ibb->end();
iib != iie; ++iib)
if (isa<PHINode>(iib))
WorkList.push_front(&*iib);
// Demote phi nodes
NumPhisDemoted += WorkList.size();
for (std::list<Instruction*>::iterator ilb = WorkList.begin(),
ile = WorkList.end(); ilb != ile; ++ilb)
DemotePHIToStack(cast<PHINode>(*ilb), AllocaInsertionPoint);
return true;
}
// createDemoteRegisterToMemory - Provide an entry point to create this pass.
//
const PassInfo *const llvm::DemoteRegisterToMemoryID = &X;
FunctionPass *llvm::createDemoteRegisterToMemoryPass() {
return new RegToMem();
}
<|endoftext|>
|
<commit_before>/*******************************************************************************
Licensed to the OpenCOR team under one or more contributor license agreements.
See the NOTICE.txt file distributed with this work for additional information
regarding copyright ownership. The OpenCOR team licenses this file to you under
the Apache License, Version 2.0 (the "License"); you may not use this file
except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
*******************************************************************************/
//==============================================================================
// COMBINE archive class
//==============================================================================
#include "combinearchive.h"
#include "corecliutils.h"
//==============================================================================
#include <QFile>
#include <QRegularExpression>
#include <QTemporaryDir>
#include <QTextStream>
//==============================================================================
#include <QZipReader>
#include <QZipWriter>
//==============================================================================
namespace OpenCOR {
namespace COMBINESupport {
//==============================================================================
CombineArchiveFile::CombineArchiveFile(const QString &pFileName,
const QString &pLocation,
const Format &pFormat,
const bool &pMaster) :
mFileName(pFileName),
mLocation(pLocation),
mFormat(pFormat),
mMaster(pMaster)
{
}
//==============================================================================
QString CombineArchiveFile::fileName() const
{
// Return our file name
return mFileName;
}
//==============================================================================
QString CombineArchiveFile::location() const
{
// Return our location
return mLocation;
}
//==============================================================================
CombineArchiveFile::Format CombineArchiveFile::format() const
{
// Return our format
return mFormat;
}
//==============================================================================
bool CombineArchiveFile::isMaster() const
{
// Return whether we are a master file
return mMaster;
}
//==============================================================================
CombineArchive::CombineArchive(const QString &pFileName) :
StandardSupport::StandardFile(pFileName),
mDirName(Core::temporaryDirName()),
mCombineArchiveFiles(CombineArchiveFiles())
{
}
//==============================================================================
CombineArchive::~CombineArchive()
{
// Delete our temporary directory
QDir(mDirName).removeRecursively();
}
//==============================================================================
static const auto ManifestFile = QStringLiteral("manifest.xml");
//==============================================================================
bool CombineArchive::load()
{
// Make sure that our file exists
if (!QFile::exists(mFileName))
return false;
// Our file is effectively a ZIP file, so extract all of our contents
OpenCOR::ZIPSupport::QZipReader zipReader(mFileName);
if (!zipReader.extractAll(mDirName))
return false;
// A COMBINE archive must contain a manifest file in its root
if (!QFile::exists(mDirName+QDir::separator()+ManifestFile))
return false;
return true;
}
//==============================================================================
static const auto CellmlFormat = QStringLiteral("http://identifiers.org/combine.specifications/cellml");
static const auto Cellml_1_0_Format = QStringLiteral("http://identifiers.org/combine.specifications/cellml.1.0");
static const auto Cellml_1_1_Format = QStringLiteral("http://identifiers.org/combine.specifications/cellml.1.1");
static const auto SedmlFormat = QStringLiteral("http://identifiers.org/combine.specifications/sed-ml");
//==============================================================================
bool CombineArchive::save(const QString &pNewFileName)
{
// Generate the contents our manifest file
QString fileList = QString();
QString fileFormat;
foreach (const CombineArchiveFile &combineArchiveFile, mCombineArchiveFiles) {
switch (combineArchiveFile.format()) {
case CombineArchiveFile::Cellml:
fileFormat = CellmlFormat;
break;
case CombineArchiveFile::Cellml_1_0:
fileFormat = Cellml_1_0_Format;
break;
case CombineArchiveFile::Cellml_1_1:
fileFormat = Cellml_1_1_Format;
break;
case CombineArchiveFile::Sedml:
fileFormat = SedmlFormat;
break;
default: // CombineArchiveFile::Unknown
return false;
}
fileList += " <content location=\""+combineArchiveFile.location()+"\" format=\""+fileFormat+"\"";
if (combineArchiveFile.isMaster())
fileList += " master=\"true\"";
fileList += "/>\n";
}
// Save ourselves to either the given file, which name is given, or to our
// current file
OpenCOR::ZIPSupport::QZipWriter zipWriter(pNewFileName.isEmpty()?mFileName:pNewFileName);
zipWriter.addFile(ManifestFile,
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"
"<omexManifest xmlns=\"http://identifiers.org/combine.specifications/omex-manifest\">\n"
" <content location=\".\" format=\"http://identifiers.org/combine.specifications/omex\"/>\n"
+fileList.toUtf8()
+"</omexManifest>\n");
foreach (const CombineArchiveFile &combineArchiveFile, mCombineArchiveFiles) {
QString combineArchiveFileContents;
if (!Core::readTextFromFile(mDirName+QDir::separator()+combineArchiveFile.location(),
combineArchiveFileContents)) {
return false;
}
zipWriter.addFile(combineArchiveFile.location(),
combineArchiveFileContents.toUtf8());
}
return true;
}
//==============================================================================
bool CombineArchive::addFile(const QString &pFileName, const QString &pLocation,
const CombineArchiveFile::Format &pFormat,
const bool &pMaster)
{
// Make sure the format is known
if (pFormat == CombineArchiveFile::Unknown)
return false;
// Add the given file to our list
mCombineArchiveFiles << CombineArchiveFile(pFileName, pLocation, pFormat, pMaster);
// Get a copy of the given file, after creating the sub-folder(s) in which
// it is, if necessary
#if defined(Q_OS_WIN)
static const QRegularExpression FileNameRegEx = QRegularExpression("\\\\[^\\\\]*$");
#elif defined(Q_OS_LINUX) || defined(Q_OS_MAC)
static const QRegularExpression FileNameRegEx = QRegularExpression("/[^/]*$");
#else
#error Unsupported platform
#endif
static QDir dir;
QString destFileName = Core::nativeCanonicalFileName(mDirName+QDir::separator()+pLocation);
QString destDirName = QString(destFileName).remove(FileNameRegEx);
if (!QDir(destDirName).exists() && !dir.mkpath(destDirName))
return false;
if (!QFile::copy(pFileName, destFileName))
return false;
return true;
}
//==============================================================================
} // namespace COMBINESupport
} // namespace OpenCOR
//==============================================================================
// End of file
//==============================================================================
<commit_msg>COMBINE archive: some work on loading/saving a COMBINE archive [ci skip].<commit_after>/*******************************************************************************
Licensed to the OpenCOR team under one or more contributor license agreements.
See the NOTICE.txt file distributed with this work for additional information
regarding copyright ownership. The OpenCOR team licenses this file to you under
the Apache License, Version 2.0 (the "License"); you may not use this file
except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
*******************************************************************************/
//==============================================================================
// COMBINE archive class
//==============================================================================
#include "combinearchive.h"
#include "corecliutils.h"
//==============================================================================
#include <QFile>
#include <QRegularExpression>
#include <QTemporaryDir>
#include <QTextStream>
//==============================================================================
#include <QZipReader>
#include <QZipWriter>
//==============================================================================
namespace OpenCOR {
namespace COMBINESupport {
//==============================================================================
CombineArchiveFile::CombineArchiveFile(const QString &pFileName,
const QString &pLocation,
const Format &pFormat,
const bool &pMaster) :
mFileName(pFileName),
mLocation(pLocation),
mFormat(pFormat),
mMaster(pMaster)
{
}
//==============================================================================
QString CombineArchiveFile::fileName() const
{
// Return our file name
return mFileName;
}
//==============================================================================
QString CombineArchiveFile::location() const
{
// Return our location
return mLocation;
}
//==============================================================================
CombineArchiveFile::Format CombineArchiveFile::format() const
{
// Return our format
return mFormat;
}
//==============================================================================
bool CombineArchiveFile::isMaster() const
{
// Return whether we are a master file
return mMaster;
}
//==============================================================================
CombineArchive::CombineArchive(const QString &pFileName) :
StandardSupport::StandardFile(pFileName),
mDirName(Core::temporaryDirName()),
mCombineArchiveFiles(CombineArchiveFiles())
{
}
//==============================================================================
CombineArchive::~CombineArchive()
{
// Delete our temporary directory
QDir(mDirName).removeRecursively();
}
//==============================================================================
static const auto ManifestFile = QStringLiteral("manifest.xml");
//==============================================================================
bool CombineArchive::load()
{
// Make sure that our file exists
if (!QFile::exists(mFileName))
return false;
// Make sure that our file starts with 0x04034b50, which is the signature of
// a ZIP file and should therefore be that of our file
// Note: we don't strictly need to check this since loading our file will
// eventually if our file is not a ZIP file. Still, if it's not a ZIP
// file, then trying to extract its context will result in a warning
// message from QZip (when in a debug mode), which is not 'neat',
// hence we prevent this by checking whether our file starts with the
// ZIP signature...
static const int SignatureSize = 4;
OpenCOR::ZIPSupport::QZipReader zipReader(mFileName);
uchar signatureData[SignatureSize];
if (zipReader.device()->read((char *) signatureData, SignatureSize) != SignatureSize)
return false;
uint signature = signatureData[0]
+(signatureData[1] << 8)
+(signatureData[2] << 16)
+(signatureData[3] << 24);
if (signature != 0x04034b50)
return false;
// Our file is effectively a ZIP file, so extract all of our contents
zipReader.device()->reset();
if (!zipReader.extractAll(mDirName))
return false;
// A COMBINE archive must contain a manifest file in its root
if (!QFile::exists(mDirName+QDir::separator()+ManifestFile))
return false;
return true;
}
//==============================================================================
static const auto CellmlFormat = QStringLiteral("http://identifiers.org/combine.specifications/cellml");
static const auto Cellml_1_0_Format = QStringLiteral("http://identifiers.org/combine.specifications/cellml.1.0");
static const auto Cellml_1_1_Format = QStringLiteral("http://identifiers.org/combine.specifications/cellml.1.1");
static const auto SedmlFormat = QStringLiteral("http://identifiers.org/combine.specifications/sed-ml");
//==============================================================================
bool CombineArchive::save(const QString &pNewFileName)
{
// Generate the contents our manifest file
QString fileList = QString();
QString fileFormat;
foreach (const CombineArchiveFile &combineArchiveFile, mCombineArchiveFiles) {
switch (combineArchiveFile.format()) {
case CombineArchiveFile::Cellml:
fileFormat = CellmlFormat;
break;
case CombineArchiveFile::Cellml_1_0:
fileFormat = Cellml_1_0_Format;
break;
case CombineArchiveFile::Cellml_1_1:
fileFormat = Cellml_1_1_Format;
break;
case CombineArchiveFile::Sedml:
fileFormat = SedmlFormat;
break;
default: // CombineArchiveFile::Unknown
return false;
}
fileList += " <content location=\""+combineArchiveFile.location()+"\" format=\""+fileFormat+"\"";
if (combineArchiveFile.isMaster())
fileList += " master=\"true\"";
fileList += "/>\n";
}
// Save ourselves to either the given file, which name is given, or to our
// current file
OpenCOR::ZIPSupport::QZipWriter zipWriter(pNewFileName.isEmpty()?mFileName:pNewFileName);
zipWriter.addFile(ManifestFile,
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"
"<omexManifest xmlns=\"http://identifiers.org/combine.specifications/omex-manifest\">\n"
" <content location=\".\" format=\"http://identifiers.org/combine.specifications/omex\"/>\n"
+fileList.toUtf8()
+"</omexManifest>\n");
foreach (const CombineArchiveFile &combineArchiveFile, mCombineArchiveFiles) {
QString combineArchiveFileContents;
if (!Core::readTextFromFile(mDirName+QDir::separator()+combineArchiveFile.location(),
combineArchiveFileContents)) {
return false;
}
zipWriter.addFile(combineArchiveFile.location(),
combineArchiveFileContents.toUtf8());
}
return true;
}
//==============================================================================
bool CombineArchive::addFile(const QString &pFileName, const QString &pLocation,
const CombineArchiveFile::Format &pFormat,
const bool &pMaster)
{
// Make sure the format is known
if (pFormat == CombineArchiveFile::Unknown)
return false;
// Add the given file to our list
mCombineArchiveFiles << CombineArchiveFile(pFileName, pLocation, pFormat, pMaster);
// Get a copy of the given file, after creating the sub-folder(s) in which
// it is, if necessary
#if defined(Q_OS_WIN)
static const QRegularExpression FileNameRegEx = QRegularExpression("\\\\[^\\\\]*$");
#elif defined(Q_OS_LINUX) || defined(Q_OS_MAC)
static const QRegularExpression FileNameRegEx = QRegularExpression("/[^/]*$");
#else
#error Unsupported platform
#endif
static QDir dir;
QString destFileName = Core::nativeCanonicalFileName(mDirName+QDir::separator()+pLocation);
QString destDirName = QString(destFileName).remove(FileNameRegEx);
if (!QDir(destDirName).exists() && !dir.mkpath(destDirName))
return false;
if (!QFile::copy(pFileName, destFileName))
return false;
return true;
}
//==============================================================================
} // namespace COMBINESupport
} // namespace OpenCOR
//==============================================================================
// End of file
//==============================================================================
<|endoftext|>
|
<commit_before>/** Implementation of the pqxx::result class and support classes.
*
* pqxx::result represents the set of result rows from a database query
*
* Copyright (c) 2001-2019, Jeroen T. Vermeulen.
*
* See COPYING for copyright license. If you did not receive a file called
* COPYING with this source code, please notify the distributor of this mistake,
* or contact the author.
*/
#include "pqxx/compiler-internal.hxx"
#include <cstdlib>
#include <cstring>
#include <stdexcept>
#include "libpq-fe.h"
#include "pqxx/except"
#include "pqxx/result"
const std::string pqxx::result::s_empty_string;
/// C++ wrapper for libpq's PQclear.
void pqxx::internal::clear_result(const pq::PGresult *data)
{
PQclear(const_cast<pq::PGresult *>(data));
}
pqxx::result::result(
pqxx::internal::pq::PGresult *rhs,
const std::string &Query,
internal::encoding_group enc) :
m_data{make_data_pointer(rhs)},
m_query{std::make_shared<std::string>(Query)},
m_encoding(enc)
{
}
bool pqxx::result::operator==(const result &rhs) const noexcept
{
if (&rhs == this) return true;
const auto s = size();
if (rhs.size() != s) return false;
for (size_type i=0; i<s; ++i)
if ((*this)[i] != rhs[i]) return false;
return true;
}
pqxx::result::const_reverse_iterator pqxx::result::rbegin() const
{
return const_reverse_iterator{end()};
}
pqxx::result::const_reverse_iterator pqxx::result::crbegin() const
{
return rbegin();
}
pqxx::result::const_reverse_iterator pqxx::result::rend() const
{
return const_reverse_iterator{begin()};
}
pqxx::result::const_reverse_iterator pqxx::result::crend() const
{
return rend();
}
pqxx::result::const_iterator pqxx::result::begin() const noexcept
{
return const_iterator{this, 0};
}
pqxx::result::const_iterator pqxx::result::cbegin() const noexcept
{
return begin();
}
pqxx::result::size_type pqxx::result::size() const noexcept
{
return m_data.get() ? size_type(PQntuples(m_data.get())) : 0;
}
bool pqxx::result::empty() const noexcept
{
return (m_data.get() == nullptr) or (PQntuples(m_data.get()) == 0);
}
pqxx::result::reference pqxx::result::front() const noexcept
{
return row{*this, 0};
}
pqxx::result::reference pqxx::result::back() const noexcept
{
return row{*this, size() - 1};
}
void pqxx::result::swap(result &rhs) noexcept
{
m_data.swap(rhs.m_data);
m_query.swap(rhs.m_query);
}
const pqxx::row pqxx::result::operator[](result_size_type i) const noexcept
{
return row{*this, i};
}
const pqxx::row pqxx::result::at(pqxx::result::size_type i) const
{
if (i >= size()) throw range_error{"Row number out of range."};
return operator[](i);
}
namespace
{
/// C string comparison.
inline bool equal(const char lhs[], const char rhs[])
{
return strcmp(lhs, rhs) == 0;
}
} // namespace
void pqxx::result::ThrowSQLError(
const std::string &Err,
const std::string &Query) const
{
// Try to establish more precise error type, and throw corresponding
// type of exception.
const char *const code = PQresultErrorField(m_data.get(), PG_DIAG_SQLSTATE);
if (code) switch (code[0])
{
case '0':
switch (code[1])
{
case '8':
throw broken_connection{Err};
case 'A':
throw feature_not_supported{Err, Query, code};
}
break;
case '2':
switch (code[1])
{
case '2':
throw data_exception{Err, Query, code};
case '3':
if (equal(code,"23001")) throw restrict_violation{Err, Query, code};
if (equal(code,"23502")) throw not_null_violation{Err, Query, code};
if (equal(code,"23503"))
throw foreign_key_violation{Err, Query, code};
if (equal(code,"23505")) throw unique_violation{Err, Query, code};
if (equal(code,"23514")) throw check_violation{Err, Query, code};
throw integrity_constraint_violation{Err, Query, code};
case '4':
throw invalid_cursor_state{Err, Query, code};
case '6':
throw invalid_sql_statement_name{Err, Query, code};
}
break;
case '3':
switch (code[1])
{
case '4':
throw invalid_cursor_name{Err, Query, code};
}
break;
case '4':
switch (code[1])
{
case '0':
if (equal(code, "40000")) throw transaction_rollback{Err};
if (equal(code, "40001")) throw serialization_failure{Err};
if (equal(code, "40001")) throw statement_completion_unknown{Err};
if (equal(code, "40P01")) throw deadlock_detected{Err};
break;
case '2':
if (equal(code,"42501")) throw insufficient_privilege{Err, Query};
if (equal(code,"42601"))
throw syntax_error{Err, Query, code, errorposition()};
if (equal(code,"42703")) throw undefined_column{Err, Query, code};
if (equal(code,"42883")) throw undefined_function{Err, Query, code};
if (equal(code,"42P01")) throw undefined_table{Err, Query, code};
}
break;
case '5':
switch (code[1])
{
case '3':
if (equal(code,"53100")) throw disk_full{Err, Query, code};
if (equal(code,"53200")) throw out_of_memory{Err, Query, code};
if (equal(code,"53300")) throw too_many_connections{Err};
throw insufficient_resources{Err, Query, code};
}
break;
case 'P':
if (equal(code, "P0001")) throw plpgsql_raise{Err, Query, code};
if (equal(code, "P0002"))
throw plpgsql_no_data_found{Err, Query, code};
if (equal(code, "P0003"))
throw plpgsql_too_many_rows{Err, Query, code};
throw plpgsql_error{Err, Query, code};
}
// Fallback: No error code.
throw sql_error{Err, Query, code};
}
void pqxx::result::check_status() const
{
const std::string Err = StatusError();
if (not Err.empty()) ThrowSQLError(Err, query());
}
std::string pqxx::result::StatusError() const
{
if (m_data.get() == nullptr) throw failure{"No result set given."};
std::string Err;
switch (PQresultStatus(m_data.get()))
{
case PGRES_EMPTY_QUERY: // The string sent to the backend was empty.
case PGRES_COMMAND_OK: // Successful completion of a command returning no data
case PGRES_TUPLES_OK: // The query successfully executed
break;
case PGRES_COPY_OUT: // Copy Out (from server) data transfer started
case PGRES_COPY_IN: // Copy In (to server) data transfer started
break;
case PGRES_BAD_RESPONSE: // The server's response was not understood
case PGRES_NONFATAL_ERROR:
case PGRES_FATAL_ERROR:
Err = PQresultErrorMessage(m_data.get());
break;
default:
throw internal_error{
"pqxx::result: Unrecognized response code " +
to_string(int(PQresultStatus(m_data.get())))};
}
return Err;
}
const char *pqxx::result::cmd_status() const noexcept
{
return PQcmdStatus(const_cast<internal::pq::PGresult *>(m_data.get()));
}
const std::string &pqxx::result::query() const noexcept
{
return m_query ? *m_query : s_empty_string;
}
pqxx::oid pqxx::result::inserted_oid() const
{
if (m_data.get() == nullptr)
throw usage_error{
"Attempt to read oid of inserted row without an INSERT result"};
return PQoidValue(const_cast<internal::pq::PGresult *>(m_data.get()));
}
pqxx::result::size_type pqxx::result::affected_rows() const
{
const char *const RowsStr = PQcmdTuples(
const_cast<internal::pq::PGresult *>(m_data.get()));
return RowsStr[0] ? size_type(atoi(RowsStr)) : 0;
}
const char *pqxx::result::GetValue(
pqxx::result::size_type Row,
pqxx::row::size_type Col) const
{
return PQgetvalue(m_data.get(), int(Row), int(Col));
}
bool pqxx::result::get_is_null(
pqxx::result::size_type Row,
pqxx::row::size_type Col) const
{
return PQgetisnull(m_data.get(), int(Row), int(Col)) != 0;
}
pqxx::field::size_type pqxx::result::get_length(
pqxx::result::size_type Row,
pqxx::row::size_type Col) const noexcept
{
return field::size_type(PQgetlength(m_data.get(), int(Row), int(Col)));
}
pqxx::oid pqxx::result::column_type(row::size_type ColNum) const
{
const oid T = PQftype(m_data.get(), int(ColNum));
if (T == oid_none)
throw argument_error{
"Attempt to retrieve type of nonexistent column " +
to_string(ColNum) + " of query result."};
return T;
}
pqxx::oid pqxx::result::column_table(row::size_type ColNum) const
{
const oid T = PQftable(m_data.get(), int(ColNum));
/* If we get oid_none, it may be because the column is computed, or because we
* got an invalid row number.
*/
if (T == oid_none and ColNum >= columns())
throw argument_error{
"Attempt to retrieve table ID for column " + to_string(ColNum) +
" out of " + to_string(columns())};
return T;
}
pqxx::row::size_type pqxx::result::table_column(row::size_type ColNum) const
{
const auto n = row::size_type(PQftablecol(m_data.get(), int(ColNum)));
if (n) return n-1;
// Failed. Now find out why, so we can throw a sensible exception.
const std::string col_num = to_string(ColNum);
if (ColNum > columns())
throw range_error{"Invalid column index in table_column(): " + col_num};
if (m_data.get() == nullptr)
throw usage_error{
"Can't query origin of column " + col_num + ": "
"result is not initialized."};
throw usage_error{
"Can't query origin of column " + col_num + ": "
"not derived from table column."};
}
int pqxx::result::errorposition() const
{
int pos = -1;
if (m_data.get())
{
const char *p = PQresultErrorField(
const_cast<internal::pq::PGresult *>(m_data.get()),
PG_DIAG_STATEMENT_POSITION);
if (p) from_string(p, pos);
}
return pos;
}
const char *pqxx::result::column_name(pqxx::row::size_type Number) const
{
const char *const N = PQfname(m_data.get(), int(Number));
if (N == nullptr)
{
if (m_data.get() == nullptr)
throw usage_error{"Queried column name on null result."};
throw range_error{
"Invalid column number: " + to_string(Number) +
" (maximum is " + to_string(columns() - 1) + ")."};
}
return N;
}
pqxx::row::size_type pqxx::result::columns() const noexcept
{
auto ptr = const_cast<internal::pq::PGresult *>(m_data.get());
return ptr ? row::size_type(PQnfields(ptr)) : 0;
}
// const_result_iterator
pqxx::const_result_iterator pqxx::const_result_iterator::operator++(int)
{
const_result_iterator old{*this};
m_index++;
return old;
}
pqxx::const_result_iterator pqxx::const_result_iterator::operator--(int)
{
const_result_iterator old{*this};
m_index--;
return old;
}
pqxx::result::const_iterator
pqxx::result::const_reverse_iterator::base() const noexcept
{
iterator_type tmp{*this};
return ++tmp;
}
pqxx::const_reverse_result_iterator
pqxx::const_reverse_result_iterator::operator++(int)
{
const_reverse_result_iterator tmp{*this};
iterator_type::operator--();
return tmp;
}
pqxx::const_reverse_result_iterator
pqxx::const_reverse_result_iterator::operator--(int)
{
const_reverse_result_iterator tmp{*this};
iterator_type::operator++();
return tmp;
}
template<>
std::string pqxx::to_string(const field &Obj)
{
return std::string{Obj.c_str(), Obj.size()};
}
<commit_msg>Fix recognition of "completion unknown."<commit_after>/** Implementation of the pqxx::result class and support classes.
*
* pqxx::result represents the set of result rows from a database query
*
* Copyright (c) 2001-2019, Jeroen T. Vermeulen.
*
* See COPYING for copyright license. If you did not receive a file called
* COPYING with this source code, please notify the distributor of this mistake,
* or contact the author.
*/
#include "pqxx/compiler-internal.hxx"
#include <cstdlib>
#include <cstring>
#include <stdexcept>
#include "libpq-fe.h"
#include "pqxx/except"
#include "pqxx/result"
const std::string pqxx::result::s_empty_string;
/// C++ wrapper for libpq's PQclear.
void pqxx::internal::clear_result(const pq::PGresult *data)
{
PQclear(const_cast<pq::PGresult *>(data));
}
pqxx::result::result(
pqxx::internal::pq::PGresult *rhs,
const std::string &Query,
internal::encoding_group enc) :
m_data{make_data_pointer(rhs)},
m_query{std::make_shared<std::string>(Query)},
m_encoding(enc)
{
}
bool pqxx::result::operator==(const result &rhs) const noexcept
{
if (&rhs == this) return true;
const auto s = size();
if (rhs.size() != s) return false;
for (size_type i=0; i<s; ++i)
if ((*this)[i] != rhs[i]) return false;
return true;
}
pqxx::result::const_reverse_iterator pqxx::result::rbegin() const
{
return const_reverse_iterator{end()};
}
pqxx::result::const_reverse_iterator pqxx::result::crbegin() const
{
return rbegin();
}
pqxx::result::const_reverse_iterator pqxx::result::rend() const
{
return const_reverse_iterator{begin()};
}
pqxx::result::const_reverse_iterator pqxx::result::crend() const
{
return rend();
}
pqxx::result::const_iterator pqxx::result::begin() const noexcept
{
return const_iterator{this, 0};
}
pqxx::result::const_iterator pqxx::result::cbegin() const noexcept
{
return begin();
}
pqxx::result::size_type pqxx::result::size() const noexcept
{
return m_data.get() ? size_type(PQntuples(m_data.get())) : 0;
}
bool pqxx::result::empty() const noexcept
{
return (m_data.get() == nullptr) or (PQntuples(m_data.get()) == 0);
}
pqxx::result::reference pqxx::result::front() const noexcept
{
return row{*this, 0};
}
pqxx::result::reference pqxx::result::back() const noexcept
{
return row{*this, size() - 1};
}
void pqxx::result::swap(result &rhs) noexcept
{
m_data.swap(rhs.m_data);
m_query.swap(rhs.m_query);
}
const pqxx::row pqxx::result::operator[](result_size_type i) const noexcept
{
return row{*this, i};
}
const pqxx::row pqxx::result::at(pqxx::result::size_type i) const
{
if (i >= size()) throw range_error{"Row number out of range."};
return operator[](i);
}
namespace
{
/// C string comparison.
inline bool equal(const char lhs[], const char rhs[])
{
return strcmp(lhs, rhs) == 0;
}
} // namespace
void pqxx::result::ThrowSQLError(
const std::string &Err,
const std::string &Query) const
{
// Try to establish more precise error type, and throw corresponding
// type of exception.
const char *const code = PQresultErrorField(m_data.get(), PG_DIAG_SQLSTATE);
if (code) switch (code[0])
{
case '0':
switch (code[1])
{
case '8':
throw broken_connection{Err};
case 'A':
throw feature_not_supported{Err, Query, code};
}
break;
case '2':
switch (code[1])
{
case '2':
throw data_exception{Err, Query, code};
case '3':
if (equal(code,"23001")) throw restrict_violation{Err, Query, code};
if (equal(code,"23502")) throw not_null_violation{Err, Query, code};
if (equal(code,"23503"))
throw foreign_key_violation{Err, Query, code};
if (equal(code,"23505")) throw unique_violation{Err, Query, code};
if (equal(code,"23514")) throw check_violation{Err, Query, code};
throw integrity_constraint_violation{Err, Query, code};
case '4':
throw invalid_cursor_state{Err, Query, code};
case '6':
throw invalid_sql_statement_name{Err, Query, code};
}
break;
case '3':
switch (code[1])
{
case '4':
throw invalid_cursor_name{Err, Query, code};
}
break;
case '4':
switch (code[1])
{
case '0':
if (equal(code, "40000")) throw transaction_rollback{Err};
if (equal(code, "40001")) throw serialization_failure{Err};
if (equal(code, "40003")) throw statement_completion_unknown{Err};
if (equal(code, "40P01")) throw deadlock_detected{Err};
break;
case '2':
if (equal(code,"42501")) throw insufficient_privilege{Err, Query};
if (equal(code,"42601"))
throw syntax_error{Err, Query, code, errorposition()};
if (equal(code,"42703")) throw undefined_column{Err, Query, code};
if (equal(code,"42883")) throw undefined_function{Err, Query, code};
if (equal(code,"42P01")) throw undefined_table{Err, Query, code};
}
break;
case '5':
switch (code[1])
{
case '3':
if (equal(code,"53100")) throw disk_full{Err, Query, code};
if (equal(code,"53200")) throw out_of_memory{Err, Query, code};
if (equal(code,"53300")) throw too_many_connections{Err};
throw insufficient_resources{Err, Query, code};
}
break;
case 'P':
if (equal(code, "P0001")) throw plpgsql_raise{Err, Query, code};
if (equal(code, "P0002"))
throw plpgsql_no_data_found{Err, Query, code};
if (equal(code, "P0003"))
throw plpgsql_too_many_rows{Err, Query, code};
throw plpgsql_error{Err, Query, code};
}
// Fallback: No error code.
throw sql_error{Err, Query, code};
}
void pqxx::result::check_status() const
{
const std::string Err = StatusError();
if (not Err.empty()) ThrowSQLError(Err, query());
}
std::string pqxx::result::StatusError() const
{
if (m_data.get() == nullptr) throw failure{"No result set given."};
std::string Err;
switch (PQresultStatus(m_data.get()))
{
case PGRES_EMPTY_QUERY: // The string sent to the backend was empty.
case PGRES_COMMAND_OK: // Successful completion of a command returning no data
case PGRES_TUPLES_OK: // The query successfully executed
break;
case PGRES_COPY_OUT: // Copy Out (from server) data transfer started
case PGRES_COPY_IN: // Copy In (to server) data transfer started
break;
case PGRES_BAD_RESPONSE: // The server's response was not understood
case PGRES_NONFATAL_ERROR:
case PGRES_FATAL_ERROR:
Err = PQresultErrorMessage(m_data.get());
break;
default:
throw internal_error{
"pqxx::result: Unrecognized response code " +
to_string(int(PQresultStatus(m_data.get())))};
}
return Err;
}
const char *pqxx::result::cmd_status() const noexcept
{
return PQcmdStatus(const_cast<internal::pq::PGresult *>(m_data.get()));
}
const std::string &pqxx::result::query() const noexcept
{
return m_query ? *m_query : s_empty_string;
}
pqxx::oid pqxx::result::inserted_oid() const
{
if (m_data.get() == nullptr)
throw usage_error{
"Attempt to read oid of inserted row without an INSERT result"};
return PQoidValue(const_cast<internal::pq::PGresult *>(m_data.get()));
}
pqxx::result::size_type pqxx::result::affected_rows() const
{
const char *const RowsStr = PQcmdTuples(
const_cast<internal::pq::PGresult *>(m_data.get()));
return RowsStr[0] ? size_type(atoi(RowsStr)) : 0;
}
const char *pqxx::result::GetValue(
pqxx::result::size_type Row,
pqxx::row::size_type Col) const
{
return PQgetvalue(m_data.get(), int(Row), int(Col));
}
bool pqxx::result::get_is_null(
pqxx::result::size_type Row,
pqxx::row::size_type Col) const
{
return PQgetisnull(m_data.get(), int(Row), int(Col)) != 0;
}
pqxx::field::size_type pqxx::result::get_length(
pqxx::result::size_type Row,
pqxx::row::size_type Col) const noexcept
{
return field::size_type(PQgetlength(m_data.get(), int(Row), int(Col)));
}
pqxx::oid pqxx::result::column_type(row::size_type ColNum) const
{
const oid T = PQftype(m_data.get(), int(ColNum));
if (T == oid_none)
throw argument_error{
"Attempt to retrieve type of nonexistent column " +
to_string(ColNum) + " of query result."};
return T;
}
pqxx::oid pqxx::result::column_table(row::size_type ColNum) const
{
const oid T = PQftable(m_data.get(), int(ColNum));
/* If we get oid_none, it may be because the column is computed, or because we
* got an invalid row number.
*/
if (T == oid_none and ColNum >= columns())
throw argument_error{
"Attempt to retrieve table ID for column " + to_string(ColNum) +
" out of " + to_string(columns())};
return T;
}
pqxx::row::size_type pqxx::result::table_column(row::size_type ColNum) const
{
const auto n = row::size_type(PQftablecol(m_data.get(), int(ColNum)));
if (n) return n-1;
// Failed. Now find out why, so we can throw a sensible exception.
const std::string col_num = to_string(ColNum);
if (ColNum > columns())
throw range_error{"Invalid column index in table_column(): " + col_num};
if (m_data.get() == nullptr)
throw usage_error{
"Can't query origin of column " + col_num + ": "
"result is not initialized."};
throw usage_error{
"Can't query origin of column " + col_num + ": "
"not derived from table column."};
}
int pqxx::result::errorposition() const
{
int pos = -1;
if (m_data.get())
{
const char *p = PQresultErrorField(
const_cast<internal::pq::PGresult *>(m_data.get()),
PG_DIAG_STATEMENT_POSITION);
if (p) from_string(p, pos);
}
return pos;
}
const char *pqxx::result::column_name(pqxx::row::size_type Number) const
{
const char *const N = PQfname(m_data.get(), int(Number));
if (N == nullptr)
{
if (m_data.get() == nullptr)
throw usage_error{"Queried column name on null result."};
throw range_error{
"Invalid column number: " + to_string(Number) +
" (maximum is " + to_string(columns() - 1) + ")."};
}
return N;
}
pqxx::row::size_type pqxx::result::columns() const noexcept
{
auto ptr = const_cast<internal::pq::PGresult *>(m_data.get());
return ptr ? row::size_type(PQnfields(ptr)) : 0;
}
// const_result_iterator
pqxx::const_result_iterator pqxx::const_result_iterator::operator++(int)
{
const_result_iterator old{*this};
m_index++;
return old;
}
pqxx::const_result_iterator pqxx::const_result_iterator::operator--(int)
{
const_result_iterator old{*this};
m_index--;
return old;
}
pqxx::result::const_iterator
pqxx::result::const_reverse_iterator::base() const noexcept
{
iterator_type tmp{*this};
return ++tmp;
}
pqxx::const_reverse_result_iterator
pqxx::const_reverse_result_iterator::operator++(int)
{
const_reverse_result_iterator tmp{*this};
iterator_type::operator--();
return tmp;
}
pqxx::const_reverse_result_iterator
pqxx::const_reverse_result_iterator::operator--(int)
{
const_reverse_result_iterator tmp{*this};
iterator_type::operator++();
return tmp;
}
template<>
std::string pqxx::to_string(const field &Obj)
{
return std::string{Obj.c_str(), Obj.size()};
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <unistd.h>
#include <string>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <errno.h>
using namespace std;
int main() {
while (1) {
string cmd;
string arg1;
string arg2;
cout << "Please enter cmd: ";
getline(cin, cmd);
cout << "Please enter arg1: ";
getline(cin, arg1);
cout << "Please enter arg2: ";
getline(cin, arg2);
int pid=fork();
if (pid ==0) {
cout << "i'm a child\n";
char * argv[4];
argv[0] = new char[3];
argv[1] = new char[3];
argv[2] = new char[3];
strcpy(argv[0], cmd.c_str());
strcpy(argv[1], arg1.c_str());
strcpy(argv[2], arg2.c_str());
argv[3] = NULL;
cout << "I REACHED EXECVP!!\n";
execvp(cmd.c_str(), argv);
}
else {
wait(NULL);
}
}
return 0;
}
<commit_msg>added basic functionality in rshell.cpp<commit_after>#include <iostream>
#include <unistd.h>
#include <string>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <errno.h>
#include <vector>
using namespace std;
int main() {
char buffer[512];
vector<string> input;
while (1) {
if (input.size() != 0)
input.clear();
cout << "Please enter cmd: ";
fgets(buffer, 512, stdin);
char * pch;
pch = strtok (buffer, " \n");
while (pch!= NULL) {
input.push_back(pch);
pch = strtok (NULL, " \n");
}
int pid=fork();
if (pid ==0) {
char * argv[input.size()+1];
for (int i = 0; i <= input.size(); i++) {
argv[i] = new char[5];
if (i != input.size())
strcpy(argv[i], input[i].c_str());
}
argv[input.size()] = NULL;
int r = execvp(argv[0], argv);
if (r == -1)
perror("execvp");
}
else {
wait(NULL);
}
}
return 0;
}
<|endoftext|>
|
<commit_before>/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// This program prints out a summary of a GraphDef file's contents, listing
// things that are useful for debugging and reusing the model it contains. For
// example it looks at the graph structure and op types to figure out likely
// input and output nodes, and shows which ops are used by the graph. To use it,
// run something like this:
//
// bazel build tensorflow/tools/graph_transforms:summarize_graph
// bazel-bin/tensorflow/tools/graph_transforms/summarize_graph \
// --in_graph=my_graph.pb
#include "tensorflow/core/framework/attr_value.pb.h"
#include "tensorflow/core/framework/node_def.pb.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.pb.h"
#include "tensorflow/core/lib/strings/str_util.h"
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/platform/init_main.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/util/command_line_flags.h"
#include "tensorflow/tools/graph_transforms/transform_utils.h"
namespace tensorflow {
namespace graph_transforms {
namespace {
void PrintNodeInfo(const NodeDef* node) {
string shape_description = "None";
if (node->attr().count("shape")) {
TensorShapeProto shape_proto = node->attr().at("shape").shape();
Status shape_status = PartialTensorShape::IsValidShape(shape_proto);
if (shape_status.ok()) {
shape_description = PartialTensorShape(shape_proto).DebugString();
} else {
shape_description = shape_status.error_message();
}
}
DataType dtype = DT_INVALID;
if (node->attr().count("dtype")) {
dtype = node->attr().at("dtype").type();
}
std::cout << "(name=" << node->name();
std::cout << ", type=" << DataTypeString(dtype) << "(" << dtype << ")";
std::cout << ", shape=" << shape_description << ") ";
}
void PrintBenchmarkUsage(const std::vector<const NodeDef*>& placeholders,
const std::vector<const NodeDef*>& variables,
const std::vector<const NodeDef*> outputs,
const string& graph_path) {
std::vector<const NodeDef*> all_inputs(placeholders);
all_inputs.insert(all_inputs.end(), variables.begin(), variables.end());
std::vector<string> input_layers;
std::vector<string> input_layer_types;
std::vector<string> input_layer_shapes;
for (const NodeDef* node : all_inputs) {
input_layers.push_back(node->name());
DataType dtype = DT_INVALID;
if (node->attr().count("dtype")) {
dtype = node->attr().at("dtype").type();
}
input_layer_types.push_back(DataTypeString(dtype));
std::vector<int64> sizes;
PartialTensorShape shape;
if (node->attr().count("shape")) {
TensorShapeProto shape_proto = node->attr().at("shape").shape();
if (PartialTensorShape::IsValid(shape_proto)) {
shape = PartialTensorShape(shape_proto);
}
}
sizes.reserve(shape.dims());
for (int i = 0; i < shape.dims(); ++i) {
sizes.push_back(shape.dim_size(i));
}
string sizes_string = str_util::Join(sizes, ",");
input_layer_shapes.push_back(sizes_string);
}
std::vector<string> output_layers;
output_layers.reserve(outputs.size());
for (const NodeDef* node : outputs) {
output_layers.push_back(node->name());
}
string input_layer_value = str_util::Join(input_layers, ",");
string input_layer_type_value = str_util::Join(input_layer_types, ",");
string input_layer_shape_value = str_util::Join(input_layer_shapes, ":");
string output_layer_value = str_util::Join(output_layers, ",");
std::cout << "To use with tensorflow/tools/benchmark:benchmark_model try "
"these arguments:"
<< std::endl;
std::cout << "bazel run tensorflow/tools/benchmark:benchmark_model --";
std::cout << " --graph=" << graph_path;
std::cout << " --show_flops";
std::cout << " --input_layer=" << input_layer_value;
std::cout << " --input_layer_type=" << input_layer_type_value;
std::cout << " --input_layer_shape=" << input_layer_shape_value;
std::cout << " --output_layer=" << output_layer_value;
std::cout << std::endl;
}
Status PrintStructure(const GraphDef& graph) {
GraphDef sorted_graph;
TF_RETURN_IF_ERROR(SortByExecutionOrder(graph, &sorted_graph));
for (const NodeDef& node : sorted_graph.node()) {
std::cout << node.name() << " (" << node.op() << "): ["
<< str_util::Join(node.input(), ", ") << "]";
if (node.op() == "Const") {
Tensor tensor;
if (node.attr().count("value") &&
tensor.FromProto(node.attr().at("value").tensor())) {
std::cout << ", value=" << tensor.DebugString();
} else {
LOG(WARNING) << "Decoding Tensor failed for node" << node.name();
}
}
std::cout << std::endl;
}
return Status::OK();
}
Status SummarizeGraph(const GraphDef& graph, const string& graph_path,
bool print_structure) {
std::vector<const NodeDef*> placeholders;
std::vector<const NodeDef*> variables;
for (const NodeDef& node : graph.node()) {
if (node.op() == "Placeholder") {
placeholders.push_back(&node);
}
if (node.op() == "Variable" || node.op() == "VariableV2") {
variables.push_back(&node);
}
}
if (placeholders.empty()) {
std::cout << "No inputs spotted." << std::endl;
} else {
std::cout << "Found " << placeholders.size() << " possible inputs: ";
for (const NodeDef* node : placeholders) {
PrintNodeInfo(node);
}
std::cout << std::endl;
}
if (variables.empty()) {
std::cout << "No variables spotted." << std::endl;
} else {
std::cout << "Found " << variables.size() << " variables: ";
for (const NodeDef* node : variables) {
PrintNodeInfo(node);
}
std::cout << std::endl;
}
std::map<string, std::vector<const NodeDef*>> output_map;
MapNodesToOutputs(graph, &output_map);
std::vector<const NodeDef*> outputs;
std::unordered_set<string> unlikely_output_types = {"Const", "Assign", "NoOp",
"Placeholder"};
for (const NodeDef& node : graph.node()) {
if ((output_map.count(node.name()) == 0) &&
(unlikely_output_types.count(node.op()) == 0)) {
outputs.push_back(&node);
}
}
if (outputs.empty()) {
std::cout << "No outputs spotted." << std::endl;
} else {
std::cout << "Found " << outputs.size() << " possible outputs: ";
for (const NodeDef* node : outputs) {
std::cout << "(name=" << node->name();
std::cout << ", op=" << node->op() << ") ";
}
std::cout << std::endl;
}
int64 const_parameter_count = 0;
int64 variable_parameter_count = 0;
int control_edge_count = 0;
std::map<string, int> device_counts;
for (const NodeDef& node : graph.node()) {
for (const string& input : node.input()) {
if (input.substr(0, 1) == "^") {
++control_edge_count;
}
}
if (!node.device().empty()) {
++device_counts[node.device()];
}
if ((node.op() == "Const") || (node.op() == "Variable") ||
(node.op() == "VariableV2")) {
Tensor tensor;
if (node.attr().count("value") &&
tensor.FromProto(node.attr().at("value").tensor())) {
const size_t num_elements = tensor.NumElements();
if (node.op() == "Const") {
const_parameter_count += num_elements;
} else {
variable_parameter_count += num_elements;
}
} else {
LOG(WARNING) << "Decoding Tensor failed for node" << node.name();
}
}
}
std::cout << "Found " << const_parameter_count << " ("
<< strings::HumanReadableNum(const_parameter_count)
<< ") const parameters, " << variable_parameter_count << " ("
<< strings::HumanReadableNum(variable_parameter_count)
<< ") variable parameters, and " << control_edge_count
<< " control_edges" << std::endl;
if (!device_counts.empty()) {
for (const auto& device_info : device_counts) {
std::cout << device_info.second << " nodes assigned to device '"
<< device_info.first << "'";
}
}
std::vector<std::pair<string, string>> invalid_inputs;
FindInvalidInputs(graph, &invalid_inputs);
if (!invalid_inputs.empty()) {
for (const std::pair<string, string>& invalid_input : invalid_inputs) {
std::cout << "Invalid input " << invalid_input.second << " for node "
<< invalid_input.first << std::endl;
}
return errors::Internal(
"Invalid graph with inputs referring to nonexistent nodes");
}
std::map<string, int> op_counts;
for (const NodeDef& node : graph.node()) {
++op_counts[node.op()];
}
std::vector<std::pair<string, int>> op_counts_vec(op_counts.begin(),
op_counts.end());
std::sort(op_counts_vec.begin(), op_counts_vec.end(),
[](std::pair<string, int> a, std::pair<string, int> b) {
return (a.second > b.second);
});
std::cout << "Op types used: ";
bool is_first = true;
for (const std::pair<string, int>& op_count : op_counts_vec) {
if (!is_first) {
std::cout << ", ";
} else {
is_first = false;
}
std::cout << op_count.second << " " << op_count.first;
}
std::cout << std::endl;
PrintBenchmarkUsage(placeholders, variables, outputs, graph_path);
if (print_structure) {
TF_RETURN_IF_ERROR(PrintStructure(graph));
}
return Status::OK();
}
int ParseFlagsAndSummarizeGraph(int argc, char* argv[]) {
string in_graph = "";
bool print_structure = false;
std::vector<Flag> flag_list = {
Flag("in_graph", &in_graph, "input graph file name"),
Flag("print_structure", &print_structure,
"whether to print the network connections of the graph"),
};
string usage = Flags::Usage(argv[0], flag_list);
const bool parse_result = Flags::Parse(&argc, argv, flag_list);
// We need to call this to set up global state for TensorFlow.
port::InitMain(argv[0], &argc, &argv);
if (!parse_result) {
LOG(ERROR) << usage;
return -1;
}
if (argc > 1) {
LOG(ERROR) << "Unknown argument " << argv[1] << ".\n" << usage;
return -1;
}
if (in_graph.empty()) {
LOG(ERROR) << "in_graph graph can't be empty.\n" << usage;
return -1;
}
GraphDef graph_def;
Status load_status = LoadTextOrBinaryGraphFile(in_graph, &graph_def);
if (!load_status.ok()) {
LOG(ERROR) << "Loading graph '" << in_graph << "' failed with "
<< load_status.error_message();
LOG(ERROR) << usage;
return -1;
}
Status summarize_result =
SummarizeGraph(graph_def, in_graph, print_structure);
if (!summarize_result.ok()) {
LOG(ERROR) << summarize_result.error_message() << "\n" << usage;
return -1;
}
return 0;
}
} // namespace
} // namespace graph_transforms
} // namespace tensorflow
int main(int argc, char* argv[]) {
return tensorflow::graph_transforms::ParseFlagsAndSummarizeGraph(argc, argv);
}
<commit_msg>Fixed crash in graph summarization tool<commit_after>/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// This program prints out a summary of a GraphDef file's contents, listing
// things that are useful for debugging and reusing the model it contains. For
// example it looks at the graph structure and op types to figure out likely
// input and output nodes, and shows which ops are used by the graph. To use it,
// run something like this:
//
// bazel build tensorflow/tools/graph_transforms:summarize_graph
// bazel-bin/tensorflow/tools/graph_transforms/summarize_graph \
// --in_graph=my_graph.pb
#include "tensorflow/core/framework/attr_value.pb.h"
#include "tensorflow/core/framework/node_def.pb.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.pb.h"
#include "tensorflow/core/lib/strings/str_util.h"
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/platform/init_main.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/util/command_line_flags.h"
#include "tensorflow/tools/graph_transforms/transform_utils.h"
namespace tensorflow {
namespace graph_transforms {
namespace {
void PrintNodeInfo(const NodeDef* node) {
string shape_description = "None";
if (node->attr().count("shape")) {
TensorShapeProto shape_proto = node->attr().at("shape").shape();
Status shape_status = PartialTensorShape::IsValidShape(shape_proto);
if (shape_status.ok()) {
shape_description = PartialTensorShape(shape_proto).DebugString();
} else {
shape_description = shape_status.error_message();
}
}
DataType dtype = DT_INVALID;
if (node->attr().count("dtype")) {
dtype = node->attr().at("dtype").type();
}
std::cout << "(name=" << node->name();
std::cout << ", type=" << DataTypeString(dtype) << "(" << dtype << ")";
std::cout << ", shape=" << shape_description << ") ";
}
void PrintBenchmarkUsage(const std::vector<const NodeDef*>& placeholders,
const std::vector<const NodeDef*>& variables,
const std::vector<const NodeDef*> outputs,
const string& graph_path) {
std::vector<const NodeDef*> all_inputs(placeholders);
all_inputs.insert(all_inputs.end(), variables.begin(), variables.end());
std::vector<string> input_layers;
std::vector<string> input_layer_types;
std::vector<string> input_layer_shapes;
for (const NodeDef* node : all_inputs) {
input_layers.push_back(node->name());
DataType dtype = DT_INVALID;
if (node->attr().count("dtype")) {
dtype = node->attr().at("dtype").type();
}
input_layer_types.push_back(DataTypeString(dtype));
std::vector<int64> sizes;
PartialTensorShape shape;
if (node->attr().count("shape")) {
TensorShapeProto shape_proto = node->attr().at("shape").shape();
if (PartialTensorShape::IsValid(shape_proto)) {
shape = PartialTensorShape(shape_proto);
}
}
string sizes_string;
if (shape.dims() == -1) {
// Unknown shapes can have -1 for dims, so leave these blank.
sizes_string = "";
} else {
sizes.reserve(shape.dims());
for (int i = 0; i < shape.dims(); ++i) {
sizes.push_back(shape.dim_size(i));
}
sizes_string = str_util::Join(sizes, ",");
}
input_layer_shapes.push_back(sizes_string);
}
std::vector<string> output_layers;
output_layers.reserve(outputs.size());
for (const NodeDef* node : outputs) {
output_layers.push_back(node->name());
}
string input_layer_value = str_util::Join(input_layers, ",");
string input_layer_type_value = str_util::Join(input_layer_types, ",");
string input_layer_shape_value = str_util::Join(input_layer_shapes, ":");
string output_layer_value = str_util::Join(output_layers, ",");
std::cout << "To use with tensorflow/tools/benchmark:benchmark_model try "
"these arguments:"
<< std::endl;
std::cout << "bazel run tensorflow/tools/benchmark:benchmark_model --";
std::cout << " --graph=" << graph_path;
std::cout << " --show_flops";
std::cout << " --input_layer=" << input_layer_value;
std::cout << " --input_layer_type=" << input_layer_type_value;
std::cout << " --input_layer_shape=" << input_layer_shape_value;
std::cout << " --output_layer=" << output_layer_value;
std::cout << std::endl;
}
Status PrintStructure(const GraphDef& graph) {
GraphDef sorted_graph;
TF_RETURN_IF_ERROR(SortByExecutionOrder(graph, &sorted_graph));
for (const NodeDef& node : sorted_graph.node()) {
std::cout << node.name() << " (" << node.op() << "): ["
<< str_util::Join(node.input(), ", ") << "]";
if (node.op() == "Const") {
Tensor tensor;
if (node.attr().count("value") &&
tensor.FromProto(node.attr().at("value").tensor())) {
std::cout << ", value=" << tensor.DebugString();
} else {
LOG(WARNING) << "Decoding Tensor failed for node" << node.name();
}
}
std::cout << std::endl;
}
return Status::OK();
}
Status SummarizeGraph(const GraphDef& graph, const string& graph_path,
bool print_structure) {
std::vector<const NodeDef*> placeholders;
std::vector<const NodeDef*> variables;
for (const NodeDef& node : graph.node()) {
if (node.op() == "Placeholder") {
placeholders.push_back(&node);
}
if (node.op() == "Variable" || node.op() == "VariableV2") {
variables.push_back(&node);
}
}
if (placeholders.empty()) {
std::cout << "No inputs spotted." << std::endl;
} else {
std::cout << "Found " << placeholders.size() << " possible inputs: ";
for (const NodeDef* node : placeholders) {
PrintNodeInfo(node);
}
std::cout << std::endl;
}
if (variables.empty()) {
std::cout << "No variables spotted." << std::endl;
} else {
std::cout << "Found " << variables.size() << " variables: ";
for (const NodeDef* node : variables) {
PrintNodeInfo(node);
}
std::cout << std::endl;
}
std::map<string, std::vector<const NodeDef*>> output_map;
MapNodesToOutputs(graph, &output_map);
std::vector<const NodeDef*> outputs;
std::unordered_set<string> unlikely_output_types = {"Const", "Assign", "NoOp",
"Placeholder"};
for (const NodeDef& node : graph.node()) {
if ((output_map.count(node.name()) == 0) &&
(unlikely_output_types.count(node.op()) == 0)) {
outputs.push_back(&node);
}
}
if (outputs.empty()) {
std::cout << "No outputs spotted." << std::endl;
} else {
std::cout << "Found " << outputs.size() << " possible outputs: ";
for (const NodeDef* node : outputs) {
std::cout << "(name=" << node->name();
std::cout << ", op=" << node->op() << ") ";
}
std::cout << std::endl;
}
int64 const_parameter_count = 0;
int64 variable_parameter_count = 0;
int control_edge_count = 0;
std::map<string, int> device_counts;
for (const NodeDef& node : graph.node()) {
for (const string& input : node.input()) {
if (input.substr(0, 1) == "^") {
++control_edge_count;
}
}
if (!node.device().empty()) {
++device_counts[node.device()];
}
if ((node.op() == "Const") || (node.op() == "Variable") ||
(node.op() == "VariableV2")) {
Tensor tensor;
if (node.attr().count("value") &&
tensor.FromProto(node.attr().at("value").tensor())) {
const size_t num_elements = tensor.NumElements();
if (node.op() == "Const") {
const_parameter_count += num_elements;
} else {
variable_parameter_count += num_elements;
}
} else {
LOG(WARNING) << "Decoding Tensor failed for node" << node.name();
}
}
}
std::cout << "Found " << const_parameter_count << " ("
<< strings::HumanReadableNum(const_parameter_count)
<< ") const parameters, " << variable_parameter_count << " ("
<< strings::HumanReadableNum(variable_parameter_count)
<< ") variable parameters, and " << control_edge_count
<< " control_edges" << std::endl;
if (!device_counts.empty()) {
for (const auto& device_info : device_counts) {
std::cout << device_info.second << " nodes assigned to device '"
<< device_info.first << "'";
}
}
std::vector<std::pair<string, string>> invalid_inputs;
FindInvalidInputs(graph, &invalid_inputs);
if (!invalid_inputs.empty()) {
for (const std::pair<string, string>& invalid_input : invalid_inputs) {
std::cout << "Invalid input " << invalid_input.second << " for node "
<< invalid_input.first << std::endl;
}
return errors::Internal(
"Invalid graph with inputs referring to nonexistent nodes");
}
std::map<string, int> op_counts;
for (const NodeDef& node : graph.node()) {
++op_counts[node.op()];
}
std::vector<std::pair<string, int>> op_counts_vec(op_counts.begin(),
op_counts.end());
std::sort(op_counts_vec.begin(), op_counts_vec.end(),
[](std::pair<string, int> a, std::pair<string, int> b) {
return (a.second > b.second);
});
std::cout << "Op types used: ";
bool is_first = true;
for (const std::pair<string, int>& op_count : op_counts_vec) {
if (!is_first) {
std::cout << ", ";
} else {
is_first = false;
}
std::cout << op_count.second << " " << op_count.first;
}
std::cout << std::endl;
PrintBenchmarkUsage(placeholders, variables, outputs, graph_path);
if (print_structure) {
TF_RETURN_IF_ERROR(PrintStructure(graph));
}
return Status::OK();
}
int ParseFlagsAndSummarizeGraph(int argc, char* argv[]) {
string in_graph = "";
bool print_structure = false;
std::vector<Flag> flag_list = {
Flag("in_graph", &in_graph, "input graph file name"),
Flag("print_structure", &print_structure,
"whether to print the network connections of the graph"),
};
string usage = Flags::Usage(argv[0], flag_list);
const bool parse_result = Flags::Parse(&argc, argv, flag_list);
// We need to call this to set up global state for TensorFlow.
port::InitMain(argv[0], &argc, &argv);
if (!parse_result) {
LOG(ERROR) << usage;
return -1;
}
if (argc > 1) {
LOG(ERROR) << "Unknown argument " << argv[1] << ".\n" << usage;
return -1;
}
if (in_graph.empty()) {
LOG(ERROR) << "in_graph graph can't be empty.\n" << usage;
return -1;
}
GraphDef graph_def;
Status load_status = LoadTextOrBinaryGraphFile(in_graph, &graph_def);
if (!load_status.ok()) {
LOG(ERROR) << "Loading graph '" << in_graph << "' failed with "
<< load_status.error_message();
LOG(ERROR) << usage;
return -1;
}
Status summarize_result =
SummarizeGraph(graph_def, in_graph, print_structure);
if (!summarize_result.ok()) {
LOG(ERROR) << summarize_result.error_message() << "\n" << usage;
return -1;
}
return 0;
}
} // namespace
} // namespace graph_transforms
} // namespace tensorflow
int main(int argc, char* argv[]) {
return tensorflow::graph_transforms::ParseFlagsAndSummarizeGraph(argc, argv);
}
<|endoftext|>
|
<commit_before>////////////////////////////////////////////////////////////////////////
// This file is part of Grappa, a system for scaling irregular
// applications on commodity clusters.
// Copyright (C) 2010-2014 University of Washington and Battelle
// Memorial Institute. University of Washington authorizes use of this
// Grappa software.
// Grappa is free software: you can redistribute it and/or modify it
// under the terms of the Affero General Public License as published
// by Affero, Inc., either version 1 of the License, or (at your
// option) any later version.
// Grappa 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
// Affero General Public License for more details.
// You should have received a copy of the Affero General Public
// License along with this program. If not, you may obtain one from
// http://www.affero.org/oagpl.html.
////////////////////////////////////////////////////////////////////////
#pragma once
#include "Addressing.hpp"
#include "Communicator.hpp"
#include "Collective.hpp"
#include "Cache.hpp"
#include "GlobalCompletionEvent.hpp"
#include "ParallelLoop.hpp"
#include "GlobalAllocator.hpp"
#include <type_traits>
#include "Delegate.hpp"
namespace Grappa {
/// @addtogroup Containers
/// @{
/// Initialize an array of elements of generic type with a given value.
///
/// This version sends a large number of active messages, the same way as the Incoherent
/// releaser, to set each part of a global array. In theory, this version should be able
/// to be called from multiple locations at the same time (to initialize different regions of global memory).
///
/// @param base Base address of the array to be set.
/// @param value Value to set every element of array to (will be copied to all the nodes)
/// @param count Number of elements to set, starting at the base address.
template< typename T, typename S >
void memset(GlobalAddress<T> base, S value, size_t count) {
call_on_all_cores([base,count,value]{
T * local_base = base.localize();
T * local_end = (base+count).localize();
for (size_t i=0; i<local_end-local_base; i++) {
local_base[i] = value;
}
});
}
/// Type-based memset for local arrays to match what is provided for distributed arrays.
template< typename T, typename S >
void memset(T* base, S value, size_t count) {
for (size_t i=0; i < count; i++) {
base[i] = value;
}
}
namespace impl {
/// Copy elements of array (src..src+nelem) that are local to corresponding locations in dst
template< typename T >
void do_memcpy_locally(GlobalAddress<T> dst, GlobalAddress<T> src, size_t nelem) {
typedef typename Incoherent<T>::WO Writeback;
auto src_end = src+nelem;
// T * local_base = src.localize(), * local_end = (src+nelem).localize();
int64_t nfirstcore = src.block_max() - src;
int64_t nlastcore = src_end - src_end.block_min();
int64_t nmiddle = nelem - nfirstcore - nlastcore;
const size_t nblock = block_size / sizeof(T);
CHECK_EQ(nmiddle % nblock, 0);
auto src_start = src;
if (src.core() == mycore()) {
int64_t nfirstcore = src.block_max() - src;
if (nfirstcore > 0 && nlastcore != nblock) {
DVLOG(3) << "nfirstcore = " << nfirstcore;
Writeback w(dst, nfirstcore, src.pointer());
src_start += nfirstcore;
}
}
if ((src_end-1).core() == mycore()) {
int64_t nlastcore = src_end - src_end.block_min();
int64_t index = nelem - nlastcore;
if (nlastcore > 0 && nlastcore != nblock) {
DVLOG(3) << "nlastcore = " << nlastcore << ", index = " << index;
CHECK((src+index).core() == mycore());
Writeback w(dst+index, nlastcore, (src+index).pointer());
src_end -= nlastcore;
}
}
auto * local_base = src_start.localize();
size_t nlocal_trimmed = src_end.localize() - local_base;
CHECK_EQ((nlocal_trimmed) % nblock, 0);
size_t nlocalblocks = nlocal_trimmed/nblock;
Writeback * ws = locale_alloc<Writeback>(nlocalblocks);
for (size_t i=0; i<nlocalblocks; i++) {
size_t j = make_linear(local_base+(i*nblock))-src;
new (ws+i) Writeback(dst+j, nblock, local_base+(i*nblock));
ws[i].start_release();
}
for (size_t i=0; i<nlocalblocks; i++) { ws[i].block_until_released(); }
locale_free(ws);
}
}
/// Memcpy over Grappa global arrays. Arguments `dst` and `src` must point into global arrays
/// (so must be linear addresses) and be non-overlapping, and both must have at least `nelem`
/// elements.
template< typename T >
void memcpy(GlobalAddress<T> dst, GlobalAddress<T> src, size_t nelem) {
on_all_cores([dst,src,nelem]{
impl::do_memcpy_locally(dst,src,nelem);
});
}
/// Helper so we don't have to change the code if we change a Global pointer to a normal pointer (in theory).
template< typename T >
inline void memcpy(T* dst, T* src, size_t nelem) {
::memcpy(dst, src, nelem*sizeof(T));
}
template<>
inline void memcpy<void>(void* dst, void* src, size_t nelem) {
::memcpy(dst, src, nelem);
}
/// Asynchronous version of memcpy, spawns only on cores with array elements. Synchronizes
/// with given GlobalCompletionEvent, so memcpy's are known to be complete after GCE->wait().
/// Note: same restrictions on `dst` and `src` as Grappa::memcpy).
template< GlobalCompletionEvent * GCE = &impl::local_gce, typename T = void >
void memcpy_async(GlobalAddress<T> dst, GlobalAddress<T> src, size_t nelem) {
on_cores_localized_async<GCE>(src, nelem, [dst,src,nelem](T* base, size_t nlocal){
impl::do_memcpy_locally(dst,src,nelem);
});
}
/// not implemented yet
template< typename T >
void prefix_sum(GlobalAddress<T> array, size_t nelem) {
// not implemented
CHECK(false) << "prefix_sum is currently unimplemented!";
}
namespace util {
/// String representation of a global array.
/// @example
/// @code
/// GlobalAddress<int> xs;
/// DVLOG(2) << array_str("x", xs, 4);
/// // (if DEBUG=1 and --v=2)
/// //> x: [
/// //> 7 4 2 3
/// //> ]
/// @endcode
template<typename T>
inline std::string array_str(const char * name, GlobalAddress<T> base, size_t nelem, int width = 10) {
std::stringstream ss; ss << "\n" << name << ": [";
for (size_t i=0; i<nelem; i++) {
if (i % width == 0) ss << "\n ";
ss << " " << delegate::read(base+i);
}
ss << "\n]";
return ss.str();
}
template< typename ArrayT, int width = 10 >
inline std::string array_str(const char * name, const ArrayT& array) {
bool multiline = array.size() > width;
std::stringstream ss;
if (name) {
ss << name << ": ";
}
ss << "[";
long i=0;
for (auto e : array) {
if (i % width == 0 && multiline) ss << "\n ";
ss << " " << e;
i++;
}
ss << (multiline ? "\n" : " ") << "]";
return ss.str();
}
template< typename ArrayT, int width = 10 >
inline std::string array_str(const ArrayT& array) {
return array_str(nullptr, array);
}
template<typename T>
struct SimpleIterator {
T * base;
size_t nelem;
T * begin() { return base; }
T * end() { return base+nelem; }
const T * begin() const { return base; }
const T * end() const { return base+nelem; }
size_t size() const { return nelem; }
};
/// Easier C++11 iteration over local array. Similar idea to Addressing::iterate_local().
///
/// @code
/// auto array = new long[N];
/// for (auto& v : util::iterate(array,N)) {
/// v++;
/// }
/// @endcode
template<typename T>
SimpleIterator<T> iterate(T* base = nullptr, size_t nelem = 0) { return SimpleIterator<T>{base, nelem}; }
/// String representation of a local array, matches form of Grappa::array_str that takes a global array.
template<typename T, int width = 10>
inline std::string array_str(const char * name, T * base, size_t nelem) {
return array_str(name, iterate(base, nelem));
}
} // namespace util
/// @}
} // namespace Grappa
template< typename T >
std::ostream& operator<<(std::ostream& o, std::vector<T> v) {
o << Grappa::util::array_str(nullptr, &v[0], v.size());
return o;
}
<commit_msg>allow specifying width of array_str<commit_after>////////////////////////////////////////////////////////////////////////
// This file is part of Grappa, a system for scaling irregular
// applications on commodity clusters.
// Copyright (C) 2010-2014 University of Washington and Battelle
// Memorial Institute. University of Washington authorizes use of this
// Grappa software.
// Grappa is free software: you can redistribute it and/or modify it
// under the terms of the Affero General Public License as published
// by Affero, Inc., either version 1 of the License, or (at your
// option) any later version.
// Grappa 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
// Affero General Public License for more details.
// You should have received a copy of the Affero General Public
// License along with this program. If not, you may obtain one from
// http://www.affero.org/oagpl.html.
////////////////////////////////////////////////////////////////////////
#pragma once
#include "Addressing.hpp"
#include "Communicator.hpp"
#include "Collective.hpp"
#include "Cache.hpp"
#include "GlobalCompletionEvent.hpp"
#include "ParallelLoop.hpp"
#include "GlobalAllocator.hpp"
#include <type_traits>
#include "Delegate.hpp"
namespace Grappa {
/// @addtogroup Containers
/// @{
/// Initialize an array of elements of generic type with a given value.
///
/// This version sends a large number of active messages, the same way as the Incoherent
/// releaser, to set each part of a global array. In theory, this version should be able
/// to be called from multiple locations at the same time (to initialize different regions of global memory).
///
/// @param base Base address of the array to be set.
/// @param value Value to set every element of array to (will be copied to all the nodes)
/// @param count Number of elements to set, starting at the base address.
template< typename T, typename S >
void memset(GlobalAddress<T> base, S value, size_t count) {
call_on_all_cores([base,count,value]{
T * local_base = base.localize();
T * local_end = (base+count).localize();
for (size_t i=0; i<local_end-local_base; i++) {
local_base[i] = value;
}
});
}
/// Type-based memset for local arrays to match what is provided for distributed arrays.
template< typename T, typename S >
void memset(T* base, S value, size_t count) {
for (size_t i=0; i < count; i++) {
base[i] = value;
}
}
namespace impl {
/// Copy elements of array (src..src+nelem) that are local to corresponding locations in dst
template< typename T >
void do_memcpy_locally(GlobalAddress<T> dst, GlobalAddress<T> src, size_t nelem) {
typedef typename Incoherent<T>::WO Writeback;
auto src_end = src+nelem;
// T * local_base = src.localize(), * local_end = (src+nelem).localize();
int64_t nfirstcore = src.block_max() - src;
int64_t nlastcore = src_end - src_end.block_min();
int64_t nmiddle = nelem - nfirstcore - nlastcore;
const size_t nblock = block_size / sizeof(T);
CHECK_EQ(nmiddle % nblock, 0);
auto src_start = src;
if (src.core() == mycore()) {
int64_t nfirstcore = src.block_max() - src;
if (nfirstcore > 0 && nlastcore != nblock) {
DVLOG(3) << "nfirstcore = " << nfirstcore;
Writeback w(dst, nfirstcore, src.pointer());
src_start += nfirstcore;
}
}
if ((src_end-1).core() == mycore()) {
int64_t nlastcore = src_end - src_end.block_min();
int64_t index = nelem - nlastcore;
if (nlastcore > 0 && nlastcore != nblock) {
DVLOG(3) << "nlastcore = " << nlastcore << ", index = " << index;
CHECK((src+index).core() == mycore());
Writeback w(dst+index, nlastcore, (src+index).pointer());
src_end -= nlastcore;
}
}
auto * local_base = src_start.localize();
size_t nlocal_trimmed = src_end.localize() - local_base;
CHECK_EQ((nlocal_trimmed) % nblock, 0);
size_t nlocalblocks = nlocal_trimmed/nblock;
Writeback * ws = locale_alloc<Writeback>(nlocalblocks);
for (size_t i=0; i<nlocalblocks; i++) {
size_t j = make_linear(local_base+(i*nblock))-src;
new (ws+i) Writeback(dst+j, nblock, local_base+(i*nblock));
ws[i].start_release();
}
for (size_t i=0; i<nlocalblocks; i++) { ws[i].block_until_released(); }
locale_free(ws);
}
}
/// Memcpy over Grappa global arrays. Arguments `dst` and `src` must point into global arrays
/// (so must be linear addresses) and be non-overlapping, and both must have at least `nelem`
/// elements.
template< typename T >
void memcpy(GlobalAddress<T> dst, GlobalAddress<T> src, size_t nelem) {
on_all_cores([dst,src,nelem]{
impl::do_memcpy_locally(dst,src,nelem);
});
}
/// Helper so we don't have to change the code if we change a Global pointer to a normal pointer (in theory).
template< typename T >
inline void memcpy(T* dst, T* src, size_t nelem) {
::memcpy(dst, src, nelem*sizeof(T));
}
template<>
inline void memcpy<void>(void* dst, void* src, size_t nelem) {
::memcpy(dst, src, nelem);
}
/// Asynchronous version of memcpy, spawns only on cores with array elements. Synchronizes
/// with given GlobalCompletionEvent, so memcpy's are known to be complete after GCE->wait().
/// Note: same restrictions on `dst` and `src` as Grappa::memcpy).
template< GlobalCompletionEvent * GCE = &impl::local_gce, typename T = void >
void memcpy_async(GlobalAddress<T> dst, GlobalAddress<T> src, size_t nelem) {
on_cores_localized_async<GCE>(src, nelem, [dst,src,nelem](T* base, size_t nlocal){
impl::do_memcpy_locally(dst,src,nelem);
});
}
/// not implemented yet
template< typename T >
void prefix_sum(GlobalAddress<T> array, size_t nelem) {
// not implemented
CHECK(false) << "prefix_sum is currently unimplemented!";
}
namespace util {
/// String representation of a global array.
/// @example
/// @code
/// GlobalAddress<int> xs;
/// DVLOG(2) << array_str("x", xs, 4);
/// // (if DEBUG=1 and --v=2)
/// //> x: [
/// //> 7 4 2 3
/// //> ]
/// @endcode
template<typename T>
inline std::string array_str(const char * name, GlobalAddress<T> base, size_t nelem, int width = 10) {
std::stringstream ss; ss << "\n" << name << ": [";
for (size_t i=0; i<nelem; i++) {
if (i % width == 0) ss << "\n ";
ss << " " << delegate::read(base+i);
}
ss << "\n]";
return ss.str();
}
template< int width = 10, typename ArrayT = nullptr_t >
inline std::string array_str(const char * name, const ArrayT& array) {
bool multiline = array.size() > width;
std::stringstream ss;
if (name) {
ss << name << ": ";
}
ss << "[";
long i=0;
for (auto e : array) {
if (i % width == 0 && multiline) ss << "\n ";
ss << " " << e;
i++;
}
ss << (multiline ? "\n" : " ") << "]";
return ss.str();
}
template< int width = 10, typename ArrayT = nullptr_t >
inline std::string array_str(const ArrayT& array) {
return array_str(nullptr, array);
}
template<typename T>
struct SimpleIterator {
T * base;
size_t nelem;
T * begin() { return base; }
T * end() { return base+nelem; }
const T * begin() const { return base; }
const T * end() const { return base+nelem; }
size_t size() const { return nelem; }
};
/// Easier C++11 iteration over local array. Similar idea to Addressing::iterate_local().
///
/// @code
/// auto array = new long[N];
/// for (auto& v : util::iterate(array,N)) {
/// v++;
/// }
/// @endcode
template<typename T>
SimpleIterator<T> iterate(T* base = nullptr, size_t nelem = 0) { return SimpleIterator<T>{base, nelem}; }
/// String representation of a local array, matches form of Grappa::array_str that takes a global array.
template< int width = 10, typename T = nullptr_t >
inline std::string array_str(const char * name, T * base, size_t nelem) {
return array_str(name, iterate(base, nelem));
}
} // namespace util
/// @}
} // namespace Grappa
template< typename T >
std::ostream& operator<<(std::ostream& o, std::vector<T> v) {
o << Grappa::util::array_str(nullptr, &v[0], v.size());
return o;
}
<|endoftext|>
|
<commit_before>#include <Halide.h>
#include <stdio.h>
#include "clock.h"
using namespace Halide;
int main(int argc, char **argv) {
Func f;
Var x, y;
f(x, y) = x + y;
f.parallel(x);
// Having more threads than tasks shouldn't hurt performance too much.
double correct_time = 0;
for (int t = 2; t <= 64; t *= 2) {
std::ostringstream ss;
ss << "HL_NUM_THREADS=" << t;
putenv(ss.str().c_str());
Halide::Internal::JITSharedRuntime::release_all();
f.compile_jit();
// Start the thread pool without giving any hints as to the
// number of tasks we'll be using.
f.realize(t, 1);
double min_time = 1e20;
for (int i = 0; i < 3; i++) {
double t1 = current_time();
f.realize(2, 1000000);
double t2 = current_time() - t1;
if (t2 < min_time) min_time = t2;
}
printf("%d: %f ms\n", t, min_time);
if (t == 2) {
correct_time = min_time;
} else if (min_time > correct_time * 5) {
printf("Unacceptable overhead when using %d threads for 2 tasks: %f ms vs %f ms\n",
t, min_time, correct_time);
return -1;
}
}
printf("Success!\n");
return 0;
}
<commit_msg>putenv takes a char *<commit_after>#include <Halide.h>
#include <stdio.h>
#include "clock.h"
using namespace Halide;
int main(int argc, char **argv) {
Func f;
Var x, y;
f(x, y) = x + y;
f.parallel(x);
// Having more threads than tasks shouldn't hurt performance too much.
double correct_time = 0;
for (int t = 2; t <= 64; t *= 2) {
std::ostringstream ss;
ss << "HL_NUM_THREADS=" << t;
std::string str = ss.str();
char buf[32] = {0};
memcpy(buf, str.c_str(), str.size());
putenv(buf);
Halide::Internal::JITSharedRuntime::release_all();
f.compile_jit();
// Start the thread pool without giving any hints as to the
// number of tasks we'll be using.
f.realize(t, 1);
double min_time = 1e20;
for (int i = 0; i < 3; i++) {
double t1 = current_time();
f.realize(2, 1000000);
double t2 = current_time() - t1;
if (t2 < min_time) min_time = t2;
}
printf("%d: %f ms\n", t, min_time);
if (t == 2) {
correct_time = min_time;
} else if (min_time > correct_time * 5) {
printf("Unacceptable overhead when using %d threads for 2 tasks: %f ms vs %f ms\n",
t, min_time, correct_time);
return -1;
}
}
printf("Success!\n");
return 0;
}
<|endoftext|>
|
<commit_before>/**
* Appcelerator Kroll - licensed under the Apache Public License 2
* see LICENSE in the root folder for details on the license.
* Copyright (c) 2009 Appcelerator, Inc. All Rights Reserved.
*/
#include "utils.h"
#include <cstdio>
namespace UTILS_NS
{
namespace PlatformUtils
{
std::string GetFirstMACAddress()
{
MACAddress address;
memset(&address, 0, sizeof(MACAddress));
try
{
PlatformUtils::GetFirstMACAddressImpl(address);
}
catch(...)
{
// Just return zeros.
}
char result[18];
std::sprintf(result, "%02x:%02x:%02x:%02x:%02x:%02x",
address[0], address[1], address[2], address[3],
address[4], address[5]);
return std::string(result);
}
std::string GetMachineId()
{
static std::string machineID;
if (machineID.empty())
machineID = DataUtils::HexMD5(GetFirstMACAddress());
return machineID;
}
}
}
<commit_msg>Fix build error on Linux.<commit_after>/**
* Appcelerator Kroll - licensed under the Apache Public License 2
* see LICENSE in the root folder for details on the license.
* Copyright (c) 2009 Appcelerator, Inc. All Rights Reserved.
*/
#include "utils.h"
#include <stdio.h>
#include <string.h>
namespace UTILS_NS
{
namespace PlatformUtils
{
std::string GetFirstMACAddress()
{
MACAddress address;
memset(&address, 0, sizeof(MACAddress));
try
{
PlatformUtils::GetFirstMACAddressImpl(address);
}
catch(...)
{
// Just return zeros.
}
char result[18];
std::sprintf(result, "%02x:%02x:%02x:%02x:%02x:%02x",
address[0], address[1], address[2], address[3],
address[4], address[5]);
return std::string(result);
}
std::string GetMachineId()
{
static std::string machineID;
if (machineID.empty())
machineID = DataUtils::HexMD5(GetFirstMACAddress());
return machineID;
}
}
}
<|endoftext|>
|
<commit_before><commit_msg>clang format<commit_after><|endoftext|>
|
<commit_before>//---------------------------------------------------------------------------
// Greenplum Database
// Copyright (C) 2011 Greenplum, Inc.
//
// @filename:
// CMDIdGPDB.cpp
//
// @doc:
// Implementation of metadata identifiers
//---------------------------------------------------------------------------
#include "naucrates/md/CMDIdGPDB.h"
#include "naucrates/dxl/xml/CXMLSerializer.h"
using namespace gpos;
using namespace gpmd;
// initialize static members
// invalid key
CMDIdGPDB CMDIdGPDB::m_mdid_invalid_key(0, 0, 0);
// int2 mdid
CMDIdGPDB CMDIdGPDB::m_mdid_int2(GPDB_INT2);
// int4 mdid
CMDIdGPDB CMDIdGPDB::m_mdid_int4(GPDB_INT4);
// int8 mdid
CMDIdGPDB CMDIdGPDB::m_mdid_int8(GPDB_INT8);
// bool mdid
CMDIdGPDB CMDIdGPDB::m_mdid_bool(GPDB_BOOL);
// oid mdid
CMDIdGPDB CMDIdGPDB::m_mdid_oid(GPDB_OID);
// numeric mdid
CMDIdGPDB CMDIdGPDB::m_mdid_numeric(GPDB_NUMERIC);
// date mdid
CMDIdGPDB CMDIdGPDB::m_mdid_date(GPDB_DATE);
// time mdid
CMDIdGPDB CMDIdGPDB::m_mdid_time(GPDB_TIME);
// time with time zone mdid
CMDIdGPDB CMDIdGPDB::m_mdid_timeTz(GPDB_TIMETZ);
// timestamp mdid
CMDIdGPDB CMDIdGPDB::m_mdid_timestamp(GPDB_TIMESTAMP);
// timestamp with time zone mdid
CMDIdGPDB CMDIdGPDB::m_mdid_timestampTz(GPDB_TIMESTAMPTZ);
// absolute time mdid
CMDIdGPDB CMDIdGPDB::m_mdid_abs_time(GPDB_ABSTIME);
// relative time mdid
CMDIdGPDB CMDIdGPDB::m_mdid_relative_time(GPDB_RELTIME);
// interval mdid
CMDIdGPDB CMDIdGPDB::m_mdid_interval(GPDB_INTERVAL);
// time interval mdid
CMDIdGPDB CMDIdGPDB::m_mdid_time_interval(GPDB_TIMEINTERVAL);
// bpchar mdid
CMDIdGPDB CMDIdGPDB::m_mdid_bpchar(GPDB_CHAR);
// varchar mdid
CMDIdGPDB CMDIdGPDB::m_mdid_varchar(GPDB_VARCHAR);
// text mdid
CMDIdGPDB CMDIdGPDB::m_mdid_text(GPDB_TEXT);
// float4 mdid
CMDIdGPDB CMDIdGPDB::m_mdid_float4(GPDB_FLOAT4);
// float8 mdid
CMDIdGPDB CMDIdGPDB::m_mdid_float8(GPDB_FLOAT8);
// cash mdid
CMDIdGPDB CMDIdGPDB::m_mdid_cash(GPDB_CASH);
// inet mdid
CMDIdGPDB CMDIdGPDB::m_mdid_inet(GPDB_INET);
// cidr mdid
CMDIdGPDB CMDIdGPDB::m_mdid_cidr(GPDB_CIDR);
// macaddr mdid
CMDIdGPDB CMDIdGPDB::m_mdid_macaddr(GPDB_MACADDR);
// count(*) mdid
CMDIdGPDB CMDIdGPDB::m_mdid_count_star(GPDB_COUNT_STAR);
// count(Any) mdid
CMDIdGPDB CMDIdGPDB::m_mdid_count_any(GPDB_COUNT_ANY);
// uuid mdid
CMDIdGPDB CMDIdGPDB::m_mdid_uuid(GPDB_UUID);
// unknown mdid
CMDIdGPDB CMDIdGPDB::m_mdid_unknown(GPDB_UNKNOWN);
//---------------------------------------------------------------------------
// @function:
// CMDIdGPDB::CMDIdGPDB
//
// @doc:
// Constructs a metadata identifier with specified oid and default version
// of 1.0
//
//---------------------------------------------------------------------------
CMDIdGPDB::CMDIdGPDB
(
CSystemId sysid,
OID oid
)
:
m_sysid(sysid),
m_oid(oid),
m_major_version(1),
m_minor_version(0),
m_str(m_mdid_array, GPOS_ARRAY_SIZE(m_mdid_array))
{
if (CMDIdGPDB::m_mdid_invalid_key.Oid() == oid)
{
// construct an invalid mdid 0.0.0
m_major_version = 0;
}
// serialize mdid into static string
Serialize();
}
//---------------------------------------------------------------------------
// @function:
// CMDIdGPDB::CMDIdGPDB
//
// @doc:
// Constructs a metadata identifier with specified oid and default version
// of 1.0
//
//---------------------------------------------------------------------------
CMDIdGPDB::CMDIdGPDB
(
OID oid
)
:
m_sysid(IMDId::EmdidGPDB, GPMD_GPDB_SYSID),
m_oid(oid),
m_major_version(1),
m_minor_version(0),
m_str(m_mdid_array, GPOS_ARRAY_SIZE(m_mdid_array))
{
if (CMDIdGPDB::m_mdid_invalid_key.Oid() == oid)
{
// construct an invalid mdid 0.0.0
m_major_version = 0;
}
// TODO: - Jan 31, 2012; supply system id in constructor
// serialize mdid into static string
Serialize();
}
//---------------------------------------------------------------------------
// @function:
// CMDIdGPDB::CMDIdGPDB
//
// @doc:
// Constructs a metadata identifier
//
//---------------------------------------------------------------------------
CMDIdGPDB::CMDIdGPDB
(
OID oid,
ULONG version_major,
ULONG version_minor
)
:
m_sysid(IMDId::EmdidGPDB, GPMD_GPDB_SYSID),
m_oid(oid),
m_major_version(version_major),
m_minor_version(version_minor),
m_str(m_mdid_array, GPOS_ARRAY_SIZE(m_mdid_array))
{
// TODO: - Jan 31, 2012; supply system id in constructor
// serialize mdid into static string
Serialize();
}
//---------------------------------------------------------------------------
// @function:
// CMDIdGPDB::CMDIdGPDB
//
// @doc:
// Copy constructor
//
//---------------------------------------------------------------------------
CMDIdGPDB::CMDIdGPDB
(
const CMDIdGPDB &mdid_source
)
:
IMDId(),
m_sysid(mdid_source.Sysid()),
m_oid(mdid_source.Oid()),
m_major_version(mdid_source.VersionMajor()),
m_minor_version(mdid_source.VersionMinor()),
m_str(m_mdid_array, GPOS_ARRAY_SIZE(m_mdid_array))
{
GPOS_ASSERT(mdid_source.IsValid());
GPOS_ASSERT(IMDId::EmdidGPDB == mdid_source.MdidType());
// serialize mdid into static string
Serialize();
}
//---------------------------------------------------------------------------
// @function:
// CMDIdGPDB::Serialize
//
// @doc:
// Serialize mdid into static string
//
//---------------------------------------------------------------------------
void
CMDIdGPDB::Serialize()
{
m_str.Reset();
// serialize mdid as SystemType.Oid.Major.Minor
m_str.AppendFormat(GPOS_WSZ_LIT("%d.%d.%d.%d"), MdidType(), m_oid, m_major_version, m_minor_version);
}
//---------------------------------------------------------------------------
// @function:
// CMDIdGPDB::GetBuffer
//
// @doc:
// Returns the string representation of the mdid
//
//---------------------------------------------------------------------------
const WCHAR *
CMDIdGPDB::GetBuffer() const
{
return m_str.GetBuffer();
}
//---------------------------------------------------------------------------
// @function:
// CMDIdGPDB::Oid
//
// @doc:
// Returns the object id
//
//---------------------------------------------------------------------------
OID
CMDIdGPDB::Oid() const
{
return m_oid;
}
//---------------------------------------------------------------------------
// @function:
// CMDIdGPDB::VersionMajor
//
// @doc:
// Returns the object's major version
//
//---------------------------------------------------------------------------
ULONG
CMDIdGPDB::VersionMajor() const
{
return m_major_version;
}
//---------------------------------------------------------------------------
// @function:
// CMDIdGPDB::VersionMinor
//
// @doc:
// Returns the object's minor version
//
//---------------------------------------------------------------------------
ULONG
CMDIdGPDB::VersionMinor() const
{
return m_minor_version;
}
//---------------------------------------------------------------------------
// @function:
// CMDIdGPDB::Equals
//
// @doc:
// Checks if the version of the current object is compatible with another version
// of the same object
//
//---------------------------------------------------------------------------
BOOL
CMDIdGPDB::Equals
(
const IMDId *mdid
)
const
{
if (NULL == mdid || EmdidGPDB != mdid->MdidType())
{
return false;
}
const CMDIdGPDB *mdidGPDB = CMDIdGPDB::CastMdid(const_cast<IMDId *>(mdid));
return (m_oid == mdidGPDB->Oid() && m_major_version == mdidGPDB->VersionMajor() &&
m_minor_version == mdidGPDB->VersionMinor());
}
//---------------------------------------------------------------------------
// @function:
// CMDIdGPDB::IsValid
//
// @doc:
// Is the mdid valid
//
//---------------------------------------------------------------------------
BOOL
CMDIdGPDB::IsValid() const
{
return !Equals(&CMDIdGPDB::m_mdid_invalid_key);
}
//---------------------------------------------------------------------------
// @function:
// CMDIdGPDB::Serialize
//
// @doc:
// Serializes the mdid as the value of the given attribute
//
//---------------------------------------------------------------------------
void
CMDIdGPDB::Serialize
(
CXMLSerializer * xml_serializer,
const CWStringConst *attribute_str
)
const
{
xml_serializer->AddAttribute(attribute_str, &m_str);
}
//---------------------------------------------------------------------------
// @function:
// CMDIdGPDB::OsPrint
//
// @doc:
// Debug print of the id in the provided stream
//
//---------------------------------------------------------------------------
IOstream &
CMDIdGPDB::OsPrint
(
IOstream &os
)
const
{
os << "(" << Oid() << "," <<
VersionMajor() << "." << VersionMinor() << ")";
return os;
}
// EOF
<commit_msg>Remove unnecessary dynamic cast<commit_after>//---------------------------------------------------------------------------
// Greenplum Database
// Copyright (C) 2011 Greenplum, Inc.
//
// @filename:
// CMDIdGPDB.cpp
//
// @doc:
// Implementation of metadata identifiers
//---------------------------------------------------------------------------
#include "naucrates/md/CMDIdGPDB.h"
#include "naucrates/dxl/xml/CXMLSerializer.h"
using namespace gpos;
using namespace gpmd;
// initialize static members
// invalid key
CMDIdGPDB CMDIdGPDB::m_mdid_invalid_key(0, 0, 0);
// int2 mdid
CMDIdGPDB CMDIdGPDB::m_mdid_int2(GPDB_INT2);
// int4 mdid
CMDIdGPDB CMDIdGPDB::m_mdid_int4(GPDB_INT4);
// int8 mdid
CMDIdGPDB CMDIdGPDB::m_mdid_int8(GPDB_INT8);
// bool mdid
CMDIdGPDB CMDIdGPDB::m_mdid_bool(GPDB_BOOL);
// oid mdid
CMDIdGPDB CMDIdGPDB::m_mdid_oid(GPDB_OID);
// numeric mdid
CMDIdGPDB CMDIdGPDB::m_mdid_numeric(GPDB_NUMERIC);
// date mdid
CMDIdGPDB CMDIdGPDB::m_mdid_date(GPDB_DATE);
// time mdid
CMDIdGPDB CMDIdGPDB::m_mdid_time(GPDB_TIME);
// time with time zone mdid
CMDIdGPDB CMDIdGPDB::m_mdid_timeTz(GPDB_TIMETZ);
// timestamp mdid
CMDIdGPDB CMDIdGPDB::m_mdid_timestamp(GPDB_TIMESTAMP);
// timestamp with time zone mdid
CMDIdGPDB CMDIdGPDB::m_mdid_timestampTz(GPDB_TIMESTAMPTZ);
// absolute time mdid
CMDIdGPDB CMDIdGPDB::m_mdid_abs_time(GPDB_ABSTIME);
// relative time mdid
CMDIdGPDB CMDIdGPDB::m_mdid_relative_time(GPDB_RELTIME);
// interval mdid
CMDIdGPDB CMDIdGPDB::m_mdid_interval(GPDB_INTERVAL);
// time interval mdid
CMDIdGPDB CMDIdGPDB::m_mdid_time_interval(GPDB_TIMEINTERVAL);
// bpchar mdid
CMDIdGPDB CMDIdGPDB::m_mdid_bpchar(GPDB_CHAR);
// varchar mdid
CMDIdGPDB CMDIdGPDB::m_mdid_varchar(GPDB_VARCHAR);
// text mdid
CMDIdGPDB CMDIdGPDB::m_mdid_text(GPDB_TEXT);
// float4 mdid
CMDIdGPDB CMDIdGPDB::m_mdid_float4(GPDB_FLOAT4);
// float8 mdid
CMDIdGPDB CMDIdGPDB::m_mdid_float8(GPDB_FLOAT8);
// cash mdid
CMDIdGPDB CMDIdGPDB::m_mdid_cash(GPDB_CASH);
// inet mdid
CMDIdGPDB CMDIdGPDB::m_mdid_inet(GPDB_INET);
// cidr mdid
CMDIdGPDB CMDIdGPDB::m_mdid_cidr(GPDB_CIDR);
// macaddr mdid
CMDIdGPDB CMDIdGPDB::m_mdid_macaddr(GPDB_MACADDR);
// count(*) mdid
CMDIdGPDB CMDIdGPDB::m_mdid_count_star(GPDB_COUNT_STAR);
// count(Any) mdid
CMDIdGPDB CMDIdGPDB::m_mdid_count_any(GPDB_COUNT_ANY);
// uuid mdid
CMDIdGPDB CMDIdGPDB::m_mdid_uuid(GPDB_UUID);
// unknown mdid
CMDIdGPDB CMDIdGPDB::m_mdid_unknown(GPDB_UNKNOWN);
//---------------------------------------------------------------------------
// @function:
// CMDIdGPDB::CMDIdGPDB
//
// @doc:
// Constructs a metadata identifier with specified oid and default version
// of 1.0
//
//---------------------------------------------------------------------------
CMDIdGPDB::CMDIdGPDB
(
CSystemId sysid,
OID oid
)
:
m_sysid(sysid),
m_oid(oid),
m_major_version(1),
m_minor_version(0),
m_str(m_mdid_array, GPOS_ARRAY_SIZE(m_mdid_array))
{
if (CMDIdGPDB::m_mdid_invalid_key.Oid() == oid)
{
// construct an invalid mdid 0.0.0
m_major_version = 0;
}
// serialize mdid into static string
Serialize();
}
//---------------------------------------------------------------------------
// @function:
// CMDIdGPDB::CMDIdGPDB
//
// @doc:
// Constructs a metadata identifier with specified oid and default version
// of 1.0
//
//---------------------------------------------------------------------------
CMDIdGPDB::CMDIdGPDB
(
OID oid
)
:
m_sysid(IMDId::EmdidGPDB, GPMD_GPDB_SYSID),
m_oid(oid),
m_major_version(1),
m_minor_version(0),
m_str(m_mdid_array, GPOS_ARRAY_SIZE(m_mdid_array))
{
if (CMDIdGPDB::m_mdid_invalid_key.Oid() == oid)
{
// construct an invalid mdid 0.0.0
m_major_version = 0;
}
// TODO: - Jan 31, 2012; supply system id in constructor
// serialize mdid into static string
Serialize();
}
//---------------------------------------------------------------------------
// @function:
// CMDIdGPDB::CMDIdGPDB
//
// @doc:
// Constructs a metadata identifier
//
//---------------------------------------------------------------------------
CMDIdGPDB::CMDIdGPDB
(
OID oid,
ULONG version_major,
ULONG version_minor
)
:
m_sysid(IMDId::EmdidGPDB, GPMD_GPDB_SYSID),
m_oid(oid),
m_major_version(version_major),
m_minor_version(version_minor),
m_str(m_mdid_array, GPOS_ARRAY_SIZE(m_mdid_array))
{
// TODO: - Jan 31, 2012; supply system id in constructor
// serialize mdid into static string
Serialize();
}
//---------------------------------------------------------------------------
// @function:
// CMDIdGPDB::CMDIdGPDB
//
// @doc:
// Copy constructor
//
//---------------------------------------------------------------------------
CMDIdGPDB::CMDIdGPDB
(
const CMDIdGPDB &mdid_source
)
:
IMDId(),
m_sysid(mdid_source.Sysid()),
m_oid(mdid_source.Oid()),
m_major_version(mdid_source.VersionMajor()),
m_minor_version(mdid_source.VersionMinor()),
m_str(m_mdid_array, GPOS_ARRAY_SIZE(m_mdid_array))
{
GPOS_ASSERT(mdid_source.IsValid());
GPOS_ASSERT(IMDId::EmdidGPDB == mdid_source.MdidType());
// serialize mdid into static string
Serialize();
}
//---------------------------------------------------------------------------
// @function:
// CMDIdGPDB::Serialize
//
// @doc:
// Serialize mdid into static string
//
//---------------------------------------------------------------------------
void
CMDIdGPDB::Serialize()
{
m_str.Reset();
// serialize mdid as SystemType.Oid.Major.Minor
m_str.AppendFormat(GPOS_WSZ_LIT("%d.%d.%d.%d"), MdidType(), m_oid, m_major_version, m_minor_version);
}
//---------------------------------------------------------------------------
// @function:
// CMDIdGPDB::GetBuffer
//
// @doc:
// Returns the string representation of the mdid
//
//---------------------------------------------------------------------------
const WCHAR *
CMDIdGPDB::GetBuffer() const
{
return m_str.GetBuffer();
}
//---------------------------------------------------------------------------
// @function:
// CMDIdGPDB::Oid
//
// @doc:
// Returns the object id
//
//---------------------------------------------------------------------------
OID
CMDIdGPDB::Oid() const
{
return m_oid;
}
//---------------------------------------------------------------------------
// @function:
// CMDIdGPDB::VersionMajor
//
// @doc:
// Returns the object's major version
//
//---------------------------------------------------------------------------
ULONG
CMDIdGPDB::VersionMajor() const
{
return m_major_version;
}
//---------------------------------------------------------------------------
// @function:
// CMDIdGPDB::VersionMinor
//
// @doc:
// Returns the object's minor version
//
//---------------------------------------------------------------------------
ULONG
CMDIdGPDB::VersionMinor() const
{
return m_minor_version;
}
//---------------------------------------------------------------------------
// @function:
// CMDIdGPDB::Equals
//
// @doc:
// Checks if the version of the current object is compatible with another version
// of the same object
//
//---------------------------------------------------------------------------
BOOL
CMDIdGPDB::Equals
(
const IMDId *mdid
)
const
{
if (NULL == mdid || EmdidGPDB != mdid->MdidType())
{
return false;
}
const CMDIdGPDB *mdidGPDB = static_cast<CMDIdGPDB *>(const_cast<IMDId *>(mdid));
return (m_oid == mdidGPDB->Oid() && m_major_version == mdidGPDB->VersionMajor() &&
m_minor_version == mdidGPDB->VersionMinor());
}
//---------------------------------------------------------------------------
// @function:
// CMDIdGPDB::IsValid
//
// @doc:
// Is the mdid valid
//
//---------------------------------------------------------------------------
BOOL
CMDIdGPDB::IsValid() const
{
return !Equals(&CMDIdGPDB::m_mdid_invalid_key);
}
//---------------------------------------------------------------------------
// @function:
// CMDIdGPDB::Serialize
//
// @doc:
// Serializes the mdid as the value of the given attribute
//
//---------------------------------------------------------------------------
void
CMDIdGPDB::Serialize
(
CXMLSerializer * xml_serializer,
const CWStringConst *attribute_str
)
const
{
xml_serializer->AddAttribute(attribute_str, &m_str);
}
//---------------------------------------------------------------------------
// @function:
// CMDIdGPDB::OsPrint
//
// @doc:
// Debug print of the id in the provided stream
//
//---------------------------------------------------------------------------
IOstream &
CMDIdGPDB::OsPrint
(
IOstream &os
)
const
{
os << "(" << Oid() << "," <<
VersionMajor() << "." << VersionMinor() << ")";
return os;
}
// EOF
<|endoftext|>
|
<commit_before>/*
MPL3115A2 Barometric Pressure Sensor Library
By: Nathan Seidle
SparkFun Electronics
Date: September 24th, 2013
License: This code is public domain but you buy me a beer if you use this and we meet someday (Beerware license).
Get pressure, altitude and temperature from the MPL3115A2 sensor.
September 6, 2016: Modified for use in OpenROV's Software
*/
#include <Arduino.h>
#include <CI2C.h>
#include "MPL3115A2.h"
using namespace mpl3115a2;
MPL3115A2::MPL3115A2( CI2C *i2cInterfaceIn )
: m_i2cAddress( mpl3115a2::MPL3115A2_ADDRESS )
, m_pI2C( i2cInterfaceIn )
, m_sensorId( 420 )
{
}
ERetCode MPL3115A2::Initialize()
{
m_isInitialized = false;
delay( 500 );
//Verify that the sensor is up and running
if( VerifyChipId() != ERetCode::SUCCESS )
{
//We were unable to verify this sensor
return ERetCode::FAILED;
}
m_isInitialized = true;
return ERetCode::SUCCESS;
}
ERetCode MPL3115A2::SetMode( EMode modeIn )
{
switch (modeIn)
{
case EMode::BAROMETER:
{
return SetModeBarometer();
}
case EMode::ALTIMETER:
{
return SetModeAltimeter();
}
case EMode::STANDBY:
{
return SetModeStandby();
}
case EMode::ACTIVE:
{
return SetModeActive();
}
default:
{
return ERetCode::FAILED;
}
}
}
//Call with a rate from 0 to 7. See page 33 for table of ratios.
//Sets the over sample rate. Datasheet calls for 128 but you can set it
//from 1 to 128 samples. The higher the oversample rate the greater
//the time between data samples.
ERetCode MPL3115A2::SetOversampleRatio( EOversampleRatio osrIn )
{
int32_t returnCode;
auto sampleRate = static_cast<int>( osrIn );
//Align it for the control register
sampleRate <<= 3;
//Read the current settings
uint8_t tempSetting;
returnCode = ReadByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );
if( returnCode != I2C::ERetCode::SUCCESS )
{
return ERetCode::FAILED;
}
//Clear out old Oversample bits
tempSetting &= B11000111;
//Mask new sample rate
tempSetting |= sampleRate;
//And write it to the register
returnCode = WriteByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );
if( returnCode != I2C::ERetCode::SUCCESS )
{
return ERetCode::FAILED;
}
return ERetCode::SUCCESS;
}
//Enables the pressure and temp measurement event flags so that we can
//test against them. This is recommended in datasheet during setup.
ERetCode MPL3115A2::EnableEventFlags()
{
// Enable all three pressure and temp event flags
auto ret = WriteByte( MPL3115A2_REGISTER::PT_DATA_CFG, 0x07);
if( ret != I2C::ERetCode::SUCCESS )
{
return ERetCode::FAILED;
}
return ERetCode::SUCCESS;
}
//Reads the current pressure in Pa
//Unit must be set in barometric pressure mode
ERetCode MPL3115A2::ReadPressure( float& pressureOut )
{
Serial.println( "In read pressure loop" );
ToggleOneShot();
int32_t returnCode;
uint8_t pdr;
//Wait for PDR bit, indicates we have new pressure data
auto counter = 0;
returnCode = ReadByte( MPL3115A2_REGISTER::STATUS, pdr );
if( returnCode != I2C::ERetCode::SUCCESS )
{
return ERetCode::FAILED_PRESSURE_READ;
}
// while( ( pdr & (1<<2) ) == 0 )
// {
// Serial.println( counter );
// if( ++counter > 100 )
// {
// return ERetCode::TIMED_OUT;
// }
// delay(1);
// }
//Read pressure registers
uint8_t buffer[3];
memset( buffer, 0, 3);
returnCode = ReadNBytes( MPL3115A2_REGISTER::PRESSURE_OUT_MSB, buffer, 3 );
if( returnCode != I2C::ERetCode::SUCCESS )
{
return ERetCode::FAILED_PRESSURE_READ;
}
//Toggle the OST bit causing the sensor to immediately take another reading
ToggleOneShot();
auto msb = buffer[0];
auto csb = buffer[1];
auto lsb = buffer[2];
// Pressure comes back as a left shifted 20 bit number
uint64_t pressure = (uint64_t)msb<<16 | (uint64_t)csb<<8 | (uint64_t)lsb;
//Pressure is an 18 bit number with 2 bits of decimal. Get rid of decimal portion.
pressure >>= 6;
//Bits 5/4 represent the fractional component
lsb &= B00110000;
//Get it right aligned
lsb >>= 4;
//Turn it into fraction
float pressure_decimal = (float)lsb/4.0;
pressureOut = (float)pressure + pressure_decimal;
return ERetCode::SUCCESS;
}
/***************************************************************************
PRIVATE FUNCTIONS
***************************************************************************/
ERetCode MPL3115A2::VerifyChipId()
{
//Read the chip id
uint8_t id;
auto ret = ReadByte( MPL3115A2_REGISTER::WHO_AM_I, id );
if( ret != I2C::ERetCode::SUCCESS )
{
return ERetCode::FAILED;
}
//Check to see if it matches the proper ID (0xC4)
if( id != 0xC4 )
{
return ERetCode::FAILED;
}
return ERetCode::SUCCESS;
}
ERetCode MPL3115A2::SetModeBarometer()
{
int32_t returnCode;
//Read the current settings
uint8_t tempSetting;
Serial.println(tempSetting, HEX);
returnCode = ReadByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );
if( returnCode != I2C::ERetCode::SUCCESS )
{
return ERetCode::FAILED;
}
Serial.println(tempSetting, HEX);
//Clear the altimeter bit
tempSetting &= ~(1<<7);
Serial.println(tempSetting, HEX);
//And write it to the register
returnCode = WriteByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );
if( returnCode != I2C::ERetCode::SUCCESS )
{
return ERetCode::FAILED;
}
Serial.println(tempSetting, HEX);
m_mode = tempSetting;
return ERetCode::SUCCESS;
}
ERetCode MPL3115A2::SetModeAltimeter()
{
int32_t returnCode;
//Read the current settings
uint8_t tempSetting;
returnCode = ReadByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );
if( returnCode != I2C::ERetCode::SUCCESS )
{
return ERetCode::FAILED;
}
//Set the altimeter bit
tempSetting |= (1<<7);
//And write it to the register
returnCode = WriteByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );
if( returnCode != I2C::ERetCode::SUCCESS )
{
return ERetCode::FAILED;
}
return ERetCode::SUCCESS;
}
//Puts the sensor in standby mode
//This is needed so that we can modify the major control registers
ERetCode MPL3115A2::SetModeStandby()
{
int32_t returnCode;
//Read the current settings
uint8_t tempSetting;
returnCode = ReadByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );
if( returnCode != I2C::ERetCode::SUCCESS )
{
return ERetCode::FAILED;
}
//Clear SBYB bit for Standby mode
tempSetting &= ~(1<<0);
//And write it to the register
returnCode = WriteByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );
if( returnCode != I2C::ERetCode::SUCCESS )
{
return ERetCode::FAILED;
}
return ERetCode::SUCCESS;
}
//Puts the sensor in active mode
//This is needed so that we can modify the major control registers
ERetCode MPL3115A2::SetModeActive()
{
int32_t returnCode;
//Read the current settings
uint8_t tempSetting;
returnCode = ReadByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );
if( returnCode != I2C::ERetCode::SUCCESS )
{
return ERetCode::FAILED;
}
//Set SBYB bit for Active mode
tempSetting |= (1<<0);
//And write it to the register
returnCode = WriteByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );
if( returnCode != I2C::ERetCode::SUCCESS )
{
return ERetCode::FAILED;
}
return ERetCode::SUCCESS;
}
//Clears and then sets the OST bit which causes the sensor to take another readings
//Needed to sample faster than 1Hz
ERetCode MPL3115A2::ToggleOneShot()
{
Serial.println( "Toggling one shot." );
Serial.print( "Mode: " );
Serial.println( m_mode );
int32_t returnCode;
//Read the current settings
uint8_t tempSetting;
returnCode = ReadByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );
if( returnCode != I2C::ERetCode::SUCCESS )
{
return ERetCode::FAILED_ONESHOT;
}
//Clear the one shot bit
tempSetting &= ~(1<<1);
returnCode = WriteByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );
if( returnCode != I2C::ERetCode::SUCCESS )
{
return ERetCode::FAILED_ONESHOT;
}
//Reat the current settings, just to be safe :)
returnCode = ReadByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );
if( returnCode != I2C::ERetCode::SUCCESS )
{
return ERetCode::FAILED_ONESHOT;
}
//Set the overshot bit
tempSetting |= (1<<1);
returnCode = WriteByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );
if( returnCode != I2C::ERetCode::SUCCESS )
{
return ERetCode::FAILED_ONESHOT;
}
return ERetCode::SUCCESS;
}
int32_t MPL3115A2::WriteByte( MPL3115A2_REGISTER addressIn, uint8_t dataIn )
{
return (int32_t)m_pI2C->WriteByte( m_i2cAddress, (uint8_t)addressIn, dataIn );
}
int32_t MPL3115A2::ReadByte( MPL3115A2_REGISTER addressIn, uint8_t &dataOut )
{
return (int32_t)m_pI2C->ReadByte( m_i2cAddress, (uint8_t)addressIn, &dataOut );
}
int32_t MPL3115A2::ReadNBytes( MPL3115A2_REGISTER addressIn, uint8_t* dataOut, uint8_t byteCountIn )
{
return (int32_t)m_pI2C->ReadBytes( m_i2cAddress, (uint8_t)addressIn, dataOut, byteCountIn );
}<commit_msg>Mode switch<commit_after>/*
MPL3115A2 Barometric Pressure Sensor Library
By: Nathan Seidle
SparkFun Electronics
Date: September 24th, 2013
License: This code is public domain but you buy me a beer if you use this and we meet someday (Beerware license).
Get pressure, altitude and temperature from the MPL3115A2 sensor.
September 6, 2016: Modified for use in OpenROV's Software
*/
#include <Arduino.h>
#include <CI2C.h>
#include "MPL3115A2.h"
using namespace mpl3115a2;
MPL3115A2::MPL3115A2( CI2C *i2cInterfaceIn )
: m_i2cAddress( mpl3115a2::MPL3115A2_ADDRESS )
, m_pI2C( i2cInterfaceIn )
, m_sensorId( 420 )
{
}
ERetCode MPL3115A2::Initialize()
{
m_isInitialized = false;
delay( 500 );
//Verify that the sensor is up and running
if( VerifyChipId() != ERetCode::SUCCESS )
{
//We were unable to verify this sensor
return ERetCode::FAILED;
}
m_isInitialized = true;
return ERetCode::SUCCESS;
}
ERetCode MPL3115A2::SetMode( EMode modeIn )
{
switch (modeIn)
{
case EMode::BAROMETER:
{
return SetModeBarometer();
}
case EMode::ALTIMETER:
{
return SetModeAltimeter();
}
case EMode::STANDBY:
{
return SetModeStandby();
}
case EMode::ACTIVE:
{
return SetModeActive();
}
default:
{
return ERetCode::FAILED;
}
}
}
//Call with a rate from 0 to 7. See page 33 for table of ratios.
//Sets the over sample rate. Datasheet calls for 128 but you can set it
//from 1 to 128 samples. The higher the oversample rate the greater
//the time between data samples.
ERetCode MPL3115A2::SetOversampleRatio( EOversampleRatio osrIn )
{
int32_t returnCode;
auto sampleRate = static_cast<int>( osrIn );
//Align it for the control register
sampleRate <<= 3;
//Read the current settings
uint8_t tempSetting;
returnCode = ReadByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );
if( returnCode != I2C::ERetCode::SUCCESS )
{
return ERetCode::FAILED;
}
//Clear out old Oversample bits
tempSetting &= B11000111;
//Mask new sample rate
tempSetting |= sampleRate;
//And write it to the register
returnCode = WriteByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );
if( returnCode != I2C::ERetCode::SUCCESS )
{
return ERetCode::FAILED;
}
return ERetCode::SUCCESS;
}
//Enables the pressure and temp measurement event flags so that we can
//test against them. This is recommended in datasheet during setup.
ERetCode MPL3115A2::EnableEventFlags()
{
// Enable all three pressure and temp event flags
auto ret = WriteByte( MPL3115A2_REGISTER::PT_DATA_CFG, 0x07);
if( ret != I2C::ERetCode::SUCCESS )
{
return ERetCode::FAILED;
}
return ERetCode::SUCCESS;
}
//Reads the current pressure in Pa
//Unit must be set in barometric pressure mode
ERetCode MPL3115A2::ReadPressure( float& pressureOut )
{
Serial.println( "In read pressure loop" );
SetMode(EMode::BAROMETER);
ToggleOneShot();
int32_t returnCode;
uint8_t pdr;
//Wait for PDR bit, indicates we have new pressure data
auto counter = 0;
returnCode = ReadByte( MPL3115A2_REGISTER::STATUS, pdr );
if( returnCode != I2C::ERetCode::SUCCESS )
{
return ERetCode::FAILED_PRESSURE_READ;
}
// while( ( pdr & (1<<2) ) == 0 )
// {
// Serial.println( counter );
// if( ++counter > 100 )
// {
// return ERetCode::TIMED_OUT;
// }
// delay(1);
// }
//Read pressure registers
uint8_t buffer[3];
memset( buffer, 0, 3);
returnCode = ReadNBytes( MPL3115A2_REGISTER::PRESSURE_OUT_MSB, buffer, 3 );
if( returnCode != I2C::ERetCode::SUCCESS )
{
return ERetCode::FAILED_PRESSURE_READ;
}
//Toggle the OST bit causing the sensor to immediately take another reading
ToggleOneShot();
auto msb = buffer[0];
auto csb = buffer[1];
auto lsb = buffer[2];
// Pressure comes back as a left shifted 20 bit number
uint64_t pressure = (uint64_t)msb<<16 | (uint64_t)csb<<8 | (uint64_t)lsb;
//Pressure is an 18 bit number with 2 bits of decimal. Get rid of decimal portion.
pressure >>= 6;
//Bits 5/4 represent the fractional component
lsb &= B00110000;
//Get it right aligned
lsb >>= 4;
//Turn it into fraction
float pressure_decimal = (float)lsb/4.0;
pressureOut = (float)pressure + pressure_decimal;
return ERetCode::SUCCESS;
}
/***************************************************************************
PRIVATE FUNCTIONS
***************************************************************************/
ERetCode MPL3115A2::VerifyChipId()
{
//Read the chip id
uint8_t id;
auto ret = ReadByte( MPL3115A2_REGISTER::WHO_AM_I, id );
if( ret != I2C::ERetCode::SUCCESS )
{
return ERetCode::FAILED;
}
//Check to see if it matches the proper ID (0xC4)
if( id != 0xC4 )
{
return ERetCode::FAILED;
}
return ERetCode::SUCCESS;
}
ERetCode MPL3115A2::SetModeBarometer()
{
int32_t returnCode;
//Read the current settings
uint8_t tempSetting;
Serial.println(tempSetting, HEX);
returnCode = ReadByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );
if( returnCode != I2C::ERetCode::SUCCESS )
{
return ERetCode::FAILED;
}
Serial.println(tempSetting, HEX);
//Clear the altimeter bit
tempSetting &= ~(1<<7);
Serial.println(tempSetting, HEX);
//And write it to the register
returnCode = WriteByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );
if( returnCode != I2C::ERetCode::SUCCESS )
{
return ERetCode::FAILED;
}
Serial.println(tempSetting, HEX);
m_mode = tempSetting;
return ERetCode::SUCCESS;
}
ERetCode MPL3115A2::SetModeAltimeter()
{
int32_t returnCode;
//Read the current settings
uint8_t tempSetting;
returnCode = ReadByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );
if( returnCode != I2C::ERetCode::SUCCESS )
{
return ERetCode::FAILED;
}
//Set the altimeter bit
tempSetting |= (1<<7);
//And write it to the register
returnCode = WriteByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );
if( returnCode != I2C::ERetCode::SUCCESS )
{
return ERetCode::FAILED;
}
return ERetCode::SUCCESS;
}
//Puts the sensor in standby mode
//This is needed so that we can modify the major control registers
ERetCode MPL3115A2::SetModeStandby()
{
int32_t returnCode;
//Read the current settings
uint8_t tempSetting;
returnCode = ReadByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );
if( returnCode != I2C::ERetCode::SUCCESS )
{
return ERetCode::FAILED;
}
//Clear SBYB bit for Standby mode
tempSetting &= ~(1<<0);
//And write it to the register
returnCode = WriteByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );
if( returnCode != I2C::ERetCode::SUCCESS )
{
return ERetCode::FAILED;
}
return ERetCode::SUCCESS;
}
//Puts the sensor in active mode
//This is needed so that we can modify the major control registers
ERetCode MPL3115A2::SetModeActive()
{
int32_t returnCode;
//Read the current settings
uint8_t tempSetting;
returnCode = ReadByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );
if( returnCode != I2C::ERetCode::SUCCESS )
{
return ERetCode::FAILED;
}
//Set SBYB bit for Active mode
tempSetting |= (1<<0);
//And write it to the register
returnCode = WriteByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );
if( returnCode != I2C::ERetCode::SUCCESS )
{
return ERetCode::FAILED;
}
return ERetCode::SUCCESS;
}
//Clears and then sets the OST bit which causes the sensor to take another readings
//Needed to sample faster than 1Hz
ERetCode MPL3115A2::ToggleOneShot()
{
Serial.println( "Toggling one shot." );
Serial.print( "Mode: " );
Serial.println( m_mode );
int32_t returnCode;
//Read the current settings
uint8_t tempSetting;
returnCode = ReadByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );
if( returnCode != I2C::ERetCode::SUCCESS )
{
return ERetCode::FAILED_ONESHOT;
}
//Clear the one shot bit
tempSetting &= ~(1<<1);
returnCode = WriteByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );
if( returnCode != I2C::ERetCode::SUCCESS )
{
return ERetCode::FAILED_ONESHOT;
}
//Reat the current settings, just to be safe :)
returnCode = ReadByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );
if( returnCode != I2C::ERetCode::SUCCESS )
{
return ERetCode::FAILED_ONESHOT;
}
//Set the overshot bit
tempSetting |= (1<<1);
returnCode = WriteByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );
if( returnCode != I2C::ERetCode::SUCCESS )
{
return ERetCode::FAILED_ONESHOT;
}
return ERetCode::SUCCESS;
}
int32_t MPL3115A2::WriteByte( MPL3115A2_REGISTER addressIn, uint8_t dataIn )
{
return (int32_t)m_pI2C->WriteByte( m_i2cAddress, (uint8_t)addressIn, dataIn );
}
int32_t MPL3115A2::ReadByte( MPL3115A2_REGISTER addressIn, uint8_t &dataOut )
{
return (int32_t)m_pI2C->ReadByte( m_i2cAddress, (uint8_t)addressIn, &dataOut );
}
int32_t MPL3115A2::ReadNBytes( MPL3115A2_REGISTER addressIn, uint8_t* dataOut, uint8_t byteCountIn )
{
return (int32_t)m_pI2C->ReadBytes( m_i2cAddress, (uint8_t)addressIn, dataOut, byteCountIn );
}<|endoftext|>
|
<commit_before>/*
MPL3115A2 Barometric Pressure Sensor Library
By: Nathan Seidle
SparkFun Electronics
Date: September 24th, 2013
License: This code is public domain but you buy me a beer if you use this and we meet someday (Beerware license).
Get pressure, altitude and temperature from the MPL3115A2 sensor.
September 6, 2016: Modified for use in OpenROV's Software
*/
#include <Arduino.h>
#include <CI2C.h>
#include "MPL3115A2.h"
using namespace mpl3115a2;
MPL3115A2::MPL3115A2( CI2C *i2cInterfaceIn )
: m_i2cAddress( mpl3115a2::MPL3115A2_ADDRESS )
, m_pI2C( i2cInterfaceIn )
, m_sensorId( 420 )
{
}
ERetCode MPL3115A2::Initialize()
{
m_isInitialized = false;
delay( 500 );
//Verify that the sensor is up and running
if( VerifyChipId() != ERetCode::SUCCESS )
{
//We were unable to verify this sensor
return ERetCode::FAILED;
}
m_isInitialized = true;
return ERetCode::SUCCESS;
}
ERetCode MPL3115A2::SetMode( EMode modeIn )
{
switch (modeIn)
{
case EMode::BAROMETER:
{
return SetModeBarometer();
}
case EMode::ALTIMETER:
{
return SetModeAltimeter();
}
case EMode::STANDBY:
{
return SetModeStandby();
}
case EMode::ACTIVE:
{
return SetModeActive();
}
default:
{
return ERetCode::FAILED;
}
}
}
//Call with a rate from 0 to 7. See page 33 for table of ratios.
//Sets the over sample rate. Datasheet calls for 128 but you can set it
//from 1 to 128 samples. The higher the oversample rate the greater
//the time between data samples.
ERetCode MPL3115A2::SetOversampleRatio( EOversampleRatio osrIn )
{
int32_t returnCode;
auto sampleRate = static_cast<int>( osrIn );
//Align it for the control register
sampleRate <<= 3;
//Read the current settings
uint8_t tempSetting;
returnCode = ReadByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );
if( returnCode != I2C::ERetCode::SUCCESS )
{
return ERetCode::FAILED;
}
//Clear out old Oversample bits
tempSetting &= B11000111;
//Mask new sample rate
tempSetting |= sampleRate;
//And write it to the register
returnCode = WriteByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );
if( returnCode != I2C::ERetCode::SUCCESS )
{
return ERetCode::FAILED;
}
return ERetCode::SUCCESS;
}
//Enables the pressure and temp measurement event flags so that we can
//test against them. This is recommended in datasheet during setup.
ERetCode MPL3115A2::EnableEventFlags()
{
// Enable all three pressure and temp event flags
auto ret = WriteByte( MPL3115A2_REGISTER::PT_DATA_CFG, 0x07);
if( ret != I2C::ERetCode::SUCCESS )
{
return ERetCode::FAILED;
}
return ERetCode::SUCCESS;
}
//Reads the current pressure in Pa
//Unit must be set in barometric pressure mode
ERetCode MPL3115A2::ReadPressure( float& pressureOut )
{
Serial.println( "In read pressure loop" );
int32_t returnCode;
//Check PDR bit, if it's not set then toggle OST
uint8_t pdr;
returnCode = ReadByte( MPL3115A2_REGISTER::STATUS, pdr );
if( returnCode != I2C::ERetCode::SUCCESS )
{
return ERetCode::FAILED_PRESSURE_READ;
}
if( ( pdr & (1<<2) ) == 0 )
{
ToggleOneShot();
}
//Wait for PDR bit, indicates we have new pressure data
auto counter = 0;
while( ( pdr & (1<<2) ) == 0 )
{
Serial.println(pdr);
returnCode = ReadByte( MPL3115A2_REGISTER::STATUS, pdr );
if( returnCode != I2C::ERetCode::SUCCESS )
{
return ERetCode::FAILED_PRESSURE_READ;
}
if( ++counter > 1000 )
{
return ERetCode::TIMED_OUT;
delay(1);
}
}
//Read pressure registers
uint8_t buffer[3];
memset( buffer, 0, 3);
returnCode = ReadNBytes( MPL3115A2_REGISTER::PRESSURE_OUT_MSB, buffer, 3 );
if( returnCode != I2C::ERetCode::SUCCESS )
{
return ERetCode::FAILED_PRESSURE_READ;
}
//Toggle the OST bit causing the sensor to immediately take another reading
ToggleOneShot();
auto msb = buffer[0];
auto csb = buffer[1];
auto lsb = buffer[2];
// Pressure comes back as a left shifted 20 bit number
uint64_t pressure = (uint64_t)msb<<16 | (uint64_t)csb<<8 | (uint64_t)lsb;
//Pressure is an 18 bit number with 2 bits of decimal. Get rid of decimal portion.
pressure >>= 6;
//Bits 5/4 represent the fractional component
lsb &= B00110000;
//Get it right aligned
lsb >>= 4;
//Turn it into fraction
float pressure_decimal = (float)lsb/4.0;
pressureOut = (float)pressure + pressure_decimal;
return ERetCode::SUCCESS;
}
/***************************************************************************
PRIVATE FUNCTIONS
***************************************************************************/
ERetCode MPL3115A2::VerifyChipId()
{
//Read the chip id
uint8_t id;
auto ret = ReadByte( MPL3115A2_REGISTER::WHO_AM_I, id );
if( ret != I2C::ERetCode::SUCCESS )
{
return ERetCode::FAILED;
}
//Check to see if it matches the proper ID (0xC4)
if( id != 0xC4 )
{
return ERetCode::FAILED;
}
return ERetCode::SUCCESS;
}
ERetCode MPL3115A2::SetModeBarometer()
{
int32_t returnCode;
//Read the current settings
uint8_t tempSetting;
returnCode = ReadByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );
if( returnCode != I2C::ERetCode::SUCCESS )
{
return ERetCode::FAILED;
}
//Clear the altimeter bit
tempSetting &= ~(1<<7);
//And write it to the register
returnCode = WriteByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );
if( returnCode != I2C::ERetCode::SUCCESS )
{
return ERetCode::FAILED;
}
m_mode = tempSetting;
return ERetCode::SUCCESS;
}
ERetCode MPL3115A2::SetModeAltimeter()
{
int32_t returnCode;
//Read the current settings
uint8_t tempSetting;
returnCode = ReadByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );
if( returnCode != I2C::ERetCode::SUCCESS )
{
return ERetCode::FAILED;
}
//Set the altimeter bit
tempSetting |= (1<<7);
//And write it to the register
returnCode = WriteByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );
if( returnCode != I2C::ERetCode::SUCCESS )
{
return ERetCode::FAILED;
}
return ERetCode::SUCCESS;
}
//Puts the sensor in standby mode
//This is needed so that we can modify the major control registers
ERetCode MPL3115A2::SetModeStandby()
{
int32_t returnCode;
//Read the current settings
uint8_t tempSetting;
returnCode = ReadByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );
if( returnCode != I2C::ERetCode::SUCCESS )
{
return ERetCode::FAILED;
}
//Clear SBYB bit for Standby mode
tempSetting &= ~(1<<0);
//And write it to the register
returnCode = WriteByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );
if( returnCode != I2C::ERetCode::SUCCESS )
{
return ERetCode::FAILED;
}
return ERetCode::SUCCESS;
}
//Puts the sensor in active mode
//This is needed so that we can modify the major control registers
ERetCode MPL3115A2::SetModeActive()
{
int32_t returnCode;
//Read the current settings
uint8_t tempSetting;
returnCode = ReadByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );
if( returnCode != I2C::ERetCode::SUCCESS )
{
return ERetCode::FAILED;
}
//Set SBYB bit for Active mode
tempSetting |= (1<<0);
//And write it to the register
returnCode = WriteByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );
if( returnCode != I2C::ERetCode::SUCCESS )
{
return ERetCode::FAILED;
}
return ERetCode::SUCCESS;
}
//Clears and then sets the OST bit which causes the sensor to take another readings
//Needed to sample faster than 1Hz
ERetCode MPL3115A2::ToggleOneShot()
{
Serial.println( "Toggling one shot." );
Serial.print( "Mode: " );
Serial.println( m_mode );
int32_t returnCode;
//Read the current settings
uint8_t tempSetting;
returnCode = ReadByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );
if( returnCode != I2C::ERetCode::SUCCESS )
{
return ERetCode::FAILED_ONESHOT;
}
//Clear the one shot bit
tempSetting &= ~(1<<1);
returnCode = WriteByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );
if( returnCode != I2C::ERetCode::SUCCESS )
{
return ERetCode::FAILED_ONESHOT;
}
//Reat the current settings, just to be safe :)
returnCode = ReadByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );
if( returnCode != I2C::ERetCode::SUCCESS )
{
return ERetCode::FAILED_ONESHOT;
}
//Set the overshot bit
tempSetting |= (1<<1);
returnCode = WriteByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );
if( returnCode != I2C::ERetCode::SUCCESS )
{
return ERetCode::FAILED_ONESHOT;
}
return ERetCode::SUCCESS;
}
int32_t MPL3115A2::WriteByte( MPL3115A2_REGISTER addressIn, uint8_t dataIn )
{
return (int32_t)m_pI2C->WriteByte( m_i2cAddress, (uint8_t)addressIn, dataIn );
}
int32_t MPL3115A2::ReadByte( MPL3115A2_REGISTER addressIn, uint8_t &dataOut )
{
return (int32_t)m_pI2C->ReadByte( m_i2cAddress, (uint8_t)addressIn, &dataOut );
}
int32_t MPL3115A2::ReadNBytes( MPL3115A2_REGISTER addressIn, uint8_t* dataOut, uint8_t byteCountIn )
{
return (int32_t)m_pI2C->ReadBytes( m_i2cAddress, (uint8_t)addressIn, dataOut, byteCountIn );
}<commit_msg>Hard revert<commit_after>/*
MPL3115A2 Barometric Pressure Sensor Library
By: Nathan Seidle
SparkFun Electronics
Date: September 24th, 2013
License: This code is public domain but you buy me a beer if you use this and we meet someday (Beerware license).
Get pressure, altitude and temperature from the MPL3115A2 sensor.
September 6, 2016: Modified for use in OpenROV's Software
*/
#include <Arduino.h>
#include <CI2C.h>
#include "MPL3115A2.h"
using namespace mpl3115a2;
MPL3115A2::MPL3115A2( CI2C *i2cInterfaceIn )
: m_i2cAddress( mpl3115a2::MPL3115A2_ADDRESS )
, m_pI2C( i2cInterfaceIn )
, m_sensorId( 420 )
{
}
ERetCode MPL3115A2::Initialize()
{
m_isInitialized = false;
delay( 500 );
//Verify that the sensor is up and running
if( VerifyChipId() != ERetCode::SUCCESS )
{
//We were unable to verify this sensor
return ERetCode::FAILED;
}
m_isInitialized = true;
return ERetCode::SUCCESS;
}
ERetCode MPL3115A2::SetMode( EMode modeIn )
{
switch (modeIn)
{
case EMode::BAROMETER:
{
return SetModeBarometer();
}
case EMode::ALTIMETER:
{
return SetModeAltimeter();
}
case EMode::STANDBY:
{
return SetModeStandby();
}
case EMode::ACTIVE:
{
return SetModeActive();
}
default:
{
return ERetCode::FAILED;
}
}
}
//Call with a rate from 0 to 7. See page 33 for table of ratios.
//Sets the over sample rate. Datasheet calls for 128 but you can set it
//from 1 to 128 samples. The higher the oversample rate the greater
//the time between data samples.
ERetCode MPL3115A2::SetOversampleRatio( EOversampleRatio osrIn )
{
int32_t returnCode;
auto sampleRate = static_cast<int>( osrIn );
//Align it for the control register
sampleRate <<= 3;
//Read the current settings
uint8_t tempSetting;
returnCode = ReadByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );
if( returnCode != I2C::ERetCode::SUCCESS )
{
return ERetCode::FAILED;
}
//Clear out old Oversample bits
tempSetting &= B11000111;
//Mask new sample rate
tempSetting |= sampleRate;
//And write it to the register
returnCode = WriteByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );
if( returnCode != I2C::ERetCode::SUCCESS )
{
return ERetCode::FAILED;
}
return ERetCode::SUCCESS;
}
//Enables the pressure and temp measurement event flags so that we can
//test against them. This is recommended in datasheet during setup.
ERetCode MPL3115A2::EnableEventFlags()
{
// Enable all three pressure and temp event flags
auto ret = WriteByte( MPL3115A2_REGISTER::PT_DATA_CFG, 0x07);
if( ret != I2C::ERetCode::SUCCESS )
{
return ERetCode::FAILED;
}
return ERetCode::SUCCESS;
}
//Reads the current pressure in Pa
//Unit must be set in barometric pressure mode
ERetCode MPL3115A2::ReadPressure( float& pressureOut )
{
Serial.println( "In read pressure loop" );
int32_t returnCode;
//Check PDR bit, if it's not set then toggle OST
uint8_t pdr;
returnCode = ReadByte( MPL3115A2_REGISTER::STATUS, pdr );
if( returnCode != I2C::ERetCode::SUCCESS )
{
return ERetCode::FAILED_PRESSURE_READ;
}
if( ( pdr & (1<<2) ) == 0 )
{
ToggleOneShot();
}
//Wait for PDR bit, indicates we have new pressure data
auto counter = 0;
while( ( pdr & (1<<2) ) == 0 )
{
Serial.println(pdr, hex);
returnCode = ReadByte( MPL3115A2_REGISTER::STATUS, pdr );
if( returnCode != I2C::ERetCode::SUCCESS )
{
return ERetCode::FAILED_PRESSURE_READ;
}
if( ++counter > 1000 )
{
return ERetCode::TIMED_OUT;
delay(1);
}
}
//Read pressure registers
uint8_t buffer[3];
memset( buffer, 0, 3);
returnCode = ReadNBytes( MPL3115A2_REGISTER::PRESSURE_OUT_MSB, buffer, 3 );
if( returnCode != I2C::ERetCode::SUCCESS )
{
return ERetCode::FAILED_PRESSURE_READ;
}
//Toggle the OST bit causing the sensor to immediately take another reading
ToggleOneShot();
auto msb = buffer[0];
auto csb = buffer[1];
auto lsb = buffer[2];
// Pressure comes back as a left shifted 20 bit number
uint64_t pressure = (uint64_t)msb<<16 | (uint64_t)csb<<8 | (uint64_t)lsb;
//Pressure is an 18 bit number with 2 bits of decimal. Get rid of decimal portion.
pressure >>= 6;
//Bits 5/4 represent the fractional component
lsb &= B00110000;
//Get it right aligned
lsb >>= 4;
//Turn it into fraction
float pressure_decimal = (float)lsb/4.0;
pressureOut = (float)pressure + pressure_decimal;
return ERetCode::SUCCESS;
}
/***************************************************************************
PRIVATE FUNCTIONS
***************************************************************************/
ERetCode MPL3115A2::VerifyChipId()
{
//Read the chip id
uint8_t id;
auto ret = ReadByte( MPL3115A2_REGISTER::WHO_AM_I, id );
if( ret != I2C::ERetCode::SUCCESS )
{
return ERetCode::FAILED;
}
//Check to see if it matches the proper ID (0xC4)
if( id != 0xC4 )
{
return ERetCode::FAILED;
}
return ERetCode::SUCCESS;
}
ERetCode MPL3115A2::SetModeBarometer()
{
int32_t returnCode;
//Read the current settings
uint8_t tempSetting;
returnCode = ReadByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );
if( returnCode != I2C::ERetCode::SUCCESS )
{
return ERetCode::FAILED;
}
//Clear the altimeter bit
tempSetting &= ~(1<<7);
//And write it to the register
returnCode = WriteByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );
if( returnCode != I2C::ERetCode::SUCCESS )
{
return ERetCode::FAILED;
}
m_mode = tempSetting;
return ERetCode::SUCCESS;
}
ERetCode MPL3115A2::SetModeAltimeter()
{
int32_t returnCode;
//Read the current settings
uint8_t tempSetting;
returnCode = ReadByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );
if( returnCode != I2C::ERetCode::SUCCESS )
{
return ERetCode::FAILED;
}
//Set the altimeter bit
tempSetting |= (1<<7);
//And write it to the register
returnCode = WriteByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );
if( returnCode != I2C::ERetCode::SUCCESS )
{
return ERetCode::FAILED;
}
return ERetCode::SUCCESS;
}
//Puts the sensor in standby mode
//This is needed so that we can modify the major control registers
ERetCode MPL3115A2::SetModeStandby()
{
int32_t returnCode;
//Read the current settings
uint8_t tempSetting;
returnCode = ReadByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );
if( returnCode != I2C::ERetCode::SUCCESS )
{
return ERetCode::FAILED;
}
//Clear SBYB bit for Standby mode
tempSetting &= ~(1<<0);
//And write it to the register
returnCode = WriteByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );
if( returnCode != I2C::ERetCode::SUCCESS )
{
return ERetCode::FAILED;
}
return ERetCode::SUCCESS;
}
//Puts the sensor in active mode
//This is needed so that we can modify the major control registers
ERetCode MPL3115A2::SetModeActive()
{
int32_t returnCode;
//Read the current settings
uint8_t tempSetting;
returnCode = ReadByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );
if( returnCode != I2C::ERetCode::SUCCESS )
{
return ERetCode::FAILED;
}
//Set SBYB bit for Active mode
tempSetting |= (1<<0);
//And write it to the register
returnCode = WriteByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );
if( returnCode != I2C::ERetCode::SUCCESS )
{
return ERetCode::FAILED;
}
return ERetCode::SUCCESS;
}
//Clears and then sets the OST bit which causes the sensor to take another readings
//Needed to sample faster than 1Hz
ERetCode MPL3115A2::ToggleOneShot()
{
Serial.println( "Toggling one shot." );
Serial.print( "Mode: " );
Serial.println( m_mode );
int32_t returnCode;
//Read the current settings
uint8_t tempSetting;
returnCode = ReadByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );
if( returnCode != I2C::ERetCode::SUCCESS )
{
return ERetCode::FAILED_ONESHOT;
}
//Clear the one shot bit
tempSetting &= ~(1<<1);
returnCode = WriteByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );
if( returnCode != I2C::ERetCode::SUCCESS )
{
return ERetCode::FAILED_ONESHOT;
}
//Reat the current settings, just to be safe :)
returnCode = ReadByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );
if( returnCode != I2C::ERetCode::SUCCESS )
{
return ERetCode::FAILED_ONESHOT;
}
//Set the overshot bit
tempSetting |= (1<<1);
returnCode = WriteByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting );
if( returnCode != I2C::ERetCode::SUCCESS )
{
return ERetCode::FAILED_ONESHOT;
}
return ERetCode::SUCCESS;
}
int32_t MPL3115A2::WriteByte( MPL3115A2_REGISTER addressIn, uint8_t dataIn )
{
return (int32_t)m_pI2C->WriteByte( m_i2cAddress, (uint8_t)addressIn, dataIn );
}
int32_t MPL3115A2::ReadByte( MPL3115A2_REGISTER addressIn, uint8_t &dataOut )
{
return (int32_t)m_pI2C->ReadByte( m_i2cAddress, (uint8_t)addressIn, &dataOut );
}
int32_t MPL3115A2::ReadNBytes( MPL3115A2_REGISTER addressIn, uint8_t* dataOut, uint8_t byteCountIn )
{
return (int32_t)m_pI2C->ReadBytes( m_i2cAddress, (uint8_t)addressIn, dataOut, byteCountIn );
}<|endoftext|>
|
<commit_before>/*****************************************************************************
* win32_factory.cpp
*****************************************************************************
* Copyright (C) 2003 VideoLAN
* $Id$
*
* Authors: Cyril Deguet <[email protected]>
* Olivier Teulire <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111, USA.
*****************************************************************************/
#ifdef WIN32_SKINS
#include "win32_factory.hpp"
#include "win32_graphics.hpp"
#include "win32_timer.hpp"
#include "win32_window.hpp"
#include "win32_tooltip.hpp"
#include "win32_loop.hpp"
LRESULT CALLBACK Win32Proc( HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam )
{
// Get pointer to thread info: should only work with the parent window
intf_thread_t *p_intf = (intf_thread_t *)GetWindowLongPtr( hwnd,
GWLP_USERDATA );
// If doesn't exist, treat windows message normally
if( p_intf == NULL || p_intf->p_sys->p_osFactory == NULL )
{
return DefWindowProc( hwnd, uMsg, wParam, lParam );
}
// Here we know we are getting a message for the parent window, since it is
// the only one to store p_intf...
// Yes, it is a kludge :)
//Win32Factory *pFactory = (Win32Factory*)Win32Factory::instance( p_intf );
//msg_Err( p_intf, "Parent window %p %p %u %i\n", pFactory->m_hParentWindow, hwnd, uMsg, wParam );
// If Window is parent window
// XXX: this test isn't needed, see the kludge above...
// if( hwnd == pFactory->m_hParentWindow )
{
if( uMsg == WM_SYSCOMMAND )
{
// If closing parent window
if( wParam == SC_CLOSE )
{
Win32Loop *pLoop = (Win32Loop*)Win32Loop::instance( p_intf );
pLoop->exit();
return 0;
}
else
{
msg_Err( p_intf, "WM_SYSCOMMAND %i", wParam );
}
// if( (Event *)wParam != NULL )
// ( (Event *)wParam )->SendEvent();
// return 0;
}
}
// If hwnd does not match any window or message not processed
return DefWindowProc( hwnd, uMsg, wParam, lParam );
}
Win32Factory::Win32Factory( intf_thread_t *pIntf ):
OSFactory( pIntf ), TransparentBlt( NULL ), AlphaBlend( NULL ),
SetLayeredWindowAttributes( NULL )
{
// see init()
}
bool Win32Factory::init()
{
// Get instance handle
m_hInst = GetModuleHandle( NULL );
if( m_hInst == NULL )
{
msg_Err( getIntf(), "Cannot get module handle" );
}
// Create window class
WNDCLASS skinWindowClass;
skinWindowClass.style = CS_VREDRAW | CS_HREDRAW | CS_DBLCLKS;
skinWindowClass.lpfnWndProc = (WNDPROC) Win32Proc;
skinWindowClass.lpszClassName = "SkinWindowClass";
skinWindowClass.lpszMenuName = NULL;
skinWindowClass.cbClsExtra = 0;
skinWindowClass.cbWndExtra = 0;
skinWindowClass.hbrBackground = HBRUSH (COLOR_WINDOW);
skinWindowClass.hCursor = LoadCursor( NULL , IDC_ARROW );
skinWindowClass.hIcon = LoadIcon( m_hInst, "VLC_ICON" );
skinWindowClass.hInstance = m_hInst;
// Register class and check it
if( !RegisterClass( &skinWindowClass ) )
{
WNDCLASS wndclass;
// Check why it failed. If it's because the class already exists
// then fine, otherwise return with an error.
if( !GetClassInfo( m_hInst, "SkinWindowClass", &wndclass ) )
{
msg_Err( getIntf(), "Cannot register window class" );
return false;
}
}
// Create Window
m_hParentWindow = CreateWindowEx( WS_EX_APPWINDOW, "SkinWindowClass",
"VLC media player", WS_SYSMENU, -200, -200, 0, 0, 0, 0, m_hInst, 0 );
if( m_hParentWindow == NULL )
{
msg_Err( getIntf(), "Cannot create parent window" );
return false;
}
// We do it this way otherwise CreateWindowEx will fail
// if WS_EX_LAYERED is not supported
SetWindowLongPtr( m_hParentWindow, GWL_EXSTYLE,
GetWindowLong( m_hParentWindow, GWL_EXSTYLE )
| WS_EX_LAYERED );
// Store with it a pointer to the interface thread
SetWindowLongPtr( m_hParentWindow, GWLP_USERDATA, (LONG_PTR)getIntf() );
ShowWindow( m_hParentWindow, SW_SHOW );
// Initialize the OLE library (for drag & drop)
OleInitialize( NULL );
// We dynamically load msimg32.dll to get a pointer to TransparentBlt()
m_hMsimg32 = LoadLibrary( "msimg32.dll" );
if( !m_hMsimg32 ||
!( TransparentBlt =
(BOOL (WINAPI*)(HDC, int, int, int, int,
HDC, int, int, int, int, unsigned int))
GetProcAddress( m_hMsimg32, "TransparentBlt" ) ) )
{
TransparentBlt = NULL;
msg_Dbg( getIntf(), "Couldn't find TransparentBlt(), "
"falling back to BitBlt()" );
}
if( !m_hMsimg32 ||
!( AlphaBlend =
(BOOL (WINAPI*)( HDC, int, int, int, int, HDC, int, int,
int, int, BLENDFUNCTION ))
GetProcAddress( m_hMsimg32, "AlphaBlend" ) ) )
{
AlphaBlend = NULL;
msg_Dbg( getIntf(), "Couldn't find AlphaBlend()" );
}
// Idem for user32.dll and SetLayeredWindowAttributes()
m_hUser32 = LoadLibrary( "user32.dll" );
if( !m_hUser32 ||
!( SetLayeredWindowAttributes =
(BOOL (WINAPI *)(HWND, COLORREF, BYTE, DWORD))
GetProcAddress( m_hUser32, "SetLayeredWindowAttributes" ) ) )
{
SetLayeredWindowAttributes = NULL;
msg_Dbg( getIntf(), "Couldn't find SetLayeredWindowAttributes()" );
}
// All went well
return true;
}
Win32Factory::~Win32Factory()
{
// Uninitialize the OLE library
OleUninitialize();
// Unload msimg32.dll and user32.dll
if( m_hMsimg32 )
FreeLibrary( m_hMsimg32 );
if( m_hUser32 )
FreeLibrary( m_hUser32 );
}
OSGraphics *Win32Factory::createOSGraphics( int width, int height )
{
return new Win32Graphics( getIntf(), width, height );
}
OSLoop *Win32Factory::getOSLoop()
{
return Win32Loop::instance( getIntf() );
}
void Win32Factory::destroyOSLoop()
{
Win32Loop::destroy( getIntf() );
}
OSTimer *Win32Factory::createOSTimer( const Callback &rCallback )
{
return new Win32Timer( getIntf(), rCallback, m_hParentWindow );
}
OSWindow *Win32Factory::createOSWindow( GenericWindow &rWindow, bool dragDrop,
bool playOnDrop )
{
return new Win32Window( getIntf(), rWindow, m_hInst, m_hParentWindow,
dragDrop, playOnDrop );
}
OSTooltip *Win32Factory::createOSTooltip()
{
return new Win32Tooltip( getIntf(), m_hInst, m_hParentWindow );
}
const string Win32Factory::getDirSeparator() const
{
return "\\";
}
int Win32Factory::getScreenWidth() const
{
return GetSystemMetrics(SM_CXSCREEN);
}
int Win32Factory::getScreenHeight() const
{
return GetSystemMetrics(SM_CYSCREEN);
}
Rect Win32Factory::getWorkArea() const
{
RECT r;
SystemParametersInfo( SPI_GETWORKAREA, 0, &r, 0 );
// Fill a Rect object
Rect rect( r.left, r.top, r.right, r.bottom );
return rect;
}
void Win32Factory::getMousePos( int &rXPos, int &rYPos ) const
{
POINT mousePos;
GetCursorPos( &mousePos );
rXPos = mousePos.x;
rYPos = mousePos.y;
}
void Win32Factory::changeCursor( CursorType_t type ) const
{
LPCTSTR id;
switch( type )
{
case kDefaultArrow:
id = IDC_ARROW;
break;
case kResizeNWSE:
id = IDC_SIZENWSE;
break;
case kResizeNS:
id = IDC_SIZENS;
break;
case kResizeWE:
id = IDC_SIZEWE;
break;
case kResizeNESW:
id = IDC_SIZENESW;
break;
default:
id = IDC_ARROW;
break;
}
HCURSOR hCurs = LoadCursor( NULL, id );
SetCursor( hCurs );
}
void Win32Factory::rmDir( const string &rPath )
{
WIN32_FIND_DATA find;
string file;
string findFiles = rPath + "\\*";
HANDLE handle = FindFirstFile( findFiles.c_str(), &find );
while( handle != INVALID_HANDLE_VALUE )
{
// If file is neither "." nor ".."
if( strcmp( find.cFileName, "." ) && strcmp( find.cFileName, ".." ) )
{
// Set file name
file = rPath + "\\" + (string)find.cFileName;
// If file is a directory, delete it recursively
if( find.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
{
rmDir( file );
}
// Else, it is a file so simply delete it
else
{
DeleteFile( file.c_str() );
}
}
// If no more file in directory, exit while
if( !FindNextFile( handle, &find ) )
break;
}
// Now directory is empty so can be removed
FindClose( handle );
RemoveDirectory( rPath.c_str() );
}
#endif
<commit_msg> * skins2/win32/win32_factory.cpp: compilation fix<commit_after>/*****************************************************************************
* win32_factory.cpp
*****************************************************************************
* Copyright (C) 2003 VideoLAN
* $Id$
*
* Authors: Cyril Deguet <[email protected]>
* Olivier Teulire <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111, USA.
*****************************************************************************/
#ifdef WIN32_SKINS
#include "win32_factory.hpp"
#include "win32_graphics.hpp"
#include "win32_timer.hpp"
#include "win32_window.hpp"
#include "win32_tooltip.hpp"
#include "win32_loop.hpp"
LRESULT CALLBACK Win32Proc( HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam )
{
// Get pointer to thread info: should only work with the parent window
intf_thread_t *p_intf = (intf_thread_t *)GetWindowLongPtr( hwnd,
GWLP_USERDATA );
// If doesn't exist, treat windows message normally
if( p_intf == NULL || p_intf->p_sys->p_osFactory == NULL )
{
return DefWindowProc( hwnd, uMsg, wParam, lParam );
}
// Here we know we are getting a message for the parent window, since it is
// the only one to store p_intf...
// Yes, it is a kludge :)
//Win32Factory *pFactory = (Win32Factory*)Win32Factory::instance( p_intf );
//msg_Err( p_intf, "Parent window %p %p %u %i\n", pFactory->m_hParentWindow, hwnd, uMsg, wParam );
// If Window is parent window
// XXX: this test isn't needed, see the kludge above...
// if( hwnd == pFactory->m_hParentWindow )
{
if( uMsg == WM_SYSCOMMAND )
{
// If closing parent window
if( wParam == SC_CLOSE )
{
Win32Loop *pLoop = (Win32Loop*)Win32Loop::instance( p_intf );
pLoop->exit();
return 0;
}
else
{
msg_Err( p_intf, "WM_SYSCOMMAND %i", wParam );
}
// if( (Event *)wParam != NULL )
// ( (Event *)wParam )->SendEvent();
// return 0;
}
}
// If hwnd does not match any window or message not processed
return DefWindowProc( hwnd, uMsg, wParam, lParam );
}
Win32Factory::Win32Factory( intf_thread_t *pIntf ):
OSFactory( pIntf ), TransparentBlt( NULL ), AlphaBlend( NULL ),
SetLayeredWindowAttributes( NULL )
{
// see init()
}
bool Win32Factory::init()
{
// Get instance handle
m_hInst = GetModuleHandle( NULL );
if( m_hInst == NULL )
{
msg_Err( getIntf(), "Cannot get module handle" );
}
// Create window class
WNDCLASS skinWindowClass;
skinWindowClass.style = CS_VREDRAW | CS_HREDRAW | CS_DBLCLKS;
skinWindowClass.lpfnWndProc = (WNDPROC) Win32Proc;
skinWindowClass.lpszClassName = "SkinWindowClass";
skinWindowClass.lpszMenuName = NULL;
skinWindowClass.cbClsExtra = 0;
skinWindowClass.cbWndExtra = 0;
skinWindowClass.hbrBackground = HBRUSH (COLOR_WINDOW);
skinWindowClass.hCursor = LoadCursor( NULL , IDC_ARROW );
skinWindowClass.hIcon = LoadIcon( m_hInst, "VLC_ICON" );
skinWindowClass.hInstance = m_hInst;
// Register class and check it
if( !RegisterClass( &skinWindowClass ) )
{
WNDCLASS wndclass;
// Check why it failed. If it's because the class already exists
// then fine, otherwise return with an error.
if( !GetClassInfo( m_hInst, "SkinWindowClass", &wndclass ) )
{
msg_Err( getIntf(), "Cannot register window class" );
return false;
}
}
// Create Window
m_hParentWindow = CreateWindowEx( WS_EX_APPWINDOW, "SkinWindowClass",
"VLC media player", WS_SYSMENU, -200, -200, 0, 0, 0, 0, m_hInst, 0 );
if( m_hParentWindow == NULL )
{
msg_Err( getIntf(), "Cannot create parent window" );
return false;
}
// We do it this way otherwise CreateWindowEx will fail
// if WS_EX_LAYERED is not supported
SetWindowLongPtr( m_hParentWindow, GWL_EXSTYLE,
GetWindowLong( m_hParentWindow, GWL_EXSTYLE )
| WS_EX_LAYERED );
// Store with it a pointer to the interface thread
SetWindowLongPtr( m_hParentWindow, GWLP_USERDATA, (LONG_PTR)getIntf() );
ShowWindow( m_hParentWindow, SW_SHOW );
// Initialize the OLE library (for drag & drop)
OleInitialize( NULL );
// We dynamically load msimg32.dll to get a pointer to TransparentBlt()
m_hMsimg32 = LoadLibrary( "msimg32.dll" );
if( !m_hMsimg32 ||
!( TransparentBlt =
(BOOL (WINAPI*)(HDC, int, int, int, int,
HDC, int, int, int, int, unsigned int))
GetProcAddress( m_hMsimg32, "TransparentBlt" ) ) )
{
TransparentBlt = NULL;
msg_Dbg( getIntf(), "Couldn't find TransparentBlt(), "
"falling back to BitBlt()" );
}
if( !m_hMsimg32 ||
!( AlphaBlend =
(BOOL (WINAPI*)( HDC, int, int, int, int, HDC, int, int,
int, int, BLENDFUNCTION ))
GetProcAddress( m_hMsimg32, "AlphaBlend" ) ) )
{
AlphaBlend = NULL;
msg_Dbg( getIntf(), "Couldn't find AlphaBlend()" );
}
// Idem for user32.dll and SetLayeredWindowAttributes()
m_hUser32 = LoadLibrary( "user32.dll" );
if( !m_hUser32 ||
!( SetLayeredWindowAttributes =
(BOOL (WINAPI *)(HWND, COLORREF, BYTE, DWORD))
GetProcAddress( m_hUser32, "SetLayeredWindowAttributes" ) ) )
{
SetLayeredWindowAttributes = NULL;
msg_Dbg( getIntf(), "Couldn't find SetLayeredWindowAttributes()" );
}
// All went well
return true;
}
Win32Factory::~Win32Factory()
{
// Uninitialize the OLE library
OleUninitialize();
// Unload msimg32.dll and user32.dll
if( m_hMsimg32 )
FreeLibrary( m_hMsimg32 );
if( m_hUser32 )
FreeLibrary( m_hUser32 );
}
OSGraphics *Win32Factory::createOSGraphics( int width, int height )
{
return new Win32Graphics( getIntf(), width, height );
}
OSLoop *Win32Factory::getOSLoop()
{
return Win32Loop::instance( getIntf() );
}
void Win32Factory::destroyOSLoop()
{
Win32Loop::destroy( getIntf() );
}
OSTimer *Win32Factory::createOSTimer( const Callback &rCallback )
{
return new Win32Timer( getIntf(), rCallback, m_hParentWindow );
}
OSWindow *Win32Factory::createOSWindow( GenericWindow &rWindow, bool dragDrop,
bool playOnDrop, OSWindow *pParent )
{
return new Win32Window( getIntf(), rWindow, m_hInst, m_hParentWindow,
dragDrop, playOnDrop );
}
OSTooltip *Win32Factory::createOSTooltip()
{
return new Win32Tooltip( getIntf(), m_hInst, m_hParentWindow );
}
const string Win32Factory::getDirSeparator() const
{
return "\\";
}
int Win32Factory::getScreenWidth() const
{
return GetSystemMetrics(SM_CXSCREEN);
}
int Win32Factory::getScreenHeight() const
{
return GetSystemMetrics(SM_CYSCREEN);
}
Rect Win32Factory::getWorkArea() const
{
RECT r;
SystemParametersInfo( SPI_GETWORKAREA, 0, &r, 0 );
// Fill a Rect object
Rect rect( r.left, r.top, r.right, r.bottom );
return rect;
}
void Win32Factory::getMousePos( int &rXPos, int &rYPos ) const
{
POINT mousePos;
GetCursorPos( &mousePos );
rXPos = mousePos.x;
rYPos = mousePos.y;
}
void Win32Factory::changeCursor( CursorType_t type ) const
{
LPCTSTR id;
switch( type )
{
case kDefaultArrow:
id = IDC_ARROW;
break;
case kResizeNWSE:
id = IDC_SIZENWSE;
break;
case kResizeNS:
id = IDC_SIZENS;
break;
case kResizeWE:
id = IDC_SIZEWE;
break;
case kResizeNESW:
id = IDC_SIZENESW;
break;
default:
id = IDC_ARROW;
break;
}
HCURSOR hCurs = LoadCursor( NULL, id );
SetCursor( hCurs );
}
void Win32Factory::rmDir( const string &rPath )
{
WIN32_FIND_DATA find;
string file;
string findFiles = rPath + "\\*";
HANDLE handle = FindFirstFile( findFiles.c_str(), &find );
while( handle != INVALID_HANDLE_VALUE )
{
// If file is neither "." nor ".."
if( strcmp( find.cFileName, "." ) && strcmp( find.cFileName, ".." ) )
{
// Set file name
file = rPath + "\\" + (string)find.cFileName;
// If file is a directory, delete it recursively
if( find.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
{
rmDir( file );
}
// Else, it is a file so simply delete it
else
{
DeleteFile( file.c_str() );
}
}
// If no more file in directory, exit while
if( !FindNextFile( handle, &find ) )
break;
}
// Now directory is empty so can be removed
FindClose( handle );
RemoveDirectory( rPath.c_str() );
}
#endif
<|endoftext|>
|
<commit_before>/*
* Matcha Robotics Application Framework
*
* Copyright (C) 2011 Yusuke Suzuki
*
* 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 MATCHA_MATH_TYPES_HPP__
#define MATCHA_MATH_TYPES_HPP__
#include <cassert>
#include <cstdint>
#include <iostream>
#include <string>
namespace matcha { namespace math {
enum class type_id_t : int32_t
{
int8_id = 0x0,
uint8_id,
int16_id,
uint16_id,
int32_id,
uint32_id,
int64_id,
uint64_id,
float_id = 0x00010000,
double_id,
unsupported = -1
};
template<typename T> constexpr bool is_supported_type(){ return false; }
template<> constexpr bool is_supported_type< int8_t>(){ return true; }
template<> constexpr bool is_supported_type< uint8_t>(){ return true; }
template<> constexpr bool is_supported_type< int16_t>(){ return true; }
template<> constexpr bool is_supported_type<uint16_t>(){ return true; }
template<> constexpr bool is_supported_type< int32_t>(){ return true; }
template<> constexpr bool is_supported_type<uint32_t>(){ return true; }
template<> constexpr bool is_supported_type< float>(){ return true; }
template<> constexpr bool is_supported_type< double>(){ return true; }
template<typename T>
constexpr type_id_t type_id()
{
static_assert(is_supported_type<T>(), "not supported");
return -1;
}
#define MATCHA_TYPE_ID_DECRARATION_TEMP_MACRO(X,Y) \
template<> constexpr type_id_t type_id<X>(){ return type_id_t::Y; }
MATCHA_TYPE_ID_DECRARATION_TEMP_MACRO( int8_t, int8_id);
MATCHA_TYPE_ID_DECRARATION_TEMP_MACRO( uint8_t, uint8_id);
MATCHA_TYPE_ID_DECRARATION_TEMP_MACRO( int16_t, int16_id);
MATCHA_TYPE_ID_DECRARATION_TEMP_MACRO(uint16_t, uint16_id);
MATCHA_TYPE_ID_DECRARATION_TEMP_MACRO( int32_t, int32_id);
MATCHA_TYPE_ID_DECRARATION_TEMP_MACRO(uint32_t, uint32_id);
MATCHA_TYPE_ID_DECRARATION_TEMP_MACRO( int64_t, int64_id);
MATCHA_TYPE_ID_DECRARATION_TEMP_MACRO(uint64_t, uint64_id);
MATCHA_TYPE_ID_DECRARATION_TEMP_MACRO( float, float_id);
MATCHA_TYPE_ID_DECRARATION_TEMP_MACRO( double, double_id);
#undef MATCHA_TYPE_ID_DECRARATION_TEMP_MACRO
template<typename T>
constexpr type_id_t type_id(const T&)
{
return type_id<T>();
}
template<typename T>
constexpr bool supported_type_assert()
{
static_assert(is_supported_type<T>(), "not supported");
return is_supported_type<T>();
}
template<type_id_t t>
constexpr bool supported_type_assert()
{
static_assert(t != type_id_t::unsupported, "not supported");
return true;
}
template<typename T, bool b = true>
struct type_of_id_base
{
typedef T type;
static const type_id_t type_id = type_id<T>();
};
template<type_id_t t>
struct type_of_id : public type_of_id_base<void, supported_type_assert<t>()>
{
};
#define MATCHA_TYPE_OF_ID_DECRARATION_TEMP_MACRO(X, Y) \
template<> struct type_of_id<type_id_t::X> : public type_of_id_base<Y> {};
MATCHA_TYPE_OF_ID_DECRARATION_TEMP_MACRO( int8_id, int8_t);
MATCHA_TYPE_OF_ID_DECRARATION_TEMP_MACRO( uint8_id, uint8_t);
MATCHA_TYPE_OF_ID_DECRARATION_TEMP_MACRO( int16_id, int16_t);
MATCHA_TYPE_OF_ID_DECRARATION_TEMP_MACRO(uint16_id, uint16_t);
MATCHA_TYPE_OF_ID_DECRARATION_TEMP_MACRO( int32_id, int32_t);
MATCHA_TYPE_OF_ID_DECRARATION_TEMP_MACRO(uint32_id, uint32_t);
MATCHA_TYPE_OF_ID_DECRARATION_TEMP_MACRO( int64_id, int64_t);
MATCHA_TYPE_OF_ID_DECRARATION_TEMP_MACRO(uint64_id, uint64_t);
MATCHA_TYPE_OF_ID_DECRARATION_TEMP_MACRO( float_id, float);
MATCHA_TYPE_OF_ID_DECRARATION_TEMP_MACRO(double_id, double);
#undef MATCHA_TYPE_OF_ID_DECRARATION_TEMP_MACRO
inline std::size_t size_of_type(type_id_t type_id)
{
#define MATCHA_SWITCH_LOCAL_MACRO(X,Y) case type_id_t::X : return sizeof(Y); break;
switch(type_id)
{
MATCHA_SWITCH_LOCAL_MACRO( int8_id, int8_t);
MATCHA_SWITCH_LOCAL_MACRO( uint8_id, uint8_t);
MATCHA_SWITCH_LOCAL_MACRO( int16_id, int16_t);
MATCHA_SWITCH_LOCAL_MACRO(uint16_id, uint16_t);
MATCHA_SWITCH_LOCAL_MACRO( int32_id, int32_t);
MATCHA_SWITCH_LOCAL_MACRO(uint32_id, uint32_t);
MATCHA_SWITCH_LOCAL_MACRO( int64_id, int64_t);
MATCHA_SWITCH_LOCAL_MACRO(uint64_id, uint64_t);
MATCHA_SWITCH_LOCAL_MACRO( float_id, float);
MATCHA_SWITCH_LOCAL_MACRO(double_id, double);
default: break;
}
#undef MATCHA_LOCAL_CASE_MACRO
assert(false && "invalid type_id");
return 0;
}
} // end of namespace math
} // end of namespace matcha
#endif
<commit_msg>Update math/types.hpp for C++11 support<commit_after>/*
* Matcha Robotics Application Framework
*
* Copyright (C) 2011 Yusuke Suzuki
*
* 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 MATCHA_MATH_TYPES_HPP__
#define MATCHA_MATH_TYPES_HPP__
#include <cassert>
#include <cstdint>
#include <iostream>
#include <string>
namespace matcha { namespace math {
enum class type_id_t : int32_t
{
int8_id = 0x0,
uint8_id,
int16_id,
uint16_id,
int32_id,
uint32_id,
int64_id,
uint64_id,
float_id = 0x00010000,
double_id,
unsupported = -1
};
template<typename T> constexpr bool is_supported_type(){ return false; }
template<> constexpr bool is_supported_type< int8_t>(){ return true; }
template<> constexpr bool is_supported_type< uint8_t>(){ return true; }
template<> constexpr bool is_supported_type< int16_t>(){ return true; }
template<> constexpr bool is_supported_type<uint16_t>(){ return true; }
template<> constexpr bool is_supported_type< int32_t>(){ return true; }
template<> constexpr bool is_supported_type<uint32_t>(){ return true; }
template<> constexpr bool is_supported_type< float>(){ return true; }
template<> constexpr bool is_supported_type< double>(){ return true; }
template<typename T>
constexpr type_id_t type_id()
{
static_assert(is_supported_type<T>(), "not supported");
return type_id_t::unsupported;
}
#define MATCHA_TYPE_ID_DECRARATION_TEMP_MACRO(X,Y) \
template<> constexpr type_id_t type_id<X>(){ return type_id_t::Y; }
MATCHA_TYPE_ID_DECRARATION_TEMP_MACRO( int8_t, int8_id);
MATCHA_TYPE_ID_DECRARATION_TEMP_MACRO( uint8_t, uint8_id);
MATCHA_TYPE_ID_DECRARATION_TEMP_MACRO( int16_t, int16_id);
MATCHA_TYPE_ID_DECRARATION_TEMP_MACRO(uint16_t, uint16_id);
MATCHA_TYPE_ID_DECRARATION_TEMP_MACRO( int32_t, int32_id);
MATCHA_TYPE_ID_DECRARATION_TEMP_MACRO(uint32_t, uint32_id);
MATCHA_TYPE_ID_DECRARATION_TEMP_MACRO( int64_t, int64_id);
MATCHA_TYPE_ID_DECRARATION_TEMP_MACRO(uint64_t, uint64_id);
MATCHA_TYPE_ID_DECRARATION_TEMP_MACRO( float, float_id);
MATCHA_TYPE_ID_DECRARATION_TEMP_MACRO( double, double_id);
#undef MATCHA_TYPE_ID_DECRARATION_TEMP_MACRO
template<typename T>
constexpr type_id_t type_id(const T&)
{
return type_id<T>();
}
template<typename T>
constexpr bool supported_type_assert()
{
static_assert(is_supported_type<T>(), "not supported");
return is_supported_type<T>();
}
template<type_id_t t>
constexpr bool supported_type_assert()
{
static_assert(t != type_id_t::unsupported, "not supported");
return true;
}
template<typename T, bool b = true>
struct type_of_id_base
{
typedef T type;
static const type_id_t type_id = type_id<T>();
};
template<type_id_t t>
struct type_of_id : public type_of_id_base<void, supported_type_assert<t>()>
{
};
#define MATCHA_TYPE_OF_ID_DECRARATION_TEMP_MACRO(X, Y) \
template<> struct type_of_id<type_id_t::X> : public type_of_id_base<Y> {};
MATCHA_TYPE_OF_ID_DECRARATION_TEMP_MACRO( int8_id, int8_t);
MATCHA_TYPE_OF_ID_DECRARATION_TEMP_MACRO( uint8_id, uint8_t);
MATCHA_TYPE_OF_ID_DECRARATION_TEMP_MACRO( int16_id, int16_t);
MATCHA_TYPE_OF_ID_DECRARATION_TEMP_MACRO(uint16_id, uint16_t);
MATCHA_TYPE_OF_ID_DECRARATION_TEMP_MACRO( int32_id, int32_t);
MATCHA_TYPE_OF_ID_DECRARATION_TEMP_MACRO(uint32_id, uint32_t);
MATCHA_TYPE_OF_ID_DECRARATION_TEMP_MACRO( int64_id, int64_t);
MATCHA_TYPE_OF_ID_DECRARATION_TEMP_MACRO(uint64_id, uint64_t);
MATCHA_TYPE_OF_ID_DECRARATION_TEMP_MACRO( float_id, float);
MATCHA_TYPE_OF_ID_DECRARATION_TEMP_MACRO(double_id, double);
#undef MATCHA_TYPE_OF_ID_DECRARATION_TEMP_MACRO
inline std::size_t size_of_type(type_id_t type_id)
{
#define MATCHA_SWITCH_LOCAL_MACRO(X,Y) case type_id_t::X : return sizeof(Y); break;
switch(type_id)
{
MATCHA_SWITCH_LOCAL_MACRO( int8_id, int8_t);
MATCHA_SWITCH_LOCAL_MACRO( uint8_id, uint8_t);
MATCHA_SWITCH_LOCAL_MACRO( int16_id, int16_t);
MATCHA_SWITCH_LOCAL_MACRO(uint16_id, uint16_t);
MATCHA_SWITCH_LOCAL_MACRO( int32_id, int32_t);
MATCHA_SWITCH_LOCAL_MACRO(uint32_id, uint32_t);
MATCHA_SWITCH_LOCAL_MACRO( int64_id, int64_t);
MATCHA_SWITCH_LOCAL_MACRO(uint64_id, uint64_t);
MATCHA_SWITCH_LOCAL_MACRO( float_id, float);
MATCHA_SWITCH_LOCAL_MACRO(double_id, double);
default: break;
}
#undef MATCHA_LOCAL_CASE_MACRO
assert(false && "invalid type_id");
return 0;
}
} // end of namespace math
} // end of namespace matcha
#endif
<|endoftext|>
|
<commit_before><commit_msg>Update open_space_info.cc<commit_after><|endoftext|>
|
<commit_before>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/prediction/prediction_component.h"
#include <algorithm>
#include <cmath>
#include <memory>
#include <mutex>
#include <vector>
#include "boost/filesystem.hpp"
#include "boost/range/iterator_range.hpp"
#include "modules/common/adapters/adapter_gflags.h"
#include "modules/common/math/vec2d.h"
#include "modules/common/time/time.h"
#include "modules/common/util/file.h"
#include "modules/prediction/common/feature_output.h"
#include "modules/prediction/common/prediction_gflags.h"
#include "modules/prediction/common/prediction_map.h"
#include "modules/prediction/common/validation_checker.h"
#include "modules/prediction/container/container_manager.h"
#include "modules/prediction/container/obstacles/obstacles_container.h"
#include "modules/prediction/container/pose/pose_container.h"
#include "modules/prediction/evaluator/evaluator_manager.h"
#include "modules/prediction/predictor/predictor_manager.h"
#include "modules/prediction/proto/prediction_obstacle.pb.h"
#include "modules/prediction/util/data_extraction.h"
namespace apollo {
namespace prediction {
using apollo::common::ErrorCode;
using apollo::common::Status;
using apollo::common::TrajectoryPoint;
using apollo::common::adapter::AdapterConfig;
using apollo::common::math::Vec2d;
using apollo::common::time::Clock;
using apollo::common::util::DirectoryExists;
using apollo::common::util::Glob;
using apollo::localization::LocalizationEstimate;
using apollo::perception::PerceptionObstacle;
using apollo::perception::PerceptionObstacles;
using apollo::planning::ADCTrajectory;
std::string PredictionComponent::Name() const {
return FLAGS_prediction_module_name;
}
void PredictionComponent::ProcessOfflineData(const std::string& filename) {
// TODO(all) implement
/**
const std::vector<std::string> topics{FLAGS_perception_obstacle_topic,
FLAGS_localization_topic};
rosbag::Bag bag;
try {
bag.open(filename, rosbag::bagmode::Read);
} catch (const rosbag::BagIOException& e) {
AERROR << "BagIOException when open bag: " << filename
<< " Exception: " << e.what();
bag.close();
return;
} catch (...) {
AERROR << "Failed to open bag: " << filename;
bag.close();
return;
}
rosbag::View view(bag, rosbag::TopicQuery(topics));
for (auto it = view.begin(); it != view.end(); ++it) {
if (it->getTopic() == FLAGS_localization_topic) {
OnLocalization(*(it->instantiate<LocalizationEstimate>()));
} else if (it->getTopic() == FLAGS_perception_obstacle_topic) {
RunOnce(*(it->instantiate<PerceptionObstacles>()));
}
}
bag.close();
**/
}
bool PredictionComponent::Init() {
AINFO << "Loading gflag from file: " << ConfigFilePath();
google::SetCommandLineOption("flagfile", ConfigFilePath().c_str());
component_start_time_ = Clock::NowInSeconds();
// Load prediction conf
prediction_conf_.Clear();
if (!common::util::GetProtoFromFile(FLAGS_prediction_conf_file,
&prediction_conf_)) {
AERROR << "Unable to load prediction conf file: "
<< FLAGS_prediction_conf_file;
return false;
} else {
ADEBUG << "Prediction config file is loaded into: "
<< prediction_conf_.ShortDebugString();
}
adapter_conf_.Clear();
if (!common::util::GetProtoFromFile(FLAGS_prediction_adapter_config_filename,
&adapter_conf_)) {
AERROR << "Unable to load adapter conf file: "
<< FLAGS_prediction_adapter_config_filename;
return false;
} else {
ADEBUG << "Adapter config file is loaded into: "
<< adapter_conf_.ShortDebugString();
}
// Initialization of all managers
ContainerManager::Instance()->Init(adapter_conf_);
EvaluatorManager::Instance()->Init(prediction_conf_);
PredictorManager::Instance()->Init(prediction_conf_);
if (!FLAGS_use_navigation_mode && !PredictionMap::Ready()) {
AERROR << "Map cannot be loaded.";
return false;
}
if (FLAGS_prediction_offline_mode) {
if (!FeatureOutput::Ready()) {
AERROR << "Feature output is not ready.";
return false;
}
if (FLAGS_prediction_offline_bags.empty()) {
return true; // use listen to ROS topic mode
}
std::vector<std::string> inputs;
apollo::common::util::split(FLAGS_prediction_offline_bags, ':', &inputs);
for (const auto& input : inputs) {
std::vector<std::string> offline_bags;
GetDataFileNames(boost::filesystem::path(input), &offline_bags);
std::sort(offline_bags.begin(), offline_bags.end());
AINFO << "For input " << input << ", found " << offline_bags.size()
<< " rosbags to process";
for (std::size_t i = 0; i < offline_bags.size(); ++i) {
AINFO << "\tProcessing: [ " << i << " / " << offline_bags.size()
<< " ]: " << offline_bags[i];
ProcessOfflineData(offline_bags[i]);
}
}
Stop();
// TODO(kechxu) accord to cybertron
// ros::shutdown();
}
return true;
}
Status PredictionComponent::Start() { return Status::OK(); }
void PredictionComponent::Stop() {
if (FLAGS_prediction_offline_mode) {
FeatureOutput::Close();
}
}
void PredictionComponent::OnLocalization(
const LocalizationEstimate& localization) {
PoseContainer* pose_container = dynamic_cast<PoseContainer*>(
ContainerManager::Instance()->GetContainer(AdapterConfig::LOCALIZATION));
CHECK_NOTNULL(pose_container);
pose_container->Insert(localization);
ADEBUG << "Received a localization message ["
<< localization.ShortDebugString() << "].";
}
void PredictionComponent::OnPlanning(
const planning::ADCTrajectory& adc_trajectory) {
ADCTrajectoryContainer* adc_trajectory_container =
dynamic_cast<ADCTrajectoryContainer*>(
ContainerManager::Instance()->GetContainer(
AdapterConfig::PLANNING_TRAJECTORY));
CHECK_NOTNULL(adc_trajectory_container);
adc_trajectory_container->Insert(adc_trajectory);
ADEBUG << "Received a planning message [" << adc_trajectory.ShortDebugString()
<< "].";
}
bool PredictionComponent::Proc(
const std::shared_ptr<PerceptionObstacles>& perception_obstacles,
const std::shared_ptr<LocalizationEstimate>& localization,
const std::shared_ptr<ADCTrajectory>& adc_trajectory) {
if (FLAGS_prediction_test_mode &&
(Clock::NowInSeconds() - component_start_time_
> FLAGS_prediction_test_duration)) {
AINFO << "Prediction finished running in test mode";
// TODO(kechxu) accord to cybertron
// ros::shutdown();
}
// Update relative map if needed
// AdapterManager::Observe();
if (FLAGS_use_navigation_mode && !PredictionMap::Ready()) {
AERROR << "Relative map is empty.";
return false;
}
double start_timestamp = Clock::NowInSeconds();
OnLocalization(*localization);
OnPlanning(*adc_trajectory);
// Insert obstacle
ObstaclesContainer* obstacles_container = dynamic_cast<ObstaclesContainer*>(
ContainerManager::Instance()->GetContainer(
AdapterConfig::PERCEPTION_OBSTACLES));
CHECK_NOTNULL(obstacles_container);
obstacles_container->Insert(*perception_obstacles);
ADEBUG << "Received a perception message ["
<< perception_obstacles->ShortDebugString() << "].";
// Update ADC status
PoseContainer* pose_container = dynamic_cast<PoseContainer*>(
ContainerManager::Instance()->GetContainer(AdapterConfig::LOCALIZATION));
ADCTrajectoryContainer* adc_container = dynamic_cast<ADCTrajectoryContainer*>(
ContainerManager::Instance()->GetContainer(
AdapterConfig::PLANNING_TRAJECTORY));
CHECK_NOTNULL(pose_container);
CHECK_NOTNULL(adc_container);
PerceptionObstacle* adc = pose_container->ToPerceptionObstacle();
if (adc != nullptr) {
obstacles_container->InsertPerceptionObstacle(*adc, adc->timestamp());
double x = adc->position().x();
double y = adc->position().y();
ADEBUG << "Get ADC position [" << std::fixed << std::setprecision(6) << x
<< ", " << std::fixed << std::setprecision(6) << y << "].";
adc_container->SetPosition({x, y});
}
// Make evaluations
EvaluatorManager::Instance()->Run(*perception_obstacles);
// No prediction trajectories for offline mode
if (FLAGS_prediction_offline_mode) {
return true;
}
// Make predictions
PredictorManager::Instance()->Run(*perception_obstacles);
auto prediction_obstacles =
PredictorManager::Instance()->prediction_obstacles();
prediction_obstacles.set_start_timestamp(start_timestamp);
prediction_obstacles.set_end_timestamp(Clock::NowInSeconds());
prediction_obstacles.mutable_header()->set_lidar_timestamp(
perception_obstacles->header().lidar_timestamp());
prediction_obstacles.mutable_header()->set_camera_timestamp(
perception_obstacles->header().camera_timestamp());
prediction_obstacles.mutable_header()->set_radar_timestamp(
perception_obstacles->header().radar_timestamp());
if (FLAGS_prediction_test_mode) {
for (auto const& prediction_obstacle :
prediction_obstacles.prediction_obstacle()) {
for (auto const& trajectory : prediction_obstacle.trajectory()) {
for (auto const& trajectory_point : trajectory.trajectory_point()) {
if (!ValidationChecker::ValidTrajectoryPoint(trajectory_point)) {
AERROR << "Invalid trajectory point ["
<< trajectory_point.ShortDebugString() << "]";
return false;
}
}
}
}
}
prediction_writer_->Write(prediction_obstacles);
return true;
}
Status PredictionComponent::OnError(const std::string& error_msg) {
return Status(ErrorCode::PREDICTION_ERROR, error_msg);
}
} // namespace prediction
} // namespace apollo
<commit_msg>Prediction: initialize prediction writer to run loops<commit_after>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/prediction/prediction_component.h"
#include <algorithm>
#include <cmath>
#include <memory>
#include <mutex>
#include <vector>
#include "boost/filesystem.hpp"
#include "boost/range/iterator_range.hpp"
#include "modules/common/adapters/adapter_gflags.h"
#include "modules/common/math/vec2d.h"
#include "modules/common/time/time.h"
#include "modules/common/util/file.h"
#include "modules/prediction/common/feature_output.h"
#include "modules/prediction/common/prediction_gflags.h"
#include "modules/prediction/common/prediction_map.h"
#include "modules/prediction/common/validation_checker.h"
#include "modules/prediction/container/container_manager.h"
#include "modules/prediction/container/obstacles/obstacles_container.h"
#include "modules/prediction/container/pose/pose_container.h"
#include "modules/prediction/evaluator/evaluator_manager.h"
#include "modules/prediction/predictor/predictor_manager.h"
#include "modules/prediction/proto/prediction_obstacle.pb.h"
#include "modules/prediction/util/data_extraction.h"
namespace apollo {
namespace prediction {
using apollo::common::ErrorCode;
using apollo::common::Status;
using apollo::common::TrajectoryPoint;
using apollo::common::adapter::AdapterConfig;
using apollo::common::math::Vec2d;
using apollo::common::time::Clock;
using apollo::common::util::DirectoryExists;
using apollo::common::util::Glob;
using apollo::localization::LocalizationEstimate;
using apollo::perception::PerceptionObstacle;
using apollo::perception::PerceptionObstacles;
using apollo::planning::ADCTrajectory;
std::string PredictionComponent::Name() const {
return FLAGS_prediction_module_name;
}
void PredictionComponent::ProcessOfflineData(const std::string& filename) {
// TODO(all) implement
/**
const std::vector<std::string> topics{FLAGS_perception_obstacle_topic,
FLAGS_localization_topic};
rosbag::Bag bag;
try {
bag.open(filename, rosbag::bagmode::Read);
} catch (const rosbag::BagIOException& e) {
AERROR << "BagIOException when open bag: " << filename
<< " Exception: " << e.what();
bag.close();
return;
} catch (...) {
AERROR << "Failed to open bag: " << filename;
bag.close();
return;
}
rosbag::View view(bag, rosbag::TopicQuery(topics));
for (auto it = view.begin(); it != view.end(); ++it) {
if (it->getTopic() == FLAGS_localization_topic) {
OnLocalization(*(it->instantiate<LocalizationEstimate>()));
} else if (it->getTopic() == FLAGS_perception_obstacle_topic) {
RunOnce(*(it->instantiate<PerceptionObstacles>()));
}
}
bag.close();
**/
}
bool PredictionComponent::Init() {
AINFO << "Loading gflag from file: " << ConfigFilePath();
google::SetCommandLineOption("flagfile", ConfigFilePath().c_str());
component_start_time_ = Clock::NowInSeconds();
// Load prediction conf
prediction_conf_.Clear();
if (!common::util::GetProtoFromFile(FLAGS_prediction_conf_file,
&prediction_conf_)) {
AERROR << "Unable to load prediction conf file: "
<< FLAGS_prediction_conf_file;
return false;
} else {
ADEBUG << "Prediction config file is loaded into: "
<< prediction_conf_.ShortDebugString();
}
adapter_conf_.Clear();
if (!common::util::GetProtoFromFile(FLAGS_prediction_adapter_config_filename,
&adapter_conf_)) {
AERROR << "Unable to load adapter conf file: "
<< FLAGS_prediction_adapter_config_filename;
return false;
} else {
ADEBUG << "Adapter config file is loaded into: "
<< adapter_conf_.ShortDebugString();
}
// Initialization of all managers
ContainerManager::Instance()->Init(adapter_conf_);
EvaluatorManager::Instance()->Init(prediction_conf_);
PredictorManager::Instance()->Init(prediction_conf_);
if (!FLAGS_use_navigation_mode && !PredictionMap::Ready()) {
AERROR << "Map cannot be loaded.";
return false;
}
prediction_writer_ =
node_->CreateWriter<PredictionObstacles>(FLAGS_prediction_topic);
if (FLAGS_prediction_offline_mode) {
if (!FeatureOutput::Ready()) {
AERROR << "Feature output is not ready.";
return false;
}
if (FLAGS_prediction_offline_bags.empty()) {
return true; // use listen to ROS topic mode
}
std::vector<std::string> inputs;
apollo::common::util::split(FLAGS_prediction_offline_bags, ':', &inputs);
for (const auto& input : inputs) {
std::vector<std::string> offline_bags;
GetDataFileNames(boost::filesystem::path(input), &offline_bags);
std::sort(offline_bags.begin(), offline_bags.end());
AINFO << "For input " << input << ", found " << offline_bags.size()
<< " rosbags to process";
for (std::size_t i = 0; i < offline_bags.size(); ++i) {
AINFO << "\tProcessing: [ " << i << " / " << offline_bags.size()
<< " ]: " << offline_bags[i];
ProcessOfflineData(offline_bags[i]);
}
}
Stop();
// TODO(kechxu) accord to cybertron
// ros::shutdown();
}
return true;
}
Status PredictionComponent::Start() { return Status::OK(); }
void PredictionComponent::Stop() {
if (FLAGS_prediction_offline_mode) {
FeatureOutput::Close();
}
}
void PredictionComponent::OnLocalization(
const LocalizationEstimate& localization) {
PoseContainer* pose_container = dynamic_cast<PoseContainer*>(
ContainerManager::Instance()->GetContainer(AdapterConfig::LOCALIZATION));
CHECK_NOTNULL(pose_container);
pose_container->Insert(localization);
ADEBUG << "Received a localization message ["
<< localization.ShortDebugString() << "].";
}
void PredictionComponent::OnPlanning(
const planning::ADCTrajectory& adc_trajectory) {
ADCTrajectoryContainer* adc_trajectory_container =
dynamic_cast<ADCTrajectoryContainer*>(
ContainerManager::Instance()->GetContainer(
AdapterConfig::PLANNING_TRAJECTORY));
CHECK_NOTNULL(adc_trajectory_container);
adc_trajectory_container->Insert(adc_trajectory);
ADEBUG << "Received a planning message [" << adc_trajectory.ShortDebugString()
<< "].";
}
bool PredictionComponent::Proc(
const std::shared_ptr<PerceptionObstacles>& perception_obstacles,
const std::shared_ptr<LocalizationEstimate>& localization,
const std::shared_ptr<ADCTrajectory>& adc_trajectory) {
if (FLAGS_prediction_test_mode &&
(Clock::NowInSeconds() - component_start_time_
> FLAGS_prediction_test_duration)) {
ADEBUG << "Prediction finished running in test mode";
// TODO(kechxu) accord to cybertron
// ros::shutdown();
}
// Update relative map if needed
// AdapterManager::Observe();
if (FLAGS_use_navigation_mode && !PredictionMap::Ready()) {
AERROR << "Relative map is empty.";
return false;
}
double start_timestamp = Clock::NowInSeconds();
OnLocalization(*localization);
OnPlanning(*adc_trajectory);
// Insert obstacle
ObstaclesContainer* obstacles_container = dynamic_cast<ObstaclesContainer*>(
ContainerManager::Instance()->GetContainer(
AdapterConfig::PERCEPTION_OBSTACLES));
CHECK_NOTNULL(obstacles_container);
obstacles_container->Insert(*perception_obstacles);
ADEBUG << "Received a perception message ["
<< perception_obstacles->ShortDebugString() << "].";
// Update ADC status
PoseContainer* pose_container = dynamic_cast<PoseContainer*>(
ContainerManager::Instance()->GetContainer(AdapterConfig::LOCALIZATION));
ADCTrajectoryContainer* adc_container = dynamic_cast<ADCTrajectoryContainer*>(
ContainerManager::Instance()->GetContainer(
AdapterConfig::PLANNING_TRAJECTORY));
CHECK_NOTNULL(pose_container);
CHECK_NOTNULL(adc_container);
PerceptionObstacle* adc = pose_container->ToPerceptionObstacle();
if (adc != nullptr) {
obstacles_container->InsertPerceptionObstacle(*adc, adc->timestamp());
double x = adc->position().x();
double y = adc->position().y();
ADEBUG << "Get ADC position [" << std::fixed << std::setprecision(6) << x
<< ", " << std::fixed << std::setprecision(6) << y << "].";
adc_container->SetPosition({x, y});
}
// Make evaluations
EvaluatorManager::Instance()->Run(*perception_obstacles);
// No prediction trajectories for offline mode
if (FLAGS_prediction_offline_mode) {
return true;
}
// Make predictions
PredictorManager::Instance()->Run(*perception_obstacles);
auto prediction_obstacles =
PredictorManager::Instance()->prediction_obstacles();
prediction_obstacles.set_start_timestamp(start_timestamp);
prediction_obstacles.set_end_timestamp(Clock::NowInSeconds());
prediction_obstacles.mutable_header()->set_lidar_timestamp(
perception_obstacles->header().lidar_timestamp());
prediction_obstacles.mutable_header()->set_camera_timestamp(
perception_obstacles->header().camera_timestamp());
prediction_obstacles.mutable_header()->set_radar_timestamp(
perception_obstacles->header().radar_timestamp());
if (FLAGS_prediction_test_mode) {
for (auto const& prediction_obstacle :
prediction_obstacles.prediction_obstacle()) {
for (auto const& trajectory : prediction_obstacle.trajectory()) {
for (auto const& trajectory_point : trajectory.trajectory_point()) {
if (!ValidationChecker::ValidTrajectoryPoint(trajectory_point)) {
AERROR << "Invalid trajectory point ["
<< trajectory_point.ShortDebugString() << "]";
return false;
}
}
}
}
}
prediction_writer_->Write(prediction_obstacles);
return true;
}
Status PredictionComponent::OnError(const std::string& error_msg) {
return Status(ErrorCode::PREDICTION_ERROR, error_msg);
}
} // namespace prediction
} // namespace apollo
<|endoftext|>
|
<commit_before>#include "net/grpc/gateway/codec/grpc_web_encoder.h"
#include <cstdint>
#include <cstring>
#include <vector>
#include "net/grpc/gateway/runtime/types.h"
#include "third_party/grpc/include/grpc++/support/byte_buffer.h"
#include "third_party/grpc/include/grpc++/support/slice.h"
namespace grpc {
namespace gateway {
namespace {
const char kGrpcStatus[] = "grpc-status: %i\r\n";
const char kGrpcMessage[] = "grpc-message: %s\r\n";
const char kGrpcTrailer[] = "%s: %s\r\n";
// GRPC Web message frame.
const uint8_t GRPC_WEB_FH_DATA = 0b0u;
// GRPC Web trailer frame.
const uint8_t GRPC_WEB_FH_TRAILER = 0b10000000u;
// Creates a new GRPC data frame with the given flags and length.
// @param flags supplies the GRPC data frame flags.
// @param length supplies the GRPC data frame length.
// @param output the buffer to store the encoded data, it's size must be 5.
void NewFrame(uint8_t flags, uint64_t length, uint8_t* output) {
output[0] = flags;
output[1] = static_cast<uint8_t>(length >> 24);
output[2] = static_cast<uint8_t>(length >> 16);
output[3] = static_cast<uint8_t>(length >> 8);
output[4] = static_cast<uint8_t>(length);
}
} // namespace
GrpcWebEncoder::GrpcWebEncoder() {}
GrpcWebEncoder::~GrpcWebEncoder() {}
void GrpcWebEncoder::Encode(grpc::ByteBuffer* input,
std::vector<Slice>* result) {
uint8_t header[5];
NewFrame(GRPC_WEB_FH_DATA, input->Length(), header);
result->push_back(
Slice(gpr_slice_from_copied_buffer(reinterpret_cast<char*>(header), 5),
Slice::STEAL_REF));
std::vector<Slice> buffer;
// TODO(fengli): Optimize if needed. Today we cannot dump data to the result
// directly since it will clear the target.
input->Dump(&buffer);
for (Slice& s : buffer) {
result->push_back(s);
}
}
void GrpcWebEncoder::EncodeStatus(const grpc::Status& status,
const Trailers* trailers,
std::vector<Slice>* result) {
std::vector<Slice> buffer;
uint64_t length = 0;
// Encodes GRPC status.
size_t grpc_status_size =
snprintf(nullptr, 0, kGrpcStatus, status.error_code());
grpc_slice grpc_status = grpc_slice_malloc(grpc_status_size + 1);
snprintf(reinterpret_cast<char*>(GPR_SLICE_START_PTR(grpc_status)),
grpc_status_size + 1, kGrpcStatus, status.error_code());
GPR_SLICE_SET_LENGTH(grpc_status, grpc_status_size);
buffer.push_back(Slice(grpc_status, Slice::STEAL_REF));
length += grpc_status_size;
// Encodes GRPC message.
if (!status.error_message().empty()) {
size_t grpc_message_size =
snprintf(nullptr, 0, kGrpcMessage, status.error_message().c_str());
grpc_slice grpc_message = grpc_slice_malloc(grpc_message_size + 1);
snprintf(reinterpret_cast<char*>(GPR_SLICE_START_PTR(grpc_message)),
grpc_message_size + 1, kGrpcMessage,
status.error_message().c_str());
GPR_SLICE_SET_LENGTH(grpc_message, grpc_message_size);
buffer.push_back(Slice(grpc_message, Slice::STEAL_REF));
length += grpc_message_size;
}
// Encodes GRPC trailers.
for (auto& trailer : *trailers) {
size_t grpc_trailer_size = snprintf(
nullptr, 0, kGrpcTrailer, trailer.first.c_str(), trailer.second.data());
grpc_slice grpc_trailer = grpc_slice_malloc(grpc_trailer_size + 1);
snprintf(reinterpret_cast<char*>(GPR_SLICE_START_PTR(grpc_trailer)),
grpc_trailer_size + 1, kGrpcTrailer, trailer.first.c_str(),
trailer.second.data());
GPR_SLICE_SET_LENGTH(grpc_trailer, grpc_trailer_size);
buffer.push_back(Slice(grpc_trailer, Slice::STEAL_REF));
length += grpc_trailer_size;
}
// Encodes GRPC trailer frame.
grpc_slice header = grpc_slice_malloc(5);
NewFrame(GRPC_WEB_FH_TRAILER, length, GPR_SLICE_START_PTR(header));
result->push_back(Slice(header, Slice::STEAL_REF));
result->insert(result->end(), buffer.begin(), buffer.end());
}
} // namespace gateway
} // namespace grpc
<commit_msg>Fix grpc-web encoder for non-zero terminated trailers.<commit_after>#include "net/grpc/gateway/codec/grpc_web_encoder.h"
#include <cstdint>
#include <cstring>
#include <vector>
#include "net/grpc/gateway/runtime/types.h"
#include "third_party/grpc/include/grpc++/support/byte_buffer.h"
#include "third_party/grpc/include/grpc++/support/slice.h"
namespace grpc {
namespace gateway {
namespace {
const char kGrpcStatus[] = "grpc-status: %i\r\n";
const char kGrpcMessage[] = "grpc-message: %s\r\n";
// GRPC Web message frame.
const uint8_t GRPC_WEB_FH_DATA = 0b0u;
// GRPC Web trailer frame.
const uint8_t GRPC_WEB_FH_TRAILER = 0b10000000u;
// Creates a new GRPC data frame with the given flags and length.
// @param flags supplies the GRPC data frame flags.
// @param length supplies the GRPC data frame length.
// @param output the buffer to store the encoded data, it's size must be 5.
void NewFrame(uint8_t flags, uint64_t length, uint8_t* output) {
output[0] = flags;
output[1] = static_cast<uint8_t>(length >> 24);
output[2] = static_cast<uint8_t>(length >> 16);
output[3] = static_cast<uint8_t>(length >> 8);
output[4] = static_cast<uint8_t>(length);
}
} // namespace
GrpcWebEncoder::GrpcWebEncoder() {}
GrpcWebEncoder::~GrpcWebEncoder() {}
void GrpcWebEncoder::Encode(grpc::ByteBuffer* input,
std::vector<Slice>* result) {
uint8_t header[5];
NewFrame(GRPC_WEB_FH_DATA, input->Length(), header);
result->push_back(
Slice(gpr_slice_from_copied_buffer(reinterpret_cast<char*>(header), 5),
Slice::STEAL_REF));
std::vector<Slice> buffer;
// TODO(fengli): Optimize if needed. Today we cannot dump data to the result
// directly since it will clear the target.
input->Dump(&buffer);
for (Slice& s : buffer) {
result->push_back(s);
}
}
void GrpcWebEncoder::EncodeStatus(const grpc::Status& status,
const Trailers* trailers,
std::vector<Slice>* result) {
std::vector<Slice> buffer;
uint64_t length = 0;
// Encodes GRPC status.
size_t grpc_status_size =
snprintf(nullptr, 0, kGrpcStatus, status.error_code());
grpc_slice grpc_status = grpc_slice_malloc(grpc_status_size + 1);
snprintf(reinterpret_cast<char*>(GPR_SLICE_START_PTR(grpc_status)),
grpc_status_size + 1, kGrpcStatus, status.error_code());
GPR_SLICE_SET_LENGTH(grpc_status, grpc_status_size);
buffer.push_back(Slice(grpc_status, Slice::STEAL_REF));
length += grpc_status_size;
// Encodes GRPC message.
if (!status.error_message().empty()) {
size_t grpc_message_size =
snprintf(nullptr, 0, kGrpcMessage, status.error_message().c_str());
grpc_slice grpc_message = grpc_slice_malloc(grpc_message_size + 1);
snprintf(reinterpret_cast<char*>(GPR_SLICE_START_PTR(grpc_message)),
grpc_message_size + 1, kGrpcMessage,
status.error_message().c_str());
GPR_SLICE_SET_LENGTH(grpc_message, grpc_message_size);
buffer.push_back(Slice(grpc_message, Slice::STEAL_REF));
length += grpc_message_size;
}
// Encodes GRPC trailers.
for (auto& trailer : *trailers) {
size_t grpc_trailer_size = trailer.first.size() + trailer.second.size() + 4;
grpc_slice grpc_trailer = grpc_slice_malloc(grpc_trailer_size);
uint8_t* p = GPR_SLICE_START_PTR(grpc_trailer);
memcpy(p, trailer.first.c_str(), trailer.first.size());
p += trailer.first.size();
memcpy(p, ": ", 2);
p += 2;
memcpy(p, trailer.second.data(), trailer.second.size());
p += trailer.second.size();
memcpy(p, "\r\n", 2);
buffer.push_back(Slice(grpc_trailer, Slice::STEAL_REF));
length += grpc_trailer_size;
}
// Encodes GRPC trailer frame.
grpc_slice header = grpc_slice_malloc(5);
NewFrame(GRPC_WEB_FH_TRAILER, length, GPR_SLICE_START_PTR(header));
result->push_back(Slice(header, Slice::STEAL_REF));
result->insert(result->end(), buffer.begin(), buffer.end());
}
} // namespace gateway
} // namespace grpc
<|endoftext|>
|
<commit_before>// @(#)root/base:$Name: $:$Id: TFolder.cxx,v 1.28 2007/01/25 11:47:53 brun Exp $
// Author: Rene Brun 02/09/2000
/*************************************************************************
* 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. *
*************************************************************************/
//______________________________________________________________________________
//
// A TFolder object is a collection of objects and folders.
// Folders have a name and a title and are identified in the folder hierarchy
// by a "Unix-like" naming mechanism. The root of all folders is //root.
// New folders can be dynamically added or removed to/from a folder.
// The folder hierarchy can be visualized via the TBrowser.
//
// The Root folders hierarchy can be seen as a whiteboard where objects
// are posted. Other classes/tasks can access these objects by specifying
// only a string pathname. This whiteboard facility greatly improves the
// modularity of an application, minimizing the class relationship problem
// that penalizes large applications.
//
// Pointers are efficient to communicate between classes.
// However, one has interest to minimize direct coupling between classes
// in the form of direct pointers. One better uses the naming and search
// service provided by the Root folders hierarchy. This makes the classes
// loosely coupled and also greatly facilitates I/O operations.
// In a client/server environment, this mechanism facilitates the access
// to any kind of object in //root stores running on different processes.
//
// A TFolder is created by invoking the TFolder constructor. It is placed
// inside an existing folder via the TFolder::AddFolder method.
// One can search for a folder or an object in a folder using the FindObject
// method. FindObject analyzes the string passed as its argument and searches
// in the hierarchy until it finds an object or folder matching the name.
//
// When a folder is deleted, its reference from the parent folder and
// possible other folders is deleted.
//
// If a folder has been declared the owner of its objects/folders via
// TFolder::SetOwner, then the contained objects are deleted when the
// folder is deleted. By default, a folder does not own its contained objects.
// NOTE that folder ownership can be set
// - via TFolder::SetOwner
// - or via TCollection::SetOwner on the collection specified to TFolder::AddFolder
//
// Standard Root objects are automatically added to the folder hierarchy.
// For example, the following folders exist:
// //root/Files with the list of currently connected Root files
// //root/Classes with the list of active classes
// //root/Geometries with active geometries
// //root/Canvases with the list of active canvases
// //root/Styles with the list of graphics styles
// //root/Colors with the list of active colors
//
// For example, if a file "myFile.root" is added to the list of files, one can
// retrieve a pointer to the corresponding TFile object with a statement like:
// TFile *myFile = (TFile*)gROOT->FindObject("//root/Files/myFile.root");
// The above statement can be abbreviated to:
// TFile *myFile = (TFile*)gROOT->FindObject("/Files/myFile.root");
// or even to:
// TFile *myFile = (TFile*)gROOT->FindObjectAny("myFile.root");
// In this last case, the TROOT::FindObjectAny function will scan the folder hierarchy
// starting at //root and will return the first object named "myFile.root".
//
// Because a string-based search mechanism is expensive, it is recommended
// to save the pointer to the object as a class member or local variable
// if this pointer is used frequently or inside loops.
//
//Begin_Html
/*
<img src="gif/folder.gif">
*/
//End_Html
#include "Riostream.h"
#include "Strlen.h"
#include "TFolder.h"
#include "TBrowser.h"
#include "TROOT.h"
#include "TClass.h"
#include "TError.h"
#include "TRegexp.h"
static const char *gFolderD[64];
static Int_t gFolderLevel = -1;
static char gFolderPath[512];
ClassImp(TFolder)
//______________________________________________________________________________
TFolder::TFolder() : TNamed()
{
// default constructor used by the Input functions
//
// This constructor should not be called by a user directly.
// The normal way to create a folder is by calling TFolder::AddFolder
fFolders = 0;
fIsOwner = kFALSE;
}
//______________________________________________________________________________
TFolder::TFolder(const char *name, const char *title) : TNamed(name,title)
{
// create a normal folder.
// use Add or AddFolder to add objects or folders to this folder
fFolders = new TList();
fIsOwner = kFALSE;
}
//______________________________________________________________________________
TFolder::TFolder(const TFolder &folder) : TNamed(folder)
{
// Copy constructor.
((TFolder&)folder).Copy(*this);
}
//______________________________________________________________________________
TFolder::~TFolder()
{
// folder destructor. Remove all objects from its lists and delete
// all its sub folders
TCollection::StartGarbageCollection();
if (fFolders) {
fFolders->Clear();
SafeDelete(fFolders);
}
TCollection::EmptyGarbageCollection();
if (gDebug)
cerr << "TFolder dtor called for "<< GetName() << endl;
}
//______________________________________________________________________________
void TFolder::Add(TObject *obj)
{
// Add object to this folder. obj must be a TObject or a TFolder
if (obj == 0 || fFolders == 0) return;
obj->SetBit(kMustCleanup);
fFolders->Add(obj);
}
//______________________________________________________________________________
TFolder *TFolder::AddFolder(const char *name, const char *title, TCollection *collection)
{
// Create a new folder and add it to the list of folders of this folder
// return a pointer to the created folder
// Note that a folder can be added to several folders
//
// if (collection is non NULL, the pointer fFolders is set to the existing
// collection, otherwise a default collection (Tlist) is created
// Note that the folder name cannot contain slashes.
if (strchr(name,'/')) {
::Error("TFolder::TFolder","folder name cannot contain a slash", name);
return 0;
}
if (strlen(GetName()) == 0) {
::Error("TFolder::TFolder","folder name cannot be \"\"");
return 0;
}
TFolder *folder = new TFolder();
folder->SetName(name);
folder->SetTitle(title);
if (!fFolders) fFolders = new TList(); //only true when gROOT creates its 1st folder
fFolders->Add(folder);
if (collection) folder->fFolders = collection;
else folder->fFolders = new TList();
return folder;
}
//______________________________________________________________________________
void TFolder::Browse(TBrowser *b)
{
// Browse this folder
if (fFolders) fFolders->Browse(b);
}
//______________________________________________________________________________
void TFolder::Clear(Option_t *option)
{
// Delete all objects from a folder list
if (fFolders) fFolders->Clear(option);
}
//______________________________________________________________________________
const char *TFolder::FindFullPathName(const char *name) const
{
// return the full pathname corresponding to subpath name
// The returned path will be re-used by the next call to GetPath().
TObject *obj = FindObject(name);
if (obj || !fFolders) {
gFolderLevel++;
gFolderD[gFolderLevel] = GetName();
gFolderPath[0] = '/';
gFolderPath[1] = 0;
for (Int_t l=0;l<=gFolderLevel;l++) {
strcat(gFolderPath,"/");
strcat(gFolderPath,gFolderD[l]);
}
strcat(gFolderPath,"/");
strcat(gFolderPath,name);
gFolderLevel = -1;
return gFolderPath;
}
if (name[0] == '/') return 0;
TIter next(fFolders);
TFolder *folder;
const char *found;
gFolderLevel++;
gFolderD[gFolderLevel] = GetName();
while ((obj=next())) {
if (!obj->InheritsFrom(TFolder::Class())) continue;
if (obj->InheritsFrom(TClass::Class())) continue;
folder = (TFolder*)obj;
found = folder->FindFullPathName(name);
if (found) return found;
}
gFolderLevel--;
return 0;
}
//______________________________________________________________________________
const char *TFolder::FindFullPathName(const TObject *) const
{
// return the full pathname corresponding to subpath name
// The returned path will be re-used by the next call to GetPath().
Error("FindFullPathname","Not yet implemented");
return 0;
}
//______________________________________________________________________________
TObject *TFolder::FindObject(const TObject *) const
{
// find object in an folder
Error("FindObject","Not yet implemented");
return 0;
}
//______________________________________________________________________________
TObject *TFolder::FindObject(const char *name) const
{
// search object identified by name in the tree of folders inside
// this folder.
// name may be of the forms:
// A, specify a full pathname starting at the top ROOT folder
// //root/xxx/yyy/name
//
// B, specify a pathname starting with a single slash. //root is assumed
// /xxx/yyy/name
//
// C, Specify a pathname relative to this folder
// xxx/yyy/name
// name
if (!fFolders) return 0;
if (name == 0) return 0;
if (name[0] == '/') {
if (name[1] == '/') {
if (!strstr(name,"//root/")) return 0;
return gROOT->GetRootFolder()->FindObject(name+7);
} else {
return gROOT->GetRootFolder()->FindObject(name+1);
}
}
char cname[1024];
strcpy(cname,name);
TObject *obj;
char *slash = strchr(cname,'/');
if (slash) {
*slash = 0;
obj = fFolders->FindObject(cname);
if (!obj) return 0;
return obj->FindObject(slash+1);
} else {
return fFolders->FindObject(name);
}
}
//______________________________________________________________________________
TObject *TFolder::FindObjectAny(const char *name) const
{
// return a pointer to the first object with name starting at this folder
TObject *obj = FindObject(name);
if (obj || !fFolders) return obj;
// if (!obj->InheritsFrom(TFolder::Class())) continue;
if (name[0] == '/') return 0;
TIter next(fFolders);
TFolder *folder;
TObject *found;
if (gFolderLevel >= 0) gFolderD[gFolderLevel] = GetName();
while ((obj=next())) {
if (!obj->InheritsFrom(TFolder::Class())) continue;
if (obj->IsA() == TClass::Class()) continue;
folder = (TFolder*)obj;
found = folder->FindObjectAny(name);
if (found) return found;
}
return 0;
}
//______________________________________________________________________________
Bool_t TFolder::IsOwner() const
{
// folder ownership has been set via
// - TFolder::SetOwner
// - TCollection::SetOwner on the collection specified to TFolder::AddFolder
if (!fFolders) return kFALSE;
return fFolders->IsOwner();
}
//______________________________________________________________________________
void TFolder::ls(Option_t *option) const
{
// List folder contents
// if option contains "dump", the Dump function of contained objects is called
// if option contains "print", the Print function of contained objects is called
// By default the ls function of contained objects is called.
// Indentation is used to identify the folder tree
//
// The <regexp> will be used to match the name of the objects.
//
if (!fFolders) return;
TROOT::IndentLevel();
cout <<ClassName()<<"*\t\t"<<GetName()<<"\t"<<GetTitle()<<endl;
TROOT::IncreaseDirLevel();
TString opta = option;
TString opt = opta.Strip(TString::kBoth);
opt.ToLower();
TString reg = opt;
Bool_t dump = opt.Contains("dump");
Bool_t print = opt.Contains("print");
TRegexp re(reg, kTRUE);
TObject *obj;
TIter nextobj(fFolders);
while ((obj = (TObject *) nextobj())) {
TString s = obj->GetName();
if (s.Index(re) == kNPOS) continue;
if (dump) obj->Dump();
else if(print) obj->Print(option);
else obj->ls(option);
}
TROOT::DecreaseDirLevel();
}
//______________________________________________________________________________
Int_t TFolder::Occurence(const TObject *object) const
{
// Return occurence number of object in the list of objects of this folder.
// The function returns the number of objects with the same name as object
// found in the list of objects in this folder before object itself.
// If only one object is found, return 0;
Int_t n = 0;
if (!fFolders) return 0;
TIter next(fFolders);
TObject *obj;
while ((obj=next())) {
if (strcmp(obj->GetName(),object->GetName()) == 0) n++;
}
if (n <=1) return n-1;
n = 0;
next.Reset();
while ((obj=next())) {
if (strcmp(obj->GetName(),object->GetName()) == 0) n++;
if (obj == object) return n;
}
return 0;
}
//______________________________________________________________________________
void TFolder::RecursiveRemove(TObject *obj)
{
// Recursively remove object from a Folder
if (fFolders) fFolders->RecursiveRemove(obj);
}
//______________________________________________________________________________
void TFolder::Remove(TObject *obj)
{
// Remove object from this folder. obj must be a TObject or a TFolder
if (obj == 0 || fFolders == 0) return;
fFolders->Remove(obj);
}
//______________________________________________________________________________
void TFolder::SaveAs(const char *filename, Option_t *option) const
{
// Save all objects in this folder in filename
// Each object in this folder will have a key in the file where the name of
// the key will be the name of the object.
if (gDirectory) gDirectory->SaveObjectAs(this,filename,option);
}
//______________________________________________________________________________
void TFolder::SetOwner(Bool_t owner)
{
// Set ownership
// If the folder is declared owner, when the folder is deleted, all
// the objects added via TFolder::Add are deleted via TObject::Delete,
// otherwise TObject::Clear is called.
//
// NOTE that folder ownership can be set
// - via TFolder::SetOwner
// - or via TCollection::SetOwner on the collection specified to TFolder::AddFolder
if (!fFolders) fFolders = new TList();
fFolders->SetOwner(owner);
}
<commit_msg>put punctuation in method comments.<commit_after>// @(#)root/base:$Name: $:$Id: TFolder.cxx,v 1.29 2007/01/28 18:37:23 brun Exp $
// Author: Rene Brun 02/09/2000
/*************************************************************************
* 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. *
*************************************************************************/
//______________________________________________________________________________
//
// A TFolder object is a collection of objects and folders.
// Folders have a name and a title and are identified in the folder hierarchy
// by a "Unix-like" naming mechanism. The root of all folders is //root.
// New folders can be dynamically added or removed to/from a folder.
// The folder hierarchy can be visualized via the TBrowser.
//
// The Root folders hierarchy can be seen as a whiteboard where objects
// are posted. Other classes/tasks can access these objects by specifying
// only a string pathname. This whiteboard facility greatly improves the
// modularity of an application, minimizing the class relationship problem
// that penalizes large applications.
//
// Pointers are efficient to communicate between classes.
// However, one has interest to minimize direct coupling between classes
// in the form of direct pointers. One better uses the naming and search
// service provided by the Root folders hierarchy. This makes the classes
// loosely coupled and also greatly facilitates I/O operations.
// In a client/server environment, this mechanism facilitates the access
// to any kind of object in //root stores running on different processes.
//
// A TFolder is created by invoking the TFolder constructor. It is placed
// inside an existing folder via the TFolder::AddFolder method.
// One can search for a folder or an object in a folder using the FindObject
// method. FindObject analyzes the string passed as its argument and searches
// in the hierarchy until it finds an object or folder matching the name.
//
// When a folder is deleted, its reference from the parent folder and
// possible other folders is deleted.
//
// If a folder has been declared the owner of its objects/folders via
// TFolder::SetOwner, then the contained objects are deleted when the
// folder is deleted. By default, a folder does not own its contained objects.
// NOTE that folder ownership can be set
// - via TFolder::SetOwner
// - or via TCollection::SetOwner on the collection specified to TFolder::AddFolder
//
// Standard Root objects are automatically added to the folder hierarchy.
// For example, the following folders exist:
// //root/Files with the list of currently connected Root files
// //root/Classes with the list of active classes
// //root/Geometries with active geometries
// //root/Canvases with the list of active canvases
// //root/Styles with the list of graphics styles
// //root/Colors with the list of active colors
//
// For example, if a file "myFile.root" is added to the list of files, one can
// retrieve a pointer to the corresponding TFile object with a statement like:
// TFile *myFile = (TFile*)gROOT->FindObject("//root/Files/myFile.root");
// The above statement can be abbreviated to:
// TFile *myFile = (TFile*)gROOT->FindObject("/Files/myFile.root");
// or even to:
// TFile *myFile = (TFile*)gROOT->FindObjectAny("myFile.root");
// In this last case, the TROOT::FindObjectAny function will scan the folder hierarchy
// starting at //root and will return the first object named "myFile.root".
//
// Because a string-based search mechanism is expensive, it is recommended
// to save the pointer to the object as a class member or local variable
// if this pointer is used frequently or inside loops.
//
//Begin_Html
/*
<img src="gif/folder.gif">
*/
//End_Html
#include "Riostream.h"
#include "Strlen.h"
#include "TFolder.h"
#include "TBrowser.h"
#include "TROOT.h"
#include "TClass.h"
#include "TError.h"
#include "TRegexp.h"
static const char *gFolderD[64];
static Int_t gFolderLevel = -1;
static char gFolderPath[512];
ClassImp(TFolder)
//______________________________________________________________________________
TFolder::TFolder() : TNamed()
{
// Default constructor used by the Input functions.
//
// This constructor should not be called by a user directly.
// The normal way to create a folder is by calling TFolder::AddFolder.
fFolders = 0;
fIsOwner = kFALSE;
}
//______________________________________________________________________________
TFolder::TFolder(const char *name, const char *title) : TNamed(name,title)
{
// Create a normal folder.
// Use Add or AddFolder to add objects or folders to this folder.
fFolders = new TList();
fIsOwner = kFALSE;
}
//______________________________________________________________________________
TFolder::TFolder(const TFolder &folder) : TNamed(folder)
{
// Copy constructor.
((TFolder&)folder).Copy(*this);
}
//______________________________________________________________________________
TFolder::~TFolder()
{
// Folder destructor. Remove all objects from its lists and delete
// all its sub folders.
TCollection::StartGarbageCollection();
if (fFolders) {
fFolders->Clear();
SafeDelete(fFolders);
}
TCollection::EmptyGarbageCollection();
if (gDebug)
cerr << "TFolder dtor called for "<< GetName() << endl;
}
//______________________________________________________________________________
void TFolder::Add(TObject *obj)
{
// Add object to this folder. obj must be a TObject or a TFolder.
if (obj == 0 || fFolders == 0) return;
obj->SetBit(kMustCleanup);
fFolders->Add(obj);
}
//______________________________________________________________________________
TFolder *TFolder::AddFolder(const char *name, const char *title, TCollection *collection)
{
// Create a new folder and add it to the list of folders of this folder,
// return a pointer to the created folder.
// Note that a folder can be added to several folders.
//
// If collection is non NULL, the pointer fFolders is set to the existing
// collection, otherwise a default collection (Tlist) is created.
// Note that the folder name cannot contain slashes.
if (strchr(name,'/')) {
::Error("TFolder::TFolder","folder name cannot contain a slash", name);
return 0;
}
if (strlen(GetName()) == 0) {
::Error("TFolder::TFolder","folder name cannot be \"\"");
return 0;
}
TFolder *folder = new TFolder();
folder->SetName(name);
folder->SetTitle(title);
if (!fFolders) fFolders = new TList(); //only true when gROOT creates its 1st folder
fFolders->Add(folder);
if (collection) folder->fFolders = collection;
else folder->fFolders = new TList();
return folder;
}
//______________________________________________________________________________
void TFolder::Browse(TBrowser *b)
{
// Browse this folder.
if (fFolders) fFolders->Browse(b);
}
//______________________________________________________________________________
void TFolder::Clear(Option_t *option)
{
// Delete all objects from a folder list.
if (fFolders) fFolders->Clear(option);
}
//______________________________________________________________________________
const char *TFolder::FindFullPathName(const char *name) const
{
// Return the full pathname corresponding to subpath name.
// The returned path will be re-used by the next call to GetPath().
TObject *obj = FindObject(name);
if (obj || !fFolders) {
gFolderLevel++;
gFolderD[gFolderLevel] = GetName();
gFolderPath[0] = '/';
gFolderPath[1] = 0;
for (Int_t l=0;l<=gFolderLevel;l++) {
strcat(gFolderPath,"/");
strcat(gFolderPath,gFolderD[l]);
}
strcat(gFolderPath,"/");
strcat(gFolderPath,name);
gFolderLevel = -1;
return gFolderPath;
}
if (name[0] == '/') return 0;
TIter next(fFolders);
TFolder *folder;
const char *found;
gFolderLevel++;
gFolderD[gFolderLevel] = GetName();
while ((obj=next())) {
if (!obj->InheritsFrom(TFolder::Class())) continue;
if (obj->InheritsFrom(TClass::Class())) continue;
folder = (TFolder*)obj;
found = folder->FindFullPathName(name);
if (found) return found;
}
gFolderLevel--;
return 0;
}
//______________________________________________________________________________
const char *TFolder::FindFullPathName(const TObject *) const
{
// Return the full pathname corresponding to subpath name.
// The returned path will be re-used by the next call to GetPath().
Error("FindFullPathname","Not yet implemented");
return 0;
}
//______________________________________________________________________________
TObject *TFolder::FindObject(const TObject *) const
{
// Find object in an folder.
Error("FindObject","Not yet implemented");
return 0;
}
//______________________________________________________________________________
TObject *TFolder::FindObject(const char *name) const
{
// Search object identified by name in the tree of folders inside
// this folder.
// Name may be of the forms:
// A, Specify a full pathname starting at the top ROOT folder
// //root/xxx/yyy/name
//
// B, Specify a pathname starting with a single slash. //root is assumed
// /xxx/yyy/name
//
// C, Specify a pathname relative to this folder
// xxx/yyy/name
// name
if (!fFolders) return 0;
if (name == 0) return 0;
if (name[0] == '/') {
if (name[1] == '/') {
if (!strstr(name,"//root/")) return 0;
return gROOT->GetRootFolder()->FindObject(name+7);
} else {
return gROOT->GetRootFolder()->FindObject(name+1);
}
}
char cname[1024];
strcpy(cname,name);
TObject *obj;
char *slash = strchr(cname,'/');
if (slash) {
*slash = 0;
obj = fFolders->FindObject(cname);
if (!obj) return 0;
return obj->FindObject(slash+1);
} else {
return fFolders->FindObject(name);
}
}
//______________________________________________________________________________
TObject *TFolder::FindObjectAny(const char *name) const
{
// Return a pointer to the first object with name starting at this folder.
TObject *obj = FindObject(name);
if (obj || !fFolders) return obj;
//if (!obj->InheritsFrom(TFolder::Class())) continue;
if (name[0] == '/') return 0;
TIter next(fFolders);
TFolder *folder;
TObject *found;
if (gFolderLevel >= 0) gFolderD[gFolderLevel] = GetName();
while ((obj=next())) {
if (!obj->InheritsFrom(TFolder::Class())) continue;
if (obj->IsA() == TClass::Class()) continue;
folder = (TFolder*)obj;
found = folder->FindObjectAny(name);
if (found) return found;
}
return 0;
}
//______________________________________________________________________________
Bool_t TFolder::IsOwner() const
{
// Folder ownership has been set via
// - TFolder::SetOwner
// - TCollection::SetOwner on the collection specified to TFolder::AddFolder
if (!fFolders) return kFALSE;
return fFolders->IsOwner();
}
//______________________________________________________________________________
void TFolder::ls(Option_t *option) const
{
// List folder contents
// If option contains "dump", the Dump function of contained objects is called.
// If option contains "print", the Print function of contained objects is called.
// By default the ls function of contained objects is called.
// Indentation is used to identify the folder tree.
//
// The <regexp> will be used to match the name of the objects.
if (!fFolders) return;
TROOT::IndentLevel();
cout <<ClassName()<<"*\t\t"<<GetName()<<"\t"<<GetTitle()<<endl;
TROOT::IncreaseDirLevel();
TString opta = option;
TString opt = opta.Strip(TString::kBoth);
opt.ToLower();
TString reg = opt;
Bool_t dump = opt.Contains("dump");
Bool_t print = opt.Contains("print");
TRegexp re(reg, kTRUE);
TObject *obj;
TIter nextobj(fFolders);
while ((obj = (TObject *) nextobj())) {
TString s = obj->GetName();
if (s.Index(re) == kNPOS) continue;
if (dump) obj->Dump();
else if(print) obj->Print(option);
else obj->ls(option);
}
TROOT::DecreaseDirLevel();
}
//______________________________________________________________________________
Int_t TFolder::Occurence(const TObject *object) const
{
// Return occurence number of object in the list of objects of this folder.
// The function returns the number of objects with the same name as object
// found in the list of objects in this folder before object itself.
// If only one object is found, return 0.
Int_t n = 0;
if (!fFolders) return 0;
TIter next(fFolders);
TObject *obj;
while ((obj=next())) {
if (strcmp(obj->GetName(),object->GetName()) == 0) n++;
}
if (n <=1) return n-1;
n = 0;
next.Reset();
while ((obj=next())) {
if (strcmp(obj->GetName(),object->GetName()) == 0) n++;
if (obj == object) return n;
}
return 0;
}
//______________________________________________________________________________
void TFolder::RecursiveRemove(TObject *obj)
{
// Recursively remove object from a folder.
if (fFolders) fFolders->RecursiveRemove(obj);
}
//______________________________________________________________________________
void TFolder::Remove(TObject *obj)
{
// Remove object from this folder. obj must be a TObject or a TFolder.
if (obj == 0 || fFolders == 0) return;
fFolders->Remove(obj);
}
//______________________________________________________________________________
void TFolder::SaveAs(const char *filename, Option_t *option) const
{
// Save all objects in this folder in filename.
// Each object in this folder will have a key in the file where the name of
// the key will be the name of the object.
if (gDirectory) gDirectory->SaveObjectAs(this,filename,option);
}
//______________________________________________________________________________
void TFolder::SetOwner(Bool_t owner)
{
// Set ownership.
// If the folder is declared owner, when the folder is deleted, all
// the objects added via TFolder::Add are deleted via TObject::Delete,
// otherwise TObject::Clear is called.
//
// NOTE that folder ownership can be set:
// - via TFolder::SetOwner
// - or via TCollection::SetOwner on the collection specified to TFolder::AddFolder
if (!fFolders) fFolders = new TList();
fFolders->SetOwner(owner);
}
<|endoftext|>
|
<commit_before>//
// FilePath.cpp
//
// Functions for helping with management of directories and file paths.
//
// Copyright (c) 2002-2004 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//
#include <stdio.h>
#include <errno.h>
#include "FilePath.h"
#ifdef unix
# include <unistd.h>
# include <sys/stat.h>
#else
# include <direct.h>
# include <io.h>
#endif
#if WIN32
# ifdef _MSC_VER
# undef mkdir // replace the one in direct.h that takes 1 param
# define mkdir(dirname,mode) _mkdir(dirname)
# define rmdir(dirname) _rmdir(dirname)
# define strdup(str) _strdup(str)
# define unlink(fname) _unlink(fname)
# define access(path,mode) _access(path,mode)
# else
# define mkdir(dirname,mode) _mkdir(dirname)
# endif
#else
# include <utime.h>
#endif
/**
* The dir_iter class provides a cross-platform way to read directories.
*/
#if WIN32
dir_iter::dir_iter()
{
m_handle = -1;
}
dir_iter::dir_iter(std::string const &dirname)
{
m_handle = _findfirst((dirname + "\\*").c_str(), &m_data);
}
dir_iter::~dir_iter()
{
if (m_handle != -1)
_findclose(m_handle);
}
bool dir_iter::is_directory()
{
return (m_data.attrib & _A_SUBDIR) != 0;
}
bool dir_iter::is_hidden()
{
return (m_data.attrib & _A_HIDDEN) != 0;
}
std::string dir_iter::filename()
{
return m_data.name;
}
void dir_iter::operator++()
{
if (m_handle != -1)
{
if (_findnext(m_handle, &m_data) == -1)
{
_findclose(m_handle);
m_handle = -1;
}
}
}
bool dir_iter::operator!=(const dir_iter &it)
{
return (m_handle == -1) != (it.m_handle == -1);
}
///////////////////////////////////////////////////////////////////////
#else // non-WIN32 platforms, i.e. generally Unix
dir_iter::dir_iter()
{
m_handle = 0;
m_stat_p = false;
}
dir_iter::dir_iter(std::string const &dirname)
{
m_handle = opendir(dirname.c_str());
m_directory = dirname;
m_stat_p = false;
if (m_directory[m_directory.size() - 1] != '/')
m_directory += '/';
operator++ ();
}
dir_iter::~dir_iter()
{
if (m_handle)
closedir(m_handle);
}
bool dir_iter::is_directory()
{
return S_ISDIR(get_stat().st_mode);
}
bool dir_iter::is_hidden()
{
return (m_current[0] == '.');
}
std::string dir_iter::filename()
{
return m_current;
}
void dir_iter::operator++()
{
if (!m_handle)
return;
m_stat_p = false;
dirent *rc = readdir(m_handle);
if (rc != 0)
m_current = rc->d_name;
else
{
m_current = "";
closedir(m_handle);
m_handle = 0;
}
}
bool dir_iter::operator!=(const dir_iter &it)
{
return (m_handle == 0) != (it.m_handle == 0);
}
#endif // !WIN32
/**
* This function will search for a given file on the given paths, returning
* the full path to the first file which is found (file exists and can be
* read from).
*
* \param paths An array of strings containing the directories to search.
* Each directory should end with a the trailing slash ("/" or "\")
*
* \param filename A filename, which can optionally contain a partial path
* as well. Examples: "foo.txt" or "Stuff/foo.txt"
*/
vtString FindFileOnPaths(const vtStringArray &paths, const char *filename)
{
FILE *fp;
// it's possible that the filename is already resolvable without
// searching the data paths
fp = fopen(filename, "r");
if (fp != NULL)
{
fclose(fp);
return vtString(filename);
}
for (unsigned int i = 0; i < paths.size(); i++)
{
vtString fname = paths[i];
fname += filename;
fp = fopen((const char *)fname, "r");
if (fp != NULL)
{
fclose(fp);
return fname;
}
}
return vtString("");
}
/**
* Recursive make directory.
* Aborts if there is an ENOENT error somewhere in the middle.
*
* \return true if OK, falso on error
*/
bool vtCreateDir(const char *dirname)
{
char *buffer = strdup(dirname);
char *p;
int len = strlen(buffer);
if (len <= 0) {
free(buffer);
return false;
}
if (buffer[len-1] == '/') {
buffer[len-1] = '\0';
}
if (mkdir(buffer, 0775) == 0)
{
free(buffer);
return 1;
}
p = buffer+1;
while (1)
{
char hold;
while(*p && *p != '\\' && *p != '/')
p++;
hold = *p;
*p = 0;
if ((mkdir(buffer, 0775) == -1) && (errno == ENOENT))
{
// fprintf(stderr,"%s: couldn't create directory %s\n",prog,buffer);
free(buffer);
return false;
}
if (hold == 0)
break;
*p++ = hold;
}
free(buffer);
return true;
}
/**
* Destroy a directory and all its contents (recusively if needed).
*/
void vtDestroyDir(const char *dirname)
{
int result;
vtStringArray con;
char fullname[1024];
dir_iter it(dirname);
for (; it != dir_iter(); ++it)
{
std::string name1 = it.filename();
if (name1 == "." || name1 == "..")
continue;
con.push_back(vtString(name1.c_str()));
}
for (unsigned int i = 0; i < con.size(); i++)
{
vtString item = con[i];
strcpy(fullname, dirname);
strcat(fullname, "/");
strcat(fullname, (const char *) item );
if (it.is_directory())
{
vtDestroyDir(fullname);
}
else
{
result = unlink(fullname);
if (result == -1)
{
// failed
if (errno == ENOENT) // not found
result = 0;
if (errno == EACCES) // found but can't delete
result = 0;
}
}
}
rmdir(dirname);
}
/**
* Delete a file.
*/
void vtDeleteFile(const char *filename)
{
unlink(filename);
}
/**
* Given a full path containing a filename, return a pointer to
* the filename portion of the string.
*/
const char *StartOfFilename(const char *szFullPath)
{
const char *tmp = szFullPath;
const char *tmp1 = strrchr(szFullPath, '/');
if (tmp1)
tmp = tmp1+1;
const char *tmp2 = strrchr(szFullPath, '\\');
if (tmp2 && tmp2 > tmp)
tmp = tmp2+1;
const char *tmp3 = strrchr(szFullPath, ':');
if (tmp3 && tmp3 > tmp)
tmp = tmp3+1;
return tmp;
}
/**
* Return whether a path is absolute or relative.
*/
bool PathIsAbsolute(const char *szPath)
{
int len = strlen(szPath);
if (len >= 2 && szPath[1] == ':')
return true;
if (len >= 1 && (szPath[0] == '/' || szPath[0] == '\\'))
return true;
return false;
}
/**
* Given a filename (which may include a path), remove any file extension(s)
* which it may have.
*/
void RemoveFileExtensions(vtString &fname)
{
for (int i = fname.GetLength()-1; i >= 0; i--)
{
char ch = fname[i];
// If we hit a path divider, stop
if (ch == ':' || ch == '\\' || ch == '/')
break;
// If we hit a period which indicates an extension, snip
if (ch == '.')
fname = fname.Left(i);
}
}
/**
* Get the full file extension(s) from a filename.
*/
vtString GetExtension(const vtString &fname, bool bFull)
{
int chop = -1;
for (int i = fname.GetLength()-1; i >= 0; i--)
{
char ch = fname[i];
// If we hit a path divider, stop
if (ch == ':' || ch == '\\' || ch == '/')
break;
// If we hit a period which indicates an extension, note it.
if (ch == '.')
{
chop = i;
if (!bFull)
break;
}
}
if (chop == -1)
return vtString("");
else
return fname.Right(fname.GetLength() - chop);
}
#include <fstream>
using namespace std;
//
// helper
//
vtString get_line_from_stream(ifstream &input)
{
char buf[80];
input.getline(buf, 80);
int len = strlen(buf);
// trim trailing CR and LF characters
while (len > 0 && (buf[len-1] == '\r' || buf[len-1] == '\n'))
{
buf[len-1] = '\0';
len--;
}
return vtString(buf);
}
/* alternate version
vtString get_line_from_stream(ifstream &input)
{
char buf[80];
// eat leading LF
if (input.peek() == '\n') {
input.ignore();
buf[0] = '\0';
} else {
input >> buf;
}
return vtString(buf);
}
*/
//
// Encapsulation for Zlib's gzip output functions. These wrappers allow
// you to do stdio file output to a compressed _or_ uncompressed file
// with one set of functions.
//
GZOutput::GZOutput(bool bCompressed)
{
fp = NULL;
gfp = NULL;
bGZip = bCompressed;
}
bool gfopen(GZOutput &out, const char *fname)
{
if (out.bGZip)
{
out.gfp = gzopen(fname, "wb");
return (out.gfp != NULL);
}
else
{
out.fp = fopen(fname, "wb");
return out.fp != NULL;
}
}
int gfprintf(GZOutput &out, const char *pFormat, ...)
{
va_list va;
va_start(va, pFormat);
if (out.bGZip)
return gzprintf(out.gfp, pFormat, va);
else
return vfprintf(out.fp, pFormat, va);
}
void gfclose(GZOutput &out)
{
if (out.bGZip)
gzclose(out.gfp);
else
fclose(out.fp);
}
<commit_msg>added catch for "" in FindFileOnPaths<commit_after>//
// FilePath.cpp
//
// Functions for helping with management of directories and file paths.
//
// Copyright (c) 2002-2004 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//
#include <stdio.h>
#include <errno.h>
#include "FilePath.h"
#ifdef unix
# include <unistd.h>
# include <sys/stat.h>
#else
# include <direct.h>
# include <io.h>
#endif
#if WIN32
# ifdef _MSC_VER
# undef mkdir // replace the one in direct.h that takes 1 param
# define mkdir(dirname,mode) _mkdir(dirname)
# define rmdir(dirname) _rmdir(dirname)
# define strdup(str) _strdup(str)
# define unlink(fname) _unlink(fname)
# define access(path,mode) _access(path,mode)
# else
# define mkdir(dirname,mode) _mkdir(dirname)
# endif
#else
# include <utime.h>
#endif
/**
* The dir_iter class provides a cross-platform way to read directories.
*/
#if WIN32
dir_iter::dir_iter()
{
m_handle = -1;
}
dir_iter::dir_iter(std::string const &dirname)
{
m_handle = _findfirst((dirname + "\\*").c_str(), &m_data);
}
dir_iter::~dir_iter()
{
if (m_handle != -1)
_findclose(m_handle);
}
bool dir_iter::is_directory()
{
return (m_data.attrib & _A_SUBDIR) != 0;
}
bool dir_iter::is_hidden()
{
return (m_data.attrib & _A_HIDDEN) != 0;
}
std::string dir_iter::filename()
{
return m_data.name;
}
void dir_iter::operator++()
{
if (m_handle != -1)
{
if (_findnext(m_handle, &m_data) == -1)
{
_findclose(m_handle);
m_handle = -1;
}
}
}
bool dir_iter::operator!=(const dir_iter &it)
{
return (m_handle == -1) != (it.m_handle == -1);
}
///////////////////////////////////////////////////////////////////////
#else // non-WIN32 platforms, i.e. generally Unix
dir_iter::dir_iter()
{
m_handle = 0;
m_stat_p = false;
}
dir_iter::dir_iter(std::string const &dirname)
{
m_handle = opendir(dirname.c_str());
m_directory = dirname;
m_stat_p = false;
if (m_directory[m_directory.size() - 1] != '/')
m_directory += '/';
operator++ ();
}
dir_iter::~dir_iter()
{
if (m_handle)
closedir(m_handle);
}
bool dir_iter::is_directory()
{
return S_ISDIR(get_stat().st_mode);
}
bool dir_iter::is_hidden()
{
return (m_current[0] == '.');
}
std::string dir_iter::filename()
{
return m_current;
}
void dir_iter::operator++()
{
if (!m_handle)
return;
m_stat_p = false;
dirent *rc = readdir(m_handle);
if (rc != 0)
m_current = rc->d_name;
else
{
m_current = "";
closedir(m_handle);
m_handle = 0;
}
}
bool dir_iter::operator!=(const dir_iter &it)
{
return (m_handle == 0) != (it.m_handle == 0);
}
#endif // !WIN32
/**
* This function will search for a given file on the given paths, returning
* the full path to the first file which is found (file exists and can be
* read from).
*
* \param paths An array of strings containing the directories to search.
* Each directory should end with a the trailing slash ("/" or "\")
*
* \param filename A filename, which can optionally contain a partial path
* as well. Examples: "foo.txt" or "Stuff/foo.txt"
*/
vtString FindFileOnPaths(const vtStringArray &paths, const char *filename)
{
FILE *fp;
if (!strcmp(filename, ""))
return vtString("");
// it's possible that the filename is already resolvable without
// searching the data paths
fp = fopen(filename, "r");
if (fp != NULL)
{
fclose(fp);
return vtString(filename);
}
for (unsigned int i = 0; i < paths.size(); i++)
{
vtString fname = paths[i];
fname += filename;
fp = fopen((const char *)fname, "r");
if (fp != NULL)
{
fclose(fp);
return fname;
}
}
return vtString("");
}
/**
* Recursive make directory.
* Aborts if there is an ENOENT error somewhere in the middle.
*
* \return true if OK, falso on error
*/
bool vtCreateDir(const char *dirname)
{
char *buffer = strdup(dirname);
char *p;
int len = strlen(buffer);
if (len <= 0) {
free(buffer);
return false;
}
if (buffer[len-1] == '/') {
buffer[len-1] = '\0';
}
if (mkdir(buffer, 0775) == 0)
{
free(buffer);
return 1;
}
p = buffer+1;
while (1)
{
char hold;
while(*p && *p != '\\' && *p != '/')
p++;
hold = *p;
*p = 0;
if ((mkdir(buffer, 0775) == -1) && (errno == ENOENT))
{
// fprintf(stderr,"%s: couldn't create directory %s\n",prog,buffer);
free(buffer);
return false;
}
if (hold == 0)
break;
*p++ = hold;
}
free(buffer);
return true;
}
/**
* Destroy a directory and all its contents (recusively if needed).
*/
void vtDestroyDir(const char *dirname)
{
int result;
vtStringArray con;
char fullname[1024];
dir_iter it(dirname);
for (; it != dir_iter(); ++it)
{
std::string name1 = it.filename();
if (name1 == "." || name1 == "..")
continue;
con.push_back(vtString(name1.c_str()));
}
for (unsigned int i = 0; i < con.size(); i++)
{
vtString item = con[i];
strcpy(fullname, dirname);
strcat(fullname, "/");
strcat(fullname, (const char *) item );
if (it.is_directory())
{
vtDestroyDir(fullname);
}
else
{
result = unlink(fullname);
if (result == -1)
{
// failed
if (errno == ENOENT) // not found
result = 0;
if (errno == EACCES) // found but can't delete
result = 0;
}
}
}
rmdir(dirname);
}
/**
* Delete a file.
*/
void vtDeleteFile(const char *filename)
{
unlink(filename);
}
/**
* Given a full path containing a filename, return a pointer to
* the filename portion of the string.
*/
const char *StartOfFilename(const char *szFullPath)
{
const char *tmp = szFullPath;
const char *tmp1 = strrchr(szFullPath, '/');
if (tmp1)
tmp = tmp1+1;
const char *tmp2 = strrchr(szFullPath, '\\');
if (tmp2 && tmp2 > tmp)
tmp = tmp2+1;
const char *tmp3 = strrchr(szFullPath, ':');
if (tmp3 && tmp3 > tmp)
tmp = tmp3+1;
return tmp;
}
/**
* Return whether a path is absolute or relative.
*/
bool PathIsAbsolute(const char *szPath)
{
int len = strlen(szPath);
if (len >= 2 && szPath[1] == ':')
return true;
if (len >= 1 && (szPath[0] == '/' || szPath[0] == '\\'))
return true;
return false;
}
/**
* Given a filename (which may include a path), remove any file extension(s)
* which it may have.
*/
void RemoveFileExtensions(vtString &fname)
{
for (int i = fname.GetLength()-1; i >= 0; i--)
{
char ch = fname[i];
// If we hit a path divider, stop
if (ch == ':' || ch == '\\' || ch == '/')
break;
// If we hit a period which indicates an extension, snip
if (ch == '.')
fname = fname.Left(i);
}
}
/**
* Get the full file extension(s) from a filename.
*/
vtString GetExtension(const vtString &fname, bool bFull)
{
int chop = -1;
for (int i = fname.GetLength()-1; i >= 0; i--)
{
char ch = fname[i];
// If we hit a path divider, stop
if (ch == ':' || ch == '\\' || ch == '/')
break;
// If we hit a period which indicates an extension, note it.
if (ch == '.')
{
chop = i;
if (!bFull)
break;
}
}
if (chop == -1)
return vtString("");
else
return fname.Right(fname.GetLength() - chop);
}
#include <fstream>
using namespace std;
//
// helper
//
vtString get_line_from_stream(ifstream &input)
{
char buf[80];
input.getline(buf, 80);
int len = strlen(buf);
// trim trailing CR and LF characters
while (len > 0 && (buf[len-1] == '\r' || buf[len-1] == '\n'))
{
buf[len-1] = '\0';
len--;
}
return vtString(buf);
}
/* alternate version
vtString get_line_from_stream(ifstream &input)
{
char buf[80];
// eat leading LF
if (input.peek() == '\n') {
input.ignore();
buf[0] = '\0';
} else {
input >> buf;
}
return vtString(buf);
}
*/
//
// Encapsulation for Zlib's gzip output functions. These wrappers allow
// you to do stdio file output to a compressed _or_ uncompressed file
// with one set of functions.
//
GZOutput::GZOutput(bool bCompressed)
{
fp = NULL;
gfp = NULL;
bGZip = bCompressed;
}
bool gfopen(GZOutput &out, const char *fname)
{
if (out.bGZip)
{
out.gfp = gzopen(fname, "wb");
return (out.gfp != NULL);
}
else
{
out.fp = fopen(fname, "wb");
return out.fp != NULL;
}
}
int gfprintf(GZOutput &out, const char *pFormat, ...)
{
va_list va;
va_start(va, pFormat);
if (out.bGZip)
return gzprintf(out.gfp, pFormat, va);
else
return vfprintf(out.fp, pFormat, va);
}
void gfclose(GZOutput &out)
{
if (out.bGZip)
gzclose(out.gfp);
else
fclose(out.fp);
}
<|endoftext|>
|
<commit_before>/*
* File: ImageJPEG.cpp
* Author: Heinrich Mellmann
*
* Created on 11. Dezember 2018, 17:24
*/
// choose the compression method
//#define JPEG_COMPRESS_TURBO
#define JPEG_COMPRESS_DEFAULT
//#define JPEG_COMPRESS_NONE
#include "ImageJPEG.h"
#include "Messages/Framework-Representations.pb.h"
#include <google/protobuf/io/zero_copy_stream_impl.h>
using namespace naoth;
using namespace std;
#ifdef JPEG_COMPRESS_DEFAULT
#include <turbojpeg/jpeglib.h>
void ImageJPEG::compress() const
{
ASSERT(image != NULL);
struct jpeg_compress_struct cinfo;
struct jpeg_error_mgr jerr;
cinfo.err = jpeg_std_error(&jerr);
jpeg_create_compress(&cinfo);
jpeg_mem_dest(&cinfo, &jpeg, &jpeg_size);
cinfo.image_width = image->width();
cinfo.image_height = image->height();
cinfo.input_components = 3;
cinfo.in_color_space = JCS_YCbCr;
jpeg_set_defaults( &cinfo );
jpeg_set_quality(&cinfo, quality, TRUE);
jpeg_start_compress( &cinfo, TRUE );
linebuf.resize(image->width() * 3);
JSAMPROW row_pointer[1];
row_pointer[0] = &linebuf[0];
while (cinfo.next_scanline < cinfo.image_height) {
unsigned i, j;
unsigned offset = cinfo.next_scanline * cinfo.image_width * 2; //offset to the correct row
for (i = 0, j = 0; i < cinfo.image_width * 2; i += 4, j += 6) { //input strides by 4 bytes, output strides by 6 (2 pixels)
linebuf[j + 0] = image->data()[offset + i + 0]; // Y (unique to this pixel)
linebuf[j + 1] = image->data()[offset + i + 1]; // U (shared between pixels)
linebuf[j + 2] = image->data()[offset + i + 3]; // V (shared between pixels)
linebuf[j + 3] = image->data()[offset + i + 2]; // Y (unique to this pixel)
linebuf[j + 4] = image->data()[offset + i + 1]; // U (shared between pixels)
linebuf[j + 5] = image->data()[offset + i + 3]; // V (shared between pixels)
}
jpeg_write_scanlines(&cinfo, row_pointer, 1);
}
jpeg_finish_compress( &cinfo );
jpeg_destroy_compress( &cinfo );
}
#endif
#ifdef JPEG_COMPRESS_TURBO
#include <turbojpeg/turbojpeg.h>
void ImageJPEG::compress() const
{
ASSERT(image != NULL);
planar.resize(image->data_size());
const uint32_t offsetU = image->width()*image->height();
const uint32_t offsetV = offsetU + offsetU/2;
for(uint32_t i = 0, j = 0; i < image->data_size(); i += 4, ++j) {
planar[j*2 + 0] = image->data()[i + 0]; // Y
planar[offsetU + j] = image->data()[i + 1]; // U
planar[j*2 + 1] = image->data()[i + 2]; // Y
planar[offsetV + j] = image->data()[i + 3]; // V
}
//static unsigned char *jpeg = (unsigned char *)tjAlloc(640*480*3);
//unsigned long jpegSize = 0;
tjhandle handle = tjInitCompress();
int flags = TJFLAG_FASTUPSAMPLE;
tjCompressFromYUV(handle, &planar[0], (int)image->width(), 1, (int)image->height(), TJSAMP::TJSAMP_422, (unsigned char**)&jpeg, &jpeg_size, quality, flags);
//std::cout << tjGetErrorStr() << std::endl;
}
#endif
#ifdef JPEG_COMPRESS_NONE
void ImageJPEG::compress() const
{
ASSERT(image != NULL);
jpeg = image->data();
jpeg_size = image->data_size();
}
#endif
void Serializer<ImageJPEG>::serialize(const ImageJPEG& parent, std::ostream& stream)
{
const Image& representation = parent.get();
// the data has to be converted to a YUV (1 byte for each) array. no interlacing
naothmessages::Image img;
img.set_height(representation.height());
img.set_width(representation.width());
parent.compress();
// fallback for the format, if no compression is avaliable
#ifdef JPEG_COMPRESS_NONE
img.set_format(naothmessages::Image_Format_YUV422);
#else
img.set_format(naothmessages::Image_Format_JPEG);
#endif
img.set_data(parent.getJPEG(), parent.getJPEGSize());
google::protobuf::io::OstreamOutputStream buf(&stream);
img.SerializeToZeroCopyStream(&buf);
}
void Serializer<ImageJPEG>::deserialize(std::istream& stream, ImageJPEG& representation)
{
assert(false); // deserialization is not supported yet
}
<commit_msg>unused variable warning<commit_after>/*
* File: ImageJPEG.cpp
* Author: Heinrich Mellmann
*
* Created on 11. Dezember 2018, 17:24
*/
// choose the compression method
//#define JPEG_COMPRESS_TURBO
#define JPEG_COMPRESS_DEFAULT
//#define JPEG_COMPRESS_NONE
#include "ImageJPEG.h"
#include "Messages/Framework-Representations.pb.h"
#include <google/protobuf/io/zero_copy_stream_impl.h>
using namespace naoth;
using namespace std;
#ifdef JPEG_COMPRESS_DEFAULT
#include <turbojpeg/jpeglib.h>
void ImageJPEG::compress() const
{
ASSERT(image != NULL);
struct jpeg_compress_struct cinfo;
struct jpeg_error_mgr jerr;
cinfo.err = jpeg_std_error(&jerr);
jpeg_create_compress(&cinfo);
jpeg_mem_dest(&cinfo, &jpeg, &jpeg_size);
cinfo.image_width = image->width();
cinfo.image_height = image->height();
cinfo.input_components = 3;
cinfo.in_color_space = JCS_YCbCr;
jpeg_set_defaults( &cinfo );
jpeg_set_quality(&cinfo, quality, TRUE);
jpeg_start_compress( &cinfo, TRUE );
linebuf.resize(image->width() * 3);
JSAMPROW row_pointer[1];
row_pointer[0] = &linebuf[0];
while (cinfo.next_scanline < cinfo.image_height) {
unsigned i, j;
unsigned offset = cinfo.next_scanline * cinfo.image_width * 2; //offset to the correct row
for (i = 0, j = 0; i < cinfo.image_width * 2; i += 4, j += 6) { //input strides by 4 bytes, output strides by 6 (2 pixels)
linebuf[j + 0] = image->data()[offset + i + 0]; // Y (unique to this pixel)
linebuf[j + 1] = image->data()[offset + i + 1]; // U (shared between pixels)
linebuf[j + 2] = image->data()[offset + i + 3]; // V (shared between pixels)
linebuf[j + 3] = image->data()[offset + i + 2]; // Y (unique to this pixel)
linebuf[j + 4] = image->data()[offset + i + 1]; // U (shared between pixels)
linebuf[j + 5] = image->data()[offset + i + 3]; // V (shared between pixels)
}
jpeg_write_scanlines(&cinfo, row_pointer, 1);
}
jpeg_finish_compress( &cinfo );
jpeg_destroy_compress( &cinfo );
}
#endif
#ifdef JPEG_COMPRESS_TURBO
#include <turbojpeg/turbojpeg.h>
void ImageJPEG::compress() const
{
ASSERT(image != NULL);
planar.resize(image->data_size());
const uint32_t offsetU = image->width()*image->height();
const uint32_t offsetV = offsetU + offsetU/2;
for(uint32_t i = 0, j = 0; i < image->data_size(); i += 4, ++j) {
planar[j*2 + 0] = image->data()[i + 0]; // Y
planar[offsetU + j] = image->data()[i + 1]; // U
planar[j*2 + 1] = image->data()[i + 2]; // Y
planar[offsetV + j] = image->data()[i + 3]; // V
}
//static unsigned char *jpeg = (unsigned char *)tjAlloc(640*480*3);
//unsigned long jpegSize = 0;
tjhandle handle = tjInitCompress();
int flags = TJFLAG_FASTUPSAMPLE;
tjCompressFromYUV(handle, &planar[0], (int)image->width(), 1, (int)image->height(), TJSAMP::TJSAMP_422, (unsigned char**)&jpeg, &jpeg_size, quality, flags);
//std::cout << tjGetErrorStr() << std::endl;
}
#endif
#ifdef JPEG_COMPRESS_NONE
void ImageJPEG::compress() const
{
ASSERT(image != NULL);
jpeg = image->data();
jpeg_size = image->data_size();
}
#endif
void Serializer<ImageJPEG>::serialize(const ImageJPEG& parent, std::ostream& stream)
{
const Image& representation = parent.get();
// the data has to be converted to a YUV (1 byte for each) array. no interlacing
naothmessages::Image img;
img.set_height(representation.height());
img.set_width(representation.width());
parent.compress();
// fallback for the format, if no compression is avaliable
#ifdef JPEG_COMPRESS_NONE
img.set_format(naothmessages::Image_Format_YUV422);
#else
img.set_format(naothmessages::Image_Format_JPEG);
#endif
img.set_data(parent.getJPEG(), parent.getJPEGSize());
google::protobuf::io::OstreamOutputStream buf(&stream);
img.SerializeToZeroCopyStream(&buf);
}
void Serializer<ImageJPEG>::deserialize(std::istream& /*stream*/, ImageJPEG& /*representation*/)
{
assert(false); // deserialization is not supported yet
}
<|endoftext|>
|
<commit_before>//
// Implements the following classes:
//
// AutoDialog - An improvement to wxDialog which makes validation easier.
//
// AutoPanel - An improvement to wxPanel which makes validation easier.
//
// wxNumericValidator - A validator capable of transfering numeric values.
//
// Copyright (c) 2001-2004 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//
#include "wx/wxprec.h"
#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif
#include "AutoDialog.h"
#include "wxString2.h"
/////////////////////////////////////////////////
//
wxNumericValidator::wxNumericValidator(int *val) : wxValidator()
{
Initialize();
m_pValInt = val;
}
wxNumericValidator::wxNumericValidator(float *val, int digits) : wxValidator()
{
Initialize();
m_pValFloat = val;
m_iDigits = digits;
}
wxNumericValidator::wxNumericValidator(double *val, int digits) : wxValidator()
{
Initialize();
m_pValDouble = val;
m_iDigits = digits;
}
wxNumericValidator::wxNumericValidator(const wxNumericValidator& val)
{
Copy(val);
}
bool wxNumericValidator::Copy(const wxNumericValidator& val)
{
wxValidator::Copy(val);
m_pValInt = val.m_pValInt;
m_pValFloat = val.m_pValFloat;
m_pValDouble = val.m_pValDouble;
m_iDigits = val.m_iDigits;
return TRUE;
}
// Called to transfer data to the window
bool wxNumericValidator::TransferToWindow()
{
if ( !m_validatorWindow )
return FALSE;
if ( !m_bEnabled )
return TRUE;
wxString str, format;
if (m_pValInt)
str.Printf(_T("%d"), *m_pValInt);
if (m_pValFloat)
{
if (m_iDigits != -1)
{
format.Printf(_T("%%.%df"), m_iDigits);
str.Printf(format, *m_pValFloat);
}
else
str.Printf(_T("%.8g"), *m_pValFloat); // 8 significant digits
}
if (m_pValDouble)
{
if (m_iDigits != -1)
{
format.Printf(_T("%%.%dlf"), m_iDigits);
str.Printf(format, *m_pValDouble);
}
else
str.Printf(_T("%.16lg"), *m_pValDouble); // 16 significant digits
}
if (m_validatorWindow->IsKindOf(CLASSINFO(wxStaticText)) )
{
wxStaticText* pControl = (wxStaticText*) m_validatorWindow;
if (pControl)
{
pControl->SetLabel(str) ;
return TRUE;
}
}
else
if (m_validatorWindow->IsKindOf(CLASSINFO(wxTextCtrl)) )
{
wxTextCtrl* pControl = (wxTextCtrl*) m_validatorWindow;
if (pControl)
{
pControl->SetValue(str) ;
return TRUE;
}
}
else
return FALSE;
// unrecognized control, or bad pointer
return FALSE;
}
// Called to transfer data from the window
bool wxNumericValidator::TransferFromWindow()
{
if ( !m_validatorWindow )
return FALSE;
if ( !m_bEnabled )
return TRUE;
wxString2 str = _T("");
// string controls
if (m_validatorWindow->IsKindOf(CLASSINFO(wxStaticText)) )
{
wxStaticText* pControl = (wxStaticText*) m_validatorWindow;
if (pControl)
str = pControl->GetLabel() ;
} else
if (m_validatorWindow->IsKindOf(CLASSINFO(wxTextCtrl)) )
{
wxTextCtrl* pControl = (wxTextCtrl*) m_validatorWindow;
if (pControl)
str = pControl->GetValue() ;
}
else // unrecognized control, or bad pointer
return FALSE;
if (str != _T(""))
{
const char *ccs = str.mb_str();
if (m_pValInt)
sscanf(ccs, "%d", m_pValInt);
if (m_pValFloat)
sscanf(ccs, "%f", m_pValFloat);
if (m_pValDouble)
sscanf(ccs, "%lf", m_pValDouble);
return TRUE;
}
return FALSE;
}
/*
Called by constructors to initialize ALL data members
*/
void wxNumericValidator::Initialize()
{
m_pValInt = NULL;
m_pValFloat = NULL;
m_pValDouble = NULL;
m_bEnabled = true;
}
/////////////////////////////////////////////////
//
BEGIN_EVENT_TABLE(AutoDialog, wxDialog)
EVT_INIT_DIALOG (AutoDialog::OnInitDialog)
END_EVENT_TABLE()
void AutoDialog::AddValidator(long id, wxString *sptr)
{
wxWindow *pWin = FindWindow(id);
if (!pWin) return;
pWin->SetValidator(wxGenericValidator(sptr)); // actually clones the one we pass in
}
void AutoDialog::AddValidator(long id, bool *bptr)
{
wxWindow *pWin = FindWindow(id);
if (!pWin) return;
pWin->SetValidator(wxGenericValidator(bptr)); // actually clones the one we pass in
}
void AutoDialog::AddValidator(long id, int *iptr)
{
wxWindow *pWin = FindWindow(id);
if (!pWin) return;
pWin->SetValidator(wxGenericValidator(iptr)); // actually clones the one we pass in
}
wxNumericValidator *AutoDialog::AddNumValidator(long id, int *iptr)
{
wxWindow *pWin = FindWindow(id);
if (!pWin) return NULL;
// actually clones the one we pass in
pWin->SetValidator(wxNumericValidator(iptr));
return (wxNumericValidator*) pWin->GetValidator();
}
wxNumericValidator *AutoDialog::AddNumValidator(long id, float *fptr, int digits)
{
wxWindow *pWin = FindWindow(id);
if (!pWin) return NULL;
// actually clones the one we pass in
pWin->SetValidator(wxNumericValidator(fptr, digits));
return (wxNumericValidator*) pWin->GetValidator();
}
wxNumericValidator *AutoDialog::AddNumValidator(long id, double *dptr, int digits)
{
wxWindow *pWin = FindWindow(id);
if (!pWin) return NULL;
// actually clones the one we pass in
pWin->SetValidator(wxNumericValidator(dptr, digits));
return (wxNumericValidator*) pWin->GetValidator();
}
/////////////////////////////////////////////////
//
BEGIN_EVENT_TABLE(AutoPanel, wxPanel)
EVT_INIT_DIALOG (AutoPanel::OnInitDialog)
END_EVENT_TABLE()
void AutoPanel::AddValidator(long id, wxString *sptr)
{
wxWindow *pWin = FindWindow(id);
if (!pWin) return;
pWin->SetValidator(wxGenericValidator(sptr)); // actually clones the one we pass in
}
void AutoPanel::AddValidator(long id, bool *bptr)
{
wxWindow *pWin = FindWindow(id);
if (!pWin) return;
pWin->SetValidator(wxGenericValidator(bptr)); // actually clones the one we pass in
}
void AutoPanel::AddValidator(long id, int *iptr)
{
wxWindow *pWin = FindWindow(id);
if (!pWin) return;
pWin->SetValidator(wxGenericValidator(iptr)); // actually clones the one we pass in
}
wxNumericValidator *AutoPanel::AddNumValidator(long id, int *iptr)
{
wxWindow *pWin = FindWindow(id);
if (!pWin) return NULL;
// actually clones the one we pass in
pWin->SetValidator(wxNumericValidator(iptr));
return (wxNumericValidator *) pWin->GetValidator();
}
wxNumericValidator *AutoPanel::AddNumValidator(long id, float *fptr, int digits)
{
wxWindow *pWin = FindWindow(id);
if (!pWin) return NULL;
// actually clones the one we pass in
pWin->SetValidator(wxNumericValidator(fptr, digits));
return (wxNumericValidator *) pWin->GetValidator();
}
wxNumericValidator *AutoPanel::AddNumValidator(long id, double *dptr, int digits)
{
wxWindow *pWin = FindWindow(id);
if (!pWin) return NULL;
pWin->SetValidator(wxNumericValidator(dptr, digits));
// actually clones the one we pass in
return (wxNumericValidator *) pWin->GetValidator();
}
<commit_msg>fixed dangerous case where m_bEnabled was uninitialized! Release-mode trouble!<commit_after>//
// Implements the following classes:
//
// AutoDialog - An improvement to wxDialog which makes validation easier.
//
// AutoPanel - An improvement to wxPanel which makes validation easier.
//
// wxNumericValidator - A validator capable of transfering numeric values.
//
// Copyright (c) 2001-2004 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//
#include "wx/wxprec.h"
#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif
#include "AutoDialog.h"
#include "wxString2.h"
/////////////////////////////////////////////////
//
wxNumericValidator::wxNumericValidator(int *val) : wxValidator()
{
Initialize();
m_pValInt = val;
}
wxNumericValidator::wxNumericValidator(float *val, int digits) : wxValidator()
{
Initialize();
m_pValFloat = val;
m_iDigits = digits;
}
wxNumericValidator::wxNumericValidator(double *val, int digits) : wxValidator()
{
Initialize();
m_pValDouble = val;
m_iDigits = digits;
}
wxNumericValidator::wxNumericValidator(const wxNumericValidator& val)
{
Initialize();
Copy(val);
}
/*
Called by constructors to initialize ALL data members
*/
void wxNumericValidator::Initialize()
{
m_pValInt = NULL;
m_pValFloat = NULL;
m_pValDouble = NULL;
m_iDigits = 0;
m_bEnabled = true;
}
bool wxNumericValidator::Copy(const wxNumericValidator& val)
{
wxValidator::Copy(val);
m_pValInt = val.m_pValInt;
m_pValFloat = val.m_pValFloat;
m_pValDouble = val.m_pValDouble;
m_iDigits = val.m_iDigits;
return TRUE;
}
// Called to transfer data to the window
bool wxNumericValidator::TransferToWindow()
{
if ( !m_validatorWindow )
return FALSE;
if ( !m_bEnabled )
return TRUE;
wxString str, format;
if (m_pValInt)
str.Printf(_T("%d"), *m_pValInt);
if (m_pValFloat)
{
if (m_iDigits != -1)
{
format.Printf(_T("%%.%df"), m_iDigits);
str.Printf(format, *m_pValFloat);
}
else
str.Printf(_T("%.8g"), *m_pValFloat); // 8 significant digits
}
if (m_pValDouble)
{
if (m_iDigits != -1)
{
format.Printf(_T("%%.%dlf"), m_iDigits);
str.Printf(format, *m_pValDouble);
}
else
str.Printf(_T("%.16lg"), *m_pValDouble); // 16 significant digits
}
if (m_validatorWindow->IsKindOf(CLASSINFO(wxStaticText)) )
{
wxStaticText* pControl = (wxStaticText*) m_validatorWindow;
if (pControl)
{
pControl->SetLabel(str) ;
return TRUE;
}
}
else
if (m_validatorWindow->IsKindOf(CLASSINFO(wxTextCtrl)) )
{
wxTextCtrl* pControl = (wxTextCtrl*) m_validatorWindow;
if (pControl)
{
pControl->SetValue(str) ;
return TRUE;
}
}
else
return FALSE;
// unrecognized control, or bad pointer
return FALSE;
}
// Called to transfer data from the window
bool wxNumericValidator::TransferFromWindow()
{
if ( !m_validatorWindow )
return FALSE;
if ( !m_bEnabled )
return TRUE;
wxString2 str = _T("");
// string controls
if (m_validatorWindow->IsKindOf(CLASSINFO(wxStaticText)) )
{
wxStaticText* pControl = (wxStaticText*) m_validatorWindow;
if (pControl)
str = pControl->GetLabel() ;
} else
if (m_validatorWindow->IsKindOf(CLASSINFO(wxTextCtrl)) )
{
wxTextCtrl* pControl = (wxTextCtrl*) m_validatorWindow;
if (pControl)
str = pControl->GetValue() ;
}
else // unrecognized control, or bad pointer
return FALSE;
if (str != _T(""))
{
const char *ccs = str.mb_str();
if (m_pValInt)
sscanf(ccs, "%d", m_pValInt);
if (m_pValFloat)
sscanf(ccs, "%f", m_pValFloat);
if (m_pValDouble)
sscanf(ccs, "%lf", m_pValDouble);
return TRUE;
}
return FALSE;
}
/////////////////////////////////////////////////
//
BEGIN_EVENT_TABLE(AutoDialog, wxDialog)
EVT_INIT_DIALOG (AutoDialog::OnInitDialog)
END_EVENT_TABLE()
void AutoDialog::AddValidator(long id, wxString *sptr)
{
wxWindow *pWin = FindWindow(id);
if (!pWin) return;
pWin->SetValidator(wxGenericValidator(sptr)); // actually clones the one we pass in
}
void AutoDialog::AddValidator(long id, bool *bptr)
{
wxWindow *pWin = FindWindow(id);
if (!pWin) return;
pWin->SetValidator(wxGenericValidator(bptr)); // actually clones the one we pass in
}
void AutoDialog::AddValidator(long id, int *iptr)
{
wxWindow *pWin = FindWindow(id);
if (!pWin) return;
pWin->SetValidator(wxGenericValidator(iptr)); // actually clones the one we pass in
}
wxNumericValidator *AutoDialog::AddNumValidator(long id, int *iptr)
{
wxWindow *pWin = FindWindow(id);
if (!pWin) return NULL;
// actually clones the one we pass in
pWin->SetValidator(wxNumericValidator(iptr));
return (wxNumericValidator*) pWin->GetValidator();
}
wxNumericValidator *AutoDialog::AddNumValidator(long id, float *fptr, int digits)
{
wxWindow *pWin = FindWindow(id);
if (!pWin) return NULL;
// actually clones the one we pass in
pWin->SetValidator(wxNumericValidator(fptr, digits));
return (wxNumericValidator*) pWin->GetValidator();
}
wxNumericValidator *AutoDialog::AddNumValidator(long id, double *dptr, int digits)
{
wxWindow *pWin = FindWindow(id);
if (!pWin) return NULL;
// actually clones the one we pass in
pWin->SetValidator(wxNumericValidator(dptr, digits));
return (wxNumericValidator*) pWin->GetValidator();
}
/////////////////////////////////////////////////
//
BEGIN_EVENT_TABLE(AutoPanel, wxPanel)
EVT_INIT_DIALOG (AutoPanel::OnInitDialog)
END_EVENT_TABLE()
void AutoPanel::AddValidator(long id, wxString *sptr)
{
wxWindow *pWin = FindWindow(id);
if (!pWin) return;
pWin->SetValidator(wxGenericValidator(sptr)); // actually clones the one we pass in
}
void AutoPanel::AddValidator(long id, bool *bptr)
{
wxWindow *pWin = FindWindow(id);
if (!pWin) return;
pWin->SetValidator(wxGenericValidator(bptr)); // actually clones the one we pass in
}
void AutoPanel::AddValidator(long id, int *iptr)
{
wxWindow *pWin = FindWindow(id);
if (!pWin) return;
pWin->SetValidator(wxGenericValidator(iptr)); // actually clones the one we pass in
}
wxNumericValidator *AutoPanel::AddNumValidator(long id, int *iptr)
{
wxWindow *pWin = FindWindow(id);
if (!pWin) return NULL;
// actually clones the one we pass in
pWin->SetValidator(wxNumericValidator(iptr));
return (wxNumericValidator *) pWin->GetValidator();
}
wxNumericValidator *AutoPanel::AddNumValidator(long id, float *fptr, int digits)
{
wxWindow *pWin = FindWindow(id);
if (!pWin) return NULL;
// actually clones the one we pass in
pWin->SetValidator(wxNumericValidator(fptr, digits));
return (wxNumericValidator *) pWin->GetValidator();
}
wxNumericValidator *AutoPanel::AddNumValidator(long id, double *dptr, int digits)
{
wxWindow *pWin = FindWindow(id);
if (!pWin) return NULL;
pWin->SetValidator(wxNumericValidator(dptr, digits));
// actually clones the one we pass in
return (wxNumericValidator *) pWin->GetValidator();
}
<|endoftext|>
|
<commit_before>// Copyright 2017 Google 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 "tink/subtle/aes_gcm_boringssl.h"
#include <string>
#include <vector>
#include "tink/subtle/wycheproof_util.h"
#include "tink/util/status.h"
#include "tink/util/statusor.h"
#include "tink/util/test_util.h"
#include "gtest/gtest.h"
#include "openssl/err.h"
namespace crypto {
namespace tink {
namespace subtle {
namespace {
TEST(AesGcmBoringSslTest, testBasic) {
std::string key(test::HexDecodeOrDie("000102030405060708090a0b0c0d0e0f"));
auto res = AesGcmBoringSsl::New(key);
EXPECT_TRUE(res.ok()) << res.status();
auto cipher = std::move(res.ValueOrDie());
std::string message = "Some data to encrypt.";
std::string aad = "Some data to authenticate.";
auto ct = cipher->Encrypt(message, aad);
EXPECT_TRUE(ct.ok()) << ct.status();
EXPECT_EQ(ct.ValueOrDie().size(), message.size() + 12 + 16);
auto pt = cipher->Decrypt(ct.ValueOrDie(), aad);
EXPECT_TRUE(pt.ok()) << pt.status();
EXPECT_EQ(pt.ValueOrDie(), message);
}
TEST(AesGcmBoringSslTest, testModification) {
std::string key(test::HexDecodeOrDie("000102030405060708090a0b0c0d0e0f"));
auto cipher = std::move(AesGcmBoringSsl::New(key).ValueOrDie());
std::string message = "Some data to encrypt.";
std::string aad = "Some data to authenticate.";
std::string ct = cipher->Encrypt(message, aad).ValueOrDie();
EXPECT_TRUE(cipher->Decrypt(ct, aad).ok());
// Modify the ciphertext
for (size_t i = 0; i < ct.size() * 8; i++) {
std::string modified_ct = ct;
modified_ct[i / 8] ^= 1 << (i % 8);
EXPECT_FALSE(cipher->Decrypt(modified_ct, aad).ok()) << i;
}
// Modify the additional data
for (size_t i = 0; i < aad.size() * 8; i++) {
std::string modified_aad = aad;
modified_aad[i / 8] ^= 1 << (i % 8);
auto decrypted = cipher->Decrypt(ct, modified_aad);
EXPECT_FALSE(decrypted.ok()) << i << " pt:" << decrypted.ValueOrDie();
}
// Truncate the ciphertext
for (size_t i = 0; i < ct.size(); i++) {
std::string truncated_ct(ct, 0, i);
EXPECT_FALSE(cipher->Decrypt(truncated_ct, aad).ok()) << i;
}
}
TEST(AesGcmBoringSslTest, testAadEmptyVersusNullStringView) {
const std::string key(test::HexDecodeOrDie("000102030405060708090a0b0c0d0e0f"));
auto cipher = std::move(AesGcmBoringSsl::New(key).ValueOrDie());
{ // AAD is a null string_view.
const std::string message = "Some data to encrypt.";
const absl::string_view aad;
const std::string ct = cipher->Encrypt(message, aad).ValueOrDie();
EXPECT_TRUE(cipher->Decrypt(ct, aad).ok());
}
{ // Both message and AAD are null string_view.
const absl::string_view message;
const absl::string_view aad;
const std::string ct = cipher->Encrypt(message, aad).ValueOrDie();
EXPECT_TRUE(cipher->Decrypt(ct, aad).ok());
}
}
static std::string GetError() {
auto err = ERR_peek_last_error();
// Sometimes there is no error message on the stack.
if (err == 0) {
return "";
}
std::string lib(ERR_lib_error_string(err));
std::string func(ERR_func_error_string(err));
std::string reason(ERR_reason_error_string(err));
return lib + ":" + func + ":" + reason;
}
// Test with test vectors from Wycheproof project.
bool WycheproofTest(const Json::Value &root) {
int errors = 0;
for (const Json::Value& test_group : root["testGroups"]) {
const size_t iv_size = test_group["ivSize"].asInt();
const size_t key_size = test_group["keySize"].asInt();
const size_t tag_size = test_group["tagSize"].asInt();
// AesGcmBoringSsl only supports 12-byte IVs and 16-byte authentication tag.
if (iv_size != 96 || tag_size != 128) {
// Not supported
continue;
}
for (const Json::Value& test : test_group["tests"]) {
std::string comment = test["comment"].asString();
std::string key = WycheproofUtil::GetBytes(test["key"]);
std::string iv = WycheproofUtil::GetBytes(test["iv"]);
std::string msg = WycheproofUtil::GetBytes(test["msg"]);
std::string ct = WycheproofUtil::GetBytes(test["ct"]);
std::string aad = WycheproofUtil::GetBytes(test["aad"]);
std::string tag = WycheproofUtil::GetBytes(test["tag"]);
std::string id = test["tcId"].asString();
std::string expected = test["result"].asString();
auto cipher =
std::move(AesGcmBoringSsl::New(key).ValueOrDie());
auto result = cipher->Decrypt(iv + ct + tag, aad);
bool success = result.ok();
if (success) {
std::string decrypted = result.ValueOrDie();
if (expected == "invalid") {
ADD_FAILURE() << "decrypted invalid ciphertext:" << id;
errors++;
} else if (msg != decrypted) {
ADD_FAILURE() << "Incorrect decryption:" << id;
errors++;
}
} else {
if (expected == "valid" || expected == "acceptable") {
ADD_FAILURE()
<< "Could not decrypt test with tcId:" << id
<< " iv_size:" << iv_size
<< " tag_size:" << tag_size
<< " key_size:" << key_size
<< " error:" << GetError();
errors++;
}
}
}
}
return errors == 0;
}
TEST(AesEaxBoringSslTest, TestVectors) {
std::unique_ptr<Json::Value> root =
WycheproofUtil::ReadTestVectors("aes_gcm_test.json");
ASSERT_TRUE(WycheproofTest(*root));
}
} // namespace
} // namespace subtle
} // namespace tink
} // namespace crypto
int main(int ac, char* av[]) {
testing::InitGoogleTest(&ac, av);
return RUN_ALL_TESTS();
}
<commit_msg>Eax --> Gcm (copy/paste fail)<commit_after>// Copyright 2017 Google 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 "tink/subtle/aes_gcm_boringssl.h"
#include <string>
#include <vector>
#include "tink/subtle/wycheproof_util.h"
#include "tink/util/status.h"
#include "tink/util/statusor.h"
#include "tink/util/test_util.h"
#include "gtest/gtest.h"
#include "openssl/err.h"
namespace crypto {
namespace tink {
namespace subtle {
namespace {
TEST(AesGcmBoringSslTest, testBasic) {
std::string key(test::HexDecodeOrDie("000102030405060708090a0b0c0d0e0f"));
auto res = AesGcmBoringSsl::New(key);
EXPECT_TRUE(res.ok()) << res.status();
auto cipher = std::move(res.ValueOrDie());
std::string message = "Some data to encrypt.";
std::string aad = "Some data to authenticate.";
auto ct = cipher->Encrypt(message, aad);
EXPECT_TRUE(ct.ok()) << ct.status();
EXPECT_EQ(ct.ValueOrDie().size(), message.size() + 12 + 16);
auto pt = cipher->Decrypt(ct.ValueOrDie(), aad);
EXPECT_TRUE(pt.ok()) << pt.status();
EXPECT_EQ(pt.ValueOrDie(), message);
}
TEST(AesGcmBoringSslTest, testModification) {
std::string key(test::HexDecodeOrDie("000102030405060708090a0b0c0d0e0f"));
auto cipher = std::move(AesGcmBoringSsl::New(key).ValueOrDie());
std::string message = "Some data to encrypt.";
std::string aad = "Some data to authenticate.";
std::string ct = cipher->Encrypt(message, aad).ValueOrDie();
EXPECT_TRUE(cipher->Decrypt(ct, aad).ok());
// Modify the ciphertext
for (size_t i = 0; i < ct.size() * 8; i++) {
std::string modified_ct = ct;
modified_ct[i / 8] ^= 1 << (i % 8);
EXPECT_FALSE(cipher->Decrypt(modified_ct, aad).ok()) << i;
}
// Modify the additional data
for (size_t i = 0; i < aad.size() * 8; i++) {
std::string modified_aad = aad;
modified_aad[i / 8] ^= 1 << (i % 8);
auto decrypted = cipher->Decrypt(ct, modified_aad);
EXPECT_FALSE(decrypted.ok()) << i << " pt:" << decrypted.ValueOrDie();
}
// Truncate the ciphertext
for (size_t i = 0; i < ct.size(); i++) {
std::string truncated_ct(ct, 0, i);
EXPECT_FALSE(cipher->Decrypt(truncated_ct, aad).ok()) << i;
}
}
TEST(AesGcmBoringSslTest, testAadEmptyVersusNullStringView) {
const std::string key(test::HexDecodeOrDie("000102030405060708090a0b0c0d0e0f"));
auto cipher = std::move(AesGcmBoringSsl::New(key).ValueOrDie());
{ // AAD is a null string_view.
const std::string message = "Some data to encrypt.";
const absl::string_view aad;
const std::string ct = cipher->Encrypt(message, aad).ValueOrDie();
EXPECT_TRUE(cipher->Decrypt(ct, aad).ok());
}
{ // Both message and AAD are null string_view.
const absl::string_view message;
const absl::string_view aad;
const std::string ct = cipher->Encrypt(message, aad).ValueOrDie();
EXPECT_TRUE(cipher->Decrypt(ct, aad).ok());
}
}
static std::string GetError() {
auto err = ERR_peek_last_error();
// Sometimes there is no error message on the stack.
if (err == 0) {
return "";
}
std::string lib(ERR_lib_error_string(err));
std::string func(ERR_func_error_string(err));
std::string reason(ERR_reason_error_string(err));
return lib + ":" + func + ":" + reason;
}
// Test with test vectors from Wycheproof project.
bool WycheproofTest(const Json::Value &root) {
int errors = 0;
for (const Json::Value& test_group : root["testGroups"]) {
const size_t iv_size = test_group["ivSize"].asInt();
const size_t key_size = test_group["keySize"].asInt();
const size_t tag_size = test_group["tagSize"].asInt();
// AesGcmBoringSsl only supports 12-byte IVs and 16-byte authentication tag.
if (iv_size != 96 || tag_size != 128) {
// Not supported
continue;
}
for (const Json::Value& test : test_group["tests"]) {
std::string comment = test["comment"].asString();
std::string key = WycheproofUtil::GetBytes(test["key"]);
std::string iv = WycheproofUtil::GetBytes(test["iv"]);
std::string msg = WycheproofUtil::GetBytes(test["msg"]);
std::string ct = WycheproofUtil::GetBytes(test["ct"]);
std::string aad = WycheproofUtil::GetBytes(test["aad"]);
std::string tag = WycheproofUtil::GetBytes(test["tag"]);
std::string id = test["tcId"].asString();
std::string expected = test["result"].asString();
auto cipher =
std::move(AesGcmBoringSsl::New(key).ValueOrDie());
auto result = cipher->Decrypt(iv + ct + tag, aad);
bool success = result.ok();
if (success) {
std::string decrypted = result.ValueOrDie();
if (expected == "invalid") {
ADD_FAILURE() << "decrypted invalid ciphertext:" << id;
errors++;
} else if (msg != decrypted) {
ADD_FAILURE() << "Incorrect decryption:" << id;
errors++;
}
} else {
if (expected == "valid" || expected == "acceptable") {
ADD_FAILURE()
<< "Could not decrypt test with tcId:" << id
<< " iv_size:" << iv_size
<< " tag_size:" << tag_size
<< " key_size:" << key_size
<< " error:" << GetError();
errors++;
}
}
}
}
return errors == 0;
}
TEST(AesGcmBoringSslTest, TestVectors) {
std::unique_ptr<Json::Value> root =
WycheproofUtil::ReadTestVectors("aes_gcm_test.json");
ASSERT_TRUE(WycheproofTest(*root));
}
} // namespace
} // namespace subtle
} // namespace tink
} // namespace crypto
int main(int ac, char* av[]) {
testing::InitGoogleTest(&ac, av);
return RUN_ALL_TESTS();
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/scoped_ptr.h"
#include "base/string_util.h"
#include "base/values.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/json_value_serializer.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "googleurl/src/gurl.h"
#include "net/base/net_util.h"
namespace {
static const FilePath::CharType kBaseUrl[] =
FILE_PATH_LITERAL("http://localhost:8000/");
static const FilePath::CharType kStartFile[] =
FILE_PATH_LITERAL("dom_checker.html");
const wchar_t kRunDomCheckerTest[] = L"run-dom-checker-test";
class DomCheckerTest : public UITest {
public:
DomCheckerTest() {
dom_automation_enabled_ = true;
enable_file_cookies_ = false;
show_window_ = true;
launch_arguments_.AppendSwitch(switches::kDisablePopupBlocking);
}
typedef std::list<std::string> ResultsList;
typedef std::set<std::string> ResultsSet;
void RunTest(bool use_http, ResultsList* new_passes,
ResultsList* new_failures) {
int test_count = 0;
ResultsSet expected_failures, current_failures;
std::string failures_file = use_http ?
"expected_failures-http.txt" : "expected_failures-file.txt";
GetExpectedFailures(failures_file, &expected_failures);
RunDomChecker(use_http, &test_count, ¤t_failures);
printf("\nTests run: %d\n", test_count);
// Compute the list of new passes and failures.
CompareSets(current_failures, expected_failures, new_passes);
CompareSets(expected_failures, current_failures, new_failures);
}
void PrintResults(const ResultsList& new_passes,
const ResultsList& new_failures) {
PrintResults(new_failures, "new tests failing", true);
PrintResults(new_passes, "new tests passing", false);
}
private:
void PrintResults(const ResultsList& results, const char* message,
bool add_failure) {
if (!results.empty()) {
if (add_failure)
ADD_FAILURE();
printf("%s:\n", message);
ResultsList::const_iterator it = results.begin();
for (; it != results.end(); ++it)
printf(" %s\n", it->c_str());
printf("\n");
}
}
// Find the elements of "b" that are not in "a".
void CompareSets(const ResultsSet& a, const ResultsSet& b,
ResultsList* only_in_b) {
ResultsSet::const_iterator it = b.begin();
for (; it != b.end(); ++it) {
if (a.find(*it) == a.end())
only_in_b->push_back(*it);
}
}
// Return the path to the DOM checker directory on the local filesystem.
FilePath GetDomCheckerDir() {
FilePath test_dir;
PathService::Get(chrome::DIR_TEST_DATA, &test_dir);
return test_dir.AppendASCII("dom_checker");
}
bool ReadExpectedResults(const std::string& failures_file,
std::string* results) {
FilePath results_path = GetDomCheckerDir();
results_path = results_path.AppendASCII(failures_file);
return file_util::ReadFileToString(results_path, results);
}
void ParseExpectedFailures(const std::string& input, ResultsSet* output) {
if (input.empty())
return;
std::vector<std::string> tokens;
SplitString(input, '\n', &tokens);
std::vector<std::string>::const_iterator it = tokens.begin();
for (; it != tokens.end(); ++it) {
// Allow comments (lines that start with #).
if (it->length() > 0 && it->at(0) != '#')
output->insert(*it);
}
}
void GetExpectedFailures(const std::string& failures_file,
ResultsSet* expected_failures) {
std::string expected_failures_text;
bool have_expected_results = ReadExpectedResults(failures_file,
&expected_failures_text);
ASSERT_TRUE(have_expected_results);
ParseExpectedFailures(expected_failures_text, expected_failures);
}
bool WaitUntilTestCompletes(TabProxy* tab) {
return WaitUntilJavaScriptCondition(tab, L"",
L"window.domAutomationController.send(automation.IsDone());",
1000, UITest::test_timeout_ms());
}
bool GetTestCount(TabProxy* tab, int* test_count) {
return tab->ExecuteAndExtractInt(L"",
L"window.domAutomationController.send(automation.GetTestCount());",
test_count);
}
bool GetTestsFailed(TabProxy* tab, ResultsSet* tests_failed) {
std::wstring json_wide;
bool succeeded = tab->ExecuteAndExtractString(L"",
L"window.domAutomationController.send("
L" JSON.stringify(automation.GetFailures()));",
&json_wide);
EXPECT_TRUE(succeeded);
if (!succeeded)
return false;
std::string json = WideToUTF8(json_wide);
JSONStringValueSerializer deserializer(json);
scoped_ptr<Value> value(deserializer.Deserialize(NULL));
EXPECT_TRUE(value.get());
if (!value.get())
return false;
EXPECT_TRUE(value->IsType(Value::TYPE_LIST));
if (!value->IsType(Value::TYPE_LIST))
return false;
ListValue* list_value = static_cast<ListValue*>(value.get());
// The parsed JSON object will be an array of strings, each of which is a
// test failure. Add those strings to the results set.
ListValue::const_iterator it = list_value->begin();
for (; it != list_value->end(); ++it) {
EXPECT_TRUE((*it)->IsType(Value::TYPE_STRING));
if ((*it)->IsType(Value::TYPE_STRING)) {
std::string test_name;
succeeded = (*it)->GetAsString(&test_name);
EXPECT_TRUE(succeeded);
if (succeeded)
tests_failed->insert(test_name);
}
}
return true;
}
void RunDomChecker(bool use_http, int* test_count, ResultsSet* tests_failed) {
GURL test_url;
FilePath::StringType start_file(kStartFile);
if (use_http) {
FilePath::StringType url_string(kBaseUrl);
url_string.append(start_file);
test_url = GURL(url_string);
} else {
FilePath test_path = GetDomCheckerDir();
test_path = test_path.Append(start_file);
test_url = net::FilePathToFileURL(test_path);
}
scoped_ptr<TabProxy> tab(GetActiveTab());
tab->NavigateToURL(test_url);
// Wait for the test to finish.
ASSERT_TRUE(WaitUntilTestCompletes(tab.get()));
// Get the test results.
ASSERT_TRUE(GetTestCount(tab.get(), test_count));
ASSERT_TRUE(GetTestsFailed(tab.get(), tests_failed));
ASSERT_GT(*test_count, 0);
}
};
} // namespace
TEST_F(DomCheckerTest, File) {
if (!CommandLine::ForCurrentProcess()->HasSwitch(kRunDomCheckerTest))
return;
ResultsList new_passes, new_failures;
RunTest(false, &new_passes, &new_failures);
PrintResults(new_passes, new_failures);
}
TEST_F(DomCheckerTest, Http) {
if (!CommandLine::ForCurrentProcess()->HasSwitch(kRunDomCheckerTest))
return;
ResultsList new_passes, new_failures;
RunTest(true, &new_passes, &new_failures);
PrintResults(new_passes, new_failures);
}
<commit_msg>Style issues: - Fix indentation. - Reorder typedefs according to style guide. - Add DISALLOW_COPY_AND_ASSIGN. Review URL: http://codereview.chromium.org/42322<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/scoped_ptr.h"
#include "base/string_util.h"
#include "base/values.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/json_value_serializer.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "googleurl/src/gurl.h"
#include "net/base/net_util.h"
namespace {
static const FilePath::CharType kBaseUrl[] =
FILE_PATH_LITERAL("http://localhost:8000/");
static const FilePath::CharType kStartFile[] =
FILE_PATH_LITERAL("dom_checker.html");
const wchar_t kRunDomCheckerTest[] = L"run-dom-checker-test";
class DomCheckerTest : public UITest {
public:
typedef std::list<std::string> ResultsList;
typedef std::set<std::string> ResultsSet;
DomCheckerTest() {
dom_automation_enabled_ = true;
enable_file_cookies_ = false;
show_window_ = true;
launch_arguments_.AppendSwitch(switches::kDisablePopupBlocking);
}
void RunTest(bool use_http, ResultsList* new_passes,
ResultsList* new_failures) {
int test_count = 0;
ResultsSet expected_failures, current_failures;
std::string failures_file = use_http ?
"expected_failures-http.txt" : "expected_failures-file.txt";
GetExpectedFailures(failures_file, &expected_failures);
RunDomChecker(use_http, &test_count, ¤t_failures);
printf("\nTests run: %d\n", test_count);
// Compute the list of new passes and failures.
CompareSets(current_failures, expected_failures, new_passes);
CompareSets(expected_failures, current_failures, new_failures);
}
void PrintResults(const ResultsList& new_passes,
const ResultsList& new_failures) {
PrintResults(new_failures, "new tests failing", true);
PrintResults(new_passes, "new tests passing", false);
}
private:
void PrintResults(const ResultsList& results, const char* message,
bool add_failure) {
if (!results.empty()) {
if (add_failure)
ADD_FAILURE();
printf("%s:\n", message);
ResultsList::const_iterator it = results.begin();
for (; it != results.end(); ++it)
printf(" %s\n", it->c_str());
printf("\n");
}
}
// Find the elements of "b" that are not in "a".
void CompareSets(const ResultsSet& a, const ResultsSet& b,
ResultsList* only_in_b) {
ResultsSet::const_iterator it = b.begin();
for (; it != b.end(); ++it) {
if (a.find(*it) == a.end())
only_in_b->push_back(*it);
}
}
// Return the path to the DOM checker directory on the local filesystem.
FilePath GetDomCheckerDir() {
FilePath test_dir;
PathService::Get(chrome::DIR_TEST_DATA, &test_dir);
return test_dir.AppendASCII("dom_checker");
}
bool ReadExpectedResults(const std::string& failures_file,
std::string* results) {
FilePath results_path = GetDomCheckerDir();
results_path = results_path.AppendASCII(failures_file);
return file_util::ReadFileToString(results_path, results);
}
void ParseExpectedFailures(const std::string& input, ResultsSet* output) {
if (input.empty())
return;
std::vector<std::string> tokens;
SplitString(input, '\n', &tokens);
std::vector<std::string>::const_iterator it = tokens.begin();
for (; it != tokens.end(); ++it) {
// Allow comments (lines that start with #).
if (it->length() > 0 && it->at(0) != '#')
output->insert(*it);
}
}
void GetExpectedFailures(const std::string& failures_file,
ResultsSet* expected_failures) {
std::string expected_failures_text;
bool have_expected_results = ReadExpectedResults(failures_file,
&expected_failures_text);
ASSERT_TRUE(have_expected_results);
ParseExpectedFailures(expected_failures_text, expected_failures);
}
bool WaitUntilTestCompletes(TabProxy* tab) {
return WaitUntilJavaScriptCondition(tab, L"",
L"window.domAutomationController.send(automation.IsDone());",
1000, UITest::test_timeout_ms());
}
bool GetTestCount(TabProxy* tab, int* test_count) {
return tab->ExecuteAndExtractInt(L"",
L"window.domAutomationController.send(automation.GetTestCount());",
test_count);
}
bool GetTestsFailed(TabProxy* tab, ResultsSet* tests_failed) {
std::wstring json_wide;
bool succeeded = tab->ExecuteAndExtractString(L"",
L"window.domAutomationController.send("
L" JSON.stringify(automation.GetFailures()));",
&json_wide);
EXPECT_TRUE(succeeded);
if (!succeeded)
return false;
std::string json = WideToUTF8(json_wide);
JSONStringValueSerializer deserializer(json);
scoped_ptr<Value> value(deserializer.Deserialize(NULL));
EXPECT_TRUE(value.get());
if (!value.get())
return false;
EXPECT_TRUE(value->IsType(Value::TYPE_LIST));
if (!value->IsType(Value::TYPE_LIST))
return false;
ListValue* list_value = static_cast<ListValue*>(value.get());
// The parsed JSON object will be an array of strings, each of which is a
// test failure. Add those strings to the results set.
ListValue::const_iterator it = list_value->begin();
for (; it != list_value->end(); ++it) {
EXPECT_TRUE((*it)->IsType(Value::TYPE_STRING));
if ((*it)->IsType(Value::TYPE_STRING)) {
std::string test_name;
succeeded = (*it)->GetAsString(&test_name);
EXPECT_TRUE(succeeded);
if (succeeded)
tests_failed->insert(test_name);
}
}
return true;
}
void RunDomChecker(bool use_http, int* test_count, ResultsSet* tests_failed) {
GURL test_url;
FilePath::StringType start_file(kStartFile);
if (use_http) {
FilePath::StringType url_string(kBaseUrl);
url_string.append(start_file);
test_url = GURL(url_string);
} else {
FilePath test_path = GetDomCheckerDir();
test_path = test_path.Append(start_file);
test_url = net::FilePathToFileURL(test_path);
}
scoped_ptr<TabProxy> tab(GetActiveTab());
tab->NavigateToURL(test_url);
// Wait for the test to finish.
ASSERT_TRUE(WaitUntilTestCompletes(tab.get()));
// Get the test results.
ASSERT_TRUE(GetTestCount(tab.get(), test_count));
ASSERT_TRUE(GetTestsFailed(tab.get(), tests_failed));
ASSERT_GT(*test_count, 0);
}
DISALLOW_COPY_AND_ASSIGN(DomCheckerTest);
};
} // namespace
TEST_F(DomCheckerTest, File) {
if (!CommandLine::ForCurrentProcess()->HasSwitch(kRunDomCheckerTest))
return;
ResultsList new_passes, new_failures;
RunTest(false, &new_passes, &new_failures);
PrintResults(new_passes, new_failures);
}
TEST_F(DomCheckerTest, Http) {
if (!CommandLine::ForCurrentProcess()->HasSwitch(kRunDomCheckerTest))
return;
ResultsList new_passes, new_failures;
RunTest(true, &new_passes, &new_failures);
PrintResults(new_passes, new_failures);
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkMinimumMaximumImageCalculatorTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "itkImage.h"
#include "itkMinimumMaximumImageCalculator.h"
#include "itkSize.h"
typedef itk::Size<3> SizeType;
typedef itk::Image<short, 3> ImageType;
typedef itk::MinimumMaximumImageCalculator<ImageType> MinMaxCalculatorType;
namespace
{
/* Define the image size and physical coordinates */
SizeType size = {{20, 20, 20}};
double origin [3] = { 0.0, 0.0, 0.0};
double spacing[3] = { 1, 1 , 1};
}
int
itkMinimumMaximumImageCalculatorTest(int ,char * [] )
{
int flag = 0; /* Did this test program work? */
std::cout << "Testing Minimum and Maximum Image Calulator:\n";
/* Allocate a simple test image */
ImageType::Pointer image = ImageType::New();
ImageType::RegionType region;
region.SetSize(size);
image->SetLargestPossibleRegion(region);
image->SetRequestedRegion(region);
image->SetBufferedRegion(region);
image->Allocate();
/* Set origin and spacing of physical coordinates */
image->SetOrigin(origin);
image->SetSpacing(spacing);
short minimum = -52;
short maximum = 103;
/* Initialize the image contents with the minimum value*/
itk::Index<3> index;
for (int slice = 0; slice < 20; slice++) {
index[2] = slice;
for (int row = 0; row <20; row++) {
index[1] = row;
for (int col = 0; col < 20; col++) {
index[0] = col;
image->SetPixel(index, minimum);
}
}
}
/* Set voxel (10,10,10) to maximum value*/
index[0] = 10;
index[1] = 10;
index[2] = 10;
image->SetPixel(index, maximum);
/* Create and initialize the calculator */
MinMaxCalculatorType::Pointer calculator = MinMaxCalculatorType::New();
calculator->SetImage(image);
calculator->Compute();
std::cout << "calculator: " << calculator;
/* Return minimum of intensity */
short minimumResult = calculator->GetMinimum();
std::cout << "The Minimum intensity value is : " << minimumResult << std::endl;
if(minimumResult != minimum)
{
std::cout << "Minimum Value is wrong : " << minimumResult ;
std::cout << " != " << minimum << std::endl;
flag = 1;
}
/* Return maximum of intensity */
short maximumResult = calculator->GetMaximum();
std::cout << "The Maximum intensity value is : " << maximumResult << std::endl;
if(maximumResult != maximum)
{
std::cout << "Maximum Value is wrong : " << maximumResult ;
std::cout << " != " << maximum << std::endl;
flag = 2;
}
/* Return results of test */
if (flag != 0) {
std::cout << "*** Some tests failed" << std::endl;
return flag; }
else {
std::cout << "All tests successfully passed" << std::endl;
return 0; }
}
<commit_msg>ERR: duplicate of test in BasicFilters.<commit_after><|endoftext|>
|
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkDiscreteGaussianImageFilterTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include <iostream>
#include "itkImage.h"
#include "itkDiscreteGaussianImageFilter.h"
#include "itkNullImageToImageFilterDriver.txx"
#include "itkVector.h"
int itkDiscreteGaussianImageFilterTest(int argc, char **argv)
{
try
{
typedef itk::Image<float, 3> ImageType;
// Set up filter
itk::DiscreteGaussianImageFilter<ImageType, ImageType>::Pointer
filter =
itk::DiscreteGaussianImageFilter<ImageType, ImageType>::New();
filter->SetVariance(1.0f);
filter->SetMaximumError(.01f);
// Run Test
itk::Size<3> sz;
sz[0] = 100 ; //atoi(argv[1]);
sz[1] = 100 ; // atoi(argv[2]);
sz[2] = 1;
// sz[2] = 10;//atoi(argv[3]);
// sz[3] = 5;//atoi(argv[4]);
itk::NullImageToImageFilterDriver< ImageType, ImageType > test1;
test1.SetImageSize(sz);
test1.SetFilter(filter.GetPointer());
test1.Execute();
}
catch(itk::ExceptionObject &err)
{
(&err)->Print(std::cerr);
return 1;
}
return 0;
}
<commit_msg>FIX: 3d Neighborhood operators apparently no longer working with single slices. Fixed test to process 3d volume.<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkDiscreteGaussianImageFilterTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include <iostream>
#include "itkImage.h"
#include "itkDiscreteGaussianImageFilter.h"
#include "itkNullImageToImageFilterDriver.txx"
#include "itkVector.h"
int itkDiscreteGaussianImageFilterTest(int argc, char **argv)
{
try
{
typedef itk::Image<float, 3> ImageType;
// Set up filter
itk::DiscreteGaussianImageFilter<ImageType, ImageType>::Pointer
filter =
itk::DiscreteGaussianImageFilter<ImageType, ImageType>::New();
filter->SetVariance(1.0f);
filter->SetMaximumError(.01f);
// Run Test
itk::Size<3> sz;
sz[0] = 100 ; //atoi(argv[1]);
sz[1] = 100 ; // atoi(argv[2]);
sz[2] = 40;
// sz[2] = 10;//atoi(argv[3]);
// sz[3] = 5;//atoi(argv[4]);
itk::NullImageToImageFilterDriver< ImageType, ImageType > test1;
test1.SetImageSize(sz);
test1.SetFilter(filter.GetPointer());
test1.Execute();
}
catch(itk::ExceptionObject &err)
{
(&err)->Print(std::cerr);
return 1;
}
return 0;
}
<|endoftext|>
|
<commit_before>#include <sstream>
#include "Exceptions.h"
#include "Extensions.h"
#include "UNetSender.h"
// -----------------------------------------------------------------------------
using namespace std;
using namespace UniSetTypes;
using namespace UniSetExtensions;
// -----------------------------------------------------------------------------
UNetSender::UNetSender( const std::string s_host, const ost::tpport_t port, SMInterface* smi,
const std::string s_f, const std::string s_val, SharedMemory* ic ):
s_field(s_f),
s_fvalue(s_val),
shm(smi),
s_host(s_host),
sendpause(150),
activated(false),
dlist(100),
maxItem(0),
s_thr(0)
{
ptPack.setTiming(UniSetTimer::WaitUpTime);
{
ostringstream s;
s << "(" << s_host << ":" << port << ")";
myname = s.str();
}
// определяем фильтр
// s_field = conf->getArgParam("--udp-filter-field");
// s_fvalue = conf->getArgParam("--udp-filter-value");
dlog[Debug::INFO] << myname << "(init): read fileter-field='" << s_field
<< "' filter-value='" << s_fvalue << "'" << endl;
if( dlog.debugging(Debug::INFO) )
dlog[Debug::INFO] << "(UNetSender): UDP set to " << s_host << ":" << port << endl;
try
{
addr = s_host.c_str();
udp = new ost::UDPBroadcast(addr,port);
}
catch( ost::SockException& e )
{
ostringstream s;
s << e.getString() << ": " << e.getSystemErrorString() << endl;
throw SystemError(s.str());
}
s_thr = new ThreadCreator<UNetSender>(this, &UNetSender::send);
// -------------------------------
if( shm->isLocalwork() )
{
readConfiguration();
dlist.resize(maxItem);
dlog[Debug::INFO] << myname << "(init): dlist size = " << dlist.size() << endl;
}
else
ic->addReadItem( sigc::mem_fun(this,&UNetSender::readItem) );
// выставляем поля, которые не меняются
mypack.msg.header.nodeID = conf->getLocalNode();
mypack.msg.header.procID = shm->ID();
}
// -----------------------------------------------------------------------------
UNetSender::~UNetSender()
{
delete s_thr;
delete udp;
delete shm;
}
// -----------------------------------------------------------------------------
void UNetSender::update( UniSetTypes::ObjectId id, long value )
{
DMap::iterator it=dlist.begin();
for( ; it!=dlist.end(); ++it )
{
if( it->si.id == id )
{
uniset_spin_lock lock(it->val_lock);
it->val = value;
}
break;
}
}
// -----------------------------------------------------------------------------
void UNetSender::send()
{
dlist.resize(maxItem);
dlog[Debug::INFO] << myname << "(init): dlist size = " << dlist.size() << endl;
/*
ost::IPV4Broadcast h = s_host.c_str();
try
{
udp->setPeer(h,port);
}
catch( ost::SockException& e )
{
ostringstream s;
s << e.getString() << ": " << e.getSystemErrorString();
dlog[Debug::CRIT] << myname << "(poll): " << s.str() << endl;
throw SystemError(s.str());
}
*/
while( activated )
{
try
{
real_send();
}
catch( ost::SockException& e )
{
cerr << e.getString() << ": " << e.getSystemErrorString() << endl;
}
catch( UniSetTypes::Exception& ex)
{
cerr << myname << "(send): " << ex << std::endl;
}
catch(...)
{
cerr << myname << "(send): catch ..." << std::endl;
}
msleep(sendpause);
}
cerr << "************* execute FINISH **********" << endl;
}
// -----------------------------------------------------------------------------
void UNetSender::real_send()
{
mypack.msg.header.num = packetnum++;
// cout << "************* send header: " << mypack.msg.header << endl;
int sz = mypack.byte_size() + sizeof(UniSetUDP::UDPHeader);
if( !udp->isPending(ost::Socket::pendingOutput) )
return;
ssize_t ret = udp->send( (char*)&(mypack.msg),sz);
if( ret < sz )
dlog[Debug::CRIT] << myname << "(send): FAILED ret=" << ret << " < sizeof=" << sz << endl;
}
// -----------------------------------------------------------------------------
void UNetSender::start()
{
if( !activated )
{
activated = true;
s_thr->start();
}
}
// -----------------------------------------------------------------------------
void UNetSender::readConfiguration()
{
xmlNode* root = conf->getXMLSensorsSection();
if(!root)
{
ostringstream err;
err << myname << "(readConfiguration): not found <sensors>";
throw SystemError(err.str());
}
UniXML_iterator it(root);
if( !it.goChildren() )
{
std::cerr << myname << "(readConfiguration): empty <sensors>?!!" << endl;
return;
}
for( ;it.getCurrent(); it.goNext() )
{
if( check_item(it) )
initItem(it);
}
}
// ------------------------------------------------------------------------------------------
bool UNetSender::check_item( UniXML_iterator& it )
{
if( s_field.empty() )
return true;
// просто проверка на не пустой field
if( s_fvalue.empty() && it.getProp(s_field).empty() )
return false;
// просто проверка что field = value
if( !s_fvalue.empty() && it.getProp(s_field)!=s_fvalue )
return false;
return true;
}
// ------------------------------------------------------------------------------------------
bool UNetSender::readItem( UniXML& xml, UniXML_iterator& it, xmlNode* sec )
{
if( check_item(it) )
initItem(it);
return true;
}
// ------------------------------------------------------------------------------------------
bool UNetSender::initItem( UniXML_iterator& it )
{
string sname( it.getProp("name") );
string tid = it.getProp("id");
ObjectId sid;
if( !tid.empty() )
{
sid = UniSetTypes::uni_atoi(tid);
if( sid <= 0 )
sid = DefaultObjectId;
}
else
sid = conf->getSensorID(sname);
if( sid == DefaultObjectId )
{
if( dlog )
dlog[Debug::CRIT] << myname << "(readItem): ID not found for "
<< sname << endl;
return false;
}
UItem p;
p.si.id = sid;
p.si.node = conf->getLocalNode();
mypack.addData(sid,0);
p.pack_ind = mypack.size()-1;
if( maxItem >= mypack.size() )
dlist.resize(maxItem+10);
dlist[maxItem] = p;
maxItem++;
if( dlog.debugging(Debug::INFO) )
dlog[Debug::INFO] << myname << "(initItem): add " << p << endl;
return true;
}
// ------------------------------------------------------------------------------------------
void UNetSender::initIterators()
{
DMap::iterator it=dlist.begin();
for( ; it!=dlist.end(); it++ )
{
shm->initDIterator(it->dit);
shm->initAIterator(it->ait);
}
}
// -----------------------------------------------------------------------------
std::ostream& operator<<( std::ostream& os, UNetSender::UItem& p )
{
return os << " sid=" << p.si.id;
}
// -----------------------------------------------------------------------------
<commit_msg>UNet2: восстановил в sender-е случайно стёртую проверку на MaxPacketNum<commit_after>#include <sstream>
#include "Exceptions.h"
#include "Extensions.h"
#include "UNetSender.h"
// -----------------------------------------------------------------------------
using namespace std;
using namespace UniSetTypes;
using namespace UniSetExtensions;
// -----------------------------------------------------------------------------
UNetSender::UNetSender( const std::string s_host, const ost::tpport_t port, SMInterface* smi,
const std::string s_f, const std::string s_val, SharedMemory* ic ):
s_field(s_f),
s_fvalue(s_val),
shm(smi),
s_host(s_host),
sendpause(150),
activated(false),
dlist(100),
maxItem(0),
s_thr(0)
{
ptPack.setTiming(UniSetTimer::WaitUpTime);
{
ostringstream s;
s << "(" << s_host << ":" << port << ")";
myname = s.str();
}
// определяем фильтр
// s_field = conf->getArgParam("--udp-filter-field");
// s_fvalue = conf->getArgParam("--udp-filter-value");
dlog[Debug::INFO] << myname << "(init): read fileter-field='" << s_field
<< "' filter-value='" << s_fvalue << "'" << endl;
if( dlog.debugging(Debug::INFO) )
dlog[Debug::INFO] << "(UNetSender): UDP set to " << s_host << ":" << port << endl;
try
{
addr = s_host.c_str();
udp = new ost::UDPBroadcast(addr,port);
}
catch( ost::SockException& e )
{
ostringstream s;
s << e.getString() << ": " << e.getSystemErrorString() << endl;
throw SystemError(s.str());
}
s_thr = new ThreadCreator<UNetSender>(this, &UNetSender::send);
// -------------------------------
if( shm->isLocalwork() )
{
readConfiguration();
dlist.resize(maxItem);
dlog[Debug::INFO] << myname << "(init): dlist size = " << dlist.size() << endl;
}
else
ic->addReadItem( sigc::mem_fun(this,&UNetSender::readItem) );
// выставляем поля, которые не меняются
mypack.msg.header.nodeID = conf->getLocalNode();
mypack.msg.header.procID = shm->ID();
}
// -----------------------------------------------------------------------------
UNetSender::~UNetSender()
{
delete s_thr;
delete udp;
delete shm;
}
// -----------------------------------------------------------------------------
void UNetSender::update( UniSetTypes::ObjectId id, long value )
{
DMap::iterator it=dlist.begin();
for( ; it!=dlist.end(); ++it )
{
if( it->si.id == id )
{
uniset_spin_lock lock(it->val_lock);
it->val = value;
}
break;
}
}
// -----------------------------------------------------------------------------
void UNetSender::send()
{
dlist.resize(maxItem);
dlog[Debug::INFO] << myname << "(init): dlist size = " << dlist.size() << endl;
/*
ost::IPV4Broadcast h = s_host.c_str();
try
{
udp->setPeer(h,port);
}
catch( ost::SockException& e )
{
ostringstream s;
s << e.getString() << ": " << e.getSystemErrorString();
dlog[Debug::CRIT] << myname << "(poll): " << s.str() << endl;
throw SystemError(s.str());
}
*/
while( activated )
{
try
{
real_send();
}
catch( ost::SockException& e )
{
cerr << e.getString() << ": " << e.getSystemErrorString() << endl;
}
catch( UniSetTypes::Exception& ex)
{
cerr << myname << "(send): " << ex << std::endl;
}
catch(...)
{
cerr << myname << "(send): catch ..." << std::endl;
}
msleep(sendpause);
}
cerr << "************* execute FINISH **********" << endl;
}
// -----------------------------------------------------------------------------
void UNetSender::real_send()
{
mypack.msg.header.num = packetnum++;
if( packetnum > UniSetUDP::MaxPacketNum )
packetnum = 1;
// cout << "************* send header: " << mypack.msg.header << endl;
int sz = mypack.byte_size() + sizeof(UniSetUDP::UDPHeader);
if( !udp->isPending(ost::Socket::pendingOutput) )
return;
ssize_t ret = udp->send( (char*)&(mypack.msg),sz);
if( ret < sz )
dlog[Debug::CRIT] << myname << "(send): FAILED ret=" << ret << " < sizeof=" << sz << endl;
}
// -----------------------------------------------------------------------------
void UNetSender::start()
{
if( !activated )
{
activated = true;
s_thr->start();
}
}
// -----------------------------------------------------------------------------
void UNetSender::readConfiguration()
{
xmlNode* root = conf->getXMLSensorsSection();
if(!root)
{
ostringstream err;
err << myname << "(readConfiguration): not found <sensors>";
throw SystemError(err.str());
}
UniXML_iterator it(root);
if( !it.goChildren() )
{
std::cerr << myname << "(readConfiguration): empty <sensors>?!!" << endl;
return;
}
for( ;it.getCurrent(); it.goNext() )
{
if( check_item(it) )
initItem(it);
}
}
// ------------------------------------------------------------------------------------------
bool UNetSender::check_item( UniXML_iterator& it )
{
if( s_field.empty() )
return true;
// просто проверка на не пустой field
if( s_fvalue.empty() && it.getProp(s_field).empty() )
return false;
// просто проверка что field = value
if( !s_fvalue.empty() && it.getProp(s_field)!=s_fvalue )
return false;
return true;
}
// ------------------------------------------------------------------------------------------
bool UNetSender::readItem( UniXML& xml, UniXML_iterator& it, xmlNode* sec )
{
if( check_item(it) )
initItem(it);
return true;
}
// ------------------------------------------------------------------------------------------
bool UNetSender::initItem( UniXML_iterator& it )
{
string sname( it.getProp("name") );
string tid = it.getProp("id");
ObjectId sid;
if( !tid.empty() )
{
sid = UniSetTypes::uni_atoi(tid);
if( sid <= 0 )
sid = DefaultObjectId;
}
else
sid = conf->getSensorID(sname);
if( sid == DefaultObjectId )
{
if( dlog )
dlog[Debug::CRIT] << myname << "(readItem): ID not found for "
<< sname << endl;
return false;
}
UItem p;
p.si.id = sid;
p.si.node = conf->getLocalNode();
mypack.addData(sid,0);
p.pack_ind = mypack.size()-1;
if( maxItem >= mypack.size() )
dlist.resize(maxItem+10);
dlist[maxItem] = p;
maxItem++;
if( dlog.debugging(Debug::INFO) )
dlog[Debug::INFO] << myname << "(initItem): add " << p << endl;
return true;
}
// ------------------------------------------------------------------------------------------
void UNetSender::initIterators()
{
DMap::iterator it=dlist.begin();
for( ; it!=dlist.end(); it++ )
{
shm->initDIterator(it->dit);
shm->initAIterator(it->ait);
}
}
// -----------------------------------------------------------------------------
std::ostream& operator<<( std::ostream& os, UNetSender::UItem& p )
{
return os << " sid=" << p.si.id;
}
// -----------------------------------------------------------------------------
<|endoftext|>
|
<commit_before>//
// "$Id: Fl_XColor.H 4288 2005-04-16 00:13:17Z mike $"
//
// X-specific color definitions for the Fast Light Tool Kit (FLTK).
//
// Copyright 1998-2001 by Bill Spitzak and others.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Library General Public License for more details.
//
// You should have received a copy of the GNU Library General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
// USA.
//
// Please report all bugs and problems on the following page:
//
// http://www.fltk.org/str.php
//
#include <config.h>
#include <FL/Enumerations.H>
// one of these for each color in fltk's "colormap":
// if overlays are enabled, another one for the overlay
struct Fl_XColor {
unsigned char r,g,b; // actual color used by X
unsigned char mapped; // true when XAllocColor done
unsigned long pixel; // the X pixel to use
};
extern Fl_XColor fl_xmap[/*overlay*/][256];
// mask & shifts to produce xcolor for truecolor visuals:
extern unsigned char fl_redmask, fl_greenmask, fl_bluemask;
extern int fl_redshift, fl_greenshift, fl_blueshift, fl_extrashift;
//
// End of "$Id: Fl_XColor.H 4288 2005-04-16 00:13:17Z mike $".
//
<commit_msg>Correction include config.h<commit_after>//
// "$Id: Fl_XColor.H 4288 2005-04-16 00:13:17Z mike $"
//
// X-specific color definitions for the Fast Light Tool Kit (FLTK).
//
// Copyright 1998-2001 by Bill Spitzak and others.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Library General Public License for more details.
//
// You should have received a copy of the GNU Library General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
// USA.
//
// Please report all bugs and problems on the following page:
//
// http://www.fltk.org/str.php
//
/*OTB Modifications: conflict name with OTB/Utilities/ITK/Utilities/nifti/znzlib/config.h*/
/*#include <config.h>*/
#include "fltk-config.h"
#include <FL/Enumerations.H>
// one of these for each color in fltk's "colormap":
// if overlays are enabled, another one for the overlay
struct Fl_XColor {
unsigned char r,g,b; // actual color used by X
unsigned char mapped; // true when XAllocColor done
unsigned long pixel; // the X pixel to use
};
extern Fl_XColor fl_xmap[/*overlay*/][256];
// mask & shifts to produce xcolor for truecolor visuals:
extern unsigned char fl_redmask, fl_greenmask, fl_bluemask;
extern int fl_redshift, fl_greenshift, fl_blueshift, fl_extrashift;
//
// End of "$Id: Fl_XColor.H 4288 2005-04-16 00:13:17Z mike $".
//
<|endoftext|>
|
<commit_before>#include <stdio.h>
#include <ctype.h>
#include <iostream>
#include <fstream>
#include <string>
#include <metaUtils.h>
#include <metaObject.h>
#include <metaScene.h>
#include <metaTube.h>
#include <metaEllipse.h>
#include <metaGaussian.h>
#include <metaImage.h>
#include <metaBlob.h>
#include <metaLandmark.h>
#include <metaLine.h>
#include <metaGroup.h>
#include <metaSurface.h>
#include <metaLandmark.h>
#include <metaMesh.h>
//
// MetaScene Constructors
//
MetaScene::
MetaScene()
:MetaObject()
{
if(META_DEBUG) std::cout << "MetaScene()" << std::endl;
Clear();
}
//
MetaScene::
MetaScene(const MetaScene *_scene)
:MetaObject()
{
if(META_DEBUG) std::cout << "MetaScene()" << std::endl;
Clear();
CopyInfo(_scene);
}
//
MetaScene::
MetaScene(unsigned int dim)
:MetaObject(dim)
{
if(META_DEBUG) std::cout << "MetaScene()" << std::endl;
Clear();
}
/** Destructor */
MetaScene::
~MetaScene()
{
Clear();
M_Destroy();
}
//
void MetaScene::
PrintInfo() const
{
MetaObject::PrintInfo();
std::cout << "Number of Objects = " << m_NObjects << std::endl;
}
void MetaScene::
CopyInfo(const MetaScene * _tube)
{
MetaObject::CopyInfo(_tube);
}
void MetaScene::
NObjects(int nobjects)
{
m_NObjects = nobjects;
}
int MetaScene::
NObjects(void) const
{
return m_NObjects;
}
void MetaScene::
AddObject(MetaObject* object)
{
m_ObjectList.push_back(object);
}
bool MetaScene::
Read(const char *_headerName)
{
if(META_DEBUG) std::cout << "MetaScene: Read" << std::endl;
int i = 0;
char suf[80];
suf[0] = '\0';
if(MET_GetFileSuffixPtr(_headerName, &i))
{
strcpy(suf, &_headerName[i]);
}
M_Destroy();
Clear();
M_SetupReadFields();
if(_headerName != NULL)
{
strcpy(m_FileName, _headerName);
}
if(META_DEBUG) std::cout << "MetaScene: Read: Opening stream" << std::endl;
M_PrepareNewReadStream();
m_ReadStream->open(m_FileName, std::ios::binary | std::ios::in);
if(!m_ReadStream->is_open())
{
std::cout << "MetaScene: Read: Cannot open file" << std::endl;
return false;
}
if(!M_Read())
{
std::cout << "MetaScene: Read: Cannot parse file" << std::endl;
m_ReadStream->close();
return false;
}
if(_headerName != NULL)
{
strcpy(m_FileName, _headerName);
}
if(m_Event)
{
m_Event->StartReading(m_NObjects);
}
/** Objects should be added here */
for(i=0;i<m_NObjects;i++)
{
if(META_DEBUG) std::cout << MET_ReadType(*m_ReadStream) << std::endl;
if(m_Event)
{
m_Event->SetCurrentIteration(i+1);
}
if(!strncmp(MET_ReadType(*m_ReadStream),"Tube",4) ||
(MET_ReadType(*m_ReadStream) == NULL && !strcmp(suf, "tre")))
{
MetaTube* tube = new MetaTube();
tube->SetEvent(m_Event);
tube->ReadStream(m_NDims,m_ReadStream);
m_ObjectList.push_back(tube);
}
else if(!strncmp(MET_ReadType(*m_ReadStream),"Ellipse",7) ||
(MET_ReadType(*m_ReadStream) == NULL && !strcmp(suf, "elp")))
{
MetaEllipse* ellipse = new MetaEllipse();
ellipse->SetEvent(m_Event);
ellipse->ReadStream(m_NDims,m_ReadStream);
m_ObjectList.push_back(ellipse);
}
else if(!strncmp(MET_ReadType(*m_ReadStream),"Gaussian",8) ||
(MET_ReadType(*m_ReadStream) == NULL && !strcmp(suf, "gau")))
{
MetaGaussian* gaussian = new MetaGaussian();
gaussian->SetEvent(m_Event);
gaussian->ReadStream(m_NDims,m_ReadStream);
m_ObjectList.push_back(gaussian);
}
else if(!strncmp(MET_ReadType(*m_ReadStream),"Image",5) ||
(MET_ReadType(*m_ReadStream) == NULL &&
(!strcmp(suf, "mhd") || !strcmp(suf, "mha"))))
{
MetaImage* image = new MetaImage();
image->SetEvent(m_Event);
image->ReadStream(m_NDims,m_ReadStream);
m_ObjectList.push_back(image);
}
else if(!strncmp(MET_ReadType(*m_ReadStream),"Blob",4) ||
(MET_ReadType(*m_ReadStream) == NULL && !strcmp(suf, "blb")))
{
MetaBlob* blob = new MetaBlob();
blob->SetEvent(m_Event);
blob->ReadStream(m_NDims,m_ReadStream);
m_ObjectList.push_back(blob);
}
else if(!strncmp(MET_ReadType(*m_ReadStream),"Landmark",8) ||
(MET_ReadType(*m_ReadStream) == NULL && !strcmp(suf, "ldm")))
{
MetaLandmark* landmark = new MetaLandmark();
landmark->SetEvent(m_Event);
landmark->ReadStream(m_NDims,m_ReadStream);
m_ObjectList.push_back(landmark);
}
else if(!strncmp(MET_ReadType(*m_ReadStream),"Surface",5) ||
(MET_ReadType(*m_ReadStream) == NULL && !strcmp(suf, "suf")))
{
MetaSurface* surface = new MetaSurface();
surface->SetEvent(m_Event);
surface->ReadStream(m_NDims,m_ReadStream);
m_ObjectList.push_back(surface);
}
else if(!strncmp(MET_ReadType(*m_ReadStream),"Line",5) ||
(MET_ReadType(*m_ReadStream) == NULL && !strcmp(suf, "lin")))
{
MetaLine* line = new MetaLine();
line->SetEvent(m_Event);
line->ReadStream(m_NDims,m_ReadStream);
m_ObjectList.push_back(line);
}
else if(!strncmp(MET_ReadType(*m_ReadStream),"Group",5) ||
(MET_ReadType(*m_ReadStream) == NULL && !strcmp(suf, "grp")))
{
MetaGroup* group = new MetaGroup();
group->SetEvent(m_Event);
group->ReadStream(m_NDims,m_ReadStream);
m_ObjectList.push_back(group);
}
else if(!strncmp(MET_ReadType(*m_ReadStream),"AffineTransform",15) ||
(MET_ReadType(*m_ReadStream) == NULL && !strcmp(suf, "trn")))
{
MetaGroup* group = new MetaGroup();
group->SetEvent(m_Event);
group->ReadStream(m_NDims,m_ReadStream);
m_ObjectList.push_back(group);
}
else if(!strncmp(MET_ReadType(*m_ReadStream),"Mesh",4) ||
(MET_ReadType(*m_ReadStream) == NULL && !strcmp(suf, "msh")))
{
MetaMesh* mesh = new MetaMesh();
mesh->SetEvent(m_Event);
mesh->ReadStream(m_NDims,m_ReadStream);
m_ObjectList.push_back(mesh);
}
}
if(m_Event)
{
m_Event->StopReading();
}
m_ReadStream->close();
return true;
}
//
//
//
bool MetaScene::
Write(const char *_headName)
{
if(META_DEBUG) std::cout << "MetaScene: Write" << std::endl;
if(_headName != NULL)
{
FileName(_headName);
}
// Set the number of objects based on the net list
//ObjectListType::const_iterator itNet = m_ObjectList.begin();
m_NObjects = m_ObjectList.size();
M_SetupWriteFields();
if(!m_WriteStream)
{
m_WriteStream = new std::ofstream;
}
#ifdef __sgi
// Create the file. This is required on some older sgi's
std::ofstream tFile(m_FileName,std::ios::out);
tFile.close();
#endif
m_WriteStream->open(m_FileName, std::ios::binary | std::ios::out);
if(!m_WriteStream->is_open())
{
return false;
delete m_WriteStream;
m_WriteStream = 0;
}
M_Write();
m_WriteStream->close();
delete m_WriteStream;
m_WriteStream = 0;
/** Then we write all the objects in the scene */
ObjectListType::iterator it = m_ObjectList.begin();
while(it != m_ObjectList.end())
{
(*it)->BinaryData(this->BinaryData());
(*it)->Append(_headName);
it++;
}
return true;
}
/** Clear tube information */
void MetaScene::
Clear(void)
{
if(META_DEBUG) std::cout << "MetaScene: Clear" << std::endl;
MetaObject::Clear();
// Delete the list of pointers to objects in the scene.
ObjectListType::iterator it = m_ObjectList.begin();
while(it != m_ObjectList.end())
{
MetaObject* object = *it;
it++;
delete object;
}
m_ObjectList.clear();
}
/** Destroy tube information */
void MetaScene::
M_Destroy(void)
{
MetaObject::M_Destroy();
}
/** Set Read fields */
void MetaScene::
M_SetupReadFields(void)
{
if(META_DEBUG) std::cout << "MetaScene: M_SetupReadFields" << std::endl;
MetaObject::M_SetupReadFields();
MET_FieldRecordType * mF;
mF = new MET_FieldRecordType;
MET_InitReadField(mF, "NObjects", MET_INT, false);
mF->required = true;
mF->terminateRead = true;
m_Fields.push_back(mF);
mF = MET_GetFieldRecord("ElementSpacing", &m_Fields);
mF->required = false;
}
void MetaScene::
M_SetupWriteFields(void)
{
strcpy(m_ObjectTypeName,"Scene");
MetaObject::M_SetupWriteFields();
MET_FieldRecordType * mF;
mF = new MET_FieldRecordType;
MET_InitWriteField(mF, "NObjects", MET_INT, m_NObjects);
m_Fields.push_back(mF);
}
bool MetaScene::
M_Read(void)
{
if(META_DEBUG) std::cout<<"MetaScene: M_Read: Loading Header"<<std::endl;
if(strncmp(MET_ReadType(*m_ReadStream),"Scene",5))
{
m_NObjects = 1;
return true;
}
if(!MetaObject::M_Read())
{
std::cout << "MetaScene: M_Read: Error parsing file" << std::endl;
return false;
}
if(META_DEBUG) std::cout << "MetaScene: M_Read: Parsing Header" << std::endl;
MET_FieldRecordType * mF;
mF = MET_GetFieldRecord("NObjects", &m_Fields);
if(mF->defined)
{
m_NObjects= (int)mF->value[0];
}
return true;
}
bool MetaScene::
M_Write(void)
{
if(!MetaObject::M_Write())
{
std::cout << "MetaScene: M_Write: Error parsing file" << std::endl;
return false;
}
return true;
}
<commit_msg>ENH: Scene does not contain a transform, color, etc. Default write fields updated accordingly.<commit_after>#include <stdio.h>
#include <ctype.h>
#include <iostream>
#include <fstream>
#include <string>
#include <metaUtils.h>
#include <metaObject.h>
#include <metaScene.h>
#include <metaTube.h>
#include <metaEllipse.h>
#include <metaGaussian.h>
#include <metaImage.h>
#include <metaBlob.h>
#include <metaLandmark.h>
#include <metaLine.h>
#include <metaGroup.h>
#include <metaSurface.h>
#include <metaLandmark.h>
#include <metaMesh.h>
//
// MetaScene Constructors
//
MetaScene::
MetaScene()
:MetaObject()
{
if(META_DEBUG) std::cout << "MetaScene()" << std::endl;
Clear();
}
//
MetaScene::
MetaScene(const MetaScene *_scene)
:MetaObject()
{
if(META_DEBUG) std::cout << "MetaScene()" << std::endl;
Clear();
CopyInfo(_scene);
}
//
MetaScene::
MetaScene(unsigned int dim)
:MetaObject(dim)
{
if(META_DEBUG) std::cout << "MetaScene()" << std::endl;
Clear();
}
/** Destructor */
MetaScene::
~MetaScene()
{
Clear();
M_Destroy();
}
//
void MetaScene::
PrintInfo() const
{
MetaObject::PrintInfo();
std::cout << "Number of Objects = " << m_NObjects << std::endl;
}
void MetaScene::
CopyInfo(const MetaScene * _tube)
{
MetaObject::CopyInfo(_tube);
}
void MetaScene::
NObjects(int nobjects)
{
m_NObjects = nobjects;
}
int MetaScene::
NObjects(void) const
{
return m_NObjects;
}
void MetaScene::
AddObject(MetaObject* object)
{
m_ObjectList.push_back(object);
}
bool MetaScene::
Read(const char *_headerName)
{
if(META_DEBUG) std::cout << "MetaScene: Read" << std::endl;
int i = 0;
char suf[80];
suf[0] = '\0';
if(MET_GetFileSuffixPtr(_headerName, &i))
{
strcpy(suf, &_headerName[i]);
}
M_Destroy();
Clear();
M_SetupReadFields();
if(_headerName != NULL)
{
strcpy(m_FileName, _headerName);
}
if(META_DEBUG) std::cout << "MetaScene: Read: Opening stream" << std::endl;
M_PrepareNewReadStream();
m_ReadStream->open(m_FileName, std::ios::binary | std::ios::in);
if(!m_ReadStream->is_open())
{
std::cout << "MetaScene: Read: Cannot open file" << std::endl;
return false;
}
if(!M_Read())
{
std::cout << "MetaScene: Read: Cannot parse file" << std::endl;
m_ReadStream->close();
return false;
}
if(_headerName != NULL)
{
strcpy(m_FileName, _headerName);
}
if(m_Event)
{
m_Event->StartReading(m_NObjects);
}
/** Objects should be added here */
for(i=0;i<m_NObjects;i++)
{
if(META_DEBUG) std::cout << MET_ReadType(*m_ReadStream) << std::endl;
if(m_Event)
{
m_Event->SetCurrentIteration(i+1);
}
if(!strncmp(MET_ReadType(*m_ReadStream),"Tube",4) ||
(MET_ReadType(*m_ReadStream) == NULL && !strcmp(suf, "tre")))
{
MetaTube* tube = new MetaTube();
tube->SetEvent(m_Event);
tube->ReadStream(m_NDims,m_ReadStream);
m_ObjectList.push_back(tube);
}
else if(!strncmp(MET_ReadType(*m_ReadStream),"Ellipse",7) ||
(MET_ReadType(*m_ReadStream) == NULL && !strcmp(suf, "elp")))
{
MetaEllipse* ellipse = new MetaEllipse();
ellipse->SetEvent(m_Event);
ellipse->ReadStream(m_NDims,m_ReadStream);
m_ObjectList.push_back(ellipse);
}
else if(!strncmp(MET_ReadType(*m_ReadStream),"Gaussian",8) ||
(MET_ReadType(*m_ReadStream) == NULL && !strcmp(suf, "gau")))
{
MetaGaussian* gaussian = new MetaGaussian();
gaussian->SetEvent(m_Event);
gaussian->ReadStream(m_NDims,m_ReadStream);
m_ObjectList.push_back(gaussian);
}
else if(!strncmp(MET_ReadType(*m_ReadStream),"Image",5) ||
(MET_ReadType(*m_ReadStream) == NULL &&
(!strcmp(suf, "mhd") || !strcmp(suf, "mha"))))
{
MetaImage* image = new MetaImage();
image->SetEvent(m_Event);
image->ReadStream(m_NDims,m_ReadStream);
m_ObjectList.push_back(image);
}
else if(!strncmp(MET_ReadType(*m_ReadStream),"Blob",4) ||
(MET_ReadType(*m_ReadStream) == NULL && !strcmp(suf, "blb")))
{
MetaBlob* blob = new MetaBlob();
blob->SetEvent(m_Event);
blob->ReadStream(m_NDims,m_ReadStream);
m_ObjectList.push_back(blob);
}
else if(!strncmp(MET_ReadType(*m_ReadStream),"Landmark",8) ||
(MET_ReadType(*m_ReadStream) == NULL && !strcmp(suf, "ldm")))
{
MetaLandmark* landmark = new MetaLandmark();
landmark->SetEvent(m_Event);
landmark->ReadStream(m_NDims,m_ReadStream);
m_ObjectList.push_back(landmark);
}
else if(!strncmp(MET_ReadType(*m_ReadStream),"Surface",5) ||
(MET_ReadType(*m_ReadStream) == NULL && !strcmp(suf, "suf")))
{
MetaSurface* surface = new MetaSurface();
surface->SetEvent(m_Event);
surface->ReadStream(m_NDims,m_ReadStream);
m_ObjectList.push_back(surface);
}
else if(!strncmp(MET_ReadType(*m_ReadStream),"Line",5) ||
(MET_ReadType(*m_ReadStream) == NULL && !strcmp(suf, "lin")))
{
MetaLine* line = new MetaLine();
line->SetEvent(m_Event);
line->ReadStream(m_NDims,m_ReadStream);
m_ObjectList.push_back(line);
}
else if(!strncmp(MET_ReadType(*m_ReadStream),"Group",5) ||
(MET_ReadType(*m_ReadStream) == NULL && !strcmp(suf, "grp")))
{
MetaGroup* group = new MetaGroup();
group->SetEvent(m_Event);
group->ReadStream(m_NDims,m_ReadStream);
m_ObjectList.push_back(group);
}
else if(!strncmp(MET_ReadType(*m_ReadStream),"AffineTransform",15) ||
(MET_ReadType(*m_ReadStream) == NULL && !strcmp(suf, "trn")))
{
MetaGroup* group = new MetaGroup();
group->SetEvent(m_Event);
group->ReadStream(m_NDims,m_ReadStream);
m_ObjectList.push_back(group);
}
else if(!strncmp(MET_ReadType(*m_ReadStream),"Mesh",4) ||
(MET_ReadType(*m_ReadStream) == NULL && !strcmp(suf, "msh")))
{
MetaMesh* mesh = new MetaMesh();
mesh->SetEvent(m_Event);
mesh->ReadStream(m_NDims,m_ReadStream);
m_ObjectList.push_back(mesh);
}
}
if(m_Event)
{
m_Event->StopReading();
}
m_ReadStream->close();
return true;
}
//
//
//
bool MetaScene::
Write(const char *_headName)
{
if(META_DEBUG) std::cout << "MetaScene: Write" << std::endl;
if(_headName != NULL)
{
FileName(_headName);
}
// Set the number of objects based on the net list
//ObjectListType::const_iterator itNet = m_ObjectList.begin();
m_NObjects = m_ObjectList.size();
M_SetupWriteFields();
if(!m_WriteStream)
{
m_WriteStream = new std::ofstream;
}
#ifdef __sgi
// Create the file. This is required on some older sgi's
std::ofstream tFile(m_FileName,std::ios::out);
tFile.close();
#endif
m_WriteStream->open(m_FileName, std::ios::binary | std::ios::out);
if(!m_WriteStream->is_open())
{
return false;
delete m_WriteStream;
m_WriteStream = 0;
}
M_Write();
m_WriteStream->close();
delete m_WriteStream;
m_WriteStream = 0;
/** Then we write all the objects in the scene */
ObjectListType::iterator it = m_ObjectList.begin();
while(it != m_ObjectList.end())
{
(*it)->BinaryData(this->BinaryData());
(*it)->Append(_headName);
it++;
}
return true;
}
/** Clear tube information */
void MetaScene::
Clear(void)
{
if(META_DEBUG) std::cout << "MetaScene: Clear" << std::endl;
MetaObject::Clear();
// Delete the list of pointers to objects in the scene.
ObjectListType::iterator it = m_ObjectList.begin();
while(it != m_ObjectList.end())
{
MetaObject* object = *it;
it++;
delete object;
}
m_ObjectList.clear();
}
/** Destroy tube information */
void MetaScene::
M_Destroy(void)
{
MetaObject::M_Destroy();
}
/** Set Read fields */
void MetaScene::
M_SetupReadFields(void)
{
if(META_DEBUG) std::cout << "MetaScene: M_SetupReadFields" << std::endl;
MetaObject::M_SetupReadFields();
MET_FieldRecordType * mF;
mF = new MET_FieldRecordType;
MET_InitReadField(mF, "NObjects", MET_INT, false);
mF->required = true;
mF->terminateRead = true;
m_Fields.push_back(mF);
mF = MET_GetFieldRecord("ElementSpacing", &m_Fields);
mF->required = false;
}
void MetaScene::
M_SetupWriteFields(void)
{
this->ClearFields();
MET_FieldRecordType * mF;
if(strlen(m_Comment)>0)
{
mF = new MET_FieldRecordType;
MET_InitWriteField(mF, "Comment", MET_STRING, strlen(m_Comment), m_Comment);
m_Fields.push_back(mF);
}
strcpy(m_ObjectTypeName,"Scene");
mF = new MET_FieldRecordType;
MET_InitWriteField(mF, "ObjectType", MET_STRING, strlen(m_ObjectTypeName),
m_ObjectTypeName);
m_Fields.push_back(mF);
mF = new MET_FieldRecordType;
MET_InitWriteField(mF, "NDims", MET_INT, m_NDims);
m_Fields.push_back(mF);
mF = new MET_FieldRecordType;
MET_InitWriteField(mF, "NObjects", MET_INT, m_NObjects);
m_Fields.push_back(mF);
}
bool MetaScene::
M_Read(void)
{
if(META_DEBUG) std::cout<<"MetaScene: M_Read: Loading Header"<<std::endl;
if(strncmp(MET_ReadType(*m_ReadStream),"Scene",5))
{
m_NObjects = 1;
return true;
}
if(!MetaObject::M_Read())
{
std::cout << "MetaScene: M_Read: Error parsing file" << std::endl;
return false;
}
if(META_DEBUG) std::cout << "MetaScene: M_Read: Parsing Header" << std::endl;
MET_FieldRecordType * mF;
mF = MET_GetFieldRecord("NObjects", &m_Fields);
if(mF->defined)
{
m_NObjects= (int)mF->value[0];
}
return true;
}
bool MetaScene::
M_Write(void)
{
if(!MetaObject::M_Write())
{
std::cout << "MetaScene: M_Write: Error parsing file" << std::endl;
return false;
}
return true;
}
<|endoftext|>
|
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/initfiles/p9_fbc_ioe_dl_scom.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
#include "p9_fbc_ioe_dl_scom.H"
#include <stdint.h>
#include <stddef.h>
#include <fapi2.H>
using namespace fapi2;
constexpr uint64_t literal_0x0B = 0x0B;
constexpr uint64_t literal_0xF = 0xF;
constexpr uint64_t literal_0b111 = 0b111;
constexpr uint64_t literal_0x6 = 0x6;
constexpr uint64_t literal_0x7 = 0x7;
fapi2::ReturnCode p9_fbc_ioe_dl_scom(const fapi2::Target<fapi2::TARGET_TYPE_XBUS>& TGT0,
const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& TGT1)
{
{
fapi2::ATTR_EC_Type l_chip_ec;
fapi2::ATTR_NAME_Type l_chip_id;
FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_NAME, TGT1, l_chip_id));
FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_EC, TGT1, l_chip_ec));
fapi2::buffer<uint64_t> l_scom_buffer;
{
FAPI_TRY(fapi2::getScom( TGT0, 0x601180aull, l_scom_buffer ));
constexpr auto l_PB_IOE_LL1_CONFIG_LINK_PAIR_ON = 0x1;
l_scom_buffer.insert<0, 1, 63, uint64_t>(l_PB_IOE_LL1_CONFIG_LINK_PAIR_ON );
constexpr auto l_PB_IOE_LL1_CONFIG_CRC_LANE_ID_ON = 0x1;
l_scom_buffer.insert<2, 1, 63, uint64_t>(l_PB_IOE_LL1_CONFIG_CRC_LANE_ID_ON );
if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) )
{
l_scom_buffer.insert<12, 4, 60, uint64_t>(literal_0x0B );
}
else if (((l_chip_id == 0x5) && (l_chip_ec == 0x20)) || ((l_chip_id == 0x5) && (l_chip_ec == 0x21))
|| ((l_chip_id == 0x5) && (l_chip_ec == 0x22)) || ((l_chip_id == 0x6) && (l_chip_ec == 0x10)) )
{
l_scom_buffer.insert<11, 5, 59, uint64_t>(literal_0x0B );
}
l_scom_buffer.insert<28, 4, 60, uint64_t>(literal_0xF );
constexpr auto l_PB_IOE_LL1_CONFIG_SL_UE_CRC_ERR_ON = 0x1;
l_scom_buffer.insert<4, 1, 63, uint64_t>(l_PB_IOE_LL1_CONFIG_SL_UE_CRC_ERR_ON );
FAPI_TRY(fapi2::putScom(TGT0, 0x601180aull, l_scom_buffer));
}
{
FAPI_TRY(fapi2::getScom( TGT0, 0x6011818ull, l_scom_buffer ));
l_scom_buffer.insert<8, 3, 61, uint64_t>(literal_0b111 );
l_scom_buffer.insert<4, 4, 60, uint64_t>(literal_0xF );
l_scom_buffer.insert<0, 4, 60, uint64_t>(literal_0x6 );
FAPI_TRY(fapi2::putScom(TGT0, 0x6011818ull, l_scom_buffer));
}
{
FAPI_TRY(fapi2::getScom( TGT0, 0x6011819ull, l_scom_buffer ));
if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) )
{
l_scom_buffer.insert<8, 2, 62, uint64_t>(literal_0b111 );
}
else if (((l_chip_id == 0x5) && (l_chip_ec == 0x20)) || ((l_chip_id == 0x5) && (l_chip_ec == 0x21))
|| ((l_chip_id == 0x5) && (l_chip_ec == 0x22)) || ((l_chip_id == 0x6) && (l_chip_ec == 0x10)) )
{
l_scom_buffer.insert<8, 3, 61, uint64_t>(literal_0b111 );
}
l_scom_buffer.insert<4, 4, 60, uint64_t>(literal_0xF );
l_scom_buffer.insert<0, 4, 60, uint64_t>(literal_0x7 );
FAPI_TRY(fapi2::putScom(TGT0, 0x6011819ull, l_scom_buffer));
}
};
fapi_try_exit:
return fapi2::current_err;
}
<commit_msg>Adding p9c_11 support.<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/initfiles/p9_fbc_ioe_dl_scom.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
#include "p9_fbc_ioe_dl_scom.H"
#include <stdint.h>
#include <stddef.h>
#include <fapi2.H>
using namespace fapi2;
constexpr uint64_t literal_0x0B = 0x0B;
constexpr uint64_t literal_0xF = 0xF;
constexpr uint64_t literal_0b111 = 0b111;
constexpr uint64_t literal_0x6 = 0x6;
constexpr uint64_t literal_0x7 = 0x7;
fapi2::ReturnCode p9_fbc_ioe_dl_scom(const fapi2::Target<fapi2::TARGET_TYPE_XBUS>& TGT0,
const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& TGT1)
{
{
fapi2::ATTR_EC_Type l_chip_ec;
fapi2::ATTR_NAME_Type l_chip_id;
FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_NAME, TGT1, l_chip_id));
FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_EC, TGT1, l_chip_ec));
fapi2::buffer<uint64_t> l_scom_buffer;
{
FAPI_TRY(fapi2::getScom( TGT0, 0x601180aull, l_scom_buffer ));
constexpr auto l_PB_IOE_LL1_CONFIG_LINK_PAIR_ON = 0x1;
l_scom_buffer.insert<0, 1, 63, uint64_t>(l_PB_IOE_LL1_CONFIG_LINK_PAIR_ON );
constexpr auto l_PB_IOE_LL1_CONFIG_CRC_LANE_ID_ON = 0x1;
l_scom_buffer.insert<2, 1, 63, uint64_t>(l_PB_IOE_LL1_CONFIG_CRC_LANE_ID_ON );
if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) )
{
l_scom_buffer.insert<12, 4, 60, uint64_t>(literal_0x0B );
}
else if (((l_chip_id == 0x5) && (l_chip_ec == 0x20)) || ((l_chip_id == 0x5) && (l_chip_ec == 0x21))
|| ((l_chip_id == 0x5) && (l_chip_ec == 0x22)) || ((l_chip_id == 0x6) && (l_chip_ec == 0x10)) || ((l_chip_id == 0x6)
&& (l_chip_ec == 0x11)) )
{
l_scom_buffer.insert<11, 5, 59, uint64_t>(literal_0x0B );
}
l_scom_buffer.insert<28, 4, 60, uint64_t>(literal_0xF );
constexpr auto l_PB_IOE_LL1_CONFIG_SL_UE_CRC_ERR_ON = 0x1;
l_scom_buffer.insert<4, 1, 63, uint64_t>(l_PB_IOE_LL1_CONFIG_SL_UE_CRC_ERR_ON );
FAPI_TRY(fapi2::putScom(TGT0, 0x601180aull, l_scom_buffer));
}
{
FAPI_TRY(fapi2::getScom( TGT0, 0x6011818ull, l_scom_buffer ));
l_scom_buffer.insert<8, 3, 61, uint64_t>(literal_0b111 );
l_scom_buffer.insert<4, 4, 60, uint64_t>(literal_0xF );
l_scom_buffer.insert<0, 4, 60, uint64_t>(literal_0x6 );
FAPI_TRY(fapi2::putScom(TGT0, 0x6011818ull, l_scom_buffer));
}
{
FAPI_TRY(fapi2::getScom( TGT0, 0x6011819ull, l_scom_buffer ));
if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) )
{
l_scom_buffer.insert<8, 2, 62, uint64_t>(literal_0b111 );
}
else if (((l_chip_id == 0x5) && (l_chip_ec == 0x20)) || ((l_chip_id == 0x5) && (l_chip_ec == 0x21))
|| ((l_chip_id == 0x5) && (l_chip_ec == 0x22)) || ((l_chip_id == 0x6) && (l_chip_ec == 0x10)) || ((l_chip_id == 0x6)
&& (l_chip_ec == 0x11)) )
{
l_scom_buffer.insert<8, 3, 61, uint64_t>(literal_0b111 );
}
l_scom_buffer.insert<4, 4, 60, uint64_t>(literal_0xF );
l_scom_buffer.insert<0, 4, 60, uint64_t>(literal_0x7 );
FAPI_TRY(fapi2::putScom(TGT0, 0x6011819ull, l_scom_buffer));
}
};
fapi_try_exit:
return fapi2::current_err;
}
<|endoftext|>
|
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/initfiles/p9_fbc_ioo_dl_scom.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
#ifndef _INIT_P9_FBC_IOO_DL_SCOM_PROCEDURE_H_
#define _INIT_P9_FBC_IOO_DL_SCOM_PROCEDURE_H_
#include <stddef.h>
#include <stdint.h>
#include <fapi2.H>
typedef fapi2::ReturnCode (*p9_fbc_ioo_dl_scom_FP_t)(const fapi2::Target<fapi2::TARGET_TYPE_OBUS>&,
const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>&);
extern "C"
{
fapi2::ReturnCode p9_fbc_ioo_dl_scom(const fapi2::Target<fapi2::TARGET_TYPE_OBUS>& TGT0,
const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& TGT1);
}
#endif
<commit_msg>Set TRAIN_TIME to 0 for simulation.<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/initfiles/p9_fbc_ioo_dl_scom.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
#ifndef _INIT_P9_FBC_IOO_DL_SCOM_PROCEDURE_H_
#define _INIT_P9_FBC_IOO_DL_SCOM_PROCEDURE_H_
#include <stddef.h>
#include <stdint.h>
#include <fapi2.H>
typedef fapi2::ReturnCode (*p9_fbc_ioo_dl_scom_FP_t)(const fapi2::Target<fapi2::TARGET_TYPE_OBUS>&,
const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>&, const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM>&);
extern "C"
{
fapi2::ReturnCode p9_fbc_ioo_dl_scom(const fapi2::Target<fapi2::TARGET_TYPE_OBUS>& TGT0,
const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& TGT1, const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM>& TGT2);
}
#endif
<|endoftext|>
|
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/perv/p9_update_security_ctrl.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
//------------------------------------------------------------------------------
/// @file p9_update_security_ctrl.H
///
/// @brief To set SUL(Secure Update Lock) bit to lock down SAB + SBE SEEPROM and to set TDP(TPM Deconfig Protect) Bit
/// Decision to set SUL is based on if Chip is in Secure mode(SAB bit is 1)
/// Decision to set TDP is based on an attribute : ATTR_SECUREBOOT_PROTECT_DECONFIGURED_TPM
///
//------------------------------------------------------------------------------
// *HWP HW Owner : Santosh Balasubramanian <[email protected]>
// *HWP HW Backup Owner : Srinivas V Naga <[email protected]>
// *HWP FW Owner : Dan Crowell <[email protected]>
// *HWP Team : Perv
// *HWP Level : 2
// *HWP Consumed by : HB
//------------------------------------------------------------------------------
#ifndef P9_UPDATE_SECURITY_CTRL_H_
#define P9_UPDATE_SECURITY_CTRL_H_
#include <fapi2.H>
typedef fapi2::ReturnCode (*p9_update_security_ctrl_FP_t)(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>&,
bool );
///
/// @param[in] i_target_chip Reference to TARGET_TYPE_PROC_CHIP target
/// @param[in] i_force_security Forces setting of SUL and TDP (if attribute is set)
/// @return FAPI2_RC_SUCCESS if success, else error code.
extern "C"
{
fapi2::ReturnCode p9_update_security_ctrl(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip,
bool i_force_security = false);
}
#endif
<commit_msg>Update hardware procedure metadata<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/perv/p9_update_security_ctrl.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
//------------------------------------------------------------------------------
/// @file p9_update_security_ctrl.H
///
/// @brief To set SUL(Secure Update Lock) bit to lock down SAB + SBE SEEPROM and to set TDP(TPM Deconfig Protect) Bit
/// Decision to set SUL is based on if Chip is in Secure mode(SAB bit is 1)
/// Decision to set TDP is based on an attribute : ATTR_SECUREBOOT_PROTECT_DECONFIGURED_TPM
///
//------------------------------------------------------------------------------
// *HWP HW Owner : Santosh Balasubramanian <[email protected]>
// *HWP HW Backup Owner : Srinivas V Naga <[email protected]>
// *HWP FW Owner : Dan Crowell <[email protected]>
// *HWP Team : Perv
// *HWP Level : 3
// *HWP Consumed by : HB
//------------------------------------------------------------------------------
#ifndef P9_UPDATE_SECURITY_CTRL_H_
#define P9_UPDATE_SECURITY_CTRL_H_
#include <fapi2.H>
typedef fapi2::ReturnCode (*p9_update_security_ctrl_FP_t)(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>&,
bool );
///
/// @param[in] i_target_chip Reference to TARGET_TYPE_PROC_CHIP target
/// @param[in] i_force_security Forces setting of SUL and TDP (if attribute is set)
/// @return FAPI2_RC_SUCCESS if success, else error code.
extern "C"
{
fapi2::ReturnCode p9_update_security_ctrl(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip,
bool i_force_security = false);
}
#endif
<|endoftext|>
|
<commit_before>#include "search.h"
#include "logging.h"
#include <boost/algorithm/string.hpp>
#include <iostream>
void SearchParams::setSearchTerms(const std::string & terms) {
search_field_ = terms;
//split search terms, and remove empty ones
boost::split(search_terms_, terms, boost::is_any_of(" "));
auto end_it = std::remove_if(search_terms_.begin(), search_terms_.end(), [](const std::string & s)-> bool { return s.empty(); });
search_terms_.erase(end_it, search_terms_.end());
regex_fail_ = false;
if(useRegex()) {
buildRegex();
} else {
search_regexes_.clear();
}
}
void SearchParams::buildRegex() {
regex_fail_ = false;
search_regexes_.clear();
search_regexes_.reserve(search_terms_.size());
for(const std::string & st : search_terms_) {
try {
search_regexes_.emplace_back(st, std::regex::ECMAScript | std::regex::optimize | (case_sensitive_ ? std::regex::flag_type(0) : std::regex::icase));
} catch (std::exception &) {
search_regexes_.clear();
regex_fail_ = true;
}
}
}
bool SearchParams::filterByName(const RefRecord * record) {
// Feels a bit messy using all these lambdas, and also I'm a bit skeptical if it all getting optimized well
const auto string_search = [this](const std::string & haystack) -> bool {
if(case_sensitive_) {
const auto case_sensitive_single_search = [&haystack](const std::string & needle) -> bool {
return haystack.cend() != std::search(haystack.begin(), haystack.end(), needle.begin(), needle.end());
};
return std::all_of(search_terms_.cbegin(), search_terms_.cend(), case_sensitive_single_search);
} else {
const auto case_insensitive_comparator = [](const char ch1, const char ch2) -> bool { return ::toupper(ch1) == ::toupper(ch2); };
const auto case_insensitive_single_search = [&case_insensitive_comparator, &haystack](const std::string & needle) -> bool {
return haystack.cend() != std::search(haystack.begin(), haystack.end(), needle.begin(), needle.end(), case_insensitive_comparator);
};
return std::all_of(search_terms_.cbegin(), search_terms_.cend(), case_insensitive_single_search);
}
};
const auto regex_search = [this](const std::string & haystack) -> bool {
auto regex_single_search = [&haystack](const std::regex & r) -> bool {
return std::regex_search(haystack.cbegin(), haystack.cend(), r);
};
return std::all_of(search_regexes_.cbegin(), search_regexes_.cend(), regex_single_search);
};
const std::string & haystack = record->getName();
if(false == search_terms_.empty()) {
if(use_regex_) {
if(false == regex_search(haystack)) {
return false;
}
} else {
if(false == string_search(haystack)) {
return false;
}
}
}
return true;
}
bool SearchParams::filterByTime(const RefRecord * record, const std::chrono::system_clock::time_point now) {
if(!change_detection_) {
return true;
}
float timediff;
if(only_large_changes_) {
timediff = float(std::chrono::duration_cast<std::chrono::seconds>(now - record->getLastBigUpdateTime()).count());
} else {
timediff = float(std::chrono::duration_cast<std::chrono::seconds>(now - record->getLastUpdateTime()).count());
}
if(timediff > 10.f) {
return false;
}
return true;
}
void SearchParams::freshSearch(std::vector<RefRecord *> & results_out, const std::vector<RefRecord *> & commandrefs, const std::vector<RefRecord *> & datarefs) {
std::back_insert_iterator<std::vector<RefRecord *>> result_inserter = std::back_inserter(results_out);
std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
results_out.clear();
//actually perform the search
if(include_drs_) {
std::copy_if(datarefs.cbegin(), datarefs.cend(), result_inserter, [this, now](const RefRecord * r) -> bool { return filterByTimeAndName(r, now); });
}
if(include_crs_) {
std::copy_if(commandrefs.cbegin(), commandrefs.cend(), result_inserter, [this, now](const RefRecord * r) -> bool { return filterByTimeAndName(r, now); });
}
sort(results_out);
}
void SearchParams::updateSearch(std::vector<RefRecord *> & results_in_out, const std::vector<RefRecord *> & new_refs, const std::vector<RefRecord *> & changed_cr, const std::vector<RefRecord *> & changed_dr) {
std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
if(change_detection_) {
//filter existing results by change date and not search term
auto new_end = std::remove_if(results_in_out.begin(), results_in_out.end(), [this, now](const RefRecord * r) -> bool { return false == filterByTime(r, now); });
results_in_out.erase(new_end, results_in_out.end());
//changed dr/cr filter by search term, and possibly filter out small changes.
{
auto filter = [this, now](const RefRecord * r) -> bool {
if(useOnlyLargeChanges()) { // need additional filtering for only bigger changes then
return filterByTimeAndName(r, now);
} else {
return filterByName(r);
}
};
working_buffer.clear();
std::back_insert_iterator<std::vector<RefRecord *>> working_inserter = std::back_inserter(working_buffer);
if(include_drs_) {
std::copy_if(changed_dr.cbegin(), changed_dr.cend(), working_inserter, filter);
}
if(include_crs_) {
std::copy_if(changed_cr.cbegin(), changed_cr.cend(), working_inserter, filter);
}
sort(working_buffer);
inplace_union(results_in_out, working_buffer);
}
//new refs, filter by search term and by update date
if(false == new_refs.empty()) {
working_buffer.clear();
std::back_insert_iterator<std::vector<RefRecord *>> working_inserter = std::back_inserter(working_buffer);
std::copy_if(new_refs.cbegin(), new_refs.cend(), working_inserter, [this, now](const RefRecord * r) -> bool { return filterByTimeAndName(r, now); });
sort(working_buffer);
inplace_union(results_in_out, working_buffer);
}
} else {
//keep existing results
//filter new refs by search term only
if(false == new_refs.empty()) {
working_buffer.clear();
std::back_insert_iterator<std::vector<RefRecord *>> working_inserter = std::back_inserter(working_buffer);
std::copy_if(new_refs.cbegin(), new_refs.cend(), working_inserter, [this, now](const RefRecord * r) -> bool { return filterByTimeAndName(r, now); });
sort(working_buffer);
inplace_union(results_in_out, working_buffer);
}
}
}<commit_msg>In change detection mode, don't remove changed datarefs even though they haven't changed in a while.<commit_after>#include "search.h"
#include "logging.h"
#include <boost/algorithm/string.hpp>
#include <iostream>
void SearchParams::setSearchTerms(const std::string & terms) {
search_field_ = terms;
//split search terms, and remove empty ones
boost::split(search_terms_, terms, boost::is_any_of(" "));
auto end_it = std::remove_if(search_terms_.begin(), search_terms_.end(), [](const std::string & s)-> bool { return s.empty(); });
search_terms_.erase(end_it, search_terms_.end());
regex_fail_ = false;
if(useRegex()) {
buildRegex();
} else {
search_regexes_.clear();
}
}
void SearchParams::buildRegex() {
regex_fail_ = false;
search_regexes_.clear();
search_regexes_.reserve(search_terms_.size());
for(const std::string & st : search_terms_) {
try {
search_regexes_.emplace_back(st, std::regex::ECMAScript | std::regex::optimize | (case_sensitive_ ? std::regex::flag_type(0) : std::regex::icase));
} catch (std::exception &) {
search_regexes_.clear();
regex_fail_ = true;
}
}
}
bool SearchParams::filterByName(const RefRecord * record) {
// Feels a bit messy using all these lambdas, and also I'm a bit skeptical if it all getting optimized well
const auto string_search = [this](const std::string & haystack) -> bool {
if(case_sensitive_) {
const auto case_sensitive_single_search = [&haystack](const std::string & needle) -> bool {
return haystack.cend() != std::search(haystack.begin(), haystack.end(), needle.begin(), needle.end());
};
return std::all_of(search_terms_.cbegin(), search_terms_.cend(), case_sensitive_single_search);
} else {
const auto case_insensitive_comparator = [](const char ch1, const char ch2) -> bool { return ::toupper(ch1) == ::toupper(ch2); };
const auto case_insensitive_single_search = [&case_insensitive_comparator, &haystack](const std::string & needle) -> bool {
return haystack.cend() != std::search(haystack.begin(), haystack.end(), needle.begin(), needle.end(), case_insensitive_comparator);
};
return std::all_of(search_terms_.cbegin(), search_terms_.cend(), case_insensitive_single_search);
}
};
const auto regex_search = [this](const std::string & haystack) -> bool {
auto regex_single_search = [&haystack](const std::regex & r) -> bool {
return std::regex_search(haystack.cbegin(), haystack.cend(), r);
};
return std::all_of(search_regexes_.cbegin(), search_regexes_.cend(), regex_single_search);
};
const std::string & haystack = record->getName();
if(false == search_terms_.empty()) {
if(use_regex_) {
if(false == regex_search(haystack)) {
return false;
}
} else {
if(false == string_search(haystack)) {
return false;
}
}
}
return true;
}
bool SearchParams::filterByTime(const RefRecord * record, const std::chrono::system_clock::time_point now) {
if(!change_detection_) {
return true;
}
float timediff;
if(only_large_changes_) {
timediff = float(std::chrono::duration_cast<std::chrono::seconds>(now - record->getLastBigUpdateTime()).count());
} else {
timediff = float(std::chrono::duration_cast<std::chrono::seconds>(now - record->getLastUpdateTime()).count());
}
if(timediff > 10.f) {
return false;
}
return true;
}
void SearchParams::freshSearch(std::vector<RefRecord *> & results_out, const std::vector<RefRecord *> & commandrefs, const std::vector<RefRecord *> & datarefs) {
std::back_insert_iterator<std::vector<RefRecord *>> result_inserter = std::back_inserter(results_out);
std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
results_out.clear();
//actually perform the search
if(include_drs_) {
std::copy_if(datarefs.cbegin(), datarefs.cend(), result_inserter, [this, now](const RefRecord * r) -> bool { return filterByTimeAndName(r, now); });
}
if(include_crs_) {
std::copy_if(commandrefs.cbegin(), commandrefs.cend(), result_inserter, [this, now](const RefRecord * r) -> bool { return filterByTimeAndName(r, now); });
}
sort(results_out);
}
void SearchParams::updateSearch(std::vector<RefRecord *> & results_in_out, const std::vector<RefRecord *> & new_refs, const std::vector<RefRecord *> & changed_cr, const std::vector<RefRecord *> & changed_dr) {
std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
if(change_detection_) {
//filter existing results by change date and not search term
/*
auto new_end = std::remove_if(results_in_out.begin(), results_in_out.end(), [this, now](const RefRecord * r) -> bool { return false == filterByTime(r, now); });
results_in_out.erase(new_end, results_in_out.end());
*/
//changed dr/cr filter by search term, and possibly filter out small changes.
{
auto filter = [this, now](const RefRecord * r) -> bool {
if(useOnlyLargeChanges()) { // need additional filtering for only bigger changes then
return filterByTimeAndName(r, now);
} else {
return filterByName(r);
}
};
working_buffer.clear();
std::back_insert_iterator<std::vector<RefRecord *>> working_inserter = std::back_inserter(working_buffer);
if(include_drs_) {
std::copy_if(changed_dr.cbegin(), changed_dr.cend(), working_inserter, filter);
}
if(include_crs_) {
std::copy_if(changed_cr.cbegin(), changed_cr.cend(), working_inserter, filter);
}
sort(working_buffer);
inplace_union(results_in_out, working_buffer);
}
//new refs, filter by search term and by update date
if(false == new_refs.empty()) {
working_buffer.clear();
std::back_insert_iterator<std::vector<RefRecord *>> working_inserter = std::back_inserter(working_buffer);
std::copy_if(new_refs.cbegin(), new_refs.cend(), working_inserter, [this, now](const RefRecord * r) -> bool { return filterByTimeAndName(r, now); });
sort(working_buffer);
inplace_union(results_in_out, working_buffer);
}
} else {
//keep existing results
//filter new refs by search term only
if(false == new_refs.empty()) {
working_buffer.clear();
std::back_insert_iterator<std::vector<RefRecord *>> working_inserter = std::back_inserter(working_buffer);
std::copy_if(new_refs.cbegin(), new_refs.cend(), working_inserter, [this, now](const RefRecord * r) -> bool { return filterByTimeAndName(r, now); });
sort(working_buffer);
inplace_union(results_in_out, working_buffer);
}
}
}<|endoftext|>
|
<commit_before>//===--- CommentDumper.cpp - Dumping implementation for Comment ASTs ------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "clang/AST/CommentVisitor.h"
#include "llvm/Support/raw_ostream.h"
namespace clang {
namespace comments {
namespace {
class CommentDumper: public comments::ConstCommentVisitor<CommentDumper> {
raw_ostream &OS;
SourceManager *SM;
unsigned IndentLevel;
public:
CommentDumper(raw_ostream &OS, SourceManager *SM) :
OS(OS), SM(SM), IndentLevel(0)
{ }
void dumpIndent() const {
for (unsigned i = 1, e = IndentLevel; i < e; ++i)
OS << " ";
}
void dumpLocation(SourceLocation Loc) {
if (SM)
Loc.print(OS, *SM);
}
void dumpSourceRange(const Comment *C);
void dumpComment(const Comment *C);
void dumpSubtree(const Comment *C);
// Inline content.
void visitTextComment(const TextComment *C);
void visitInlineCommandComment(const InlineCommandComment *C);
void visitHTMLStartTagComment(const HTMLStartTagComment *C);
void visitHTMLEndTagComment(const HTMLEndTagComment *C);
// Block content.
void visitParagraphComment(const ParagraphComment *C);
void visitBlockCommandComment(const BlockCommandComment *C);
void visitParamCommandComment(const ParamCommandComment *C);
void visitVerbatimBlockComment(const VerbatimBlockComment *C);
void visitVerbatimBlockLineComment(const VerbatimBlockLineComment *C);
void visitVerbatimLineComment(const VerbatimLineComment *C);
void visitFullComment(const FullComment *C);
};
void CommentDumper::dumpSourceRange(const Comment *C) {
if (!SM)
return;
SourceRange SR = C->getSourceRange();
OS << " <";
dumpLocation(SR.getBegin());
if (SR.getBegin() != SR.getEnd()) {
OS << ", ";
dumpLocation(SR.getEnd());
}
OS << ">";
}
void CommentDumper::dumpComment(const Comment *C) {
dumpIndent();
OS << "(" << C->getCommentKindName()
<< " " << (void *) C;
dumpSourceRange(C);
}
void CommentDumper::dumpSubtree(const Comment *C) {
++IndentLevel;
if (C) {
visit(C);
for (Comment::child_iterator I = C->child_begin(),
E = C->child_end();
I != E; ++I) {
OS << '\n';
dumpSubtree(*I);
}
OS << ')';
} else {
dumpIndent();
OS << "<<<NULL>>>";
}
--IndentLevel;
}
void CommentDumper::visitTextComment(const TextComment *C) {
dumpComment(C);
OS << " Text=\"" << C->getText() << "\"";
}
void CommentDumper::visitInlineCommandComment(const InlineCommandComment *C) {
dumpComment(C);
for (unsigned i = 0, e = C->getNumArgs(); i != e; ++i)
OS << " Arg[" << i << "]=\"" << C->getArgText(i) << "\"";
}
void CommentDumper::visitHTMLStartTagComment(const HTMLStartTagComment *C) {
dumpComment(C);
OS << " Name=\"" << C->getTagName() << "\"";
if (C->getNumAttrs() != 0) {
OS << " Attrs: ";
for (unsigned i = 0, e = C->getNumAttrs(); i != e; ++i) {
const HTMLStartTagComment::Attribute &Attr = C->getAttr(i);
OS << " \"" << Attr.Name << "=\"" << Attr.Value << "\"";
}
}
if (C->isSelfClosing())
OS << " SelfClosing";
}
void CommentDumper::visitHTMLEndTagComment(const HTMLEndTagComment *C) {
dumpComment(C);
OS << " Name=\"" << C->getTagName() << "\"";
}
void CommentDumper::visitParagraphComment(const ParagraphComment *C) {
dumpComment(C);
}
void CommentDumper::visitBlockCommandComment(const BlockCommandComment *C) {
dumpComment(C);
OS << " Name=\"" << C->getCommandName() << "\"";
}
void CommentDumper::visitParamCommandComment(const ParamCommandComment *C) {
dumpComment(C);
OS << " " << ParamCommandComment::getDirectionAsString(C->getDirection());
if (C->isDirectionExplicit())
OS << " explicitly";
else
OS << " implicitly";
if (C->hasParamName()) {
OS << " Param=\"" << C->getParamName() << "\"";
}
}
void CommentDumper::visitVerbatimBlockComment(const VerbatimBlockComment *C) {
dumpComment(C);
OS << " Name=\"" << C->getCommandName() << "\""
" CloseName=\"" << C->getCloseName() << "\"";
}
void CommentDumper::visitVerbatimBlockLineComment(const VerbatimBlockLineComment *C) {
dumpComment(C);
OS << " Text=\"" << C->getText() << "\"";
}
void CommentDumper::visitVerbatimLineComment(const VerbatimLineComment *C) {
dumpComment(C);
OS << " Text=\"" << C->getText() << "\"";
}
void CommentDumper::visitFullComment(const FullComment *C) {
dumpComment(C);
}
} // unnamed namespace
void Comment::dump(llvm::raw_ostream &OS, SourceManager *SM) const {
CommentDumper D(llvm::errs(), SM);
D.dumpSubtree(this);
llvm::errs() << '\n';
}
} // end namespace comments
} // end namespace clang
<commit_msg>Comment::dump(): show name of inline command<commit_after>//===--- CommentDumper.cpp - Dumping implementation for Comment ASTs ------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "clang/AST/CommentVisitor.h"
#include "llvm/Support/raw_ostream.h"
namespace clang {
namespace comments {
namespace {
class CommentDumper: public comments::ConstCommentVisitor<CommentDumper> {
raw_ostream &OS;
SourceManager *SM;
unsigned IndentLevel;
public:
CommentDumper(raw_ostream &OS, SourceManager *SM) :
OS(OS), SM(SM), IndentLevel(0)
{ }
void dumpIndent() const {
for (unsigned i = 1, e = IndentLevel; i < e; ++i)
OS << " ";
}
void dumpLocation(SourceLocation Loc) {
if (SM)
Loc.print(OS, *SM);
}
void dumpSourceRange(const Comment *C);
void dumpComment(const Comment *C);
void dumpSubtree(const Comment *C);
// Inline content.
void visitTextComment(const TextComment *C);
void visitInlineCommandComment(const InlineCommandComment *C);
void visitHTMLStartTagComment(const HTMLStartTagComment *C);
void visitHTMLEndTagComment(const HTMLEndTagComment *C);
// Block content.
void visitParagraphComment(const ParagraphComment *C);
void visitBlockCommandComment(const BlockCommandComment *C);
void visitParamCommandComment(const ParamCommandComment *C);
void visitVerbatimBlockComment(const VerbatimBlockComment *C);
void visitVerbatimBlockLineComment(const VerbatimBlockLineComment *C);
void visitVerbatimLineComment(const VerbatimLineComment *C);
void visitFullComment(const FullComment *C);
};
void CommentDumper::dumpSourceRange(const Comment *C) {
if (!SM)
return;
SourceRange SR = C->getSourceRange();
OS << " <";
dumpLocation(SR.getBegin());
if (SR.getBegin() != SR.getEnd()) {
OS << ", ";
dumpLocation(SR.getEnd());
}
OS << ">";
}
void CommentDumper::dumpComment(const Comment *C) {
dumpIndent();
OS << "(" << C->getCommentKindName()
<< " " << (void *) C;
dumpSourceRange(C);
}
void CommentDumper::dumpSubtree(const Comment *C) {
++IndentLevel;
if (C) {
visit(C);
for (Comment::child_iterator I = C->child_begin(),
E = C->child_end();
I != E; ++I) {
OS << '\n';
dumpSubtree(*I);
}
OS << ')';
} else {
dumpIndent();
OS << "<<<NULL>>>";
}
--IndentLevel;
}
void CommentDumper::visitTextComment(const TextComment *C) {
dumpComment(C);
OS << " Text=\"" << C->getText() << "\"";
}
void CommentDumper::visitInlineCommandComment(const InlineCommandComment *C) {
dumpComment(C);
OS << " Name=\"" << C->getCommandName() << "\"";
for (unsigned i = 0, e = C->getNumArgs(); i != e; ++i)
OS << " Arg[" << i << "]=\"" << C->getArgText(i) << "\"";
}
void CommentDumper::visitHTMLStartTagComment(const HTMLStartTagComment *C) {
dumpComment(C);
OS << " Name=\"" << C->getTagName() << "\"";
if (C->getNumAttrs() != 0) {
OS << " Attrs: ";
for (unsigned i = 0, e = C->getNumAttrs(); i != e; ++i) {
const HTMLStartTagComment::Attribute &Attr = C->getAttr(i);
OS << " \"" << Attr.Name << "=\"" << Attr.Value << "\"";
}
}
if (C->isSelfClosing())
OS << " SelfClosing";
}
void CommentDumper::visitHTMLEndTagComment(const HTMLEndTagComment *C) {
dumpComment(C);
OS << " Name=\"" << C->getTagName() << "\"";
}
void CommentDumper::visitParagraphComment(const ParagraphComment *C) {
dumpComment(C);
}
void CommentDumper::visitBlockCommandComment(const BlockCommandComment *C) {
dumpComment(C);
OS << " Name=\"" << C->getCommandName() << "\"";
}
void CommentDumper::visitParamCommandComment(const ParamCommandComment *C) {
dumpComment(C);
OS << " " << ParamCommandComment::getDirectionAsString(C->getDirection());
if (C->isDirectionExplicit())
OS << " explicitly";
else
OS << " implicitly";
if (C->hasParamName()) {
OS << " Param=\"" << C->getParamName() << "\"";
}
}
void CommentDumper::visitVerbatimBlockComment(const VerbatimBlockComment *C) {
dumpComment(C);
OS << " Name=\"" << C->getCommandName() << "\""
" CloseName=\"" << C->getCloseName() << "\"";
}
void CommentDumper::visitVerbatimBlockLineComment(const VerbatimBlockLineComment *C) {
dumpComment(C);
OS << " Text=\"" << C->getText() << "\"";
}
void CommentDumper::visitVerbatimLineComment(const VerbatimLineComment *C) {
dumpComment(C);
OS << " Text=\"" << C->getText() << "\"";
}
void CommentDumper::visitFullComment(const FullComment *C) {
dumpComment(C);
}
} // unnamed namespace
void Comment::dump(llvm::raw_ostream &OS, SourceManager *SM) const {
CommentDumper D(llvm::errs(), SM);
D.dumpSubtree(this);
llvm::errs() << '\n';
}
} // end namespace comments
} // end namespace clang
<|endoftext|>
|
<commit_before>
#ifdef _WIN32
#define GLEW_STATIC 1
#include <GL/glew.h>
#endif
#include "efk.GraphicsGL.h"
#include <EffekseerRendererGL/EffekseerRenderer/EffekseerRendererGL.GLExtension.h>
#include <EffekseerRendererGL/EffekseerRenderer/GraphicsDevice.h>
namespace efk
{
RenderTextureGL::RenderTextureGL(Graphics* graphics)
: graphics(graphics)
{
}
RenderTextureGL::~RenderTextureGL()
{
}
bool RenderTextureGL::Initialize(Effekseer::Tool::Vector2DI size, Effekseer::Backend::TextureFormatType format, uint32_t multisample)
{
auto g = (GraphicsGL*)graphics;
auto gd = g->GetGraphicsDevice().DownCast<EffekseerRendererGL::Backend::GraphicsDevice>();
Effekseer::Backend::RenderTextureParameter param;
param.Format = format;
param.SamplingCount = multisample;
param.Size = {size.X, size.Y};
texture_ = gd->CreateRenderTexture(param).DownCast<EffekseerRendererGL::Backend::Texture>();
this->size_ = size;
this->samplingCount_ = multisample;
this->format_ = format;
if (multisample <= 1 && texture_ != nullptr)
{
GLint bound;
glGetIntegerv(GL_TEXTURE_BINDING_2D, &bound);
glBindTexture(GL_TEXTURE_2D, texture_->GetBuffer());
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glBindTexture(GL_TEXTURE_2D, bound);
}
return texture_ != nullptr;
}
DepthTextureGL::DepthTextureGL(Graphics* graphics)
: graphics_(graphics)
{
}
DepthTextureGL::~DepthTextureGL()
{
}
bool DepthTextureGL::Initialize(int32_t width, int32_t height, uint32_t multisample)
{
if (glGetError() != GL_NO_ERROR)
return false;
auto g = (GraphicsGL*)graphics_;
auto gd = g->GetGraphicsDevice().DownCast<EffekseerRendererGL::Backend::GraphicsDevice>();
Effekseer::Backend::DepthTextureParameter param;
param.Format = Effekseer::Backend::TextureFormatType::D32;
param.SamplingCount = multisample;
param.Size = {width, height};
texture_ = gd->CreateDepthTexture(param).DownCast<EffekseerRendererGL::Backend::Texture>();
if (multisample <= 1 && texture_ != nullptr)
{
glBindTexture(GL_TEXTURE_2D, texture_->GetBuffer());
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glBindTexture(GL_TEXTURE_2D, 0);
}
return texture_ != nullptr;
}
bool SaveTextureGL(std::vector<Effekseer::Color>& dst, GLuint texture, int32_t width, int32_t height)
{
GLCheckError();
std::vector<Effekseer::Color> src;
src.resize(width * height);
dst.resize(width * height);
glBindTexture(GL_TEXTURE_2D, texture);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, src.data());
glBindTexture(GL_TEXTURE_2D, 0);
auto size = width * height;
dst.resize(size);
for (auto y = 0; y < height; y++)
{
for (auto x = 0; x < width; x++)
{
dst[x + y * width] = src[x + (height - y - 1) * width];
}
}
GLCheckError();
return true;
}
GraphicsGL::GraphicsGL()
{
}
GraphicsGL::~GraphicsGL()
{
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glDeleteFramebuffers(1, &frameBuffer);
glDeleteFramebuffers(1, &frameBufferForCopySrc);
glDeleteFramebuffers(1, &frameBufferForCopyDst);
backTarget.reset();
}
bool GraphicsGL::Initialize(void* windowHandle, int32_t windowWidth, int32_t windowHeight)
{
this->windowWidth = windowWidth;
this->windowHeight = windowHeight;
glDisable(GL_FRAMEBUFFER_SRGB);
glGenFramebuffers(1, &frameBuffer);
// for bug
glBindFramebuffer(GL_FRAMEBUFFER, frameBuffer);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
GLCheckError();
// TODO
// create VAO
// for glBlitFramebuffer
glGenFramebuffers(1, &frameBufferForCopySrc);
glGenFramebuffers(1, &frameBufferForCopyDst);
graphicsDevice_ = Effekseer::MakeRefPtr<EffekseerRendererGL::Backend::GraphicsDevice>(EffekseerRendererGL::OpenGLDeviceType::OpenGL3);
return true;
}
void GraphicsGL::CopyTo(Effekseer::Backend::TextureRef src, Effekseer::Backend::TextureRef dst)
{
if (src->GetSize() != dst->GetSize())
return;
if (src->GetFormat() != dst->GetFormat())
return;
if (src->GetSamplingCount() != dst->GetSamplingCount())
{
ResolveRenderTarget(src, dst);
}
else
{
// Copy to background
GLint backupFramebuffer;
glGetIntegerv(GL_FRAMEBUFFER_BINDING, &backupFramebuffer);
auto s = src.DownCast<EffekseerRendererGL::Backend::Texture>();
auto d = dst.DownCast<EffekseerRendererGL::Backend::Texture>();
if (s->GetSamplingCount() > 1)
{
glBindFramebuffer(GL_FRAMEBUFFER, frameBufferForCopySrc);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, s->GetRenderBuffer());
}
else
{
glBindFramebuffer(GL_FRAMEBUFFER, frameBufferForCopySrc);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, s->GetBuffer(), 0);
}
glBindTexture(GL_TEXTURE_2D, d->GetBuffer());
glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, dst->GetSize()[0], dst->GetSize()[1]);
glBindTexture(GL_TEXTURE_2D, 0);
glBindFramebuffer(GL_FRAMEBUFFER, backupFramebuffer);
}
}
void GraphicsGL::Resize(int32_t width, int32_t height)
{
this->windowWidth = width;
this->windowHeight = height;
ResetDevice();
glViewport(0, 0, this->windowWidth, this->windowHeight);
}
bool GraphicsGL::Present()
{
if (Presented != nullptr)
{
Presented();
}
return true;
}
void GraphicsGL::BeginScene()
{
}
void GraphicsGL::EndScene()
{
}
void GraphicsGL::SetRenderTarget(std::vector<Effekseer::Backend::TextureRef> renderTextures, Effekseer::Backend::TextureRef depthTexture)
{
assert(renderTextures.size() > 0);
GLCheckError();
// reset
for (int32_t i = 0; i < 4; i++)
{
glActiveTexture(GL_TEXTURE0 + i);
glBindTexture(GL_TEXTURE_2D, 0);
}
glActiveTexture(GL_TEXTURE0);
GLCheckError();
if (renderTextures[0] == nullptr)
{
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glDrawBuffer(GL_BACK);
glViewport(0, 0, windowWidth, windowHeight);
currentRenderTargetCount_ = 0;
hasDepthBuffer_ = true;
}
else
{
glBindFramebuffer(GL_FRAMEBUFFER, frameBuffer);
auto rt = renderTextures[0].DownCast<EffekseerRendererGL::Backend::Texture>();
auto dt = depthTexture.DownCast<EffekseerRendererGL::Backend::Texture>();
for (size_t i = 0; i < renderTextures.size(); i++)
{
auto rti = renderTextures[i].DownCast<EffekseerRendererGL::Backend::Texture>();
if (rti == nullptr)
{
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i, GL_RENDERBUFFER, 0);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i, GL_TEXTURE_2D, 0, 0);
}
else if (rti->GetSamplingCount() > 1)
{
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i, GL_RENDERBUFFER, rti->GetRenderBuffer());
}
else
{
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i, GL_TEXTURE_2D, rti->GetBuffer(), 0);
}
}
for (size_t i = renderTextures.size(); i < 4; i++)
{
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i, GL_RENDERBUFFER, 0);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i, GL_TEXTURE_2D, 0, 0);
}
if (dt != nullptr)
{
if (dt->GetSamplingCount() > 1)
{
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, dt->GetRenderBuffer());
}
else
{
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, dt->GetBuffer(), 0);
}
}
else
{
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, 0);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
}
static const GLenum bufs[] = {
GL_COLOR_ATTACHMENT0,
GL_COLOR_ATTACHMENT1,
GL_COLOR_ATTACHMENT2,
GL_COLOR_ATTACHMENT3,
};
glDrawBuffers(renderTextures.size(), bufs);
GLCheckError();
glViewport(0, 0, renderTextures[0]->GetSize()[0], renderTextures[0]->GetSize()[1]);
currentRenderTargetCount_ = renderTextures.size();
hasDepthBuffer_ = depthTexture != nullptr;
}
}
void GraphicsGL::SaveTexture(Effekseer::Backend::TextureRef texture, std::vector<Effekseer::Color>& pixels)
{
auto t = texture.DownCast<EffekseerRendererGL::Backend::Texture>();
pixels.resize(t->GetSize()[0] * t->GetSize()[1]);
SaveTextureGL(pixels, t->GetBuffer(), t->GetSize()[0], t->GetSize()[1]);
}
void GraphicsGL::Clear(Effekseer::Color color)
{
GLCheckError();
if (currentRenderTargetCount_ == 0)
{
GLbitfield bit = 0;
{
bit = bit | GL_COLOR_BUFFER_BIT;
glClearColor(color.R / 255.0f, color.G / 255.0f, color.B / 255.0f, color.A / 255.0f);
}
{
// Need that GL_DEPTH_TEST & WRITE are enabled
glEnable(GL_DEPTH_TEST);
glDepthMask(GL_TRUE);
bit = bit | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT;
glClearDepth(1.0f);
}
if (bit != 0)
{
glClear(bit);
}
}
else
{
std::array<float, 4> colorf = {color.R / 255.0f, color.G / 255.0f, color.B / 255.0f, color.A / 255.0f};
for (int32_t i = 0; i < currentRenderTargetCount_; i++)
{
glClearBufferfv(GL_COLOR, i, colorf.data());
GLCheckError();
}
if (hasDepthBuffer_)
{
float clearDepth[] = {1.0f};
glClearBufferfv(GL_DEPTH, 0, clearDepth);
GLCheckError();
}
}
GLCheckError();
}
void GraphicsGL::ResolveRenderTarget(Effekseer::Backend::TextureRef src, Effekseer::Backend::TextureRef dest)
{
auto rtSrc = src.DownCast<EffekseerRendererGL::Backend::Texture>();
auto rtDest = dest.DownCast<EffekseerRendererGL::Backend::Texture>();
GLint frameBufferBinding = 0;
glGetIntegerv(GL_FRAMEBUFFER_BINDING, &frameBufferBinding);
glBindFramebuffer(GL_READ_FRAMEBUFFER, frameBufferForCopySrc);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, frameBufferForCopyDst);
GLCheckError();
glFramebufferRenderbuffer(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, rtSrc->GetRenderBuffer());
glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, rtDest->GetBuffer(), 0);
GLCheckError();
glBlitFramebuffer(0, 0, src->GetSize()[0], src->GetSize()[1], 0, 0, dest->GetSize()[0], dest->GetSize()[1], GL_COLOR_BUFFER_BIT, GL_NEAREST);
GLCheckError();
glFramebufferRenderbuffer(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, 0);
glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0);
GLCheckError();
glBindFramebuffer(GL_READ_FRAMEBUFFER, 0);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
glBindFramebuffer(GL_FRAMEBUFFER, frameBufferBinding);
}
void GraphicsGL::ResetDevice()
{
}
} // namespace efk
<commit_msg>Fix a bug where Recorder doesn't run in OpenGL<commit_after>
#ifdef _WIN32
#define GLEW_STATIC 1
#include <GL/glew.h>
#endif
#include "efk.GraphicsGL.h"
#include <EffekseerRendererGL/EffekseerRenderer/EffekseerRendererGL.GLExtension.h>
#include <EffekseerRendererGL/EffekseerRenderer/GraphicsDevice.h>
namespace efk
{
RenderTextureGL::RenderTextureGL(Graphics* graphics)
: graphics(graphics)
{
}
RenderTextureGL::~RenderTextureGL()
{
}
bool RenderTextureGL::Initialize(Effekseer::Tool::Vector2DI size, Effekseer::Backend::TextureFormatType format, uint32_t multisample)
{
auto g = (GraphicsGL*)graphics;
auto gd = g->GetGraphicsDevice().DownCast<EffekseerRendererGL::Backend::GraphicsDevice>();
Effekseer::Backend::RenderTextureParameter param;
param.Format = format;
param.SamplingCount = multisample;
param.Size = {size.X, size.Y};
texture_ = gd->CreateRenderTexture(param).DownCast<EffekseerRendererGL::Backend::Texture>();
this->size_ = size;
this->samplingCount_ = multisample;
this->format_ = format;
if (multisample <= 1 && texture_ != nullptr)
{
GLint bound;
glGetIntegerv(GL_TEXTURE_BINDING_2D, &bound);
glBindTexture(GL_TEXTURE_2D, texture_->GetBuffer());
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glBindTexture(GL_TEXTURE_2D, bound);
}
return texture_ != nullptr;
}
DepthTextureGL::DepthTextureGL(Graphics* graphics)
: graphics_(graphics)
{
}
DepthTextureGL::~DepthTextureGL()
{
}
bool DepthTextureGL::Initialize(int32_t width, int32_t height, uint32_t multisample)
{
if (glGetError() != GL_NO_ERROR)
return false;
auto g = (GraphicsGL*)graphics_;
auto gd = g->GetGraphicsDevice().DownCast<EffekseerRendererGL::Backend::GraphicsDevice>();
Effekseer::Backend::DepthTextureParameter param;
param.Format = Effekseer::Backend::TextureFormatType::D32;
param.SamplingCount = multisample;
param.Size = {width, height};
texture_ = gd->CreateDepthTexture(param).DownCast<EffekseerRendererGL::Backend::Texture>();
if (multisample <= 1 && texture_ != nullptr)
{
glBindTexture(GL_TEXTURE_2D, texture_->GetBuffer());
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glBindTexture(GL_TEXTURE_2D, 0);
}
return texture_ != nullptr;
}
bool SaveTextureGL(std::vector<Effekseer::Color>& dst, GLuint texture, int32_t width, int32_t height)
{
GLCheckError();
std::vector<Effekseer::Color> src;
src.resize(width * height);
dst.resize(width * height);
glBindTexture(GL_TEXTURE_2D, texture);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, src.data());
glBindTexture(GL_TEXTURE_2D, 0);
auto size = width * height;
dst.resize(size);
for (auto y = 0; y < height; y++)
{
for (auto x = 0; x < width; x++)
{
dst[x + y * width] = src[x + (height - y - 1) * width];
}
}
GLCheckError();
return true;
}
GraphicsGL::GraphicsGL()
{
}
GraphicsGL::~GraphicsGL()
{
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glDeleteFramebuffers(1, &frameBuffer);
glDeleteFramebuffers(1, &frameBufferForCopySrc);
glDeleteFramebuffers(1, &frameBufferForCopyDst);
backTarget.reset();
}
bool GraphicsGL::Initialize(void* windowHandle, int32_t windowWidth, int32_t windowHeight)
{
this->windowWidth = windowWidth;
this->windowHeight = windowHeight;
glDisable(GL_FRAMEBUFFER_SRGB);
glGenFramebuffers(1, &frameBuffer);
// for bug
glBindFramebuffer(GL_FRAMEBUFFER, frameBuffer);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
GLCheckError();
// TODO
// create VAO
// for glBlitFramebuffer
glGenFramebuffers(1, &frameBufferForCopySrc);
glGenFramebuffers(1, &frameBufferForCopyDst);
graphicsDevice_ = Effekseer::MakeRefPtr<EffekseerRendererGL::Backend::GraphicsDevice>(EffekseerRendererGL::OpenGLDeviceType::OpenGL3);
return true;
}
void GraphicsGL::CopyTo(Effekseer::Backend::TextureRef src, Effekseer::Backend::TextureRef dst)
{
if (src->GetSize() != dst->GetSize())
return;
if (src->GetFormat() != dst->GetFormat())
return;
if (src->GetSamplingCount() != dst->GetSamplingCount())
{
ResolveRenderTarget(src, dst);
}
else
{
// Copy to background
GLint backupFramebuffer;
glGetIntegerv(GL_FRAMEBUFFER_BINDING, &backupFramebuffer);
auto s = src.DownCast<EffekseerRendererGL::Backend::Texture>();
auto d = dst.DownCast<EffekseerRendererGL::Backend::Texture>();
if (s->GetSamplingCount() > 1)
{
glBindFramebuffer(GL_FRAMEBUFFER, frameBufferForCopySrc);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, s->GetRenderBuffer());
}
else
{
glBindFramebuffer(GL_FRAMEBUFFER, frameBufferForCopySrc);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, s->GetBuffer(), 0);
}
glBindTexture(GL_TEXTURE_2D, d->GetBuffer());
glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, dst->GetSize()[0], dst->GetSize()[1]);
glBindTexture(GL_TEXTURE_2D, 0);
glBindFramebuffer(GL_FRAMEBUFFER, backupFramebuffer);
}
}
void GraphicsGL::Resize(int32_t width, int32_t height)
{
this->windowWidth = width;
this->windowHeight = height;
ResetDevice();
glViewport(0, 0, this->windowWidth, this->windowHeight);
}
bool GraphicsGL::Present()
{
if (Presented != nullptr)
{
Presented();
}
return true;
}
void GraphicsGL::BeginScene()
{
}
void GraphicsGL::EndScene()
{
}
void GraphicsGL::SetRenderTarget(std::vector<Effekseer::Backend::TextureRef> renderTextures, Effekseer::Backend::TextureRef depthTexture)
{
assert(renderTextures.size() > 0);
GLCheckError();
// reset
for (int32_t i = 0; i < 4; i++)
{
glActiveTexture(GL_TEXTURE0 + i);
glBindTexture(GL_TEXTURE_2D, 0);
}
glActiveTexture(GL_TEXTURE0);
GLCheckError();
if (renderTextures[0] == nullptr)
{
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glDrawBuffer(GL_BACK);
glViewport(0, 0, windowWidth, windowHeight);
currentRenderTargetCount_ = 0;
hasDepthBuffer_ = true;
}
else
{
glBindFramebuffer(GL_FRAMEBUFFER, frameBuffer);
auto rt = renderTextures[0].DownCast<EffekseerRendererGL::Backend::Texture>();
auto dt = depthTexture.DownCast<EffekseerRendererGL::Backend::Texture>();
for (size_t i = 0; i < renderTextures.size(); i++)
{
auto rti = renderTextures[i].DownCast<EffekseerRendererGL::Backend::Texture>();
if (rti == nullptr)
{
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i, GL_RENDERBUFFER, 0);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i, GL_TEXTURE_2D, 0, 0);
}
else if (rti->GetSamplingCount() > 1)
{
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i, GL_RENDERBUFFER, rti->GetRenderBuffer());
}
else
{
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i, GL_TEXTURE_2D, rti->GetBuffer(), 0);
}
}
for (size_t i = renderTextures.size(); i < 4; i++)
{
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i, GL_RENDERBUFFER, 0);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i, GL_TEXTURE_2D, 0, 0);
}
if (dt != nullptr)
{
if (dt->GetSamplingCount() > 1)
{
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, dt->GetRenderBuffer());
}
else
{
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, dt->GetBuffer(), 0);
}
}
else
{
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, 0);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
}
static const GLenum bufs[] = {
GL_COLOR_ATTACHMENT0,
GL_COLOR_ATTACHMENT1,
GL_COLOR_ATTACHMENT2,
GL_COLOR_ATTACHMENT3,
};
glDrawBuffers(renderTextures.size(), bufs);
GLCheckError();
glViewport(0, 0, renderTextures[0]->GetSize()[0], renderTextures[0]->GetSize()[1]);
currentRenderTargetCount_ = renderTextures.size();
hasDepthBuffer_ = depthTexture != nullptr;
}
}
void GraphicsGL::SaveTexture(Effekseer::Backend::TextureRef texture, std::vector<Effekseer::Color>& pixels)
{
auto t = texture.DownCast<EffekseerRendererGL::Backend::Texture>();
pixels.resize(t->GetSize()[0] * t->GetSize()[1]);
SaveTextureGL(pixels, t->GetBuffer(), t->GetSize()[0], t->GetSize()[1]);
}
void GraphicsGL::Clear(Effekseer::Color color)
{
GLCheckError();
if (currentRenderTargetCount_ == 0)
{
GLbitfield bit = 0;
{
bit = bit | GL_COLOR_BUFFER_BIT;
glClearColor(color.R / 255.0f, color.G / 255.0f, color.B / 255.0f, color.A / 255.0f);
}
{
// Need that GL_DEPTH_TEST & WRITE are enabled
glEnable(GL_DEPTH_TEST);
glDepthMask(GL_TRUE);
bit = bit | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT;
glClearDepth(1.0f);
}
if (bit != 0)
{
glClear(bit);
}
}
else
{
std::array<float, 4> colorf = {color.R / 255.0f, color.G / 255.0f, color.B / 255.0f, color.A / 255.0f};
for (int32_t i = 0; i < currentRenderTargetCount_; i++)
{
glClearBufferfv(GL_COLOR, i, colorf.data());
GLCheckError();
}
if (hasDepthBuffer_)
{
glDepthMask(GL_TRUE);
float clearDepth[] = {1.0f};
glClearBufferfv(GL_DEPTH, 0, clearDepth);
GLCheckError();
}
}
GLCheckError();
}
void GraphicsGL::ResolveRenderTarget(Effekseer::Backend::TextureRef src, Effekseer::Backend::TextureRef dest)
{
auto rtSrc = src.DownCast<EffekseerRendererGL::Backend::Texture>();
auto rtDest = dest.DownCast<EffekseerRendererGL::Backend::Texture>();
GLint frameBufferBinding = 0;
glGetIntegerv(GL_FRAMEBUFFER_BINDING, &frameBufferBinding);
glBindFramebuffer(GL_READ_FRAMEBUFFER, frameBufferForCopySrc);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, frameBufferForCopyDst);
GLCheckError();
glFramebufferRenderbuffer(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, rtSrc->GetRenderBuffer());
glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, rtDest->GetBuffer(), 0);
GLCheckError();
glBlitFramebuffer(0, 0, src->GetSize()[0], src->GetSize()[1], 0, 0, dest->GetSize()[0], dest->GetSize()[1], GL_COLOR_BUFFER_BIT, GL_NEAREST);
GLCheckError();
glFramebufferRenderbuffer(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, 0);
glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0);
GLCheckError();
glBindFramebuffer(GL_READ_FRAMEBUFFER, 0);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
glBindFramebuffer(GL_FRAMEBUFFER, frameBufferBinding);
}
void GraphicsGL::ResetDevice()
{
}
} // namespace efk
<|endoftext|>
|
<commit_before>#ifndef test_entitygetpublicid
#define test_entitygetpublicid
/*
This c++ source file was generated by for Arabica
and is a derived work from the source document.
The source document contained the following notice:
Copyright (c) 2001-2004 World Wide Web Consortium,
(Massachusetts Institute of Technology, Institut National de
Recherche en Informatique et en Automatique, Keio University). All
Rights Reserved. This program is distributed under the W3C's Software
Intellectual Property License. This program is distributed in the
hope that it will be useful, but WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.
See W3C License http://www.w3.org/Consortium/Legal/ for more details.
*/
/**
* The "getPublicId()" method of an Entity node contains
* the public identifier associated with the entity, if
* one was specified.
*
* Retrieve the entity named "ent5" and access its
* public identifier. The string "entityURI" should be
* returned.
* @author NIST
* @author Mary Brady
* @see <a href="http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-core#ID-D7303025">http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-core#ID-D7303025</a>
* @see <a href="http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-core#ID-6ABAEB38">http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-core#ID-6ABAEB38</a>
* @see <a href="http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-core#ID-D7C29F3E">http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-core#ID-D7C29F3E</a>
*/
template<class string_type, class string_adaptor>
class entitygetpublicid : public DOMTestCase<string_type, string_adaptor>
{
typedef DOMTestCase<string_type, string_adaptor> baseT;
public:
entitygetpublicid(std::string name) : baseT(name)
{
// check if loaded documents are supported for content type
const std::string contentType = baseT::getContentType();
baseT::preload(contentType, "staff", false);
}
typedef typename Arabica::DOM::DOMImplementation<string_type, string_adaptor> DOMImplementation;
typedef typename Arabica::DOM::Document<string_type, string_adaptor> Document;
typedef typename Arabica::DOM::DocumentType<string_type, string_adaptor> DocumentType;
typedef typename Arabica::DOM::DocumentFragment<string_type, string_adaptor> DocumentFragment;
typedef typename Arabica::DOM::Node<string_type, string_adaptor> Node;
typedef typename Arabica::DOM::Element<string_type, string_adaptor> Element;
typedef typename Arabica::DOM::Attr<string_type, string_adaptor> Attr;
typedef typename Arabica::DOM::NodeList<string_type, string_adaptor> NodeList;
typedef typename Arabica::DOM::NamedNodeMap<string_type, string_adaptor> NamedNodeMap;
typedef typename Arabica::DOM::Entity<string_type, string_adaptor> Entity;
typedef typename Arabica::DOM::EntityReference<string_type, string_adaptor> EntityReference;
typedef typename Arabica::DOM::CharacterData<string_type, string_adaptor> CharacterData;
typedef typename Arabica::DOM::CDATASection<string_type, string_adaptor> CDATASection;
typedef typename Arabica::DOM::Text<string_type, string_adaptor> Text;
typedef typename Arabica::DOM::Comment<string_type, string_adaptor> Comment;
typedef typename Arabica::DOM::ProcessingInstruction<string_type, string_adaptor> ProcessingInstruction;
typedef typename Arabica::DOM::Notation<string_type, string_adaptor> Notation;
typedef typename Arabica::DOM::DOMException DOMException;
typedef string_type String;
typedef string_adaptor SA;
typedef bool boolean;
/*
* Runs the test case.
*/
void runTest()
{
Document doc;
DocumentType docType;
NamedNodeMap entityList;
Entity entityNode;
String publicId;
String systemId;
String notation;
doc = (Document) baseT::load("staff", false);
docType = doc.getDoctype();
baseT::assertNotNull(docType, __LINE__, __FILE__);
entityList = docType.getEntities();
baseT::assertNotNull(entityList, __LINE__, __FILE__);
entityNode = (Entity) entityList.getNamedItem(SA::construct_from_utf8("ent5"));
baseT::skipIfNull(entityNode);
publicId = entityNode.getPublicId();
baseT::assertEquals("entityURI", publicId, __LINE__, __FILE__);
systemId = entityNode.getSystemId();
baseT::assertURIEquals("systemId", "", "", "", "entityFile", "", "", "", false, systemId);
notation = entityNode.getNotationName();
baseT::assertEquals("notation1", notation, __LINE__, __FILE__);
}
/*
* Gets URI that identifies the test.
*/
std::string getTargetURI() const
{
return "http://www.w3.org/2001/DOM-Test-Suite/level1/core/entitygetpublicid";
}
};
#endif
<commit_msg>whitespace changes in generated code<commit_after>#ifndef test_entitygetpublicid
#define test_entitygetpublicid
/*
This c++ source file was generated by for Arabica
and is a derived work from the source document.
The source document contained the following notice:
Copyright (c) 2001-2004 World Wide Web Consortium,
(Massachusetts Institute of Technology, Institut National de
Recherche en Informatique et en Automatique, Keio University). All
Rights Reserved. This program is distributed under the W3C's Software
Intellectual Property License. This program is distributed in the
hope that it will be useful, but WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.
See W3C License http://www.w3.org/Consortium/Legal/ for more details.
*/
/**
* The "getPublicId()" method of an Entity node contains
* the public identifier associated with the entity, if
* one was specified.
*
* Retrieve the entity named "ent5" and access its
* public identifier. The string "entityURI" should be
* returned.
* @author NIST
* @author Mary Brady
* @see <a href="http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-core#ID-D7303025">http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-core#ID-D7303025</a>
* @see <a href="http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-core#ID-6ABAEB38">http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-core#ID-6ABAEB38</a>
* @see <a href="http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-core#ID-D7C29F3E">http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-core#ID-D7C29F3E</a>
*/
template<class string_type, class string_adaptor>
class entitygetpublicid : public DOMTestCase<string_type, string_adaptor>
{
typedef DOMTestCase<string_type, string_adaptor> baseT;
public:
entitygetpublicid(std::string name) : baseT(name)
{
// check if loaded documents are supported for content type
const std::string contentType = baseT::getContentType();
baseT::preload(contentType, "staff", false);
}
typedef typename Arabica::DOM::DOMImplementation<string_type, string_adaptor> DOMImplementation;
typedef typename Arabica::DOM::Document<string_type, string_adaptor> Document;
typedef typename Arabica::DOM::DocumentType<string_type, string_adaptor> DocumentType;
typedef typename Arabica::DOM::DocumentFragment<string_type, string_adaptor> DocumentFragment;
typedef typename Arabica::DOM::Node<string_type, string_adaptor> Node;
typedef typename Arabica::DOM::Element<string_type, string_adaptor> Element;
typedef typename Arabica::DOM::Attr<string_type, string_adaptor> Attr;
typedef typename Arabica::DOM::NodeList<string_type, string_adaptor> NodeList;
typedef typename Arabica::DOM::NamedNodeMap<string_type, string_adaptor> NamedNodeMap;
typedef typename Arabica::DOM::Entity<string_type, string_adaptor> Entity;
typedef typename Arabica::DOM::EntityReference<string_type, string_adaptor> EntityReference;
typedef typename Arabica::DOM::CharacterData<string_type, string_adaptor> CharacterData;
typedef typename Arabica::DOM::CDATASection<string_type, string_adaptor> CDATASection;
typedef typename Arabica::DOM::Text<string_type, string_adaptor> Text;
typedef typename Arabica::DOM::Comment<string_type, string_adaptor> Comment;
typedef typename Arabica::DOM::ProcessingInstruction<string_type, string_adaptor> ProcessingInstruction;
typedef typename Arabica::DOM::Notation<string_type, string_adaptor> Notation;
typedef typename Arabica::DOM::DOMException DOMException;
typedef string_type String;
typedef string_adaptor SA;
typedef bool boolean;
/*
* Runs the test case.
*/
void runTest()
{
Document doc;
DocumentType docType;
NamedNodeMap entityList;
Entity entityNode;
String publicId;
String systemId;
String notation;
doc = (Document) baseT::load("staff", false);
docType = doc.getDoctype();
baseT::assertNotNull(docType, __LINE__, __FILE__);
entityList = docType.getEntities();
baseT::assertNotNull(entityList, __LINE__, __FILE__);
entityNode = (Entity) entityList.getNamedItem(SA::construct_from_utf8("ent5"));
baseT::skipIfNull(entityNode);
publicId = entityNode.getPublicId();
baseT::assertEquals("entityURI", publicId, __LINE__, __FILE__);
systemId = entityNode.getSystemId();
baseT::assertURIEquals("systemId", "", "", "", "entityFile", "", "", "", false, systemId);
notation = entityNode.getNotationName();
baseT::assertEquals("notation1", notation, __LINE__, __FILE__);
}
/*
* Gets URI that identifies the test.
*/
std::string getTargetURI() const
{
return "http://www.w3.org/2001/DOM-Test-Suite/level1/core/entitygetpublicid";
}
};
#endif
<|endoftext|>
|
<commit_before>/*
* FUNCTION:
* ODBC driver -- developed/tested with unixodbc http://www.unixodbc.org
*
* ODBC is basically brain-damaged, and so is this driver.
* The problem is that ODBC forces you to guess how many columns there
* are in your reply, and etc. which we don't know a-priori. Also
* makes VARCHAR difficult (impossible ??) to support correctly!
* Blame it on SQLBindCol(), which is a terrible idea. @#$%^ Microsoft.
*
* Threading:
* ----------
* This class is thread-enabled but not thread-safe. Two threads should
* not try to use one instance of this class at the same time. Each
* thread should construct it's own instance of this class. This class
* uses no globals.
*
* HISTORY:
* Copyright (c) 2002,2008 Linas Vepstas <[email protected]>
* created by Linas Vepstas March 2002
* ported to C++ March 2008
*
* LICENSE:
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#ifdef HAVE_ODBC_STORAGE
#include <stack>
#include <string>
#include <sql.h>
#include <sqlext.h>
#include <stdio.h>
#include <opencog/util/exceptions.h>
#include <opencog/util/Logger.h>
#include <opencog/util/platform.h>
#include "odbcxx.h"
#define PERR(...) \
throw opencog::RuntimeException(TRACE_INFO, __VA_ARGS__);
/* =========================================================== */
#define PRINT_SQLERR(HTYPE,HAN) \
{ \
char sql_stat[10]; \
SQLSMALLINT msglen; \
SQLINTEGER err; \
char msg[200]; \
\
SQLGetDiagRec(HTYPE, HAN, 1, (SQLCHAR *) sql_stat, \
&err, (SQLCHAR*) msg, sizeof(msg), &msglen); \
opencog::logger().warn("(%ld) %s\n", (long int) err, msg); \
}
/* =========================================================== */
ODBCConnection::ODBCConnection(const char * uri)
{
SQLRETURN rc;
is_connected = false;
sql_hdbc = NULL;
sql_henv = NULL;
// We expect odbc://user:password/database
if (0 != strncmp("odbc://", uri, 7))
{
PERR("Invalid URI specified: %s", uri);
return;
}
uri += 7; // skip past odbc://
char* curi = strdup(uri);
char* username = curi;
char* authentication;
char* p = strchr(curi, ':');
if (p)
{
*p = 0;
authentication = ++p;
}
else
{
// Point at the null byte at the end of the string.
authentication = curi+strlen(curi);
p = curi;
}
p = strchr(p, '/');
if (!p)
{
free(curi);
PERR("Invalid URI specified: %s", uri);
}
*p = 0;
char *dbname = ++p;
/* Allocate environment handle */
rc = SQLAllocEnv(&sql_henv);
if ((SQL_SUCCESS != rc) and (SQL_SUCCESS_WITH_INFO != rc))
{
free(curi);
PERR("Can't SQLAllocEnv, rc=%d", rc);
return;
}
/* Set the ODBC version */
rc = SQLSetEnvAttr(sql_henv, SQL_ATTR_ODBC_VERSION,
(void*)SQL_OV_ODBC3, 0);
if ((SQL_SUCCESS != rc) and (SQL_SUCCESS_WITH_INFO != rc))
{
free(curi);
PRINT_SQLERR (SQL_HANDLE_ENV, sql_henv);
SQLFreeHandle(SQL_HANDLE_ENV, sql_henv);
sql_henv = NULL;
PERR("Can't SQLSetEnv, rc=%d", rc);
return;
}
/* Allocate the connection handle */
rc = SQLAllocConnect(sql_henv, &sql_hdbc);
if ((SQL_SUCCESS != rc) and (SQL_SUCCESS_WITH_INFO != rc))
{
free(curi);
PRINT_SQLERR (SQL_HANDLE_ENV, sql_henv);
SQLFreeHandle(SQL_HANDLE_ENV, sql_henv);
sql_henv = NULL;
PERR ("Can't SQLAllocConnect handle rc=%d", rc);
return;
}
/* set the timeout to 5 seconds ?? hack alert fixme */
// SQLSetConnectAttr(sql_hdbc, SQL_LOGIN_TIMEOUT, (SQLPOINTER *)5, 0);
rc = SQLConnect(sql_hdbc,
(SQLCHAR*) dbname, SQL_NTS,
(SQLCHAR*) username, SQL_NTS,
(SQLCHAR*) authentication, SQL_NTS);
if ((SQL_SUCCESS != rc) and (SQL_SUCCESS_WITH_INFO != rc))
{
free(curi);
PRINT_SQLERR (SQL_HANDLE_DBC, sql_hdbc);
SQLFreeHandle(SQL_HANDLE_DBC, sql_hdbc);
SQLFreeHandle(SQL_HANDLE_ENV, sql_henv);
sql_henv = NULL;
sql_hdbc = NULL;
PERR ("Can't perform SQLConnect rc=%d", rc);
return;
}
is_connected = true;
free(curi);
}
/* =========================================================== */
ODBCConnection::~ODBCConnection()
{
if (sql_hdbc)
{
SQLDisconnect(sql_hdbc);
SQLFreeHandle(SQL_HANDLE_DBC, sql_hdbc);
sql_hdbc = NULL;
}
if (sql_henv)
{
SQLFreeHandle(SQL_HANDLE_ENV, sql_henv);
sql_henv = NULL;
}
}
/* =========================================================== */
#define DEFAULT_NUM_COLS 50
ODBCRecordSet * ODBCConnection::get_record_set(void)
{
ODBCRecordSet *rs;
if (!free_pool.empty())
{
LLRecordSet* llrs = free_pool.top();
rs = dynamic_cast<ODBCRecordSet*>(llrs);
free_pool.pop();
rs->ncols = -1;
}
else
{
rs = new ODBCRecordSet(this);
}
rs->alloc_and_bind_cols(DEFAULT_NUM_COLS);
return rs;
}
/* =========================================================== */
void ODBCConnection::extract_error(const char *msg)
{
SQLRETURN ret;
SQLINTEGER i = 0;
SQLINTEGER native;
SQLCHAR state[7];
SQLCHAR text[256];
SQLSMALLINT len;
do
{
ret = SQLGetDiagRec(SQL_HANDLE_ENV, sql_henv, ++i,
state, &native, text, sizeof(text), &len);
if (SQL_SUCCEEDED(ret))
opencog::logger().warn("\t%s : %d : %d : %s\n",
state, i, native, text);
} while (ret == SQL_SUCCESS);
}
/* =========================================================== */
LLRecordSet *
ODBCConnection::exec(const char * buff)
{
if (!is_connected) return NULL;
ODBCRecordSet* rs = get_record_set();
SQLRETURN rc = SQLExecDirect(rs->sql_hstmt, (SQLCHAR *)buff, SQL_NTS);
/* If query returned no data, its not necessarily an error:
* its simply "no data", that's all.
*/
if (SQL_NO_DATA == rc)
{
rs->release();
return NULL;
}
if ((SQL_SUCCESS != rc) and (SQL_SUCCESS_WITH_INFO != rc))
{
PRINT_SQLERR (SQL_HANDLE_STMT, rs->sql_hstmt);
rs->release();
opencog::logger().warn("\tQuery was: %s\n", buff);
extract_error("exec");
PERR ("Can't perform query rc=%d ", rc);
return NULL;
}
/* Use numbr of columns to indicate that the query hasn't
* given results yet. */
rs->ncols = -1;
return rs;
}
/* =========================================================== */
#define DEFAULT_COLUMN_NAME_SIZE 121
#define DEFAULT_VARCHAR_SIZE 4040
void
ODBCRecordSet::alloc_and_bind_cols(int new_ncols)
{
int i;
// This static alloc of column names and values is crazy and
// bizarre, but it is driven by the fact that ODBC must be given
// mem locations in which to scribble it's results. Which is
// a nutty design, given that we don't know sizes of the columns
// in advance. Only Microsoft could invent something this nasty.
if (new_ncols > arrsize)
{
if (column_labels)
{
for (i=0; i<arrsize; i++)
{
if (column_labels[i])
{
delete[] column_labels[i];
}
}
delete[] column_labels;
}
if (column_datatype) delete[] column_datatype;
if (values)
{
for (i=0; i<arrsize; i++)
{
if (values[i])
{
delete[] values[i];
}
}
delete[] values;
}
if (vsizes) delete[] vsizes;
column_labels = new char*[new_ncols];
column_datatype = new int[new_ncols];
values = new char*[new_ncols];
vsizes = new int[new_ncols];
/* intialize */
for (i = 0; i<new_ncols; i++)
{
column_labels[i] = new char[DEFAULT_COLUMN_NAME_SIZE];
column_labels[i][0] = 0;
column_datatype[i] = 0;
values[i] = new char[DEFAULT_VARCHAR_SIZE];
vsizes[i] = DEFAULT_VARCHAR_SIZE;
values[i][0] = 0;
}
arrsize = new_ncols;
}
ODBCConnection* oconn = dynamic_cast<ODBCConnection*>(conn);
SQLRETURN rc = SQLAllocStmt (oconn->sql_hdbc, &sql_hstmt);
if ((SQL_SUCCESS != rc) and (SQL_SUCCESS_WITH_INFO != rc))
{
PRINT_SQLERR (SQL_HANDLE_STMT, sql_hstmt);
PERR("Can't allocate statement handle, rc=%d", rc);
/* oops memory leak */
return;
}
// IMPORTANT! MUST NOT BE ON STACK!! Else stack corruption will result.
// The ODBC driver really wants to write a return value here!
static SQLLEN bogus;
/* Initialize the newly realloc'ed entries */
for (i=0; i<new_ncols; i++)
{
rc = SQLBindCol(sql_hstmt, i+1, SQL_C_CHAR,
values[i], vsizes[i], &bogus);
if ((SQL_SUCCESS != rc) and (SQL_SUCCESS_WITH_INFO != rc))
{
PRINT_SQLERR (SQL_HANDLE_STMT, sql_hstmt);
PERR ("Can't bind col=%d rc=%d", i, rc);
return;
}
}
}
/* =========================================================== */
/* pseudo-private routine */
ODBCRecordSet::ODBCRecordSet(ODBCConnection* _conn)
: LLRecordSet(_conn)
{
sql_hstmt = NULL;
}
/* =========================================================== */
void
ODBCRecordSet::release(void)
{
ncols = -1;
// Avoid accidental double-release
if (NULL == sql_hstmt) return;
// SQLFreeStmt(sql_hstmt, SQL_UNBIND);
// SQLFreeStmt(sql_hstmt, SQL_CLOSE);
SQLFreeHandle(SQL_HANDLE_STMT, sql_hstmt);
sql_hstmt = NULL;
LLRecordSet::release();
}
/* =========================================================== */
ODBCRecordSet::~ODBCRecordSet()
{
for (int i=0; i<arrsize; i++)
{
delete[] column_labels[i];
delete[] values[i];
}
}
/* =========================================================== */
void
ODBCRecordSet::get_column_labels(void)
{
SQLSMALLINT _ncols;
SQLRETURN rc;
int i;
if (0 <= ncols) return;
/* If number of columns is negative, then we haven't
* gotten any results back yet. Start by getting the
* column labels.
*/
rc = SQLNumResultCols(sql_hstmt, &_ncols);
if ((SQL_SUCCESS != rc) and (SQL_SUCCESS_WITH_INFO != rc))
{
PRINT_SQLERR (SQL_HANDLE_STMT, sql_hstmt);
PERR ("Can't get num columns rc=%d", rc);
return;
}
if (_ncols > arrsize)
{
_ncols = arrsize;
PERR( "screwed not enough columns !! ");
}
for (i=0; i<_ncols; i++)
{
char namebuff[300];
SQLSMALLINT namelen;
SQLULEN column_size;
SQLSMALLINT datatype;
SQLSMALLINT decimal_digits;
SQLSMALLINT nullable;
rc = SQLDescribeCol (sql_hstmt, i+1,
(SQLCHAR *) namebuff, 299, &namelen,
&datatype, &column_size, &decimal_digits, &nullable);
if ((SQL_SUCCESS != rc) and (SQL_SUCCESS_WITH_INFO != rc))
{
PRINT_SQLERR (SQL_HANDLE_STMT, sql_hstmt);
PERR ("Can't describe col rc=%d", rc);
return;
}
namebuff[namelen] = 0x0;
// PINFO ("column %d has name\'%s\'", i, namebuff);
strncpy(column_labels[i], namebuff, DEFAULT_COLUMN_NAME_SIZE);
column_labels[i][DEFAULT_COLUMN_NAME_SIZE-1] = 0;
column_datatype[i] = datatype;
}
ncols = _ncols;
}
/* =========================================================== */
bool
ODBCRecordSet::fetch_row(void)
{
// Columns can have null values. In this case, the ODBC shims
// will neither set nor clear the value-strings. As a result,
// some random value from a previous query will still be sitting
// there, in the values, and get reported to the unlucky user.
for (int i=0; i<ncols; i++) values[i][0] = 0;
SQLRETURN rc = SQLFetch(sql_hstmt);
/* no more data */
if (SQL_NO_DATA == rc) return false;
if (SQL_NULL_DATA == rc) return false;
if ((SQL_SUCCESS != rc) and (SQL_SUCCESS_WITH_INFO != rc))
{
PRINT_SQLERR (SQL_HANDLE_STMT, sql_hstmt);
PERR ("Can't fetch row rc=%d", rc);
return false;
}
return true;
}
#endif /* HAVE_ODBC_STORAGE */
/* ============================= END OF FILE ================= */
<commit_msg>Lets lead in with the tirade<commit_after>/*
* FUNCTION:
* ODBC driver -- developed/tested with unixodbc http://www.unixodbc.org
*
* ODBC is basically brain-damaged, and so is this driver.
*
* ODBC has several problems:
* 1) It forces you to guess how many columns there are in your reply,
* which we don't know a-priori.
* 2) VARCHAR is difficult (impossible ??) to support correctly!
* 3) The use of the question mark as a special character, even when
* you have nothing bound, nothing at all, giving this message:
* (34) The # of binded parameters < the # of parameter markers;
* Wow! Aside from the bad English, this is a stunningly bad idea!
* 4) It's slowww. Terrible performance. The native bindings are 3x
* faster!
*
* Blame it on SQLBindCol(), which is a terrible idea. @#$%^ Microsoft.
*
* Threading:
* ----------
* This class is thread-enabled but not thread-safe. Two threads should
* not try to use one instance of this class at the same time. Each
* thread should construct it's own instance of this class. This class
* uses no globals.
*
* HISTORY:
* Copyright (c) 2002,2008 Linas Vepstas <[email protected]>
* created by Linas Vepstas March 2002
* ported to C++ March 2008
*
* LICENSE:
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#ifdef HAVE_ODBC_STORAGE
#include <stack>
#include <string>
#include <sql.h>
#include <sqlext.h>
#include <stdio.h>
#include <opencog/util/exceptions.h>
#include <opencog/util/Logger.h>
#include <opencog/util/platform.h>
#include "odbcxx.h"
#define PERR(...) \
throw opencog::RuntimeException(TRACE_INFO, __VA_ARGS__);
/* =========================================================== */
#define PRINT_SQLERR(HTYPE,HAN) \
{ \
char sql_stat[10]; \
SQLSMALLINT msglen; \
SQLINTEGER err; \
char msg[200]; \
\
SQLGetDiagRec(HTYPE, HAN, 1, (SQLCHAR *) sql_stat, \
&err, (SQLCHAR*) msg, sizeof(msg), &msglen); \
opencog::logger().warn("(%ld) %s\n", (long int) err, msg); \
}
/* =========================================================== */
ODBCConnection::ODBCConnection(const char * uri)
{
SQLRETURN rc;
is_connected = false;
sql_hdbc = NULL;
sql_henv = NULL;
// We expect odbc://user:password/database
if (0 != strncmp("odbc://", uri, 7))
{
PERR("Invalid URI specified: %s", uri);
return;
}
uri += 7; // skip past odbc://
char* curi = strdup(uri);
char* username = curi;
char* authentication;
char* p = strchr(curi, ':');
if (p)
{
*p = 0;
authentication = ++p;
}
else
{
// Point at the null byte at the end of the string.
authentication = curi+strlen(curi);
p = curi;
}
p = strchr(p, '/');
if (!p)
{
free(curi);
PERR("Invalid URI specified: %s", uri);
}
*p = 0;
char *dbname = ++p;
/* Allocate environment handle */
rc = SQLAllocEnv(&sql_henv);
if ((SQL_SUCCESS != rc) and (SQL_SUCCESS_WITH_INFO != rc))
{
free(curi);
PERR("Can't SQLAllocEnv, rc=%d", rc);
return;
}
/* Set the ODBC version */
rc = SQLSetEnvAttr(sql_henv, SQL_ATTR_ODBC_VERSION,
(void*)SQL_OV_ODBC3, 0);
if ((SQL_SUCCESS != rc) and (SQL_SUCCESS_WITH_INFO != rc))
{
free(curi);
PRINT_SQLERR (SQL_HANDLE_ENV, sql_henv);
SQLFreeHandle(SQL_HANDLE_ENV, sql_henv);
sql_henv = NULL;
PERR("Can't SQLSetEnv, rc=%d", rc);
return;
}
/* Allocate the connection handle */
rc = SQLAllocConnect(sql_henv, &sql_hdbc);
if ((SQL_SUCCESS != rc) and (SQL_SUCCESS_WITH_INFO != rc))
{
free(curi);
PRINT_SQLERR (SQL_HANDLE_ENV, sql_henv);
SQLFreeHandle(SQL_HANDLE_ENV, sql_henv);
sql_henv = NULL;
PERR ("Can't SQLAllocConnect handle rc=%d", rc);
return;
}
/* set the timeout to 5 seconds ?? hack alert fixme */
// SQLSetConnectAttr(sql_hdbc, SQL_LOGIN_TIMEOUT, (SQLPOINTER *)5, 0);
rc = SQLConnect(sql_hdbc,
(SQLCHAR*) dbname, SQL_NTS,
(SQLCHAR*) username, SQL_NTS,
(SQLCHAR*) authentication, SQL_NTS);
if ((SQL_SUCCESS != rc) and (SQL_SUCCESS_WITH_INFO != rc))
{
free(curi);
PRINT_SQLERR (SQL_HANDLE_DBC, sql_hdbc);
SQLFreeHandle(SQL_HANDLE_DBC, sql_hdbc);
SQLFreeHandle(SQL_HANDLE_ENV, sql_henv);
sql_henv = NULL;
sql_hdbc = NULL;
PERR ("Can't perform SQLConnect rc=%d", rc);
return;
}
is_connected = true;
free(curi);
}
/* =========================================================== */
ODBCConnection::~ODBCConnection()
{
if (sql_hdbc)
{
SQLDisconnect(sql_hdbc);
SQLFreeHandle(SQL_HANDLE_DBC, sql_hdbc);
sql_hdbc = NULL;
}
if (sql_henv)
{
SQLFreeHandle(SQL_HANDLE_ENV, sql_henv);
sql_henv = NULL;
}
}
/* =========================================================== */
#define DEFAULT_NUM_COLS 50
ODBCRecordSet * ODBCConnection::get_record_set(void)
{
ODBCRecordSet *rs;
if (!free_pool.empty())
{
LLRecordSet* llrs = free_pool.top();
rs = dynamic_cast<ODBCRecordSet*>(llrs);
free_pool.pop();
rs->ncols = -1;
}
else
{
rs = new ODBCRecordSet(this);
}
rs->alloc_and_bind_cols(DEFAULT_NUM_COLS);
return rs;
}
/* =========================================================== */
void ODBCConnection::extract_error(const char *msg)
{
SQLRETURN ret;
SQLINTEGER i = 0;
SQLINTEGER native;
SQLCHAR state[7];
SQLCHAR text[256];
SQLSMALLINT len;
do
{
ret = SQLGetDiagRec(SQL_HANDLE_ENV, sql_henv, ++i,
state, &native, text, sizeof(text), &len);
if (SQL_SUCCEEDED(ret))
opencog::logger().warn("\t%s : %d : %d : %s\n",
state, i, native, text);
} while (ret == SQL_SUCCESS);
}
/* =========================================================== */
LLRecordSet *
ODBCConnection::exec(const char * buff)
{
if (!is_connected) return NULL;
ODBCRecordSet* rs = get_record_set();
SQLRETURN rc = SQLExecDirect(rs->sql_hstmt, (SQLCHAR *)buff, SQL_NTS);
/* If query returned no data, its not necessarily an error:
* its simply "no data", that's all.
*/
if (SQL_NO_DATA == rc)
{
rs->release();
return NULL;
}
if ((SQL_SUCCESS != rc) and (SQL_SUCCESS_WITH_INFO != rc))
{
PRINT_SQLERR (SQL_HANDLE_STMT, rs->sql_hstmt);
rs->release();
opencog::logger().warn("\tQuery was: %s\n", buff);
extract_error("exec");
PERR ("Can't perform query rc=%d ", rc);
return NULL;
}
/* Use numbr of columns to indicate that the query hasn't
* given results yet. */
rs->ncols = -1;
return rs;
}
/* =========================================================== */
#define DEFAULT_COLUMN_NAME_SIZE 121
#define DEFAULT_VARCHAR_SIZE 4040
void
ODBCRecordSet::alloc_and_bind_cols(int new_ncols)
{
int i;
// This static alloc of column names and values is crazy and
// bizarre, but it is driven by the fact that ODBC must be given
// mem locations in which to scribble it's results. Which is
// a nutty design, given that we don't know sizes of the columns
// in advance. Only Microsoft could invent something this nasty.
if (new_ncols > arrsize)
{
if (column_labels)
{
for (i=0; i<arrsize; i++)
{
if (column_labels[i])
{
delete[] column_labels[i];
}
}
delete[] column_labels;
}
if (column_datatype) delete[] column_datatype;
if (values)
{
for (i=0; i<arrsize; i++)
{
if (values[i])
{
delete[] values[i];
}
}
delete[] values;
}
if (vsizes) delete[] vsizes;
column_labels = new char*[new_ncols];
column_datatype = new int[new_ncols];
values = new char*[new_ncols];
vsizes = new int[new_ncols];
/* intialize */
for (i = 0; i<new_ncols; i++)
{
column_labels[i] = new char[DEFAULT_COLUMN_NAME_SIZE];
column_labels[i][0] = 0;
column_datatype[i] = 0;
values[i] = new char[DEFAULT_VARCHAR_SIZE];
vsizes[i] = DEFAULT_VARCHAR_SIZE;
values[i][0] = 0;
}
arrsize = new_ncols;
}
ODBCConnection* oconn = dynamic_cast<ODBCConnection*>(conn);
SQLRETURN rc = SQLAllocStmt (oconn->sql_hdbc, &sql_hstmt);
if ((SQL_SUCCESS != rc) and (SQL_SUCCESS_WITH_INFO != rc))
{
PRINT_SQLERR (SQL_HANDLE_STMT, sql_hstmt);
PERR("Can't allocate statement handle, rc=%d", rc);
/* oops memory leak */
return;
}
// IMPORTANT! MUST NOT BE ON STACK!! Else stack corruption will result.
// The ODBC driver really wants to write a return value here!
static SQLLEN bogus;
/* Initialize the newly realloc'ed entries */
for (i=0; i<new_ncols; i++)
{
rc = SQLBindCol(sql_hstmt, i+1, SQL_C_CHAR,
values[i], vsizes[i], &bogus);
if ((SQL_SUCCESS != rc) and (SQL_SUCCESS_WITH_INFO != rc))
{
PRINT_SQLERR (SQL_HANDLE_STMT, sql_hstmt);
PERR ("Can't bind col=%d rc=%d", i, rc);
return;
}
}
}
/* =========================================================== */
/* pseudo-private routine */
ODBCRecordSet::ODBCRecordSet(ODBCConnection* _conn)
: LLRecordSet(_conn)
{
sql_hstmt = NULL;
}
/* =========================================================== */
void
ODBCRecordSet::release(void)
{
ncols = -1;
// Avoid accidental double-release
if (NULL == sql_hstmt) return;
// SQLFreeStmt(sql_hstmt, SQL_UNBIND);
// SQLFreeStmt(sql_hstmt, SQL_CLOSE);
SQLFreeHandle(SQL_HANDLE_STMT, sql_hstmt);
sql_hstmt = NULL;
LLRecordSet::release();
}
/* =========================================================== */
ODBCRecordSet::~ODBCRecordSet()
{
for (int i=0; i<arrsize; i++)
{
delete[] column_labels[i];
delete[] values[i];
}
}
/* =========================================================== */
void
ODBCRecordSet::get_column_labels(void)
{
SQLSMALLINT _ncols;
SQLRETURN rc;
int i;
if (0 <= ncols) return;
/* If number of columns is negative, then we haven't
* gotten any results back yet. Start by getting the
* column labels.
*/
rc = SQLNumResultCols(sql_hstmt, &_ncols);
if ((SQL_SUCCESS != rc) and (SQL_SUCCESS_WITH_INFO != rc))
{
PRINT_SQLERR (SQL_HANDLE_STMT, sql_hstmt);
PERR ("Can't get num columns rc=%d", rc);
return;
}
if (_ncols > arrsize)
{
_ncols = arrsize;
PERR( "screwed not enough columns !! ");
}
for (i=0; i<_ncols; i++)
{
char namebuff[300];
SQLSMALLINT namelen;
SQLULEN column_size;
SQLSMALLINT datatype;
SQLSMALLINT decimal_digits;
SQLSMALLINT nullable;
rc = SQLDescribeCol (sql_hstmt, i+1,
(SQLCHAR *) namebuff, 299, &namelen,
&datatype, &column_size, &decimal_digits, &nullable);
if ((SQL_SUCCESS != rc) and (SQL_SUCCESS_WITH_INFO != rc))
{
PRINT_SQLERR (SQL_HANDLE_STMT, sql_hstmt);
PERR ("Can't describe col rc=%d", rc);
return;
}
namebuff[namelen] = 0x0;
// PINFO ("column %d has name\'%s\'", i, namebuff);
strncpy(column_labels[i], namebuff, DEFAULT_COLUMN_NAME_SIZE);
column_labels[i][DEFAULT_COLUMN_NAME_SIZE-1] = 0;
column_datatype[i] = datatype;
}
ncols = _ncols;
}
/* =========================================================== */
bool
ODBCRecordSet::fetch_row(void)
{
// Columns can have null values. In this case, the ODBC shims
// will neither set nor clear the value-strings. As a result,
// some random value from a previous query will still be sitting
// there, in the values, and get reported to the unlucky user.
for (int i=0; i<ncols; i++) values[i][0] = 0;
SQLRETURN rc = SQLFetch(sql_hstmt);
/* no more data */
if (SQL_NO_DATA == rc) return false;
if (SQL_NULL_DATA == rc) return false;
if ((SQL_SUCCESS != rc) and (SQL_SUCCESS_WITH_INFO != rc))
{
PRINT_SQLERR (SQL_HANDLE_STMT, sql_hstmt);
PERR ("Can't fetch row rc=%d", rc);
return false;
}
return true;
}
#endif /* HAVE_ODBC_STORAGE */
/* ============================= END OF FILE ================= */
<|endoftext|>
|
<commit_before>/*
This file is part of Magnum.
Copyright © 2010, 2011, 2012, 2013 Vladimír Vondruš <[email protected]>
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 "SphereRenderer.h"
#include "Mesh.h"
#include "DebugTools/ShapeRenderer.h"
#include "Physics/Sphere.h"
#include "Primitives/Circle.h"
#include "Shaders/FlatShader.h"
#include "Trade/MeshData2D.h"
namespace Magnum { namespace DebugTools { namespace Implementation {
AbstractSphereRenderer<2>::AbstractSphereRenderer(): AbstractShapeRenderer<2>("sphere2d", "sphere2d-vertices", {}) {
if(!mesh) this->createResources(Primitives::Circle::wireframe(40));
}
template<UnsignedInt dimensions> SphereRenderer<dimensions>::SphereRenderer(Physics::Sphere<dimensions>& sphere): sphere(sphere) {}
template<UnsignedInt dimensions> void SphereRenderer<dimensions>::draw(Resource<ShapeRendererOptions>& options, const typename DimensionTraits<dimensions>::MatrixType& projectionMatrix) {
this->shader->setTransformationProjectionMatrix(projectionMatrix*
DimensionTraits<dimensions>::MatrixType::translation(sphere.position())*
DimensionTraits<dimensions>::MatrixType::scaling(typename DimensionTraits<dimensions>::VectorType(sphere.radius())))
->setColor(options->color())
->use();
this->mesh->draw();
}
template class SphereRenderer<2>;
}}}
<commit_msg>DebugTools: use proper sphere parameters in ShapeRenderer.<commit_after>/*
This file is part of Magnum.
Copyright © 2010, 2011, 2012, 2013 Vladimír Vondruš <[email protected]>
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 "SphereRenderer.h"
#include "Mesh.h"
#include "DebugTools/ShapeRenderer.h"
#include "Physics/Sphere.h"
#include "Primitives/Circle.h"
#include "Shaders/FlatShader.h"
#include "Trade/MeshData2D.h"
namespace Magnum { namespace DebugTools { namespace Implementation {
AbstractSphereRenderer<2>::AbstractSphereRenderer(): AbstractShapeRenderer<2>("sphere2d", "sphere2d-vertices", {}) {
if(!mesh) this->createResources(Primitives::Circle::wireframe(40));
}
template<UnsignedInt dimensions> SphereRenderer<dimensions>::SphereRenderer(Physics::Sphere<dimensions>& sphere): sphere(sphere) {}
template<UnsignedInt dimensions> void SphereRenderer<dimensions>::draw(Resource<ShapeRendererOptions>& options, const typename DimensionTraits<dimensions>::MatrixType& projectionMatrix) {
this->shader->setTransformationProjectionMatrix(projectionMatrix*
DimensionTraits<dimensions>::MatrixType::translation(sphere.transformedPosition())*
DimensionTraits<dimensions>::MatrixType::scaling(typename DimensionTraits<dimensions>::VectorType(sphere.transformedRadius())))
->setColor(options->color())
->use();
this->mesh->draw();
}
template class SphereRenderer<2>;
}}}
<|endoftext|>
|
<commit_before>//===--- Migrator.cpp -----------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "swift/Frontend/Frontend.h"
#include "swift/Migrator/EditorAdapter.h"
#include "swift/Migrator/FixitApplyDiagnosticConsumer.h"
#include "swift/Migrator/Migrator.h"
#include "swift/Migrator/RewriteBufferEditsReceiver.h"
#include "swift/Migrator/SyntacticMigratorPass.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Edit/EditedSource.h"
#include "clang/Rewrite/Core/RewriteBuffer.h"
#include "llvm/Support/FileSystem.h"
using namespace swift;
using namespace swift::migrator;
bool migrator::updateCodeAndEmitRemap(const CompilerInvocation &Invocation) {
Migrator M { Invocation }; // Provide inputs and configuration
// Phase 1:
// Perform any syntactic transformations if requested.
// TODO
auto FailedSyntacticPasses = M.performSyntacticPasses();
if (FailedSyntacticPasses) {
return true;
}
// Phase 2:
// Perform fix-it based migrations on the compiler, some number of times in
// order to give the compiler an opportunity to
// take its time reaching a fixed point.
if (M.getMigratorOptions().EnableMigratorFixits) {
M.repeatFixitMigrations(Migrator::MaxCompilerFixitPassIterations);
}
// OK, we have a final resulting text. Now we compare against the input
// to calculate a replacement map describing the changes to the input
// necessary to get the output.
// TODO: Document replacement map format.
auto EmitRemapFailed = M.emitRemap();
auto EmitMigratedFailed = M.emitMigratedFile();
auto DumpMigrationStatesFailed = M.dumpStates();
return EmitRemapFailed || EmitMigratedFailed || DumpMigrationStatesFailed;
}
Migrator::Migrator(const CompilerInvocation &StartInvocation)
: StartInvocation(StartInvocation) {
auto ErrorOrStartBuffer = llvm::MemoryBuffer::getFile(getInputFilename());
auto &StartBuffer = ErrorOrStartBuffer.get();
auto StartBufferID = SrcMgr.addNewSourceBuffer(std::move(StartBuffer));
States.push_back(MigrationState::start(SrcMgr, StartBufferID));
}
void Migrator::
repeatFixitMigrations(const unsigned Iterations) {
for (unsigned i = 0; i < Iterations; ++i) {
auto ThisResult = performAFixItMigration();
if (!ThisResult.hasValue()) {
// Something went wrong? Track error in the state?
break;
} else {
if (ThisResult.getValue()->outputDiffersFromInput()) {
States.push_back(ThisResult.getValue());
} else {
break;
}
}
}
}
llvm::Optional<RC<MigrationState>>
Migrator::performAFixItMigration() {
auto InputState = States.back();
auto InputBuffer =
llvm::MemoryBuffer::getMemBufferCopy(InputState->getOutputText(),
getInputFilename());
CompilerInvocation Invocation { StartInvocation };
Invocation.clearInputs();
Invocation.addInputBuffer(InputBuffer.get());
CompilerInstance Instance;
if (Instance.setup(Invocation)) {
// TODO: Return a state with an error attached?
return None;
}
FixitApplyDiagnosticConsumer FixitApplyConsumer {
InputState->getInputText(),
getInputFilename(),
};
Instance.addDiagnosticConsumer(&FixitApplyConsumer);
Instance.performSema();
StringRef ResultText = InputState->getInputText();
unsigned ResultBufferID = InputState->getInputBufferID();
if (FixitApplyConsumer.getNumFixitsApplied() > 0) {
SmallString<4096> Scratch;
llvm::raw_svector_ostream OS(Scratch);
FixitApplyConsumer.printResult(OS);
auto ResultBuffer = llvm::MemoryBuffer::getMemBufferCopy(OS.str());
ResultText = ResultBuffer->getBuffer();
ResultBufferID = SrcMgr.addNewSourceBuffer(std::move(ResultBuffer));
}
return MigrationState::make(MigrationKind::CompilerFixits,
SrcMgr, InputState->getInputBufferID(),
ResultBufferID);
}
bool Migrator::performSyntacticPasses() {
clang::FileSystemOptions ClangFileSystemOptions;
clang::FileManager ClangFileManager { ClangFileSystemOptions };
llvm::IntrusiveRefCntPtr<clang::DiagnosticIDs> DummyClangDiagIDs {
new clang::DiagnosticIDs()
};
auto ClangDiags =
llvm::make_unique<clang::DiagnosticsEngine>(DummyClangDiagIDs,
new clang::DiagnosticOptions,
new clang::DiagnosticConsumer(),
/*ShouldOwnClient=*/true);
clang::SourceManager ClangSourceManager { *ClangDiags, ClangFileManager };
clang::LangOptions ClangLangOpts;
clang::edit::EditedSource Edits { ClangSourceManager, ClangLangOpts };
// Make a CompilerInstance
// Perform Sema
// auto SF = CI.getPrimarySourceFile() ?
CompilerInvocation Invocation { StartInvocation };
auto InputState = States.back();
auto TempInputBuffer =
llvm::MemoryBuffer::getMemBufferCopy(InputState->getOutputText(),
getInputFilename());
Invocation.clearInputs();
Invocation.addInputBuffer(TempInputBuffer.get());
CompilerInstance Instance;
if (Instance.setup(StartInvocation)) {
return true;
}
Instance.performSema();
if (Instance.getDiags().hasFatalErrorOccurred()) {
return true;
}
EditorAdapter Editor { Instance.getSourceMgr(), ClangSourceManager };
// const auto SF = Instance.getPrimarySourceFile();
// From here, create the syntactic pass:
//
// SyntacticMigratorPass MyPass {
// Editor, Sema's SourceMgr, ClangSrcManager, SF
// };
// MyPass.run();
//
// Once it has run, push the edits into Edits above:
// Edits.commit(YourPass.getEdits());
SyntacticMigratorPass SPass(Editor, Instance.getPrimarySourceFile(),
getMigratorOptions());
SPass.run();
Edits.commit(SPass.getEdits());
// Now, we'll take all of the changes we've accumulated, get a resulting text,
// and push a MigrationState.
auto InputText = States.back()->getOutputText();
RewriteBufferEditsReceiver Rewriter {
ClangSourceManager,
Editor.getClangFileIDForSwiftBufferID(
Instance.getPrimarySourceFile()->getBufferID().getValue()),
InputState->getOutputText()
};
Edits.applyRewrites(Rewriter);
SmallString<1024> Scratch;
llvm::raw_svector_ostream OS(Scratch);
Rewriter.printResult(OS);
auto ResultBuffer = this->SrcMgr.addMemBufferCopy(OS.str());
States.push_back(
MigrationState::make(MigrationKind::Syntactic,
this->SrcMgr,
States.back()->getInputBufferID(),
ResultBuffer));
return false;
}
bool Migrator::emitRemap() const {
// TODO: Need to integrate diffing library to diff start and end state's
// output text.
return false;
}
bool Migrator::emitMigratedFile() const {
const auto &OutFilename = getMigratorOptions().EmitMigratedFilePath;
if (OutFilename.empty()) {
return false;
}
std::error_code Error;
llvm::raw_fd_ostream FileOS(OutFilename,
Error, llvm::sys::fs::F_Text);
if (FileOS.has_error()) {
return true;
}
FileOS << States.back()->getOutputText();
FileOS.flush();
return FileOS.has_error();
}
bool Migrator::dumpStates() const {
const auto &OutDir = getMigratorOptions().DumpMigrationStatesDir;
if (OutDir.empty()) {
return false;
}
auto Failed = false;
for (size_t i = 0; i < States.size(); ++i) {
Failed |= States[i]->print(i, OutDir);
}
return Failed;
}
const MigratorOptions &Migrator::getMigratorOptions() const {
return StartInvocation.getMigratorOptions();
}
const StringRef Migrator::getInputFilename() const {
auto PrimaryInput =
StartInvocation.getFrontendOptions().PrimaryInput.getValue();
return StartInvocation.getInputFilenames()[PrimaryInput.Index];
}
<commit_msg>[Migrator] Set language version to 4 for the fix-it passes<commit_after>//===--- Migrator.cpp -----------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "swift/Frontend/Frontend.h"
#include "swift/Migrator/EditorAdapter.h"
#include "swift/Migrator/FixitApplyDiagnosticConsumer.h"
#include "swift/Migrator/Migrator.h"
#include "swift/Migrator/RewriteBufferEditsReceiver.h"
#include "swift/Migrator/SyntacticMigratorPass.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Edit/EditedSource.h"
#include "clang/Rewrite/Core/RewriteBuffer.h"
#include "llvm/Support/FileSystem.h"
using namespace swift;
using namespace swift::migrator;
bool migrator::updateCodeAndEmitRemap(const CompilerInvocation &Invocation) {
Migrator M { Invocation }; // Provide inputs and configuration
// Phase 1:
// Perform any syntactic transformations if requested.
// TODO
auto FailedSyntacticPasses = M.performSyntacticPasses();
if (FailedSyntacticPasses) {
return true;
}
// Phase 2:
// Perform fix-it based migrations on the compiler, some number of times in
// order to give the compiler an opportunity to
// take its time reaching a fixed point.
if (M.getMigratorOptions().EnableMigratorFixits) {
M.repeatFixitMigrations(Migrator::MaxCompilerFixitPassIterations);
}
// OK, we have a final resulting text. Now we compare against the input
// to calculate a replacement map describing the changes to the input
// necessary to get the output.
// TODO: Document replacement map format.
auto EmitRemapFailed = M.emitRemap();
auto EmitMigratedFailed = M.emitMigratedFile();
auto DumpMigrationStatesFailed = M.dumpStates();
return EmitRemapFailed || EmitMigratedFailed || DumpMigrationStatesFailed;
}
Migrator::Migrator(const CompilerInvocation &StartInvocation)
: StartInvocation(StartInvocation) {
auto ErrorOrStartBuffer = llvm::MemoryBuffer::getFile(getInputFilename());
auto &StartBuffer = ErrorOrStartBuffer.get();
auto StartBufferID = SrcMgr.addNewSourceBuffer(std::move(StartBuffer));
States.push_back(MigrationState::start(SrcMgr, StartBufferID));
}
void Migrator::
repeatFixitMigrations(const unsigned Iterations) {
for (unsigned i = 0; i < Iterations; ++i) {
auto ThisResult = performAFixItMigration();
if (!ThisResult.hasValue()) {
// Something went wrong? Track error in the state?
break;
} else {
if (ThisResult.getValue()->outputDiffersFromInput()) {
States.push_back(ThisResult.getValue());
} else {
break;
}
}
}
}
llvm::Optional<RC<MigrationState>>
Migrator::performAFixItMigration() {
auto InputState = States.back();
auto InputBuffer =
llvm::MemoryBuffer::getMemBufferCopy(InputState->getOutputText(),
getInputFilename());
CompilerInvocation Invocation { StartInvocation };
Invocation.clearInputs();
Invocation.addInputBuffer(InputBuffer.get());
Invocation.getLangOptions().EffectiveLanguageVersion = { 4, 0, 0 };
CompilerInstance Instance;
if (Instance.setup(Invocation)) {
// TODO: Return a state with an error attached?
return None;
}
FixitApplyDiagnosticConsumer FixitApplyConsumer {
InputState->getInputText(),
getInputFilename(),
};
Instance.addDiagnosticConsumer(&FixitApplyConsumer);
Instance.performSema();
StringRef ResultText = InputState->getInputText();
unsigned ResultBufferID = InputState->getInputBufferID();
if (FixitApplyConsumer.getNumFixitsApplied() > 0) {
SmallString<4096> Scratch;
llvm::raw_svector_ostream OS(Scratch);
FixitApplyConsumer.printResult(OS);
auto ResultBuffer = llvm::MemoryBuffer::getMemBufferCopy(OS.str());
ResultText = ResultBuffer->getBuffer();
ResultBufferID = SrcMgr.addNewSourceBuffer(std::move(ResultBuffer));
}
return MigrationState::make(MigrationKind::CompilerFixits,
SrcMgr, InputState->getInputBufferID(),
ResultBufferID);
}
bool Migrator::performSyntacticPasses() {
clang::FileSystemOptions ClangFileSystemOptions;
clang::FileManager ClangFileManager { ClangFileSystemOptions };
llvm::IntrusiveRefCntPtr<clang::DiagnosticIDs> DummyClangDiagIDs {
new clang::DiagnosticIDs()
};
auto ClangDiags =
llvm::make_unique<clang::DiagnosticsEngine>(DummyClangDiagIDs,
new clang::DiagnosticOptions,
new clang::DiagnosticConsumer(),
/*ShouldOwnClient=*/true);
clang::SourceManager ClangSourceManager { *ClangDiags, ClangFileManager };
clang::LangOptions ClangLangOpts;
clang::edit::EditedSource Edits { ClangSourceManager, ClangLangOpts };
// Make a CompilerInstance
// Perform Sema
// auto SF = CI.getPrimarySourceFile() ?
CompilerInvocation Invocation { StartInvocation };
auto InputState = States.back();
auto TempInputBuffer =
llvm::MemoryBuffer::getMemBufferCopy(InputState->getOutputText(),
getInputFilename());
Invocation.clearInputs();
Invocation.addInputBuffer(TempInputBuffer.get());
CompilerInstance Instance;
if (Instance.setup(StartInvocation)) {
return true;
}
Instance.performSema();
if (Instance.getDiags().hasFatalErrorOccurred()) {
return true;
}
EditorAdapter Editor { Instance.getSourceMgr(), ClangSourceManager };
// const auto SF = Instance.getPrimarySourceFile();
// From here, create the syntactic pass:
//
// SyntacticMigratorPass MyPass {
// Editor, Sema's SourceMgr, ClangSrcManager, SF
// };
// MyPass.run();
//
// Once it has run, push the edits into Edits above:
// Edits.commit(YourPass.getEdits());
SyntacticMigratorPass SPass(Editor, Instance.getPrimarySourceFile(),
getMigratorOptions());
SPass.run();
Edits.commit(SPass.getEdits());
// Now, we'll take all of the changes we've accumulated, get a resulting text,
// and push a MigrationState.
auto InputText = States.back()->getOutputText();
RewriteBufferEditsReceiver Rewriter {
ClangSourceManager,
Editor.getClangFileIDForSwiftBufferID(
Instance.getPrimarySourceFile()->getBufferID().getValue()),
InputState->getOutputText()
};
Edits.applyRewrites(Rewriter);
SmallString<1024> Scratch;
llvm::raw_svector_ostream OS(Scratch);
Rewriter.printResult(OS);
auto ResultBuffer = this->SrcMgr.addMemBufferCopy(OS.str());
States.push_back(
MigrationState::make(MigrationKind::Syntactic,
this->SrcMgr,
States.back()->getInputBufferID(),
ResultBuffer));
return false;
}
bool Migrator::emitRemap() const {
// TODO: Need to integrate diffing library to diff start and end state's
// output text.
return false;
}
bool Migrator::emitMigratedFile() const {
const auto &OutFilename = getMigratorOptions().EmitMigratedFilePath;
if (OutFilename.empty()) {
return false;
}
std::error_code Error;
llvm::raw_fd_ostream FileOS(OutFilename,
Error, llvm::sys::fs::F_Text);
if (FileOS.has_error()) {
return true;
}
FileOS << States.back()->getOutputText();
FileOS.flush();
return FileOS.has_error();
}
bool Migrator::dumpStates() const {
const auto &OutDir = getMigratorOptions().DumpMigrationStatesDir;
if (OutDir.empty()) {
return false;
}
auto Failed = false;
for (size_t i = 0; i < States.size(); ++i) {
Failed |= States[i]->print(i, OutDir);
}
return Failed;
}
const MigratorOptions &Migrator::getMigratorOptions() const {
return StartInvocation.getMigratorOptions();
}
const StringRef Migrator::getInputFilename() const {
auto PrimaryInput =
StartInvocation.getFrontendOptions().PrimaryInput.getValue();
return StartInvocation.getInputFilenames()[PrimaryInput.Index];
}
<|endoftext|>
|
<commit_before>/**
* Copyright (c) 2016, Loic Blot <[email protected]>
* All rights reserved.
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <cppunit/TestFixture.h>
#include <cppunit/TestAssert.h>
#include <cppunit/TestCaller.h>
#include <cppunit/TestSuite.h>
#include <cppunit/ui/text/TestRunner.h>
#include <gitlabapiclient.h>
#define CPPUNIT_TESTSUITE_CREATE(s) CppUnit::TestSuite *suiteOfTests = new CppUnit::TestSuite(std::string(s));
#define CPPUNIT_ADDTEST(c, s, f) suiteOfTests->addTest(new CppUnit::TestCaller<c>(s, &c::f));
static std::string GITLAB_TOKEN = "";
static std::string RUN_TIMESTAMP = std::to_string(time(NULL));
class WinterWindTests: public CppUnit::TestFixture
{
public:
WinterWindTests() {}
virtual ~WinterWindTests()
{
delete m_gitlab_client;
}
static CppUnit::Test *suite()
{
CPPUNIT_TESTSUITE_CREATE("WinterWind")
CPPUNIT_ADDTEST(WinterWindTests, "Group - Test1 - Creation", create_default_groups);
CPPUNIT_ADDTEST(WinterWindTests, "Group - Test2 - Creation (parameters)", create_group);
// Should be done at the end
CPPUNIT_ADDTEST(WinterWindTests, "Group - Test3 - Removal", remove_group);
CPPUNIT_ADDTEST(WinterWindTests, "Group - Test3 - Removal (multiple)", remove_groups);
return suiteOfTests;
}
/// Setup method
void setUp()
{
m_gitlab_client = new GitlabAPIClient("https://gitlab.com", GITLAB_TOKEN);
}
/// Teardown method
void tearDown() {}
protected:
void create_default_groups()
{
Json::Value res;
GitlabGroup g("ww_testgroup_default_" + RUN_TIMESTAMP, "ww_testgroup_default_" + RUN_TIMESTAMP);
CPPUNIT_ASSERT(m_gitlab_client->create_group(g, res));
GitlabGroup g2("ww_testgroup2_default_" + RUN_TIMESTAMP, "ww_testgroup2_default_" + RUN_TIMESTAMP);
CPPUNIT_ASSERT(m_gitlab_client->create_group(g2, res));
}
void create_group()
{
Json::Value res;
GitlabGroup g("ww_testgroup_" + RUN_TIMESTAMP, "ww_testgroup_" + RUN_TIMESTAMP);
g.description = "test";
g.visibility = GITLAB_GROUP_PUBLIC;
CPPUNIT_ASSERT(m_gitlab_client->create_group(g, res));
}
void remove_group()
{
CPPUNIT_ASSERT(m_gitlab_client->delete_group("ww_testgroup_" + RUN_TIMESTAMP) == GITLAB_RC_OK);
}
void remove_groups()
{
CPPUNIT_ASSERT(m_gitlab_client->delete_groups({
"ww_testgroup_default_" + RUN_TIMESTAMP,
"ww_testgroup_default2_" + RUN_TIMESTAMP }) == GITLAB_RC_OK);
}
private:
GitlabAPIClient *m_gitlab_client = nullptr;
};
int main(int argc, const char* argv[])
{
if (argc < 2) {
std::cerr << argv[0] << ": Missing gitlab token" << std::endl;
return -1;
}
GITLAB_TOKEN = std::string(argv[1]);
CppUnit::TextUi::TestRunner runner;
runner.addTest(WinterWindTests::suite());
std::cout << "Starting unittests...." << std::endl;
return runner.run() ? 0 : 1;
}
<commit_msg>And fix the mass removal unittest<commit_after>/**
* Copyright (c) 2016, Loic Blot <[email protected]>
* All rights reserved.
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <cppunit/TestFixture.h>
#include <cppunit/TestAssert.h>
#include <cppunit/TestCaller.h>
#include <cppunit/TestSuite.h>
#include <cppunit/ui/text/TestRunner.h>
#include <gitlabapiclient.h>
#define CPPUNIT_TESTSUITE_CREATE(s) CppUnit::TestSuite *suiteOfTests = new CppUnit::TestSuite(std::string(s));
#define CPPUNIT_ADDTEST(c, s, f) suiteOfTests->addTest(new CppUnit::TestCaller<c>(s, &c::f));
static std::string GITLAB_TOKEN = "";
static std::string RUN_TIMESTAMP = std::to_string(time(NULL));
class WinterWindTests: public CppUnit::TestFixture
{
public:
WinterWindTests() {}
virtual ~WinterWindTests()
{
delete m_gitlab_client;
}
static CppUnit::Test *suite()
{
CPPUNIT_TESTSUITE_CREATE("WinterWind")
CPPUNIT_ADDTEST(WinterWindTests, "Group - Test1 - Creation", create_default_groups);
CPPUNIT_ADDTEST(WinterWindTests, "Group - Test2 - Creation (parameters)", create_group);
// Should be done at the end
CPPUNIT_ADDTEST(WinterWindTests, "Group - Test3 - Removal", remove_group);
CPPUNIT_ADDTEST(WinterWindTests, "Group - Test3 - Removal (multiple)", remove_groups);
return suiteOfTests;
}
/// Setup method
void setUp()
{
m_gitlab_client = new GitlabAPIClient("https://gitlab.com", GITLAB_TOKEN);
}
/// Teardown method
void tearDown() {}
protected:
void create_default_groups()
{
Json::Value res;
GitlabGroup g("ww_testgroup_default_" + RUN_TIMESTAMP, "ww_testgroup_default_" + RUN_TIMESTAMP);
CPPUNIT_ASSERT(m_gitlab_client->create_group(g, res));
GitlabGroup g2("ww_testgroup2_default_" + RUN_TIMESTAMP, "ww_testgroup2_default_" + RUN_TIMESTAMP);
CPPUNIT_ASSERT(m_gitlab_client->create_group(g2, res));
}
void create_group()
{
Json::Value res;
GitlabGroup g("ww_testgroup_" + RUN_TIMESTAMP, "ww_testgroup_" + RUN_TIMESTAMP);
g.description = "test";
g.visibility = GITLAB_GROUP_PUBLIC;
CPPUNIT_ASSERT(m_gitlab_client->create_group(g, res));
}
void remove_group()
{
CPPUNIT_ASSERT(m_gitlab_client->delete_group("ww_testgroup_" + RUN_TIMESTAMP) == GITLAB_RC_OK);
}
void remove_groups()
{
CPPUNIT_ASSERT(m_gitlab_client->delete_groups({
"ww_testgroup_default_" + RUN_TIMESTAMP,
"ww_testgroup2_default_" + RUN_TIMESTAMP }) == GITLAB_RC_OK);
}
private:
GitlabAPIClient *m_gitlab_client = nullptr;
};
int main(int argc, const char* argv[])
{
if (argc < 2) {
std::cerr << argv[0] << ": Missing gitlab token" << std::endl;
return -1;
}
GITLAB_TOKEN = std::string(argv[1]);
CppUnit::TextUi::TestRunner runner;
runner.addTest(WinterWindTests::suite());
std::cout << "Starting unittests...." << std::endl;
return runner.run() ? 0 : 1;
}
<|endoftext|>
|
<commit_before><commit_msg>[lsan] Add _os_trace into LSan's suppression list<commit_after><|endoftext|>
|
<commit_before>// common re2 things
#include <stdio.h>
#include <re2/re2.h>
#include <iostream>
#include <string>
#include <sys/time.h>
#include <algorithm>
#include <inttypes.h>
using namespace std;
#ifndef USE_UTF8
#define ENCODING_OPTION RE2::Options::EncodingLatin1
#else
#define ENCODING_OPTION RE2::Options::EncodingUTF8
#endif
#define MATCH_ERROR \
fprintf(stderr, "match error on line %d\n%s", line, buffer); \
return 1;
#define PRE_COMPILE \
uint64_t preCompile = getTimeMs(); \
RE2 pattern(regex, options);
#define START_TIMING uint64_t start = getTimeMs();
#define PRINT_TIMES \
uint64_t stop = getTimeMs(); \
fprintf(stderr, "\ncompilation (ms): %" PRIu64 "\n", start - preCompile); \
fprintf(stderr, "matching (ms): %" PRIu64 "\n", stop - start);
// Initialize capture arguments
#define INIT_RE2_CAPTURE_ARGS(N) \
RE2::Arg *args[N]; \
string target[N]; \
for (int i = 0; i < N; i++) { \
args[i] = new RE2::Arg(&target[i]); \
}
// C-style fgets() is much much faster than C++-style getline(), so always use that.
#define BUFFER_SIZE (200*1024*1024)
char buffer[BUFFER_SIZE] = {0};
#define SETOPTS \
RE2::Options options; \
options.set_dot_nl(true); \
options.set_encoding(ENCODING_OPTION);
#define FOR_EACH_LINE(BODY) \
int line = 0; \
while(fgets(buffer, LINE_LEN, stdin)) { \
line++; \
BODY \
}
// Size of the chunks we read in at a time
#define INPUT_BLOCK_SIZE (1024*1024)
// Maximum line length
#define LINE_LEN 100000000
// Number of capturing parentheses
#ifndef NO_CAPTURE
#define CAPTURE true
#else
#define CAPTURE false
#endif
/** Gets the current timestamp in millisecond resolution */
uint64_t getTimeMs() {
struct timeval tv;
gettimeofday(&tv, NULL);
return tv.tv_usec / 1000 + tv.tv_sec * 1000;
}
<commit_msg>Don't output mismatching input line.<commit_after>// common re2 things
#include <stdio.h>
#include <re2/re2.h>
#include <iostream>
#include <string>
#include <sys/time.h>
#include <algorithm>
#include <inttypes.h>
using namespace std;
#ifndef USE_UTF8
#define ENCODING_OPTION RE2::Options::EncodingLatin1
#else
#define ENCODING_OPTION RE2::Options::EncodingUTF8
#endif
#define MATCH_ERROR \
fprintf(stderr, "match error on line %d\n", line); \
return 1;
#define PRE_COMPILE \
uint64_t preCompile = getTimeMs(); \
RE2 pattern(regex, options);
#define START_TIMING uint64_t start = getTimeMs();
#define PRINT_TIMES \
uint64_t stop = getTimeMs(); \
fprintf(stderr, "\ncompilation (ms): %" PRIu64 "\n", start - preCompile); \
fprintf(stderr, "matching (ms): %" PRIu64 "\n", stop - start);
// Initialize capture arguments
#define INIT_RE2_CAPTURE_ARGS(N) \
RE2::Arg *args[N]; \
string target[N]; \
for (int i = 0; i < N; i++) { \
args[i] = new RE2::Arg(&target[i]); \
}
// C-style fgets() is much much faster than C++-style getline(), so always use that.
#define BUFFER_SIZE (200*1024*1024)
char buffer[BUFFER_SIZE] = {0};
#define SETOPTS \
RE2::Options options; \
options.set_dot_nl(true); \
options.set_encoding(ENCODING_OPTION);
#define FOR_EACH_LINE(BODY) \
int line = 0; \
while(fgets(buffer, LINE_LEN, stdin)) { \
line++; \
BODY \
}
// Size of the chunks we read in at a time
#define INPUT_BLOCK_SIZE (1024*1024)
// Maximum line length
#define LINE_LEN 100000000
// Number of capturing parentheses
#ifndef NO_CAPTURE
#define CAPTURE true
#else
#define CAPTURE false
#endif
/** Gets the current timestamp in millisecond resolution */
uint64_t getTimeMs() {
struct timeval tv;
gettimeofday(&tv, NULL);
return tv.tv_usec / 1000 + tv.tv_sec * 1000;
}
<|endoftext|>
|
<commit_before>/*
* CustomVar.cpp
* OpenLieroX
*
* Created by Albert Zeyer on 24.02.10.
* code under LGPL
*
*/
#include "CustomVar.h"
#include "CBytestream.h"
#include "Debug.h"
#include "game/Attr.h"
#include "util/macros.h"
void CustomVar::reset() {
assert( thisRef.classId != ClassId(-1) );
std::vector<const AttrDesc*> attribs = getAttrDescs(thisRef.classId, true);
foreach(a, attribs) {
(*a)->set(this, (*a)->defaultValue);
}
}
CustomVar* CustomVar::copy() const {
// this copy() relies on the ClassInfo. otherwise it cannot work. provide your own in this case, it's virtual
assert( thisRef.classId != ClassId(-1) );
const ClassInfo* classInfo = getClassInfo(thisRef.classId);
assert( classInfo != NULL );
BaseObject* obj = classInfo->createInstance();
assert( obj != NULL );
CustomVar* v = dynamic_cast<CustomVar*>(obj);
assert( v != NULL );
v->copyFrom(*this);
return v;
}
bool CustomVar::operator==(const CustomVar& v) const {
if( thisRef.classId != v.thisRef.classId ) return false;
assert( thisRef.classId != ClassId(-1) );
std::vector<const AttrDesc*> attribs = getAttrDescs(thisRef.classId, true);
foreach(a, attribs) {
ScriptVar_t value = (*a)->get(this);
if(value != (*a)->get(&v)) return false;
}
return true;
}
bool CustomVar::operator<(const CustomVar& v) const {
if( thisRef.classId != v.thisRef.classId )
return thisRef.classId < v.thisRef.classId;
assert( thisRef.classId != ClassId(-1) );
std::vector<const AttrDesc*> attribs = getAttrDescs(thisRef.classId, true);
foreach(a, attribs) {
ScriptVar_t value = (*a)->get(this);
if(value != (*a)->get(&v))
return value < (*a)->get(&v);
}
return true;
}
void CustomVar::copyFrom(const CustomVar& v) {
assert( thisRef.classId != ClassId(-1) );
assert( v.thisRef.classId != ClassId(-1) );
assert( thisRef.classId == v.thisRef.classId );
std::vector<const AttrDesc*> attribs = getAttrDescs(thisRef.classId, true);
foreach(a, attribs) {
ScriptVar_t value = (*a)->get(&v);
if(value == (*a)->get(this)) continue;
(*a)->set(this, value);
}
}
void CustomVar::fromScriptVar(const ScriptVar_t& v) {
if(v.isCustomType()
&& v.customVar()->thisRef.classId != ClassId(-1)
&& v.customVar()->thisRef.classId == thisRef.classId
)
copyFrom(*v.customVar());
else
fromString(v.toString());
}
Result CustomVar::ToBytestream(CBytestream* bs, const CustomVar* diffTo) const {
assert( thisRef.classId != ClassId(-1) );
bs->writeInt16(thisRef.classId);
return toBytestream(bs, diffTo);
}
Result CustomVar::toBytestream(CBytestream *bs, const CustomVar* diffTo) const {
assert( thisRef.classId != ClassId(-1) );
if(diffTo)
assert( thisRef.classId == diffTo->thisRef.classId );
std::vector<const AttrDesc*> attribs = getAttrDescs(thisRef.classId, true);
size_t numChangesOld = 0;
size_t numChangesDefault = 0;
if(diffTo) {
foreach(a, attribs) {
ScriptVar_t value = (*a)->get(this);
if(value != (*a)->defaultValue) numChangesDefault++;
if(diffTo && value != (*a)->get(diffTo)) numChangesOld++;
}
}
if(diffTo && numChangesOld < numChangesDefault) {
bs->writeInt(CUSTOMVAR_STREAM_DiffToOld, 1);
foreach(a, attribs) {
ScriptVar_t value = (*a)->get(this);
if(value == (*a)->get(diffTo)) continue;
bs->writeInt16((*a)->objTypeId);
bs->writeInt16((*a)->attrId);
bs->writeVar(value);
}
bs->writeInt16(ClassId(-1));
}
else {
bs->writeInt(CUSTOMVAR_STREAM_DiffToDefault, 1);
foreach(a, attribs) {
ScriptVar_t value = (*a)->get(this);
if(value == (*a)->defaultValue) continue;
bs->writeInt16((*a)->objTypeId);
bs->writeInt16((*a)->attrId);
bs->writeVar(value);
}
bs->writeInt16(ClassId(-1));
}
return true;
}
Result CustomVar::fromBytestream(CBytestream *bs, bool expectDiffToDefault) {
assert( thisRef.classId != ClassId(-1) );
{
int streamType = bs->readInt(1);
switch(streamType) {
case CUSTOMVAR_STREAM_DiffToDefault: reset(); break;
case CUSTOMVAR_STREAM_DiffToOld:
if(expectDiffToDefault) {
errors << "CustomVar::fromBytestream: got unexpected diffToOld data on " << thisRef.description() << endl;
// continue anyway, there might be still something useful
}
/* nothing to do */ break;
default:
errors << "CustomVar::fromBytestream: got invalid streamType " << streamType << " for object " << thisRef.description() << endl;
// It doesn't really make sense to continue.
// This cannot be a bug, the stream is messed up.
return "stream messed up. invalid streamtype";
}
}
Result r = true;
while(true) {
AttribRef a;
a.objTypeId = bs->readInt16();
if(a.objTypeId == ClassId(-1)) break;
a.attrId = bs->readInt16();
const AttrDesc* attrDesc = a.getAttrDesc();
if(attrDesc == NULL) {
errors << "CustomVar::fromBytestream: unknown attrib " << a.objTypeId << ":" << a.attrId << " for object " << thisRef.description() << endl;
// try to continue
r = "unknown attrib";
bs->SkipVar();
continue;
}
const ClassInfo* classInfo = getClassInfo(a.objTypeId);
if(classInfo == NULL) {
errors << "CustomVar::fromBytestream: unknown class for attrib " << a.description() << " for object " << thisRef.description() << endl;
// try to continue
r = "unknown class";
bs->SkipVar();
continue;
}
if(!classInfo->isTypeOf(a.objTypeId)) {
errors << "CustomVar::fromBytestream: attrib " << a.description() << " does not belong to class " << classInfo->name << " for object " << thisRef.description() << endl;
// try to continue
r = "invalid attrib for class";
bs->SkipVar();
continue;
}
ScriptVar_t var;
bs->readVar(var);
attrDesc->set(this, var);
}
return r;
}
CustomVar::Ref CustomVar::FromBytestream( CBytestream* bs ) {
ClassId classId = bs->readInt16();
const ClassInfo* classInfo = getClassInfo(classId);
if(classInfo == NULL) {
errors << "CustomVar::FromBytestream: class ID " << classId << " unknown" << endl;
return NULL;
}
if(!classInfo->isTypeOf(LuaID<CustomVar>::value)) {
errors << "CustomVar::FromBytestream: class " << classInfo->name << " is not a CustomVar" << endl;
return NULL;
}
if(classInfo->id == LuaID<CustomVar>::value) {
errors << "CustomVar::FromBytestream: class " << classInfo->name << " is abstract" << endl;
return NULL;
}
CustomVar::Ref obj = (CustomVar*) classInfo->createInstance();
if(!obj) {
errors << "CustomVar::FromBytestream: couldn't create instance of " << classInfo->name << endl;
return NULL;
}
if(NegResult r = obj->fromBytestream(bs, true)) {
errors << "CustomVar::FromBytestream: error while reading " << classInfo->name << " instance: " << r.res.humanErrorMsg << endl;
// continue anyway, maybe we have some useful data
}
return obj;
}
// We cannot use the REGISTER_CLASS macro because we cannot instantiate it.
static bool registerClass_CustomVar() {
ClassInfo i;
i.id = LuaID<CustomVar>::value;
i.name = "CustomVar";
i.memSize = sizeof(CustomVar);
registerClass(i);
return true;
}
static bool registerClass_CustomVar_init = registerClass_CustomVar();
<commit_msg>fix/hack for now<commit_after>/*
* CustomVar.cpp
* OpenLieroX
*
* Created by Albert Zeyer on 24.02.10.
* code under LGPL
*
*/
#include "CustomVar.h"
#include "CBytestream.h"
#include "Debug.h"
#include "game/Attr.h"
#include "util/macros.h"
void CustomVar::reset() {
assert( thisRef.classId != ClassId(-1) );
std::vector<const AttrDesc*> attribs = getAttrDescs(thisRef.classId, true);
foreach(a, attribs) {
(*a)->set(this, (*a)->defaultValue);
}
}
CustomVar* CustomVar::copy() const {
// this copy() relies on the ClassInfo. otherwise it cannot work. provide your own in this case, it's virtual
assert( thisRef.classId != ClassId(-1) );
const ClassInfo* classInfo = getClassInfo(thisRef.classId);
assert( classInfo != NULL );
BaseObject* obj = classInfo->createInstance();
assert( obj != NULL );
CustomVar* v = dynamic_cast<CustomVar*>(obj);
assert( v != NULL );
v->copyFrom(*this);
return v;
}
bool CustomVar::operator==(const CustomVar& v) const {
if( thisRef.classId != v.thisRef.classId ) return false;
assert( thisRef.classId != ClassId(-1) );
std::vector<const AttrDesc*> attribs = getAttrDescs(thisRef.classId, true);
foreach(a, attribs) {
ScriptVar_t value = (*a)->get(this);
if(value != (*a)->get(&v)) return false;
}
return true;
}
bool CustomVar::operator<(const CustomVar& v) const {
if( thisRef.classId != v.thisRef.classId )
return thisRef.classId < v.thisRef.classId;
assert( thisRef.classId != ClassId(-1) );
std::vector<const AttrDesc*> attribs = getAttrDescs(thisRef.classId, true);
foreach(a, attribs) {
ScriptVar_t value = (*a)->get(this);
if(value != (*a)->get(&v))
return value < (*a)->get(&v);
}
return true;
}
void CustomVar::copyFrom(const CustomVar& v) {
assert( thisRef.classId != ClassId(-1) );
assert( v.thisRef.classId != ClassId(-1) );
assert( thisRef.classId == v.thisRef.classId );
std::vector<const AttrDesc*> attribs = getAttrDescs(thisRef.classId, true);
foreach(a, attribs) {
ScriptVar_t value = (*a)->get(&v);
if(value == (*a)->get(this)) continue;
(*a)->set(this, value);
}
}
void CustomVar::fromScriptVar(const ScriptVar_t& v) {
if(v.isCustomType()
&& v.customVar()->thisRef.classId != ClassId(-1)
&& v.customVar()->thisRef.classId == thisRef.classId
)
copyFrom(*v.customVar());
else
fromString(v.toString());
}
Result CustomVar::ToBytestream(CBytestream* bs, const CustomVar* diffTo) const {
assert( thisRef.classId != ClassId(-1) );
bs->writeInt16(thisRef.classId);
return toBytestream(bs, diffTo);
}
Result CustomVar::toBytestream(CBytestream *bs, const CustomVar* diffTo) const {
assert( thisRef.classId != ClassId(-1) );
if(diffTo)
assert( thisRef.classId == diffTo->thisRef.classId );
std::vector<const AttrDesc*> attribs = getAttrDescs(thisRef.classId, true);
size_t numChangesOld = 0;
size_t numChangesDefault = 0;
if(diffTo) {
foreach(a, attribs) {
ScriptVar_t value = (*a)->get(this);
if(value != (*a)->defaultValue) numChangesDefault++;
if(diffTo && value != (*a)->get(diffTo)) numChangesOld++;
}
}
if(diffTo && numChangesOld < numChangesDefault) {
bs->writeInt(CUSTOMVAR_STREAM_DiffToOld, 1);
foreach(a, attribs) {
ScriptVar_t value = (*a)->get(this);
if(value == (*a)->get(diffTo)) continue;
bs->writeInt16((*a)->objTypeId);
bs->writeInt16((*a)->attrId);
bs->writeVar(value);
}
bs->writeInt16(ClassId(-1));
}
else {
bs->writeInt(CUSTOMVAR_STREAM_DiffToDefault, 1);
foreach(a, attribs) {
ScriptVar_t value = (*a)->get(this);
if(value == (*a)->defaultValue) continue;
bs->writeInt16((*a)->objTypeId);
bs->writeInt16((*a)->attrId);
bs->writeVar(value);
}
bs->writeInt16(ClassId(-1));
}
return true;
}
Result CustomVar::fromBytestream(CBytestream *bs, bool expectDiffToDefault) {
assert( thisRef.classId != ClassId(-1) );
{
int streamType = bs->readInt(1);
switch(streamType) {
case CUSTOMVAR_STREAM_DiffToDefault: reset(); break;
case CUSTOMVAR_STREAM_DiffToOld:
if(expectDiffToDefault) {
errors << "CustomVar::fromBytestream: got unexpected diffToOld data on " << thisRef.description() << endl;
// continue anyway, there might be still something useful
}
/* nothing to do */ break;
default:
errors << "CustomVar::fromBytestream: got invalid streamType " << streamType << " for object " << thisRef.description() << endl;
// It doesn't really make sense to continue.
// This cannot be a bug, the stream is messed up.
return "stream messed up. invalid streamtype";
}
}
Result r = true;
while(true) {
AttribRef a;
a.objTypeId = bs->readInt16();
if(a.objTypeId == ClassId(-1)) break;
a.attrId = bs->readInt16();
const AttrDesc* attrDesc = a.getAttrDesc();
if(attrDesc == NULL) {
errors << "CustomVar::fromBytestream: unknown attrib " << a.objTypeId << ":" << a.attrId << " for object " << thisRef.description() << endl;
// try to continue
r = "unknown attrib";
bs->SkipVar();
continue;
}
const ClassInfo* classInfo = getClassInfo(a.objTypeId);
if(classInfo == NULL) {
errors << "CustomVar::fromBytestream: unknown class for attrib " << a.description() << " for object " << thisRef.description() << endl;
// try to continue
r = "unknown class";
bs->SkipVar();
continue;
}
if(!classInfo->isTypeOf(a.objTypeId)) {
errors << "CustomVar::fromBytestream: attrib " << a.description() << " does not belong to class " << classInfo->name << " for object " << thisRef.description() << endl;
// try to continue
r = "invalid attrib for class";
bs->SkipVar();
continue;
}
ScriptVar_t var;
bs->readVar(var);
attrDesc->set(this, var, true);
}
return r;
}
CustomVar::Ref CustomVar::FromBytestream( CBytestream* bs ) {
ClassId classId = bs->readInt16();
const ClassInfo* classInfo = getClassInfo(classId);
if(classInfo == NULL) {
errors << "CustomVar::FromBytestream: class ID " << classId << " unknown" << endl;
return NULL;
}
if(!classInfo->isTypeOf(LuaID<CustomVar>::value)) {
errors << "CustomVar::FromBytestream: class " << classInfo->name << " is not a CustomVar" << endl;
return NULL;
}
if(classInfo->id == LuaID<CustomVar>::value) {
errors << "CustomVar::FromBytestream: class " << classInfo->name << " is abstract" << endl;
return NULL;
}
CustomVar::Ref obj = (CustomVar*) classInfo->createInstance();
if(!obj) {
errors << "CustomVar::FromBytestream: couldn't create instance of " << classInfo->name << endl;
return NULL;
}
if(NegResult r = obj->fromBytestream(bs, true)) {
errors << "CustomVar::FromBytestream: error while reading " << classInfo->name << " instance: " << r.res.humanErrorMsg << endl;
// continue anyway, maybe we have some useful data
}
return obj;
}
// We cannot use the REGISTER_CLASS macro because we cannot instantiate it.
static bool registerClass_CustomVar() {
ClassInfo i;
i.id = LuaID<CustomVar>::value;
i.name = "CustomVar";
i.memSize = sizeof(CustomVar);
registerClass(i);
return true;
}
static bool registerClass_CustomVar_init = registerClass_CustomVar();
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2014-2018 Kartik Kumar ([email protected])
* Copyright (c) 2014-2016 Marko Jankovic, DFKI GmbH
* Copyright (c) 2014-2016 Natalia Ortiz, University of Southampton
* Copyright (c) 2014-2016 Juan Romero, University of Strathclyde
* Distributed under the MIT License.
* See accompanying file LICENSE.md or copy at http://opensource.org/licenses/MIT
*/
#ifndef ASTRO_RADIATION_PRESSURE_ACCELERATION_MODEL_HPP
#define ASTRO_RADIATION_PRESSURE_ACCELERATION_MODEL_HPP
#include "astro/constants.hpp"
namespace astro
{
//! Compute radiation pressure for complete absorption.
/*!
* Computes radiation pressure for complete absorption from a given energy flux:
*
* \f[
* P = \frac{W}{c}
* \f]
*
* where \f$P\f$ is the computed radiation pressure, \f$W\f$ is the energy flux, and \f$c\f$ is the
* speed of light.
*
* @tparam Real Floating-point type
* @param[in] energyFlux Energy flux generated by source, i.e., Sun [W m^-2]
* @return Computed radiation pressure [N m^-2]
*/
template< typename Real >
Real computeAbsorptionRadiationPressure( const Real energyFlux )
{
return energyFlux / ASTRO_SPEED_OF_LIGHT;
}
//! Compute radiation pressure.
/*!
* Computes radiation pressure at a specified distance from the source, e.g., the Sun, by scaling
* with respect to a given reference. Typically, the reference is taken to be the average energy
* flux at Earth, i.e., approximately 1 AU.
*
* Since the flux is inversely proportional to the square of the distance, the radiation presurre
* at a given distance is computed using the following equation:
*
* \f[
* P = P_{ref} \frac{R_{ref}^{2}}{R^{2}}
* \f]
*
* where \f$P\f$ is the computed radiation pressure, \f$P_{ref}\f$ is the reference radiation
* pressure, \f$R_{ref}\f$ is the reference distance, and \f$R\f$ is the specified distance.
*
* The distances can be given in any units, so long as they are both in the same units.
*
* @tparam Real Floating-point type
* @param[in] referenceRadiationPressure Reference radiation pressure [N m^-2]
* @param[in] referenceDistance Reference distance [AU]
* @param[in] distance Given distance from the Sun [AU]
* @return Radiation pressure at given distance [N m^-2]
*/
template< typename Real >
Real computeRadiationPressure( const Real referenceRadiationPressure,
const Real referenceDistance,
const Real distance )
{
return referenceRadiationPressure
* ( referenceDistance * referenceDistance / ( distance * distance ) );
}
//! Compute radiation pressure acceleration for a cannonball.
/*!
* Compute radiation pressure acceleration for a canonball. The model for the radiation
* pressure acceleration is given by (Montenbruck, 2000):
*
* \f[
* a = -C_{R} \frac{3}{4r\rho} P \vec{u}
* \f]
*
* where \f$P\f$ is the radiation pressure for complete absorption at a specified distance from the
* source, \f$C_{R}\f$ is the radiation pressure coefficient (\f$C_{R} = 1\f$ for complete
* absorption and \f$C_{R} = 2\f$ for specular reflection), \f$r\f$ is the radius of the
* cannonball, \f$ \rho \f$ is the bulk density of the cannonball, and \f$ \vec{u} \f$ is the unit
* vector pointing to the source of the radiation pressure, e.g., the Sun.
*
* This function can be used to compute the 1st-order effects of radiation pressure on small
* particles in the Solar System. The higher-order terms, stemming from Poynting-Robertson drag
* are neglected.
*
* @sa computeCannonballPoyntingRobertsonDragAcceleration
* @tparam Real Floating-point type
* @tparam Vector3 3-vector type
* @param[in] radiationPressure Radiation pressure [N m^-2]
* @param[in] radiationPressureCoefficient Radiation pressure coefficient [-]
* @param[in] unitVectorToSource Unit vector pointing to radiation source [-]
* @param[in] radius Radius of cannonball [m]
* @param[in] bulkDensity Bulk density of cannonball [kg m^-3]
* @return Computed radiation pressure acceleration [m s^-2]
*/
template< typename Real, typename Vector3 >
Vector3 computeCannonballRadiationPressureAcceleration( const Real radiationPressure,
const Real radiationPressureCoefficient,
const Vector3& unitVectorToSource,
const Real radius,
const Real bulkDensity )
{
Vector3 acceleration = unitVectorToSource;
const Real preMultiplier = -radiationPressure
* radiationPressureCoefficient
* 0.75 / ( radius * bulkDensity );
acceleration[ 0 ] = preMultiplier * unitVectorToSource[ 0 ];
acceleration[ 1 ] = preMultiplier * unitVectorToSource[ 1 ];
acceleration[ 2 ] = preMultiplier * unitVectorToSource[ 2 ];
return acceleration;
}
//! Compute Poynting-Roberson drag acceleration for a cannonball.
/*!
* Compute Poynting-Roberson (PR) drag acceleration for a cannonball. The model for PR drag
* acceleration in an inertial reference frame is given by (Mignard, 1984):
*
* \f[
* a = C_{R} \frac{3}{4r\rho} P \left[ \vec{u} \vec{V}^{T} \vec{u} + \vec{V} \right]
* \f]
*
* where \f$P\f$ is the radiation pressure for complete absorption at a specified distance from the
* source, \f$C_{R}\f$ is the radiation pressure coefficient (\f$C_{R} = 1\f$ for complete
* absorption and \f$C_{R} = 2\f$ for specular reflection), \f$r\f$ is the radius of the
* cannonball, \f$\rho\f$ is the bulk density of the cannonball, \f$ \vec{u} \f$ is the unit vector
* pointing from the source of the radiation pressure, e.g., the Sun, and \f$ \vec{V} \f$ is the
* total velocity of the cannonball in an inertial frame centered at the source.
*
* This function can be used to compute the higher-order effects of radiation pressure on small
* particles in the Solar System. The 1st-order effect (zeroth-order in \f$\frac{\vec{V}}{c}\f$) is
* not included.
*
* @sa computeCannonballRadiationPressureAcceleration
* @tparam Real Floating-point type
* @tparam Vector3 3-vector type
* @param[in] radiationPressure Radiation pressure [N m^-2]
* @param[in] radiationPressureCoefficient Radiation pressure coefficient [-]
* @param[in] unitVectorToSource Unit vector pointing to radiation source [-]
* @param[in] radius Radius of cannonball [m]
* @param[in] bulkDensity Bulk density of cannonball [kg m^-3]
* @param[in] velocity Total orbital velocity of cannonball wrt
* inertial centered at radiation source [m s^-1]
* @return Computed radiation pressure acceleration [m s^-2]
*/
template< typename Real, typename Vector3 >
Vector3 computeCannonballPoyntingRobertsonDragAcceleration(
const Real radiationPressure,
const Real radiationPressureCoefficient,
const Vector3& unitVectorToSource,
const Real radius,
const Real bulkDensity,
const Vector3& velocity )
{
Vector3 acceleration = unitVectorToSource;
const Real preMultiplier = radiationPressure
* radiationPressureCoefficient
* 0.75 / ( radius * bulkDensity * ASTRO_SPEED_OF_LIGHT );
acceleration[ 0 ]
= preMultiplier * ( ( unitVectorToSource[ 0 ] * unitVectorToSource[ 0 ] * velocity[ 0 ]
+ unitVectorToSource[ 0 ] * unitVectorToSource[ 1 ] * velocity[ 1 ]
+ unitVectorToSource[ 0 ] * unitVectorToSource[ 2 ] * velocity[ 2 ] )
+ velocity[ 0 ] );
acceleration[ 1 ]
= preMultiplier * ( ( unitVectorToSource[ 1 ] * unitVectorToSource[ 0 ] * velocity[ 0 ]
+ unitVectorToSource[ 1 ] * unitVectorToSource[ 1 ] * velocity[ 1 ]
+ unitVectorToSource[ 1 ] * unitVectorToSource[ 2 ] * velocity[ 2 ] )
+ velocity[ 1 ] );
acceleration[ 2 ]
= preMultiplier * ( ( unitVectorToSource[ 2 ] * unitVectorToSource[ 0 ] * velocity[ 0 ]
+ unitVectorToSource[ 2 ] * unitVectorToSource[ 1 ] * velocity[ 1 ]
+ unitVectorToSource[ 2 ] * unitVectorToSource[ 2 ] * velocity[ 2 ] )
+ velocity[ 2 ] );
return acceleration;
}
} // namespace astro
#endif // ASTRO_RADIATION_PRESSURE_ACCELERATION_MODEL_HPP
<commit_msg>Fix scalar equations for PR drag acceleration model after discerning notation error in Mignard (1984).<commit_after>/*
* Copyright (c) 2014-2018 Kartik Kumar ([email protected])
* Copyright (c) 2014-2016 Marko Jankovic, DFKI GmbH
* Copyright (c) 2014-2016 Natalia Ortiz, University of Southampton
* Copyright (c) 2014-2016 Juan Romero, University of Strathclyde
* Distributed under the MIT License.
* See accompanying file LICENSE.md or copy at http://opensource.org/licenses/MIT
*/
#ifndef ASTRO_RADIATION_PRESSURE_ACCELERATION_MODEL_HPP
#define ASTRO_RADIATION_PRESSURE_ACCELERATION_MODEL_HPP
#include "astro/constants.hpp"
namespace astro
{
//! Compute radiation pressure for complete absorption.
/*!
* Computes radiation pressure for complete absorption from a given energy flux:
*
* \f[
* P = \frac{W}{c}
* \f]
*
* where \f$P\f$ is the computed radiation pressure, \f$W\f$ is the energy flux, and \f$c\f$ is the
* speed of light.
*
* @tparam Real Floating-point type
* @param[in] energyFlux Energy flux generated by source, i.e., Sun [W m^-2]
* @return Computed radiation pressure [N m^-2]
*/
template< typename Real >
Real computeAbsorptionRadiationPressure( const Real energyFlux )
{
return energyFlux / ASTRO_SPEED_OF_LIGHT;
}
//! Compute radiation pressure.
/*!
* Computes radiation pressure at a specified distance from the source, e.g., the Sun, by scaling
* with respect to a given reference. Typically, the reference is taken to be the average energy
* flux at Earth, i.e., approximately 1 AU.
*
* Since the flux is inversely proportional to the square of the distance, the radiation presurre
* at a given distance is computed using the following equation:
*
* \f[
* P = P_{ref} \frac{R_{ref}^{2}}{R^{2}}
* \f]
*
* where \f$P\f$ is the computed radiation pressure, \f$P_{ref}\f$ is the reference radiation
* pressure, \f$R_{ref}\f$ is the reference distance, and \f$R\f$ is the specified distance.
*
* The distances can be given in any units, so long as they are both in the same units.
*
* @tparam Real Floating-point type
* @param[in] referenceRadiationPressure Reference radiation pressure [N m^-2]
* @param[in] referenceDistance Reference distance [AU]
* @param[in] distance Given distance from the Sun [AU]
* @return Radiation pressure at given distance [N m^-2]
*/
template< typename Real >
Real computeRadiationPressure( const Real referenceRadiationPressure,
const Real referenceDistance,
const Real distance )
{
return referenceRadiationPressure
* ( referenceDistance * referenceDistance / ( distance * distance ) );
}
//! Compute radiation pressure acceleration for a cannonball.
/*!
* Compute radiation pressure acceleration for a canonball. The model for the radiation
* pressure acceleration is given by (Montenbruck, 2000):
*
* \f[
* a = -C_{R} \frac{3}{4r\rho} P \vec{u}
* \f]
*
* where \f$P\f$ is the radiation pressure for complete absorption at a specified distance from the
* source, \f$C_{R}\f$ is the radiation pressure coefficient (\f$C_{R} = 1\f$ for complete
* absorption and \f$C_{R} = 2\f$ for specular reflection), \f$r\f$ is the radius of the
* cannonball, \f$ \rho \f$ is the bulk density of the cannonball, and \f$ \vec{u} \f$ is the unit
* vector pointing to the source of the radiation pressure, e.g., the Sun.
*
* This function can be used to compute the 1st-order effects of radiation pressure on small
* particles in the Solar System. The higher-order terms, stemming from Poynting-Robertson drag
* are neglected.
*
* @sa computeCannonballPoyntingRobertsonDragAcceleration
* @tparam Real Floating-point type
* @tparam Vector3 3-vector type
* @param[in] radiationPressure Radiation pressure [N m^-2]
* @param[in] radiationPressureCoefficient Radiation pressure coefficient [-]
* @param[in] unitVectorToSource Unit vector pointing to radiation source [-]
* @param[in] radius Radius of cannonball [m]
* @param[in] bulkDensity Bulk density of cannonball [kg m^-3]
* @return Computed radiation pressure acceleration [m s^-2]
*/
template< typename Real, typename Vector3 >
Vector3 computeCannonballRadiationPressureAcceleration( const Real radiationPressure,
const Real radiationPressureCoefficient,
const Vector3& unitVectorToSource,
const Real radius,
const Real bulkDensity )
{
Vector3 acceleration = unitVectorToSource;
const Real preMultiplier = -radiationPressure
* radiationPressureCoefficient
* 0.75 / ( radius * bulkDensity );
acceleration[ 0 ] = preMultiplier * unitVectorToSource[ 0 ];
acceleration[ 1 ] = preMultiplier * unitVectorToSource[ 1 ];
acceleration[ 2 ] = preMultiplier * unitVectorToSource[ 2 ];
return acceleration;
}
//! Compute Poynting-Roberson drag acceleration for a cannonball.
/*!
* Compute Poynting-Roberson (PR) drag acceleration for a cannonball. The model for PR drag
* acceleration in an inertial reference frame is given by (Mignard, 1984):
*
* \f[
* a = C_{R} \frac{3}{4r\rho} P \left[ \vec{u} \vec{V}^{T} \vec{u} + \vec{V} \right]
* \f]
*
* where \f$P\f$ is the radiation pressure for complete absorption at a specified distance from the
* source, \f$C_{R}\f$ is the radiation pressure coefficient (\f$C_{R} = 1\f$ for complete
* absorption and \f$C_{R} = 2\f$ for specular reflection), \f$r\f$ is the radius of the
* cannonball, \f$\rho\f$ is the bulk density of the cannonball, \f$ \vec{u} \f$ is the unit vector
* pointing from the source of the radiation pressure, e.g., the Sun, and \f$ \vec{V} \f$ is the
* total velocity of the cannonball in an inertial frame centered at the source.
*
* This function can be used to compute the higher-order effects of radiation pressure on small
* particles in the Solar System. The 1st-order effect (zeroth-order in \f$\frac{\vec{V}}{c}\f$) is
* not included.
*
* @sa computeCannonballRadiationPressureAcceleration
* @tparam Real Floating-point type
* @tparam Vector3 3-vector type
* @param[in] radiationPressure Radiation pressure [N m^-2]
* @param[in] radiationPressureCoefficient Radiation pressure coefficient [-]
* @param[in] unitVectorToSource Unit vector pointing to radiation source [-]
* @param[in] radius Radius of cannonball [m]
* @param[in] bulkDensity Bulk density of cannonball [kg m^-3]
* @param[in] velocity Total orbital velocity of cannonball wrt
* inertial centered at radiation source [m s^-1]
* @return Computed radiation pressure acceleration [m s^-2]
*/
template< typename Real, typename Vector3 >
Vector3 computeCannonballPoyntingRobertsonDragAcceleration(
const Real radiationPressure,
const Real radiationPressureCoefficient,
const Vector3& unitVectorToSource,
const Real radius,
const Real bulkDensity,
const Vector3& velocity )
{
Vector3 acceleration = unitVectorToSource;
const Real preMultiplier = radiationPressure
* radiationPressureCoefficient
* 0.75 / ( radius * bulkDensity * ASTRO_SPEED_OF_LIGHT );
acceleration[ 0 ]
= preMultiplier * ( unitVectorToSource[ 0 ] * unitVectorToSource[ 0 ] + 1.0 ) * velocity[ 0 ];
acceleration[ 1 ]
= preMultiplier * ( unitVectorToSource[ 1 ] * unitVectorToSource[ 1 ] + 1.0 ) * velocity[ 1 ];
acceleration[ 2 ]
= preMultiplier * ( unitVectorToSource[ 2 ] * unitVectorToSource[ 2 ] + 1.0 ) * velocity[ 2 ];
return acceleration;
}
} // namespace astro
#endif // ASTRO_RADIATION_PRESSURE_ACCELERATION_MODEL_HPP
<|endoftext|>
|
<commit_before>#ifndef HOUGH_IMAGE_HPP
#define HOUGH_IMAGE_HPP
#include "fast_hough.hh"
#include "vpp/algorithms/Line_tracker_4_sfm/Hough_Extruder/feature_matching_hough.hh"
#include "vpp/algorithms/Line_tracker_4_sfm/miscellanous/operations.hh"
namespace vpp{
int SobelX[3][3] =
{
-1, 0, 1,
-2, 0, 2,
-1, 0, 1
};
int SobelY[3][3] =
{
1, 2, 1,
0, 0, 0,
-1,-2,-1
};
template <typename type_>
inline
float function_diff(int k1,int k2)
{
return fabs((k1-k2)/(k1+k2));
}
class compare_1 {
public:
bool operator()(const int x,const int y) {
return x>y;
}
};
void Hough_Accumulator(image2d<uchar> img, int mode, int T_theta,Mat &bv,float acc_threshold)
{
typedef vfloat3 F;
typedef vuchar3 V;
int ncols,nrows;
ncols = img.ncols();
nrows = img.nrows();
int rhomax=int(sqrt(pow(ncols,2)+pow(nrows,2)));
int thetamax = T_theta;
float max_of_accu = 0;
image2d<uchar> out(img.domain());
std::vector<float> t_accumulator(rhomax*thetamax,0);
if(mode==hough_parallel)
{
Hough_Lines_Parallel(img,t_accumulator,thetamax,rhomax,max_of_accu,out,acc_threshold);
}
}
Mat Hough_Accumulator_Video_Map_and_Clusters(image2d<vuchar1> img, int mode, int T_theta,
std::vector<float>& t_accumulator, std::list<vint2> &interestedPoints, float rhomax)
{
typedef vfloat3 F;
typedef vuchar3 V;
float max_of_accu = 0;
if(mode==hough_parallel)
{
cout << "Parallel" << endl;
//interestedPoints = Hough_Lines_Parallel(img,t_accumulator,T_theta,max_of_accu,5);
return accumulatorToFrame(t_accumulator,
max_of_accu
,rhomax,T_theta);
}
}
cv::Mat Hough_Accumulator_Video_Clusters(image2d<vuchar1> img, int mode , int T_theta,
std::vector<float>& t_accumulator, std::list<vint2>& interestedPoints, float rhomax)
{
typedef vfloat3 F;
typedef vuchar3 V;
float max_of_accu = 0;
if(mode==hough_parallel)
{
cout << "Parallel" << endl;
//interestedPoints = Hough_Lines_Parallel(img,t_accumulator,T_theta,max_of_accu,5);
return accumulatorToFrame(interestedPoints,rhomax,T_theta);
}
}
int getThetaMax(Theta_max discr)
{
if(Theta_max::XLARGE == discr)
return 1500;
else if(Theta_max::LARGE == discr)
return 1000;
else if(Theta_max::MEDIUM == discr)
return 500;
else if(Theta_max::SMALL == discr)
return 255;
else
return 0;
}
int getWKF(With_Kalman_Filter wkf)
{
if(With_Kalman_Filter::YES == wkf)
{
return 1;
}
else{
return 0;
}
}
float getScaleRho(Sclare_rho discr)
{
if(Sclare_rho::SAME == discr)
return 1;
else if(Sclare_rho::THREE_QUART == discr)
return 0.75;
else if(Sclare_rho::HALF == discr)
return 0.5;
else if(Sclare_rho::ONE_QUART == discr)
return 0.25;
else
return 0;
}
cv::Mat accumulatorToFrame(std::vector<float> t_accumulator, float big_max, int rhomax, int T_theta)
{
Mat T(int(rhomax),int(T_theta),CV_8UC1);
for(int rho = 0 ; rho < rhomax ; rho ++ )
{
#pragma omp parallel for
for(int theta = 0 ; theta < T_theta ; theta++)
{
float res = ( t_accumulator[rho*T_theta + theta] * 255.0 ) / big_max;
uchar encoded = ( pow( (res / 255) , (1 / 2.2))) * 255;
T.at<uchar>(rho,theta) = encoded;
}
}
return T;
}
cv::Mat accumulatorToFrame(std::list<vint2> interestedPoints, int rhomax, int T_theta)
{
Mat T = Mat(int(rhomax),int(T_theta),CV_8UC1,cvScalar(0));
int r = 0;
for(auto& ip : interestedPoints)
{
//int radius = round(5-0.1*r);
circle(T,cv::Point(ip[1],ip[0]),1,Scalar(255),CV_FILLED,8,0);
r++;
//break;
}
return T;
}
void hough_image(int T_theta,float acc_threshold)
{
typedef image2d<uchar> Image;
Mat bv = cv::imread("m.png",0);
Image img = (from_opencv<uchar>(bv));
//timer t;
//t.start();
//for(int i=0 ; i < 1000 ; i++)
{
Hough_Accumulator(img,hough_parallel,T_theta,bv,acc_threshold);
}
//t.end();
//cout << " temps d'execution " << t.us()/1000.0 << endl;
}
}
#endif // HOUGH_IMAGE_HPP
<commit_msg>Update fast_hough.hpp<commit_after>#ifndef HOUGH_IMAGE_HPP
#define HOUGH_IMAGE_HPP
#include "fast_hough.hh"
#include "vpp/algorithms/Line_tracker_4_sfm/Hough_Extruder/feature_matching_hough.hh"
#include "vpp/algorithms/Line_tracker_4_sfm/miscellanous/operations.hh"
namespace vpp{
int SobelX[3][3] =
{
-1, 0, 1,
-2, 0, 2,
-1, 0, 1
};
int SobelY[3][3] =
{
1, 2, 1,
0, 0, 0,
-1,-2,-1
};
template <typename type_>
inline
float function_diff(int k1,int k2)
{
return fabs((k1-k2)/(k1+k2));
}
class compare_1 {
public:
bool operator()(const int x,const int y) {
return x>y;
}
};
void Hough_Accumulator(image2d<uchar> img, int T_theta,Mat &bv,float acc_threshold)
{
int ncols,nrows;
ncols = img.ncols();
nrows = img.nrows();
int rhomax=int(sqrt(pow(ncols,2)+pow(nrows,2)));
int thetamax = T_theta;
float max_of_accu = 0;
image2d<uchar> out(img.domain());
std::vector<float> t_accumulator(rhomax*thetamax,0);
Hough_Lines_Parallel(img,t_accumulator,thetamax,rhomax,max_of_accu,out,acc_threshold);
}
Mat Hough_Accumulator_Video_Map_and_Clusters(image2d<vuchar1> img, int mode, int T_theta,
std::vector<float>& t_accumulator, std::list<vint2> &interestedPoints, float rhomax)
{
float max_of_accu = 0;
cout << "Parallel" << endl;
//interestedPoints = Hough_Lines_Parallel(img,t_accumulator,T_theta,max_of_accu,5);
return accumulatorToFrame(t_accumulator,
max_of_accu
,rhomax,T_theta);
}
cv::Mat Hough_Accumulator_Video_Clusters(image2d<vuchar1> img, int mode , int T_theta,
std::vector<float>& t_accumulator, std::list<vint2>& interestedPoints, float rhomax)
{
float max_of_accu = 0;
cout << "Parallel" << endl;
//interestedPoints = Hough_Lines_Parallel(img,t_accumulator,T_theta,max_of_accu,5);
return accumulatorToFrame(interestedPoints,rhomax,T_theta);
}
int getThetaMax(Theta_max discr)
{
if(Theta_max::XLARGE == discr)
return 1500;
else if(Theta_max::LARGE == discr)
return 1000;
else if(Theta_max::MEDIUM == discr)
return 500;
else if(Theta_max::SMALL == discr)
return 255;
else
return 0;
}
int getWKF(With_Kalman_Filter wkf)
{
if(With_Kalman_Filter::YES == wkf)
{
return 1;
}
else{
return 0;
}
}
float getScaleRho(Sclare_rho discr)
{
if(Sclare_rho::SAME == discr)
return 1;
else if(Sclare_rho::THREE_QUART == discr)
return 0.75;
else if(Sclare_rho::HALF == discr)
return 0.5;
else if(Sclare_rho::ONE_QUART == discr)
return 0.25;
else
return 0;
}
cv::Mat accumulatorToFrame(std::vector<float> t_accumulator, float big_max, int rhomax, int T_theta)
{
Mat T(int(rhomax),int(T_theta),CV_8UC1);
for(int rho = 0 ; rho < rhomax ; rho ++ )
{
#pragma omp parallel for
for(int theta = 0 ; theta < T_theta ; theta++)
{
float res = ( t_accumulator[rho*T_theta + theta] * 255.0 ) / big_max;
uchar encoded = ( pow( (res / 255) , (1 / 2.2))) * 255;
T.at<uchar>(rho,theta) = encoded;
}
}
return T;
}
cv::Mat accumulatorToFrame(std::list<vint2> interestedPoints, int rhomax, int T_theta)
{
Mat T = Mat(int(rhomax),int(T_theta),CV_8UC1,cvScalar(0));
int r = 0;
for(auto& ip : interestedPoints)
{
//int radius = round(5-0.1*r);
circle(T,cv::Point(ip[1],ip[0]),1,Scalar(255),CV_FILLED,8,0);
r++;
//break;
}
return T;
}
void hough_image(int T_theta,float acc_threshold)
{
typedef image2d<uchar> Image;
Mat bv = cv::imread("m.png",0);
Image img = (from_opencv<uchar>(bv));
//timer t;
//t.start();
//for(int i=0 ; i < 1000 ; i++)
{
Hough_Accumulator(img,T_theta,bv,acc_threshold);
}
//t.end();
//cout << " temps d'execution " << t.us()/1000.0 << endl;
}
}
#endif // HOUGH_IMAGE_HPP
<|endoftext|>
|
<commit_before>//===--- SROA.cpp - Scalar Replacement of Aggregates ----------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Simplify aggregate types into scalar types.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "sil-sroa"
#include "swift/SILPasses/Passes.h"
#include "swift/SILPasses/Utils/Local.h"
#include "swift/SIL/SILInstruction.h"
#include "swift/SIL/SILVisitor.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SIL/SILModule.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Support/Debug.h"
using namespace swift;
using namespace swift::Lowering;
STATISTIC(NumExpand, "Number of instructions expanded.");
//===----------------------------------------------------------------------===//
// Higher Level Operation Expansion
//===----------------------------------------------------------------------===//
/// \brief Lower copy_addr into loads/stores/retain/release if we have a
/// non-address only type. We do this here so we can process the resulting
/// loads/stores.
///
/// This peephole implements the following optimizations:
///
/// copy_addr %0 to %1 : $*T
/// ->
/// %new = load %0 : $*T // Load the new value from the source
/// %old = load %1 : $*T // Load the old value from the destination
/// strong_retain %new : $T // Retain the new value
/// strong_release %old : $T // Release the old
/// store %new to %1 : $*T // Store the new value to the destination
///
/// copy_addr [take] %0 to %1 : $*T
/// ->
/// %new = load %0 : $*T
/// %old = load %1 : $*T
/// // no retain of %new!
/// strong_release %old : $T
/// store %new to %1 : $*T
///
/// copy_addr %0 to [initialization] %1 : $*T
/// ->
/// %new = load %0 : $*T
/// strong_retain %new : $T
/// // no load/release of %old!
/// store %new to %1 : $*T
///
/// copy_addr [take] %0 to [initialization] %1 : $*T
/// ->
/// %new = load %0 : $*T
/// // no retain of %new!
/// // no load/release of %old!
/// store %new to %1 : $*T
static bool expandCopyAddr(CopyAddrInst *CA) {
SILModule &M = CA->getModule();
SILValue Source = CA->getSrc();
// If we have an address only type don't do anything.
SILType SrcType = Source.getType();
if (SrcType.isAddressOnly(M))
return false;
SILBuilder Builder(CA);
// %new = load %0 : $*T
LoadInst *New = Builder.createLoad(CA->getLoc(), Source);
SILValue Destination = CA->getDest();
// If our object type is not trivial, we may need to release the old value and
// retain the new one.
// If we have a non-trivial type...
if (!SrcType.isTrivial(M)) {
// If we are not initializing:
// %old = load %1 : $*T
IsInitialization_t IsInit = CA->isInitializationOfDest();
LoadInst *Old = nullptr;
if (IsInitialization_t::IsNotInitialization == IsInit) {
Old = Builder.createLoad(CA->getLoc(), Destination);
}
// If we are not taking and have a reference type:
// strong_retain %new : $*T
// or if we have a non-trivial non-reference type.
// copy_value %new : $*T
IsTake_t IsTake = CA->isTakeOfSrc();
if (IsTake_t::IsNotTake == IsTake) {
if (SrcType.hasReferenceSemantics())
Builder.createStrongRetain(CA->getLoc(), New);
else
Builder.createCopyValue(CA->getLoc(), New);
}
// If we are not initializing:
// strong_release %old : $*T
// *or*
// destroy_value %new : $*T
if (Old) {
if (SrcType.hasReferenceSemantics())
Builder.createStrongRelease(CA->getLoc(), Old);
else
Builder.createDestroyValue(CA->getLoc(), Old);
}
}
// Create the store.
Builder.createStore(CA->getLoc(), New, Destination);
++NumExpand;
return true;
}
static bool expandDestroyAddr(DestroyAddrInst *DA) {
SILModule &Module = DA->getModule();
SILBuilder Builder(DA);
// Strength reduce destroy_addr inst into release/store if
// we have a non-address only type.
SILValue Addr = DA->getOperand();
// If we have an address only type, do nothing.
SILType Type = Addr.getType();
if (Type.isAddressOnly(Module))
return false;
// If we have a non-trivial type...
if (!Type.isTrivial(Module)) {
// If we have a type with reference semantics, emit a load/strong release.
LoadInst *LI = Builder.createLoad(DA->getLoc(), Addr);
if (Type.hasReferenceSemantics())
Builder.createStrongRelease(DA->getLoc(), LI);
else
Builder.createDestroyValue(DA->getLoc(), LI);
}
++NumExpand;
return true;
}
//===----------------------------------------------------------------------===//
// Top Level Driver
//===----------------------------------------------------------------------===//
static void processFunction(SILFunction &Fn) {
for (auto BI = Fn.begin(), BE = Fn.end(); BI != BE; ++BI) {
auto II = BI->begin(), IE = BI->end();
while (II != IE) {
SILInstruction *Inst = &*II;
DEBUG(llvm::dbgs() << "Visiting: " << *Inst);
if (auto *CA = dyn_cast<CopyAddrInst>(Inst))
if (expandCopyAddr(CA)) {
++II;
CA->eraseFromParent();
continue;
}
if (auto *DA = dyn_cast<DestroyAddrInst>(Inst))
if (expandDestroyAddr(DA)) {
++II;
DA->eraseFromParent();
continue;
}
++II;
}
}
}
void swift::performSILSROA(SILModule *M) {
DEBUG(llvm::dbgs() << "*** SIL SROA ***\n");
// For each function Fn in M...
for (auto &Fn : *M) {
// If Fn has no basic blocks skip it.
if (Fn.empty())
continue;
DEBUG(llvm::dbgs() << "***** Visiting " << Fn.getName() << " *****\n");
// Otherwise perform SROA and then verify it.
processFunction(Fn);
Fn.verify();
}
}
<commit_msg>Fix typo.<commit_after>//===--- SILSROA.cpp - Scalar Replacement of Aggregates -------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Simplify aggregate types into scalar types.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "sil-sroa"
#include "swift/SILPasses/Passes.h"
#include "swift/SILPasses/Utils/Local.h"
#include "swift/SIL/SILInstruction.h"
#include "swift/SIL/SILVisitor.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SIL/SILModule.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Support/Debug.h"
using namespace swift;
using namespace swift::Lowering;
STATISTIC(NumExpand, "Number of instructions expanded.");
//===----------------------------------------------------------------------===//
// Higher Level Operation Expansion
//===----------------------------------------------------------------------===//
/// \brief Lower copy_addr into loads/stores/retain/release if we have a
/// non-address only type. We do this here so we can process the resulting
/// loads/stores.
///
/// This peephole implements the following optimizations:
///
/// copy_addr %0 to %1 : $*T
/// ->
/// %new = load %0 : $*T // Load the new value from the source
/// %old = load %1 : $*T // Load the old value from the destination
/// strong_retain %new : $T // Retain the new value
/// strong_release %old : $T // Release the old
/// store %new to %1 : $*T // Store the new value to the destination
///
/// copy_addr [take] %0 to %1 : $*T
/// ->
/// %new = load %0 : $*T
/// %old = load %1 : $*T
/// // no retain of %new!
/// strong_release %old : $T
/// store %new to %1 : $*T
///
/// copy_addr %0 to [initialization] %1 : $*T
/// ->
/// %new = load %0 : $*T
/// strong_retain %new : $T
/// // no load/release of %old!
/// store %new to %1 : $*T
///
/// copy_addr [take] %0 to [initialization] %1 : $*T
/// ->
/// %new = load %0 : $*T
/// // no retain of %new!
/// // no load/release of %old!
/// store %new to %1 : $*T
static bool expandCopyAddr(CopyAddrInst *CA) {
SILModule &M = CA->getModule();
SILValue Source = CA->getSrc();
// If we have an address only type don't do anything.
SILType SrcType = Source.getType();
if (SrcType.isAddressOnly(M))
return false;
SILBuilder Builder(CA);
// %new = load %0 : $*T
LoadInst *New = Builder.createLoad(CA->getLoc(), Source);
SILValue Destination = CA->getDest();
// If our object type is not trivial, we may need to release the old value and
// retain the new one.
// If we have a non-trivial type...
if (!SrcType.isTrivial(M)) {
// If we are not initializing:
// %old = load %1 : $*T
IsInitialization_t IsInit = CA->isInitializationOfDest();
LoadInst *Old = nullptr;
if (IsInitialization_t::IsNotInitialization == IsInit) {
Old = Builder.createLoad(CA->getLoc(), Destination);
}
// If we are not taking and have a reference type:
// strong_retain %new : $*T
// or if we have a non-trivial non-reference type.
// copy_value %new : $*T
IsTake_t IsTake = CA->isTakeOfSrc();
if (IsTake_t::IsNotTake == IsTake) {
if (SrcType.hasReferenceSemantics())
Builder.createStrongRetain(CA->getLoc(), New);
else
Builder.createCopyValue(CA->getLoc(), New);
}
// If we are not initializing:
// strong_release %old : $*T
// *or*
// destroy_value %new : $*T
if (Old) {
if (SrcType.hasReferenceSemantics())
Builder.createStrongRelease(CA->getLoc(), Old);
else
Builder.createDestroyValue(CA->getLoc(), Old);
}
}
// Create the store.
Builder.createStore(CA->getLoc(), New, Destination);
++NumExpand;
return true;
}
static bool expandDestroyAddr(DestroyAddrInst *DA) {
SILModule &Module = DA->getModule();
SILBuilder Builder(DA);
// Strength reduce destroy_addr inst into release/store if
// we have a non-address only type.
SILValue Addr = DA->getOperand();
// If we have an address only type, do nothing.
SILType Type = Addr.getType();
if (Type.isAddressOnly(Module))
return false;
// If we have a non-trivial type...
if (!Type.isTrivial(Module)) {
// If we have a type with reference semantics, emit a load/strong release.
LoadInst *LI = Builder.createLoad(DA->getLoc(), Addr);
if (Type.hasReferenceSemantics())
Builder.createStrongRelease(DA->getLoc(), LI);
else
Builder.createDestroyValue(DA->getLoc(), LI);
}
++NumExpand;
return true;
}
//===----------------------------------------------------------------------===//
// Top Level Driver
//===----------------------------------------------------------------------===//
static void processFunction(SILFunction &Fn) {
for (auto BI = Fn.begin(), BE = Fn.end(); BI != BE; ++BI) {
auto II = BI->begin(), IE = BI->end();
while (II != IE) {
SILInstruction *Inst = &*II;
DEBUG(llvm::dbgs() << "Visiting: " << *Inst);
if (auto *CA = dyn_cast<CopyAddrInst>(Inst))
if (expandCopyAddr(CA)) {
++II;
CA->eraseFromParent();
continue;
}
if (auto *DA = dyn_cast<DestroyAddrInst>(Inst))
if (expandDestroyAddr(DA)) {
++II;
DA->eraseFromParent();
continue;
}
++II;
}
}
}
void swift::performSILSROA(SILModule *M) {
DEBUG(llvm::dbgs() << "*** SIL SROA ***\n");
// For each function Fn in M...
for (auto &Fn : *M) {
// If Fn has no basic blocks skip it.
if (Fn.empty())
continue;
DEBUG(llvm::dbgs() << "***** Visiting " << Fn.getName() << " *****\n");
// Otherwise perform SROA and then verify it.
processFunction(Fn);
Fn.verify();
}
}
<|endoftext|>
|
<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// author: Axel Naumann <[email protected]>
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------
#include "cling/Interpreter/StoredValueRef.h"
#include "cling/Interpreter/Interpreter.h"
#include "cling/Interpreter/Transaction.h"
#include "cling/Interpreter/ValuePrinter.h"
#include "cling/Utils/AST.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/ExecutionEngine/ExecutionEngine.h"
#include "llvm/ExecutionEngine/GenericValue.h"
#include "llvm/IR/Module.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/DeclCXX.h"
#include "clang/Frontend/CompilerInstance.h"
using namespace cling;
using namespace clang;
using namespace llvm;
StoredValueRef::StoredValue::StoredValue(Interpreter& interp,
QualType clangTy,
const llvm::Type* llvm_Ty)
: Value(GenericValue(), clangTy, llvm_Ty), m_Interp(interp), m_Mem(0){
if (clangTy->isIntegralOrEnumerationType() ||
clangTy->isRealFloatingType() ||
clangTy->hasPointerRepresentation()) {
return;
};
if (const MemberPointerType* MPT = clangTy->getAs<MemberPointerType>()) {
if (MPT->isMemberDataPointer()) {
return;
}
}
m_Mem = m_Buf;
const uint64_t size = (uint64_t) getAllocSizeInBytes();
if (size > sizeof(m_Buf)) {
m_Mem = new char[size];
}
setGV(llvm::PTOGV(m_Mem));
}
StoredValueRef::StoredValue::~StoredValue() {
// Destruct the object, then delete the memory if needed.
Destruct();
if (m_Mem != m_Buf)
delete [] m_Mem;
}
void* StoredValueRef::StoredValue::GetDtorWrapperPtr(CXXRecordDecl* CXXRD) {
std::string funcname;
{
llvm::raw_string_ostream namestr(funcname);
namestr << "__cling_StoredValue_Destruct_" << CXXRD;
}
std::string code("extern \"C\" void ");
{
std::string typeName
= utils::TypeName::GetFullyQualifiedName(getClangType(),
CXXRD->getASTContext());
std::string dtorName = CXXRD->getNameAsString();
code += funcname + "(void* obj){((" + typeName + "*)obj)->~"
+ dtorName + "();}";
}
return m_Interp.compileFunction(funcname, code, true /*ifUniq*/,
false /*withAccessControl*/);
}
void StoredValueRef::StoredValue::Destruct() {
// If applicable, call addr->~Type() to destruct the object.
// template <typename T> void destr(T* obj = 0) { (T)obj->~T(); }
// |-FunctionDecl destr 'void (struct XB *)'
// |-TemplateArgument type 'struct XB'
// |-ParmVarDecl obj 'struct XB *'
// `-CompoundStmt
// `-CXXMemberCallExpr 'void'
// `-MemberExpr '<bound member function type>' ->~XB
// `-ImplicitCastExpr 'struct XB *' <LValueToRValue>
// `-DeclRefExpr 'struct XB *' lvalue ParmVar 'obj' 'struct XB *'
QualType QT = getClangType();
const RecordType* RT = 0;
while (!RT) {
if (QT.isConstQualified())
return;
const clang::Type* Ty = QT.getTypePtr();
RT = dyn_cast<RecordType>(Ty);
if (!RT) {
const ElaboratedType* ET = 0;
const TemplateSpecializationType* TT = 0;
if ((ET = dyn_cast<ElaboratedType>(Ty)))
QT = ET->getNamedType();
else if ((TT = dyn_cast<TemplateSpecializationType>(Ty)))
QT = TT->desugar();
if (!RT && !ET && !TT)
return;
}
}
CXXRecordDecl* CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl());
if (!CXXRD || CXXRD->hasTrivialDestructor() || !CXXRD->getDeclName())
return;
CXXRD = CXXRD->getCanonicalDecl();
void* funcPtr = GetDtorWrapperPtr(CXXRD);
if (!funcPtr)
return;
typedef void (*DtorWrapperFunc_t)(void* obj);
// Go via void** to avoid fun-cast warning:
DtorWrapperFunc_t wrapperFuncPtr = *(DtorWrapperFunc_t*) &funcPtr;
(*wrapperFuncPtr)(getAs<void*>());
}
long long StoredValueRef::StoredValue::getAllocSizeInBytes() const {
const ASTContext& ctx = m_Interp.getCI()->getASTContext();
return (long long) ctx.getTypeSizeInChars(getClangType()).getQuantity();
}
void StoredValueRef::dump() const {
ASTContext& ctx = m_Value->m_Interp.getCI()->getASTContext();
valuePrinterInternal::StreamStoredValueRef(llvm::errs(), this, ctx);
}
StoredValueRef StoredValueRef::allocate(Interpreter& interp, QualType t,
const llvm::Type* llvmTy) {
return new StoredValue(interp, t, llvmTy);
}
StoredValueRef StoredValueRef::bitwiseCopy(Interpreter& interp,
const cling::Value& value) {
StoredValue* SValue
= new StoredValue(interp, value.getClangType(), value.getLLVMType());
if (SValue->m_Mem) {
const char* src = (const char*)value.getGV().PointerVal;
// It's not a pointer. LLVM stores a char[5] (i.e. 5 x i8) as an i40,
// so use that instead. We don't keep it as an int; instead, we "allocate"
// it as a "proper" char[5] in the m_Mem. "Allocate" because it uses the
// m_Buf, so no actual allocation happens.
uint64_t IntVal = value.getGV().IntVal.getSExtValue();
if (!src) src = (const char*)&IntVal;
memcpy(SValue->m_Mem, src,
SValue->getAllocSizeInBytes());
} else {
SValue->setGV(value.getGV());
}
return SValue;
}
<commit_msg>Add comments.<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// author: Axel Naumann <[email protected]>
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------
#include "cling/Interpreter/StoredValueRef.h"
#include "cling/Interpreter/Interpreter.h"
#include "cling/Interpreter/Transaction.h"
#include "cling/Interpreter/ValuePrinter.h"
#include "cling/Utils/AST.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/ExecutionEngine/ExecutionEngine.h"
#include "llvm/ExecutionEngine/GenericValue.h"
#include "llvm/IR/Module.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/DeclCXX.h"
#include "clang/Frontend/CompilerInstance.h"
using namespace cling;
using namespace clang;
using namespace llvm;
StoredValueRef::StoredValue::StoredValue(Interpreter& interp,
QualType clangTy,
const llvm::Type* llvm_Ty)
: Value(GenericValue(), clangTy, llvm_Ty), m_Interp(interp), m_Mem(0){
if (clangTy->isIntegralOrEnumerationType() ||
clangTy->isRealFloatingType() ||
clangTy->hasPointerRepresentation()) {
return;
};
if (const MemberPointerType* MPT = clangTy->getAs<MemberPointerType>()) {
if (MPT->isMemberDataPointer()) {
return;
}
}
m_Mem = m_Buf;
const uint64_t size = (uint64_t) getAllocSizeInBytes();
if (size > sizeof(m_Buf)) {
m_Mem = new char[size];
}
setGV(llvm::PTOGV(m_Mem));
}
StoredValueRef::StoredValue::~StoredValue() {
// Destruct the object, then delete the memory if needed.
Destruct();
if (m_Mem != m_Buf)
delete [] m_Mem;
}
void* StoredValueRef::StoredValue::GetDtorWrapperPtr(CXXRecordDecl* CXXRD) {
std::string funcname;
{
llvm::raw_string_ostream namestr(funcname);
namestr << "__cling_StoredValue_Destruct_" << CXXRD;
}
std::string code("extern \"C\" void ");
{
std::string typeName
= utils::TypeName::GetFullyQualifiedName(getClangType(),
CXXRD->getASTContext());
std::string dtorName = CXXRD->getNameAsString();
code += funcname + "(void* obj){((" + typeName + "*)obj)->~"
+ dtorName + "();}";
}
return m_Interp.compileFunction(funcname, code, true /*ifUniq*/,
false /*withAccessControl*/);
}
void StoredValueRef::StoredValue::Destruct() {
// If applicable, call addr->~Type() to destruct the object.
// template <typename T> void destr(T* obj = 0) { (T)obj->~T(); }
// |-FunctionDecl destr 'void (struct XB *)'
// |-TemplateArgument type 'struct XB'
// |-ParmVarDecl obj 'struct XB *'
// `-CompoundStmt
// `-CXXMemberCallExpr 'void'
// `-MemberExpr '<bound member function type>' ->~XB
// `-ImplicitCastExpr 'struct XB *' <LValueToRValue>
// `-DeclRefExpr 'struct XB *' lvalue ParmVar 'obj' 'struct XB *'
QualType QT = getClangType();
const RecordType* RT = 0;
// Find the underlying record type.
while (!RT) {
if (QT.isConstQualified())
return;
const clang::Type* Ty = QT.getTypePtr();
RT = dyn_cast<RecordType>(Ty);
if (!RT) {
const ElaboratedType* ET = 0;
const TemplateSpecializationType* TT = 0;
if ((ET = dyn_cast<ElaboratedType>(Ty)))
QT = ET->getNamedType();
else if ((TT = dyn_cast<TemplateSpecializationType>(Ty)))
QT = TT->desugar();
if (!RT && !ET && !TT)
return;
}
}
CXXRecordDecl* CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl());
// Freeing will happen either way; construction only exists for RecordDecls.
// And it's only worth calling it for non-trivial d'tors. But without
// synthesizing AST nodes we can only invoke the d'tor for named decls.
if (!CXXRD || CXXRD->hasTrivialDestructor() || !CXXRD->getDeclName())
return;
CXXRD = CXXRD->getCanonicalDecl();
void* funcPtr = GetDtorWrapperPtr(CXXRD);
if (!funcPtr)
return;
typedef void (*DtorWrapperFunc_t)(void* obj);
// Go via void** to avoid fun-cast warning:
DtorWrapperFunc_t wrapperFuncPtr = *(DtorWrapperFunc_t*) &funcPtr;
(*wrapperFuncPtr)(getAs<void*>());
}
long long StoredValueRef::StoredValue::getAllocSizeInBytes() const {
const ASTContext& ctx = m_Interp.getCI()->getASTContext();
return (long long) ctx.getTypeSizeInChars(getClangType()).getQuantity();
}
void StoredValueRef::dump() const {
ASTContext& ctx = m_Value->m_Interp.getCI()->getASTContext();
valuePrinterInternal::StreamStoredValueRef(llvm::errs(), this, ctx);
}
StoredValueRef StoredValueRef::allocate(Interpreter& interp, QualType t,
const llvm::Type* llvmTy) {
return new StoredValue(interp, t, llvmTy);
}
StoredValueRef StoredValueRef::bitwiseCopy(Interpreter& interp,
const cling::Value& value) {
StoredValue* SValue
= new StoredValue(interp, value.getClangType(), value.getLLVMType());
if (SValue->m_Mem) {
const char* src = (const char*)value.getGV().PointerVal;
// It's not a pointer. LLVM stores a char[5] (i.e. 5 x i8) as an i40,
// so use that instead. We don't keep it as an int; instead, we "allocate"
// it as a "proper" char[5] in the m_Mem. "Allocate" because it uses the
// m_Buf, so no actual allocation happens.
uint64_t IntVal = value.getGV().IntVal.getSExtValue();
if (!src) src = (const char*)&IntVal;
memcpy(SValue->m_Mem, src,
SValue->getAllocSizeInBytes());
} else {
SValue->setGV(value.getGV());
}
return SValue;
}
<|endoftext|>
|
<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------
// RUN: cat %s | %cling | FileCheck %s
// Checks for infinite recursion when we combine nested calls of process line
// with global initializers.
#include "cling/Interpreter/Interpreter.h"
class MyClass { public: MyClass(){ gCling->process("gCling->getVersion()");} };
MyClass *My = new MyClass(); // CHECK: (const char *) "cling http://cern.ch/cling
.q
<commit_msg>Update the test to more generically 'detect' the version.<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------
// RUN: cat %s | %cling | FileCheck %s
// Checks for infinite recursion when we combine nested calls of process line
// with global initializers.
#include "cling/Interpreter/Interpreter.h"
class MyClass { public: MyClass(){ gCling->process("gCling->getVersion()");} };
MyClass *My = new MyClass(); // CHECK: (const char *) "{{.*}}"
.q
<|endoftext|>
|
<commit_before>// Copyright (C) 2017 Elviss Strazdins
// This file is part of the Ouzel engine.
#include "TextureD3D11.h"
#include "core/Engine.h"
#include "RendererD3D11.h"
#include "utils/Log.h"
namespace ouzel
{
namespace graphics
{
static DXGI_FORMAT convertPixelFormat(PixelFormat pixelFormat)
{
switch (pixelFormat)
{
case PixelFormat::A8_UNORM: return DXGI_FORMAT_A8_UNORM;
case PixelFormat::R8_UNORM: return DXGI_FORMAT_R8_UNORM;
case PixelFormat::R8_SNORM: return DXGI_FORMAT_R8_SNORM;
case PixelFormat::R8_UINT: return DXGI_FORMAT_R8_UINT;
case PixelFormat::R8_SINT: return DXGI_FORMAT_R8_SINT;
case PixelFormat::R16_UNORM: return DXGI_FORMAT_R16_UNORM;
case PixelFormat::R16_SNORM: return DXGI_FORMAT_R16_SNORM;
case PixelFormat::R16_UINT: return DXGI_FORMAT_R16_UINT;
case PixelFormat::R16_SINT: return DXGI_FORMAT_R16_SINT;
case PixelFormat::R16_FLOAT: return DXGI_FORMAT_R16_FLOAT;
case PixelFormat::R32_UINT: return DXGI_FORMAT_R32_UINT;
case PixelFormat::R32_SINT: return DXGI_FORMAT_R32_SINT;
case PixelFormat::R32_FLOAT: return DXGI_FORMAT_R32_FLOAT;
case PixelFormat::RG8_UNORM: return DXGI_FORMAT_R8G8_UNORM;
case PixelFormat::RG8_SNORM: return DXGI_FORMAT_R8G8_SNORM;
case PixelFormat::RG8_UINT: return DXGI_FORMAT_R8G8_UINT;
case PixelFormat::RG8_SINT: return DXGI_FORMAT_R8G8_SINT;
case PixelFormat::RGB8_UNORM: return DXGI_FORMAT_UNKNOWN;
case PixelFormat::RGB8_SNORM: return DXGI_FORMAT_UNKNOWN;
case PixelFormat::RGB8_UINT: return DXGI_FORMAT_UNKNOWN;
case PixelFormat::RGB8_SINT: return DXGI_FORMAT_UNKNOWN;
case PixelFormat::RGBA8_UNORM: return DXGI_FORMAT_R8G8B8A8_UNORM;
case PixelFormat::RGBA8_SNORM: return DXGI_FORMAT_R8G8B8A8_SNORM;
case PixelFormat::RGBA8_UINT: return DXGI_FORMAT_R8G8B8A8_UINT;
case PixelFormat::RGBA8_SINT: return DXGI_FORMAT_R8G8B8A8_SINT;
case PixelFormat::ABGR8_UNORM: return DXGI_FORMAT_UNKNOWN;
case PixelFormat::RGBA16_UNORM: return DXGI_FORMAT_R16G16B16A16_UNORM;
case PixelFormat::RGBA16_SNORM: return DXGI_FORMAT_R16G16B16A16_SNORM;
case PixelFormat::RGBA16_UINT: return DXGI_FORMAT_R16G16B16A16_UINT;
case PixelFormat::RGBA16_SINT: return DXGI_FORMAT_R16G16B16A16_SINT;
case PixelFormat::RGBA16_FLOAT: return DXGI_FORMAT_R16G16B16A16_FLOAT;
case PixelFormat::RGBA32_UINT: return DXGI_FORMAT_R32G32B32A32_UINT;
case PixelFormat::RGBA32_SINT: return DXGI_FORMAT_R32G32B32A32_SINT;
case PixelFormat::RGBA32_FLOAT: return DXGI_FORMAT_R32G32B32A32_FLOAT;
case PixelFormat::R5G5B5A1_UNORM: return DXGI_FORMAT_UNKNOWN;
default: return DXGI_FORMAT_UNKNOWN;
}
}
TextureD3D11::TextureD3D11()
{
}
TextureD3D11::~TextureD3D11()
{
if (depthStencilTexture)
{
depthStencilTexture->Release();
}
if (depthStencilView)
{
depthStencilView->Release();
}
if (renderTargetView)
{
renderTargetView->Release();
}
if (resourceView)
{
resourceView->Release();
}
if (texture)
{
texture->Release();
}
if (samplerState)
{
samplerState->Release();
}
width = 0;
height = 0;
}
bool TextureD3D11::upload()
{
std::lock_guard<std::mutex> lock(uploadMutex);
if (dirty)
{
RendererD3D11* rendererD3D11 = static_cast<RendererD3D11*>(sharedEngine->getRenderer());
if (dirty & DIRTY_DATA)
{
if (size.v[0] > 0 &&
size.v[1] > 0)
{
if (!texture ||
static_cast<UINT>(size.v[0]) != width ||
static_cast<UINT>(size.v[1]) != height)
{
if (texture)
{
texture->Release();
}
if (resourceView)
{
resourceView->Release();
resourceView = nullptr;
}
width = static_cast<UINT>(size.v[0]);
height = static_cast<UINT>(size.v[1]);
D3D11_TEXTURE2D_DESC textureDesc;
textureDesc.Width = width;
textureDesc.Height = height;
textureDesc.MipLevels = (levels.size() > 1) ? 0 : 1;
textureDesc.ArraySize = 1;
textureDesc.Format = convertPixelFormat(pixelFormat);
textureDesc.Usage = (dynamic && !renderTarget) ? D3D11_USAGE_DYNAMIC : D3D11_USAGE_DEFAULT;
textureDesc.CPUAccessFlags = (dynamic && !renderTarget) ? D3D11_CPU_ACCESS_WRITE : 0;
textureDesc.SampleDesc.Count = sampleCount;
textureDesc.SampleDesc.Quality = 0;
textureDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE | (renderTarget ? D3D11_BIND_RENDER_TARGET : 0);
textureDesc.MiscFlags = 0;
HRESULT hr = rendererD3D11->getDevice()->CreateTexture2D(&textureDesc, nullptr, &texture);
if (FAILED(hr))
{
Log(Log::Level::ERR) << "Failed to create Direct3D 11 texture";
return false;
}
D3D11_SHADER_RESOURCE_VIEW_DESC resourceViewDesc;
resourceViewDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
resourceViewDesc.ViewDimension = (sampleCount > 1) ? D3D11_SRV_DIMENSION_TEXTURE2DMS : D3D11_SRV_DIMENSION_TEXTURE2D;
if (sampleCount == 1)
{
resourceViewDesc.Texture2D.MostDetailedMip = 0;
resourceViewDesc.Texture2D.MipLevels = static_cast<UINT>(levels.size());
}
hr = rendererD3D11->getDevice()->CreateShaderResourceView(texture, &resourceViewDesc, &resourceView);
if (FAILED(hr))
{
Log(Log::Level::ERR) << "Failed to create Direct3D 11 shader resource view";
return false;
}
if (renderTarget)
{
if (renderTargetView)
{
renderTargetView->Release();
}
D3D11_RENDER_TARGET_VIEW_DESC renderTargetViewDesc;
renderTargetViewDesc.Format = textureDesc.Format;
renderTargetViewDesc.ViewDimension = (sampleCount > 1) ? D3D11_RTV_DIMENSION_TEXTURE2DMS : D3D11_RTV_DIMENSION_TEXTURE2D;
if (sampleCount == 1)
{
renderTargetViewDesc.Texture2D.MipSlice = 0;
}
HRESULT hr = rendererD3D11->getDevice()->CreateRenderTargetView(texture, &renderTargetViewDesc, &renderTargetView);
if (FAILED(hr))
{
Log(Log::Level::ERR) << "Failed to create Direct3D 11 render target view";
return false;
}
}
if (depth)
{
if (depthStencilTexture)
{
depthStencilTexture->Release();
}
if (depthStencilView)
{
depthStencilView->Release();
depthStencilView = nullptr;
}
D3D11_TEXTURE2D_DESC depthStencilDesc;
depthStencilDesc.Width = width;
depthStencilDesc.Height = height;
depthStencilDesc.MipLevels = 1;
depthStencilDesc.ArraySize = 1;
depthStencilDesc.Format = DXGI_FORMAT_D32_FLOAT;
depthStencilDesc.SampleDesc.Count = sampleCount;
depthStencilDesc.SampleDesc.Quality = 0;
depthStencilDesc.Usage = D3D11_USAGE_DEFAULT;
depthStencilDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
depthStencilDesc.CPUAccessFlags = 0;
depthStencilDesc.MiscFlags = 0;
hr = rendererD3D11->getDevice()->CreateTexture2D(&depthStencilDesc, nullptr, &depthStencilTexture);
if (FAILED(hr))
{
Log(Log::Level::ERR) << "Failed to create Direct3D 11 depth stencil texture";
return false;
}
hr = rendererD3D11->getDevice()->CreateDepthStencilView(depthStencilTexture, nullptr, &depthStencilView);
if (FAILED(hr))
{
Log(Log::Level::ERR) << "Failed to create Direct3D 11 depth stencil view";
return false;
}
}
}
for (size_t level = 0; level < levels.size(); ++level)
{
if (!levels[level].data.empty())
{
rendererD3D11->getContext()->UpdateSubresource(texture, static_cast<UINT>(level),
nullptr, levels[level].data.data(),
static_cast<UINT>(levels[level].pitch), 0);
}
}
}
}
if (dirty & DIRTY_DATA)
{
clearFrameBufferView = clearColorBuffer;
clearDepthBufferView = clearDepthBuffer;
frameBufferClearColor[0] = clearColor.normR();
frameBufferClearColor[1] = clearColor.normG();
frameBufferClearColor[2] = clearColor.normB();
frameBufferClearColor[3] = clearColor.normA();
if (samplerState) samplerState->Release();
RendererD3D11::SamplerStateDesc samplerDesc;
samplerDesc.filter = (filter == Texture::Filter::DEFAULT) ? rendererD3D11->getTextureFilter() : filter;
samplerDesc.addressX = addressX;
samplerDesc.addressY = addressY;
samplerDesc.maxAnisotropy = (maxAnisotropy == 0) ? rendererD3D11->getMaxAnisotropy() : maxAnisotropy;
samplerState = rendererD3D11->getSamplerState(samplerDesc);
if (!samplerState)
{
Log(Log::Level::ERR) << "Failed to get D3D11 sampler state";
return false;
}
samplerState->AddRef();
}
dirty = 0;
}
return true;
}
} // namespace graphics
} // namespace ouzel
<commit_msg>Use the same pixel format for resource view as texture on Direct3D 11<commit_after>// Copyright (C) 2017 Elviss Strazdins
// This file is part of the Ouzel engine.
#include "TextureD3D11.h"
#include "core/Engine.h"
#include "RendererD3D11.h"
#include "utils/Log.h"
namespace ouzel
{
namespace graphics
{
static DXGI_FORMAT convertPixelFormat(PixelFormat pixelFormat)
{
switch (pixelFormat)
{
case PixelFormat::A8_UNORM: return DXGI_FORMAT_A8_UNORM;
case PixelFormat::R8_UNORM: return DXGI_FORMAT_R8_UNORM;
case PixelFormat::R8_SNORM: return DXGI_FORMAT_R8_SNORM;
case PixelFormat::R8_UINT: return DXGI_FORMAT_R8_UINT;
case PixelFormat::R8_SINT: return DXGI_FORMAT_R8_SINT;
case PixelFormat::R16_UNORM: return DXGI_FORMAT_R16_UNORM;
case PixelFormat::R16_SNORM: return DXGI_FORMAT_R16_SNORM;
case PixelFormat::R16_UINT: return DXGI_FORMAT_R16_UINT;
case PixelFormat::R16_SINT: return DXGI_FORMAT_R16_SINT;
case PixelFormat::R16_FLOAT: return DXGI_FORMAT_R16_FLOAT;
case PixelFormat::R32_UINT: return DXGI_FORMAT_R32_UINT;
case PixelFormat::R32_SINT: return DXGI_FORMAT_R32_SINT;
case PixelFormat::R32_FLOAT: return DXGI_FORMAT_R32_FLOAT;
case PixelFormat::RG8_UNORM: return DXGI_FORMAT_R8G8_UNORM;
case PixelFormat::RG8_SNORM: return DXGI_FORMAT_R8G8_SNORM;
case PixelFormat::RG8_UINT: return DXGI_FORMAT_R8G8_UINT;
case PixelFormat::RG8_SINT: return DXGI_FORMAT_R8G8_SINT;
case PixelFormat::RGB8_UNORM: return DXGI_FORMAT_UNKNOWN;
case PixelFormat::RGB8_SNORM: return DXGI_FORMAT_UNKNOWN;
case PixelFormat::RGB8_UINT: return DXGI_FORMAT_UNKNOWN;
case PixelFormat::RGB8_SINT: return DXGI_FORMAT_UNKNOWN;
case PixelFormat::RGBA8_UNORM: return DXGI_FORMAT_R8G8B8A8_UNORM;
case PixelFormat::RGBA8_SNORM: return DXGI_FORMAT_R8G8B8A8_SNORM;
case PixelFormat::RGBA8_UINT: return DXGI_FORMAT_R8G8B8A8_UINT;
case PixelFormat::RGBA8_SINT: return DXGI_FORMAT_R8G8B8A8_SINT;
case PixelFormat::ABGR8_UNORM: return DXGI_FORMAT_UNKNOWN;
case PixelFormat::RGBA16_UNORM: return DXGI_FORMAT_R16G16B16A16_UNORM;
case PixelFormat::RGBA16_SNORM: return DXGI_FORMAT_R16G16B16A16_SNORM;
case PixelFormat::RGBA16_UINT: return DXGI_FORMAT_R16G16B16A16_UINT;
case PixelFormat::RGBA16_SINT: return DXGI_FORMAT_R16G16B16A16_SINT;
case PixelFormat::RGBA16_FLOAT: return DXGI_FORMAT_R16G16B16A16_FLOAT;
case PixelFormat::RGBA32_UINT: return DXGI_FORMAT_R32G32B32A32_UINT;
case PixelFormat::RGBA32_SINT: return DXGI_FORMAT_R32G32B32A32_SINT;
case PixelFormat::RGBA32_FLOAT: return DXGI_FORMAT_R32G32B32A32_FLOAT;
case PixelFormat::R5G5B5A1_UNORM: return DXGI_FORMAT_UNKNOWN;
default: return DXGI_FORMAT_UNKNOWN;
}
}
TextureD3D11::TextureD3D11()
{
}
TextureD3D11::~TextureD3D11()
{
if (depthStencilTexture)
{
depthStencilTexture->Release();
}
if (depthStencilView)
{
depthStencilView->Release();
}
if (renderTargetView)
{
renderTargetView->Release();
}
if (resourceView)
{
resourceView->Release();
}
if (texture)
{
texture->Release();
}
if (samplerState)
{
samplerState->Release();
}
width = 0;
height = 0;
}
bool TextureD3D11::upload()
{
std::lock_guard<std::mutex> lock(uploadMutex);
if (dirty)
{
RendererD3D11* rendererD3D11 = static_cast<RendererD3D11*>(sharedEngine->getRenderer());
if (dirty & DIRTY_DATA)
{
if (size.v[0] > 0 &&
size.v[1] > 0)
{
if (!texture ||
static_cast<UINT>(size.v[0]) != width ||
static_cast<UINT>(size.v[1]) != height)
{
if (texture)
{
texture->Release();
}
if (resourceView)
{
resourceView->Release();
resourceView = nullptr;
}
width = static_cast<UINT>(size.v[0]);
height = static_cast<UINT>(size.v[1]);
D3D11_TEXTURE2D_DESC textureDesc;
textureDesc.Width = width;
textureDesc.Height = height;
textureDesc.MipLevels = (levels.size() > 1) ? 0 : 1;
textureDesc.ArraySize = 1;
textureDesc.Format = convertPixelFormat(pixelFormat);
textureDesc.Usage = (dynamic && !renderTarget) ? D3D11_USAGE_DYNAMIC : D3D11_USAGE_DEFAULT;
textureDesc.CPUAccessFlags = (dynamic && !renderTarget) ? D3D11_CPU_ACCESS_WRITE : 0;
textureDesc.SampleDesc.Count = sampleCount;
textureDesc.SampleDesc.Quality = 0;
textureDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE | (renderTarget ? D3D11_BIND_RENDER_TARGET : 0);
textureDesc.MiscFlags = 0;
HRESULT hr = rendererD3D11->getDevice()->CreateTexture2D(&textureDesc, nullptr, &texture);
if (FAILED(hr))
{
Log(Log::Level::ERR) << "Failed to create Direct3D 11 texture";
return false;
}
D3D11_SHADER_RESOURCE_VIEW_DESC resourceViewDesc;
resourceViewDesc.Format = textureDesc.Format;
resourceViewDesc.ViewDimension = (sampleCount > 1) ? D3D11_SRV_DIMENSION_TEXTURE2DMS : D3D11_SRV_DIMENSION_TEXTURE2D;
if (sampleCount == 1)
{
resourceViewDesc.Texture2D.MostDetailedMip = 0;
resourceViewDesc.Texture2D.MipLevels = static_cast<UINT>(levels.size());
}
hr = rendererD3D11->getDevice()->CreateShaderResourceView(texture, &resourceViewDesc, &resourceView);
if (FAILED(hr))
{
Log(Log::Level::ERR) << "Failed to create Direct3D 11 shader resource view";
return false;
}
if (renderTarget)
{
if (renderTargetView)
{
renderTargetView->Release();
}
D3D11_RENDER_TARGET_VIEW_DESC renderTargetViewDesc;
renderTargetViewDesc.Format = textureDesc.Format;
renderTargetViewDesc.ViewDimension = (sampleCount > 1) ? D3D11_RTV_DIMENSION_TEXTURE2DMS : D3D11_RTV_DIMENSION_TEXTURE2D;
if (sampleCount == 1)
{
renderTargetViewDesc.Texture2D.MipSlice = 0;
}
HRESULT hr = rendererD3D11->getDevice()->CreateRenderTargetView(texture, &renderTargetViewDesc, &renderTargetView);
if (FAILED(hr))
{
Log(Log::Level::ERR) << "Failed to create Direct3D 11 render target view";
return false;
}
}
if (depth)
{
if (depthStencilTexture)
{
depthStencilTexture->Release();
}
if (depthStencilView)
{
depthStencilView->Release();
depthStencilView = nullptr;
}
D3D11_TEXTURE2D_DESC depthStencilDesc;
depthStencilDesc.Width = width;
depthStencilDesc.Height = height;
depthStencilDesc.MipLevels = 1;
depthStencilDesc.ArraySize = 1;
depthStencilDesc.Format = DXGI_FORMAT_D32_FLOAT;
depthStencilDesc.SampleDesc.Count = sampleCount;
depthStencilDesc.SampleDesc.Quality = 0;
depthStencilDesc.Usage = D3D11_USAGE_DEFAULT;
depthStencilDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
depthStencilDesc.CPUAccessFlags = 0;
depthStencilDesc.MiscFlags = 0;
hr = rendererD3D11->getDevice()->CreateTexture2D(&depthStencilDesc, nullptr, &depthStencilTexture);
if (FAILED(hr))
{
Log(Log::Level::ERR) << "Failed to create Direct3D 11 depth stencil texture";
return false;
}
hr = rendererD3D11->getDevice()->CreateDepthStencilView(depthStencilTexture, nullptr, &depthStencilView);
if (FAILED(hr))
{
Log(Log::Level::ERR) << "Failed to create Direct3D 11 depth stencil view";
return false;
}
}
}
for (size_t level = 0; level < levels.size(); ++level)
{
if (!levels[level].data.empty())
{
rendererD3D11->getContext()->UpdateSubresource(texture, static_cast<UINT>(level),
nullptr, levels[level].data.data(),
static_cast<UINT>(levels[level].pitch), 0);
}
}
}
}
if (dirty & DIRTY_DATA)
{
clearFrameBufferView = clearColorBuffer;
clearDepthBufferView = clearDepthBuffer;
frameBufferClearColor[0] = clearColor.normR();
frameBufferClearColor[1] = clearColor.normG();
frameBufferClearColor[2] = clearColor.normB();
frameBufferClearColor[3] = clearColor.normA();
if (samplerState) samplerState->Release();
RendererD3D11::SamplerStateDesc samplerDesc;
samplerDesc.filter = (filter == Texture::Filter::DEFAULT) ? rendererD3D11->getTextureFilter() : filter;
samplerDesc.addressX = addressX;
samplerDesc.addressY = addressY;
samplerDesc.maxAnisotropy = (maxAnisotropy == 0) ? rendererD3D11->getMaxAnisotropy() : maxAnisotropy;
samplerState = rendererD3D11->getSamplerState(samplerDesc);
if (!samplerState)
{
Log(Log::Level::ERR) << "Failed to get D3D11 sampler state";
return false;
}
samplerState->AddRef();
}
dirty = 0;
}
return true;
}
} // namespace graphics
} // namespace ouzel
<|endoftext|>
|
<commit_before>#include "AssembledSolver.h"
#include <sofa/component/linearsolver/EigenSparseMatrix.h>
#include <sofa/component/linearsolver/EigenVector.h>
#include <sofa/core/ObjectFactory.h>
#include <sofa/simulation/common/MechanicalOperations.h>
#include <sofa/simulation/common/VectorOperations.h>
#include "AssemblyVisitor.h"
#include "utils/minres.h"
#include "utils/scoped.h"
namespace sofa {
namespace component {
namespace odesolver {
SOFA_DECL_CLASS(AssembledSolver);
int AssembledSolverClass = core::RegisterObject("Example compliance solver using assembly").add< AssembledSolver >();
using namespace sofa::defaulttype;
using namespace sofa::helper;
using namespace core::behavior;
AssembledSolver::AssembledSolver()
: use_velocity(initData(&use_velocity,
true,
"use_velocity",
"solve velocity dynamics (otherwise acceleration). this might cause damping when used with iterative solver unless warm_start is on.")),
warm_start(initData(&warm_start,
true,
"warm_start",
"warm start iterative solvers: avoids biasing solution towards zero (and speeds-up resolution)")),
propagate_lambdas(initData(&propagate_lambdas,
false,
"propagate_lambdas",
"propagate Lagrange multipliers in force vector at the end of time step"))
{
}
void AssembledSolver::send(simulation::Visitor& vis) {
scoped::timer step("visitor execution");
this->getContext()->executeVisitor( &vis );
}
void AssembledSolver::integrate(const core::MechanicalParams* params) {
scoped::timer step("position integration");
SReal dt = params->dt();
// integrate positions
sofa::simulation::common::VectorOperations vop( params, this->getContext() );
MultiVecCoord pos(&vop, core::VecCoordId::position() );
MultiVecDeriv vel(&vop, core::VecDerivId::velocity() );
typedef core::behavior::BaseMechanicalState::VMultiOp VMultiOp;
VMultiOp multi;
multi.resize(1);
multi[0].first = pos.id();
multi[0].second.push_back( std::make_pair(pos.id(), 1.0) );
multi[0].second.push_back( std::make_pair(vel.id(), dt) );
vop.v_multiop( multi );
}
void AssembledSolver::alloc(const core::ExecParams& params) {
scoped::timer step("lambdas alloc");
sofa::simulation::common::VectorOperations vop( ¶ms, this->getContext() );
lagrange.set(&vop);
lagrange.realloc( true );
}
AssembledSolver::~AssembledSolver() {
}
void AssembledSolver::cleanup() {
sofa::simulation::common::VectorOperations vop( core::ExecParams::defaultInstance(), this->getContext() );
vop.v_free( lagrange.id(), false );
}
void AssembledSolver::forces(const core::ExecParams& params) {
scoped::timer step("forces computation");
sofa::simulation::common::MechanicalOperations mop( ¶ms, this->getContext() );
sofa::simulation::common::VectorOperations vop( ¶ms, this->getContext() );
MultiVecDeriv f (&vop, core::VecDerivId::force() );
mop.computeForce(f);
// mop.projectResponse(f);
}
void AssembledSolver::propagate(const core::MechanicalParams* params) {
simulation::MechanicalPropagatePositionAndVelocityVisitor bob( params );
send( bob );
}
core::MechanicalParams AssembledSolver::mparams(const core::ExecParams& params,
double dt) const {
core::MechanicalParams res( params );
res.setMFactor( 1.0 );
res.setDt( dt );
res.setImplicitVelocity( 1 );
res.setImplicitPosition( 1 );
return res;
}
// implicit euler
linearsolver::KKTSolver::vec AssembledSolver::rhs(const system_type& sys) const {
kkt_type::vec res = kkt_type::vec::Zero( sys.size() );
if( use_velocity.getValue() ) {
res.head( sys.m ) = sys.P * (sys.p + sys.dt * sys.f);
} else {
// H = M - h^2 K
// p = M v
// hence hKv = 1/h ( p - H v )
kkt_type::vec hKv = (sys.p - (sys.H * sys.v)) / sys.dt;
res.head( sys.m ) = sys.P * (sys.f + hKv);
}
if( sys.n ) {
if( use_velocity.getValue() ) {
// remove velocity part from rhs as it's handled implicitly here
// (this is due to weird Compliance API, TODO fix this)
res.tail( sys.n ) = sys.phi + sys.J * sys.v;
} else {
res.tail( sys.n ) = sys.phi / sys.dt;
}
}
return res;
}
linearsolver::KKTSolver::vec AssembledSolver::warm(const system_type& sys) const {
kkt_type::vec res = kkt_type::vec::Zero( sys.size() );
// warm starting is a bad idea anyways
if( warm_start.getValue() ) {
if( use_velocity.getValue() ) {
res.head( sys.m ) = sys.P * sys.v;
if( sys.n ) res.tail( sys.n ) = sys.dt * sys.lambda;
} else {
if( sys.n ) res.tail( sys.n ) = sys.lambda;
}
}
return res;
}
// AssembledSolver::system_type AssembledSolver::assemble(const simulation::AssemblyVisitor& vis) const {
// system_type sys = vis.assemble();
// // TODO this should be done during system assembly
// // fix compliance
// if( sys.n ) {
// // std::cerr << "compliance" << std::endl;
// system_type::vec h = system_type::vec::Constant(sys.n, sys.dt);
// system_type::vec fix; fix.resize(sys.n);
// fix.array() = 1 / ( h.array() * (h.array() + sys.damping.array()) );
// sys.C = sys.C * fix.asDiagonal();
// }
// return sys;
// }
AssembledSolver::kkt_type::vec AssembledSolver::velocity(const system_type& sys,
const kkt_type::vec& x) const {
if( use_velocity.getValue() ) return sys.P * x.head( sys.m );
else return sys.P * (sys.v + sys.dt * x.head( sys.m ));
}
// this is a force
AssembledSolver::kkt_type::vec AssembledSolver::lambda(const system_type& sys,
const kkt_type::vec& x) const {
if( use_velocity.getValue() ) return x.tail( sys.n ) / sys.dt;
else return x.tail( sys.n );
}
struct propagate_visitor : simulation::MechanicalVisitor {
core::MultiVecDerivId out, in;
propagate_visitor(const sofa::core::MechanicalParams* mparams) : simulation::MechanicalVisitor(mparams) { }
Result fwdMechanicalState(simulation::Node* /*node*/, core::behavior::BaseMechanicalState* mm) {
// clear dst
mm->resetForce(this->params /* PARAMS FIRST */, out.getId(mm));
return RESULT_CONTINUE;
}
void bwdMechanicalMapping(simulation::Node* /*node*/, core::BaseMapping* map) {
map->applyJT(mparams /* PARAMS FIRST */, out, in);
}
};
void AssembledSolver::solve(const core::ExecParams* params,
double dt,
sofa::core::MultiVecCoordId ,
sofa::core::MultiVecDerivId ) {
assert(kkt && "i need a kkt solver lol");
// obtain mparams
core::MechanicalParams mparams = this->mparams(*params, dt);
// compute forces
forces( mparams );
// assembly visitor
simulation::AssemblyVisitor vis(&mparams);
// TODO do this inside visitor ctor instead
vis.lagrange = lagrange.id();
// fetch data
send( vis );
typedef linearsolver::AssembledSystem system_type;
sofa::helper::AdvancedTimer::stepBegin( "assembly" );
system_type sys = vis.assemble();
sofa::helper::AdvancedTimer::stepEnd( "assembly" );
// solution vector
system_type::vec x = warm( sys );
{
scoped::timer step("system solve");
kkt->factor( sys );
kkt->solve(x, sys, rhs( sys ) );
}
// distribute (projected) velocities
vis.distribute_master( core::VecId::velocity(), velocity(sys, x) );
if( sys.n ) {
vis.distribute_compliant( lagrange.id(), lambda(sys, x) );
if( propagate_lambdas.getValue() ) {
scoped::timer step("lambdas propagation");
propagate_visitor prop( &mparams );
prop.out = core::VecId::force();
prop.in = lagrange.id();
send( prop );
}
}
// update positions TODO use xResult/vResult
integrate( &mparams );
}
void AssembledSolver::init() {
// let's find a KKTSolver
kkt = this->getContext()->get<kkt_type>();
// TODO less dramatic error
if( !kkt ) throw std::logic_error("AssembledSolver needs a KKTSolver lol");
}
}
}
}
<commit_msg>r9683/sofa : Compliant: fixed inconsistency in state vector alloc/release<commit_after>#include "AssembledSolver.h"
#include <sofa/component/linearsolver/EigenSparseMatrix.h>
#include <sofa/component/linearsolver/EigenVector.h>
#include <sofa/core/ObjectFactory.h>
#include <sofa/simulation/common/MechanicalOperations.h>
#include <sofa/simulation/common/VectorOperations.h>
#include "AssemblyVisitor.h"
#include "utils/minres.h"
#include "utils/scoped.h"
namespace sofa {
namespace component {
namespace odesolver {
SOFA_DECL_CLASS(AssembledSolver);
int AssembledSolverClass = core::RegisterObject("Example compliance solver using assembly").add< AssembledSolver >();
using namespace sofa::defaulttype;
using namespace sofa::helper;
using namespace core::behavior;
AssembledSolver::AssembledSolver()
: use_velocity(initData(&use_velocity,
true,
"use_velocity",
"solve velocity dynamics (otherwise acceleration). this might cause damping when used with iterative solver unless warm_start is on.")),
warm_start(initData(&warm_start,
true,
"warm_start",
"warm start iterative solvers: avoids biasing solution towards zero (and speeds-up resolution)")),
propagate_lambdas(initData(&propagate_lambdas,
false,
"propagate_lambdas",
"propagate Lagrange multipliers in force vector at the end of time step"))
{
}
void AssembledSolver::send(simulation::Visitor& vis) {
scoped::timer step("visitor execution");
this->getContext()->executeVisitor( &vis );
}
void AssembledSolver::integrate(const core::MechanicalParams* params) {
scoped::timer step("position integration");
SReal dt = params->dt();
// integrate positions
sofa::simulation::common::VectorOperations vop( params, this->getContext() );
MultiVecCoord pos(&vop, core::VecCoordId::position() );
MultiVecDeriv vel(&vop, core::VecDerivId::velocity() );
typedef core::behavior::BaseMechanicalState::VMultiOp VMultiOp;
VMultiOp multi;
multi.resize(1);
multi[0].first = pos.id();
multi[0].second.push_back( std::make_pair(pos.id(), 1.0) );
multi[0].second.push_back( std::make_pair(vel.id(), dt) );
vop.v_multiop( multi );
}
void AssembledSolver::alloc(const core::ExecParams& params) {
scoped::timer step("lambdas alloc");
sofa::simulation::common::VectorOperations vop( ¶ms, this->getContext() );
lagrange.set(&vop);
lagrange.realloc( false );
}
AssembledSolver::~AssembledSolver() {
}
void AssembledSolver::cleanup() {
sofa::simulation::common::VectorOperations vop( core::ExecParams::defaultInstance(), this->getContext() );
vop.v_free( lagrange.id(), false );
}
void AssembledSolver::forces(const core::ExecParams& params) {
scoped::timer step("forces computation");
sofa::simulation::common::MechanicalOperations mop( ¶ms, this->getContext() );
sofa::simulation::common::VectorOperations vop( ¶ms, this->getContext() );
MultiVecDeriv f (&vop, core::VecDerivId::force() );
mop.computeForce(f);
// mop.projectResponse(f);
}
void AssembledSolver::propagate(const core::MechanicalParams* params) {
simulation::MechanicalPropagatePositionAndVelocityVisitor bob( params );
send( bob );
}
core::MechanicalParams AssembledSolver::mparams(const core::ExecParams& params,
double dt) const {
core::MechanicalParams res( params );
res.setMFactor( 1.0 );
res.setDt( dt );
res.setImplicitVelocity( 1 );
res.setImplicitPosition( 1 );
return res;
}
// implicit euler
linearsolver::KKTSolver::vec AssembledSolver::rhs(const system_type& sys) const {
kkt_type::vec res = kkt_type::vec::Zero( sys.size() );
if( use_velocity.getValue() ) {
res.head( sys.m ) = sys.P * (sys.p + sys.dt * sys.f);
} else {
// H = M - h^2 K
// p = M v
// hence hKv = 1/h ( p - H v )
kkt_type::vec hKv = (sys.p - (sys.H * sys.v)) / sys.dt;
res.head( sys.m ) = sys.P * (sys.f + hKv);
}
if( sys.n ) {
if( use_velocity.getValue() ) {
// remove velocity part from rhs as it's handled implicitly here
// (this is due to weird Compliance API, TODO fix this)
res.tail( sys.n ) = sys.phi + sys.J * sys.v;
} else {
res.tail( sys.n ) = sys.phi / sys.dt;
}
}
return res;
}
linearsolver::KKTSolver::vec AssembledSolver::warm(const system_type& sys) const {
kkt_type::vec res = kkt_type::vec::Zero( sys.size() );
// warm starting is a bad idea anyways
if( warm_start.getValue() ) {
if( use_velocity.getValue() ) {
res.head( sys.m ) = sys.P * sys.v;
if( sys.n ) res.tail( sys.n ) = sys.dt * sys.lambda;
} else {
if( sys.n ) res.tail( sys.n ) = sys.lambda;
}
}
return res;
}
// AssembledSolver::system_type AssembledSolver::assemble(const simulation::AssemblyVisitor& vis) const {
// system_type sys = vis.assemble();
// // TODO this should be done during system assembly
// // fix compliance
// if( sys.n ) {
// // std::cerr << "compliance" << std::endl;
// system_type::vec h = system_type::vec::Constant(sys.n, sys.dt);
// system_type::vec fix; fix.resize(sys.n);
// fix.array() = 1 / ( h.array() * (h.array() + sys.damping.array()) );
// sys.C = sys.C * fix.asDiagonal();
// }
// return sys;
// }
AssembledSolver::kkt_type::vec AssembledSolver::velocity(const system_type& sys,
const kkt_type::vec& x) const {
if( use_velocity.getValue() ) return sys.P * x.head( sys.m );
else return sys.P * (sys.v + sys.dt * x.head( sys.m ));
}
// this is a force
AssembledSolver::kkt_type::vec AssembledSolver::lambda(const system_type& sys,
const kkt_type::vec& x) const {
if( use_velocity.getValue() ) return x.tail( sys.n ) / sys.dt;
else return x.tail( sys.n );
}
struct propagate_visitor : simulation::MechanicalVisitor {
core::MultiVecDerivId out, in;
propagate_visitor(const sofa::core::MechanicalParams* mparams) : simulation::MechanicalVisitor(mparams) { }
Result fwdMechanicalState(simulation::Node* /*node*/, core::behavior::BaseMechanicalState* mm) {
// clear dst
mm->resetForce(this->params /* PARAMS FIRST */, out.getId(mm));
return RESULT_CONTINUE;
}
void bwdMechanicalMapping(simulation::Node* /*node*/, core::BaseMapping* map) {
map->applyJT(mparams /* PARAMS FIRST */, out, in);
}
};
void AssembledSolver::solve(const core::ExecParams* params,
double dt,
sofa::core::MultiVecCoordId ,
sofa::core::MultiVecDerivId ) {
assert(kkt && "i need a kkt solver lol");
// obtain mparams
core::MechanicalParams mparams = this->mparams(*params, dt);
// compute forces
forces( mparams );
// assembly visitor
simulation::AssemblyVisitor vis(&mparams);
// TODO do this inside visitor ctor instead
vis.lagrange = lagrange.id();
// fetch data
send( vis );
typedef linearsolver::AssembledSystem system_type;
sofa::helper::AdvancedTimer::stepBegin( "assembly" );
system_type sys = vis.assemble();
sofa::helper::AdvancedTimer::stepEnd( "assembly" );
// solution vector
system_type::vec x = warm( sys );
{
scoped::timer step("system solve");
kkt->factor( sys );
kkt->solve(x, sys, rhs( sys ) );
}
// distribute (projected) velocities
vis.distribute_master( core::VecId::velocity(), velocity(sys, x) );
if( sys.n ) {
vis.distribute_compliant( lagrange.id(), lambda(sys, x) );
if( propagate_lambdas.getValue() ) {
scoped::timer step("lambdas propagation");
propagate_visitor prop( &mparams );
prop.out = core::VecId::force();
prop.in = lagrange.id();
send( prop );
}
}
// update positions TODO use xResult/vResult
integrate( &mparams );
}
void AssembledSolver::init() {
// let's find a KKTSolver
kkt = this->getContext()->get<kkt_type>();
// TODO less dramatic error
if( !kkt ) throw std::logic_error("AssembledSolver needs a KKTSolver lol");
}
}
}
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt 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 "otbWrapperOutputImageParameter.h"
#include "otbClampImageFilter.h"
#include "otbClampVectorImageFilter.h"
namespace otb
{
namespace Wrapper
{
OutputImageParameter::OutputImageParameter()
: m_PixelType(ImagePixelType_float), m_RAMValue(0)
{
this->SetName("Output Image");
this->SetKey("out");
this->SetRole(Role_Output);
}
OutputImageParameter::~OutputImageParameter()
{
}
void OutputImageParameter::InitializeWriters()
{
m_UInt8Writer = UInt8WriterType::New();
m_Int16Writer = Int16WriterType::New();
m_UInt16Writer = UInt16WriterType::New();
m_Int32Writer = Int32WriterType::New();
m_UInt32Writer = UInt32WriterType::New();
m_FloatWriter = FloatWriterType::New();
m_DoubleWriter = DoubleWriterType::New();
m_VectorUInt8Writer = VectorUInt8WriterType::New();
m_VectorInt16Writer = VectorInt16WriterType::New();
m_VectorUInt16Writer = VectorUInt16WriterType::New();
m_VectorInt32Writer = VectorInt32WriterType::New();
m_VectorUInt32Writer = VectorUInt32WriterType::New();
m_VectorFloatWriter = VectorFloatWriterType::New();
m_VectorDoubleWriter = VectorDoubleWriterType::New();
m_RGBUInt8Writer = RGBUInt8WriterType::New();
m_RGBAUInt8Writer = RGBAUInt8WriterType::New();
}
#define otbClampAndWriteImageMacro(InputImageType, OutputImageType, writer) \
{ \
typedef otb::ClampImageFilter<InputImageType, OutputImageType> ClampFilterType; \
typename ClampFilterType::Pointer clampFilter = ClampFilterType::New(); \
clampFilter->SetInput( dynamic_cast<InputImageType*>(m_Image.GetPointer()) ); \
writer->SetFileName( this->GetFileName() ); \
writer->SetInput(clampFilter->GetOutput()); \
writer->SetAutomaticAdaptativeStreaming(m_RAMValue); \
writer->Update(); \
}
#define otbClampAndWriteVectorImageMacro(InputImageType, OutputImageType, writer) \
{ \
typedef otb::ClampVectorImageFilter<InputImageType, OutputImageType> ClampFilterType; \
typename ClampFilterType::Pointer clampFilter = ClampFilterType::New(); \
clampFilter->SetInput( dynamic_cast<InputImageType*>(m_Image.GetPointer()) ); \
writer->SetFileName(this->GetFileName() ); \
writer->SetInput(clampFilter->GetOutput()); \
writer->SetAutomaticAdaptativeStreaming(m_RAMValue); \
writer->Update(); \
}
template <class TInputImageType>
void
OutputImageParameter::SwitchImageWrite()
{
switch(m_PixelType )
{
case ImagePixelType_uint8:
{
otbClampAndWriteImageMacro(TInputImageType, UInt8ImageType, m_UInt8Writer);
break;
}
case ImagePixelType_int16:
{
otbClampAndWriteImageMacro(TInputImageType, Int16ImageType, m_Int16Writer);
break;
}
case ImagePixelType_uint16:
{
otbClampAndWriteImageMacro(TInputImageType, UInt16ImageType, m_UInt16Writer);
break;
}
case ImagePixelType_int32:
{
otbClampAndWriteImageMacro(TInputImageType, Int32ImageType, m_Int32Writer);
break;
}
case ImagePixelType_uint32:
{
otbClampAndWriteImageMacro(TInputImageType, UInt32ImageType, m_UInt32Writer);
break;
}
case ImagePixelType_float:
{
otbClampAndWriteImageMacro(TInputImageType, FloatImageType, m_FloatWriter);
break;
}
case ImagePixelType_double:
{
otbClampAndWriteImageMacro(TInputImageType, DoubleImageType, m_DoubleWriter);
break;
}
}
}
template <class TInputVectorImageType>
void
OutputImageParameter::SwitchVectorImageWrite()
{
switch(m_PixelType )
{
case ImagePixelType_uint8:
{
otbClampAndWriteVectorImageMacro(TInputVectorImageType, UInt8VectorImageType, m_VectorUInt8Writer);
break;
}
case ImagePixelType_int16:
{
otbClampAndWriteVectorImageMacro(TInputVectorImageType, Int16VectorImageType, m_VectorInt16Writer);
break;
}
case ImagePixelType_uint16:
{
otbClampAndWriteVectorImageMacro(TInputVectorImageType, UInt16VectorImageType, m_VectorUInt16Writer);
break;
}
case ImagePixelType_int32:
{
otbClampAndWriteVectorImageMacro(TInputVectorImageType, Int32VectorImageType, m_VectorInt32Writer);
break;
}
case ImagePixelType_uint32:
{
otbClampAndWriteVectorImageMacro(TInputVectorImageType, UInt32VectorImageType, m_VectorUInt32Writer);
break;
}
case ImagePixelType_float:
{
otbClampAndWriteVectorImageMacro(TInputVectorImageType, FloatVectorImageType, m_VectorFloatWriter);
break;
}
case ImagePixelType_double:
{
otbClampAndWriteVectorImageMacro(TInputVectorImageType, DoubleVectorImageType, m_VectorDoubleWriter);
break;
}
}
}
template <class TInputRGBAImageType>
void
OutputImageParameter::SwitchRGBAImageWrite()
{
if( m_PixelType == ImagePixelType_uint8 )
{
m_RGBAUInt8Writer->SetFileName( this->GetFileName() );
m_RGBAUInt8Writer->SetInput(dynamic_cast<UInt8RGBAImageType*>(m_Image.GetPointer()) );
m_RGBAUInt8Writer->SetAutomaticAdaptativeStreaming(m_RAMValue);
m_RGBAUInt8Writer->Update();
}
else
itkExceptionMacro("Unknown PixelType for RGBA Image.");
}
template <class TInputRGBImageType>
void
OutputImageParameter::SwitchRGBImageWrite()
{
if( m_PixelType == ImagePixelType_uint8 )
{
m_RGBUInt8Writer->SetFileName( this->GetFileName() );
m_RGBUInt8Writer->SetInput(dynamic_cast<UInt8RGBImageType*>(m_Image.GetPointer()) );
m_RGBUInt8Writer->SetAutomaticAdaptativeStreaming(m_RAMValue);
m_RGBUInt8Writer->Update();
}
else
itkExceptionMacro("Unknown PixelType for RGB Image.");
}
void
OutputImageParameter::Write()
{
m_Image->UpdateOutputInformation();
if (dynamic_cast<UInt8ImageType*>(m_Image.GetPointer()))
{
SwitchImageWrite<UInt8ImageType>();
}
else if (dynamic_cast<Int16ImageType*>(m_Image.GetPointer()))
{
SwitchImageWrite<Int16ImageType>();
}
else if (dynamic_cast<UInt16ImageType*>(m_Image.GetPointer()))
{
SwitchImageWrite<UInt16ImageType>();
}
else if (dynamic_cast<Int32ImageType*>(m_Image.GetPointer()))
{
SwitchImageWrite<Int32ImageType>();
}
else if (dynamic_cast<UInt32ImageType*>(m_Image.GetPointer()))
{
SwitchImageWrite<UInt32ImageType>();
}
else if (dynamic_cast<FloatImageType*>(m_Image.GetPointer()))
{
SwitchImageWrite<FloatImageType>();
}
else if (dynamic_cast<DoubleImageType*>(m_Image.GetPointer()))
{
SwitchImageWrite<DoubleImageType>();
}
else if (dynamic_cast<UInt8VectorImageType*>(m_Image.GetPointer()))
{
SwitchVectorImageWrite<UInt8VectorImageType>();
}
else if (dynamic_cast<Int16VectorImageType*>(m_Image.GetPointer()))
{
SwitchVectorImageWrite<Int16VectorImageType>();
}
else if (dynamic_cast<UInt16VectorImageType*>(m_Image.GetPointer()))
{
SwitchVectorImageWrite<UInt16VectorImageType>();
}
else if (dynamic_cast<Int32VectorImageType*>(m_Image.GetPointer()))
{
SwitchVectorImageWrite<Int32VectorImageType>();
}
else if (dynamic_cast<UInt32VectorImageType*>(m_Image.GetPointer()))
{
SwitchVectorImageWrite<UInt32VectorImageType>();
}
else if (dynamic_cast<FloatVectorImageType*>(m_Image.GetPointer()))
{
SwitchVectorImageWrite<FloatVectorImageType>();
}
else if (dynamic_cast<DoubleVectorImageType*>(m_Image.GetPointer()))
{
SwitchVectorImageWrite<DoubleVectorImageType>();
}
else if (dynamic_cast<UInt8RGBImageType*>(m_Image.GetPointer()))
{
SwitchRGBImageWrite<UInt8RGBImageType>();
}
else if (dynamic_cast<UInt8RGBAImageType*>(m_Image.GetPointer()))
{
SwitchRGBAImageWrite<UInt8RGBAImageType>();
}
else
{
itkExceptionMacro("Unknown image type");
}
}
itk::ProcessObject*
OutputImageParameter::GetWriter()
{
int type = 0;
// 0 : image
// 1 : VectorImage
// 2 : RGBAImage
// 3 : RGBImage
itk::ProcessObject* writer = 0;
if (dynamic_cast<UInt8VectorImageType*> (m_Image.GetPointer())
|| dynamic_cast<Int16VectorImageType*> (m_Image.GetPointer())
|| dynamic_cast<UInt16VectorImageType*> (m_Image.GetPointer())
|| dynamic_cast<Int32VectorImageType*> (m_Image.GetPointer())
|| dynamic_cast<UInt32VectorImageType*> (m_Image.GetPointer())
|| dynamic_cast<FloatVectorImageType*> (m_Image.GetPointer())
|| dynamic_cast<DoubleVectorImageType*> (m_Image.GetPointer()))
{
type = 1;
}
else
if (dynamic_cast<UInt8RGBAImageType*> (m_Image.GetPointer()))
{
type = 2;
writer = m_RGBAUInt8Writer;
itkWarningMacro("UInt8RGBAImageType will be saved in UInt8 format.");
return writer;
}
else
if (dynamic_cast<UInt8RGBImageType*> (m_Image.GetPointer()))
{
type = 3;
writer = m_RGBUInt8Writer;
itkWarningMacro("UInt8RGBImageType will be saved in UInt8 format.");
return writer;
}
switch (GetPixelType())
{
case ImagePixelType_uint8:
{
if (type == 1)
writer = m_VectorUInt8Writer;
else
if (type == 0)
writer = m_UInt8Writer;
else
if (type == 2)
writer = m_RGBAUInt8Writer;
else writer = m_RGBUInt8Writer;
break;
}
case ImagePixelType_int16:
{
if (type == 1)
writer = m_VectorInt16Writer;
else
if (type == 0) writer = m_Int16Writer;
break;
}
case ImagePixelType_uint16:
{
if (type == 1)
writer = m_VectorUInt16Writer;
else
if (type == 0) writer = m_UInt16Writer;
break;
}
case ImagePixelType_int32:
{
if (type == 1)
writer = m_VectorInt32Writer;
else
if (type == 0) writer = m_Int32Writer;
break;
}
case ImagePixelType_uint32:
{
if (type == 1)
writer = m_VectorUInt32Writer;
else
if (type == 0) writer = m_UInt32Writer;
break;
}
case ImagePixelType_float:
{
if (type == 1)
writer = m_VectorFloatWriter;
else
if (type == 0) writer = m_FloatWriter;
break;
}
case ImagePixelType_double:
{
if (type == 1)
writer = m_VectorDoubleWriter;
else
if (type == 0) writer = m_DoubleWriter;
break;
}
}
if (0 == writer)
{
itkExceptionMacro("Unknown Writer type.");
}
return writer;
}
OutputImageParameter::ImageBaseType*
OutputImageParameter::GetValue( )
{
return m_Image;
}
void
OutputImageParameter::SetValue(ImageBaseType* image)
{
m_Image = image;
SetActive(true);
}
bool
OutputImageParameter::HasValue() const
{
std::string filename(this->GetFileName());
return !filename.empty();
}
}
}
<commit_msg>DOC: add information about failure, to help user to understand why process fails in colormapping application using RGB image with wrong pixel type.<commit_after>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt 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 "otbWrapperOutputImageParameter.h"
#include "otbClampImageFilter.h"
#include "otbClampVectorImageFilter.h"
namespace otb
{
namespace Wrapper
{
OutputImageParameter::OutputImageParameter()
: m_PixelType(ImagePixelType_float), m_RAMValue(0)
{
this->SetName("Output Image");
this->SetKey("out");
this->SetRole(Role_Output);
}
OutputImageParameter::~OutputImageParameter()
{
}
void OutputImageParameter::InitializeWriters()
{
m_UInt8Writer = UInt8WriterType::New();
m_Int16Writer = Int16WriterType::New();
m_UInt16Writer = UInt16WriterType::New();
m_Int32Writer = Int32WriterType::New();
m_UInt32Writer = UInt32WriterType::New();
m_FloatWriter = FloatWriterType::New();
m_DoubleWriter = DoubleWriterType::New();
m_VectorUInt8Writer = VectorUInt8WriterType::New();
m_VectorInt16Writer = VectorInt16WriterType::New();
m_VectorUInt16Writer = VectorUInt16WriterType::New();
m_VectorInt32Writer = VectorInt32WriterType::New();
m_VectorUInt32Writer = VectorUInt32WriterType::New();
m_VectorFloatWriter = VectorFloatWriterType::New();
m_VectorDoubleWriter = VectorDoubleWriterType::New();
m_RGBUInt8Writer = RGBUInt8WriterType::New();
m_RGBAUInt8Writer = RGBAUInt8WriterType::New();
}
#define otbClampAndWriteImageMacro(InputImageType, OutputImageType, writer) \
{ \
typedef otb::ClampImageFilter<InputImageType, OutputImageType> ClampFilterType; \
typename ClampFilterType::Pointer clampFilter = ClampFilterType::New(); \
clampFilter->SetInput( dynamic_cast<InputImageType*>(m_Image.GetPointer()) ); \
writer->SetFileName( this->GetFileName() ); \
writer->SetInput(clampFilter->GetOutput()); \
writer->SetAutomaticAdaptativeStreaming(m_RAMValue); \
writer->Update(); \
}
#define otbClampAndWriteVectorImageMacro(InputImageType, OutputImageType, writer) \
{ \
typedef otb::ClampVectorImageFilter<InputImageType, OutputImageType> ClampFilterType; \
typename ClampFilterType::Pointer clampFilter = ClampFilterType::New(); \
clampFilter->SetInput( dynamic_cast<InputImageType*>(m_Image.GetPointer()) ); \
writer->SetFileName(this->GetFileName() ); \
writer->SetInput(clampFilter->GetOutput()); \
writer->SetAutomaticAdaptativeStreaming(m_RAMValue); \
writer->Update(); \
}
template <class TInputImageType>
void
OutputImageParameter::SwitchImageWrite()
{
switch(m_PixelType )
{
case ImagePixelType_uint8:
{
otbClampAndWriteImageMacro(TInputImageType, UInt8ImageType, m_UInt8Writer);
break;
}
case ImagePixelType_int16:
{
otbClampAndWriteImageMacro(TInputImageType, Int16ImageType, m_Int16Writer);
break;
}
case ImagePixelType_uint16:
{
otbClampAndWriteImageMacro(TInputImageType, UInt16ImageType, m_UInt16Writer);
break;
}
case ImagePixelType_int32:
{
otbClampAndWriteImageMacro(TInputImageType, Int32ImageType, m_Int32Writer);
break;
}
case ImagePixelType_uint32:
{
otbClampAndWriteImageMacro(TInputImageType, UInt32ImageType, m_UInt32Writer);
break;
}
case ImagePixelType_float:
{
otbClampAndWriteImageMacro(TInputImageType, FloatImageType, m_FloatWriter);
break;
}
case ImagePixelType_double:
{
otbClampAndWriteImageMacro(TInputImageType, DoubleImageType, m_DoubleWriter);
break;
}
}
}
template <class TInputVectorImageType>
void
OutputImageParameter::SwitchVectorImageWrite()
{
switch(m_PixelType )
{
case ImagePixelType_uint8:
{
otbClampAndWriteVectorImageMacro(TInputVectorImageType, UInt8VectorImageType, m_VectorUInt8Writer);
break;
}
case ImagePixelType_int16:
{
otbClampAndWriteVectorImageMacro(TInputVectorImageType, Int16VectorImageType, m_VectorInt16Writer);
break;
}
case ImagePixelType_uint16:
{
otbClampAndWriteVectorImageMacro(TInputVectorImageType, UInt16VectorImageType, m_VectorUInt16Writer);
break;
}
case ImagePixelType_int32:
{
otbClampAndWriteVectorImageMacro(TInputVectorImageType, Int32VectorImageType, m_VectorInt32Writer);
break;
}
case ImagePixelType_uint32:
{
otbClampAndWriteVectorImageMacro(TInputVectorImageType, UInt32VectorImageType, m_VectorUInt32Writer);
break;
}
case ImagePixelType_float:
{
otbClampAndWriteVectorImageMacro(TInputVectorImageType, FloatVectorImageType, m_VectorFloatWriter);
break;
}
case ImagePixelType_double:
{
otbClampAndWriteVectorImageMacro(TInputVectorImageType, DoubleVectorImageType, m_VectorDoubleWriter);
break;
}
}
}
template <class TInputRGBAImageType>
void
OutputImageParameter::SwitchRGBAImageWrite()
{
if( m_PixelType == ImagePixelType_uint8 )
{
m_RGBAUInt8Writer->SetFileName( this->GetFileName() );
m_RGBAUInt8Writer->SetInput(dynamic_cast<UInt8RGBAImageType*>(m_Image.GetPointer()) );
m_RGBAUInt8Writer->SetAutomaticAdaptativeStreaming(m_RAMValue);
m_RGBAUInt8Writer->Update();
}
else
itkExceptionMacro("Unknown PixelType for RGBA Image. Only uint8 is supported.");
}
template <class TInputRGBImageType>
void
OutputImageParameter::SwitchRGBImageWrite()
{
if( m_PixelType == ImagePixelType_uint8 )
{
m_RGBUInt8Writer->SetFileName( this->GetFileName() );
m_RGBUInt8Writer->SetInput(dynamic_cast<UInt8RGBImageType*>(m_Image.GetPointer()) );
m_RGBUInt8Writer->SetAutomaticAdaptativeStreaming(m_RAMValue);
m_RGBUInt8Writer->Update();
}
else
itkExceptionMacro("Unknown PixelType for RGB Image. Only uint8 is supported.");
}
void
OutputImageParameter::Write()
{
m_Image->UpdateOutputInformation();
if (dynamic_cast<UInt8ImageType*>(m_Image.GetPointer()))
{
SwitchImageWrite<UInt8ImageType>();
}
else if (dynamic_cast<Int16ImageType*>(m_Image.GetPointer()))
{
SwitchImageWrite<Int16ImageType>();
}
else if (dynamic_cast<UInt16ImageType*>(m_Image.GetPointer()))
{
SwitchImageWrite<UInt16ImageType>();
}
else if (dynamic_cast<Int32ImageType*>(m_Image.GetPointer()))
{
SwitchImageWrite<Int32ImageType>();
}
else if (dynamic_cast<UInt32ImageType*>(m_Image.GetPointer()))
{
SwitchImageWrite<UInt32ImageType>();
}
else if (dynamic_cast<FloatImageType*>(m_Image.GetPointer()))
{
SwitchImageWrite<FloatImageType>();
}
else if (dynamic_cast<DoubleImageType*>(m_Image.GetPointer()))
{
SwitchImageWrite<DoubleImageType>();
}
else if (dynamic_cast<UInt8VectorImageType*>(m_Image.GetPointer()))
{
SwitchVectorImageWrite<UInt8VectorImageType>();
}
else if (dynamic_cast<Int16VectorImageType*>(m_Image.GetPointer()))
{
SwitchVectorImageWrite<Int16VectorImageType>();
}
else if (dynamic_cast<UInt16VectorImageType*>(m_Image.GetPointer()))
{
SwitchVectorImageWrite<UInt16VectorImageType>();
}
else if (dynamic_cast<Int32VectorImageType*>(m_Image.GetPointer()))
{
SwitchVectorImageWrite<Int32VectorImageType>();
}
else if (dynamic_cast<UInt32VectorImageType*>(m_Image.GetPointer()))
{
SwitchVectorImageWrite<UInt32VectorImageType>();
}
else if (dynamic_cast<FloatVectorImageType*>(m_Image.GetPointer()))
{
SwitchVectorImageWrite<FloatVectorImageType>();
}
else if (dynamic_cast<DoubleVectorImageType*>(m_Image.GetPointer()))
{
SwitchVectorImageWrite<DoubleVectorImageType>();
}
else if (dynamic_cast<UInt8RGBImageType*>(m_Image.GetPointer()))
{
SwitchRGBImageWrite<UInt8RGBImageType>();
}
else if (dynamic_cast<UInt8RGBAImageType*>(m_Image.GetPointer()))
{
SwitchRGBAImageWrite<UInt8RGBAImageType>();
}
else
{
itkExceptionMacro("Unknown image type");
}
}
itk::ProcessObject*
OutputImageParameter::GetWriter()
{
int type = 0;
// 0 : image
// 1 : VectorImage
// 2 : RGBAImage
// 3 : RGBImage
itk::ProcessObject* writer = 0;
if (dynamic_cast<UInt8VectorImageType*> (m_Image.GetPointer())
|| dynamic_cast<Int16VectorImageType*> (m_Image.GetPointer())
|| dynamic_cast<UInt16VectorImageType*> (m_Image.GetPointer())
|| dynamic_cast<Int32VectorImageType*> (m_Image.GetPointer())
|| dynamic_cast<UInt32VectorImageType*> (m_Image.GetPointer())
|| dynamic_cast<FloatVectorImageType*> (m_Image.GetPointer())
|| dynamic_cast<DoubleVectorImageType*> (m_Image.GetPointer()))
{
type = 1;
}
else
if (dynamic_cast<UInt8RGBAImageType*> (m_Image.GetPointer()))
{
type = 2;
writer = m_RGBAUInt8Writer;
itkWarningMacro("UInt8RGBAImageType will be saved in UInt8 format.");
return writer;
}
else
if (dynamic_cast<UInt8RGBImageType*> (m_Image.GetPointer()))
{
type = 3;
writer = m_RGBUInt8Writer;
itkWarningMacro("UInt8RGBImageType will be saved in UInt8 format.");
return writer;
}
switch (GetPixelType())
{
case ImagePixelType_uint8:
{
if (type == 1)
writer = m_VectorUInt8Writer;
else
if (type == 0)
writer = m_UInt8Writer;
else
if (type == 2)
writer = m_RGBAUInt8Writer;
else writer = m_RGBUInt8Writer;
break;
}
case ImagePixelType_int16:
{
if (type == 1)
writer = m_VectorInt16Writer;
else
if (type == 0) writer = m_Int16Writer;
break;
}
case ImagePixelType_uint16:
{
if (type == 1)
writer = m_VectorUInt16Writer;
else
if (type == 0) writer = m_UInt16Writer;
break;
}
case ImagePixelType_int32:
{
if (type == 1)
writer = m_VectorInt32Writer;
else
if (type == 0) writer = m_Int32Writer;
break;
}
case ImagePixelType_uint32:
{
if (type == 1)
writer = m_VectorUInt32Writer;
else
if (type == 0) writer = m_UInt32Writer;
break;
}
case ImagePixelType_float:
{
if (type == 1)
writer = m_VectorFloatWriter;
else
if (type == 0) writer = m_FloatWriter;
break;
}
case ImagePixelType_double:
{
if (type == 1)
writer = m_VectorDoubleWriter;
else
if (type == 0) writer = m_DoubleWriter;
break;
}
}
if (0 == writer)
{
itkExceptionMacro("Unknown Writer type.");
}
return writer;
}
OutputImageParameter::ImageBaseType*
OutputImageParameter::GetValue( )
{
return m_Image;
}
void
OutputImageParameter::SetValue(ImageBaseType* image)
{
m_Image = image;
SetActive(true);
}
bool
OutputImageParameter::HasValue() const
{
std::string filename(this->GetFileName());
return !filename.empty();
}
}
}
<|endoftext|>
|
<commit_before>////////////////////////////////////////////////////////////////////////////////
/// @brief map the environment to javascript
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2014 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// heavily inspired by
/// https://github.com/joyent/node/blob/master/src/node.cc
////////////////////////////////////////////////////////////////////////////////
#ifdef _WIN32
#include "Basics/win-utils.h"
#endif
#include "v8-utils.h"
static void EnvGetter(v8::Local<v8::String> property,
const v8::PropertyCallbackInfo<v8::Value>& args) {
v8::Isolate* isolate = args.GetIsolate();
v8::HandleScope scope(isolate);
v8::String::Utf8Value const key(property);
#ifndef _WIN32
const char* val = getenv(*key);
if (val) {
TRI_V8_RETURN_STRING(val);
}
#else // _WIN32
WCHAR buffer[32767]; // The maximum size allowed for environment variables.
DWORD result = GetEnvironmentVariableW(reinterpret_cast<WCHAR*>(*key),
buffer,
ARRAY_SIZE(buffer));
// If result >= sizeof buffer the buffer was too small. That should never
// happen. If result == 0 and result != ERROR_SUCCESS the variable was not
// not found.
if ((result > 0 || GetLastError() == ERROR_SUCCESS) &&
result < ARRAY_SIZE(buffer)) {
const uint16_t* two_byte_buffer = reinterpret_cast<const uint16_t*>(buffer);
v8::Local<v8::String> rc = v8::String::NewFromTwoByte(env->isolate(), two_byte_buffer);
TRI_V8_RETURN_STD_STRING(rc);
}
#endif
// Not found. Fetch from prototype.
TRI_V8_RETURN(args.Data().As<v8::Object>()->Get(property));
}
static void EnvSetter(v8::Local<v8::String> property,
v8::Local<v8::Value> value,
const v8::PropertyCallbackInfo<v8::Value>& args) {
v8::Isolate* isolate = args.GetIsolate();
v8::HandleScope scope(isolate);
#ifndef _WIN32
v8::String::Utf8Value key(property);
v8::String::Utf8Value val(value);
setenv(*key, *val, 1);
#else // _WIN32
v8::String::Value key(property);
v8::String::Value val(value);
WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
// Environment variables that start with '=' are read-only.
if (key_ptr[0] != L'=') {
SetEnvironmentVariableW(key_ptr, reinterpret_cast<WCHAR*>(*val));
}
#endif
// Whether it worked or not, always return rval.
TRI_V8_RETURN(value);
}
static void EnvQuery(v8::Local<v8::String> property,
const v8::PropertyCallbackInfo<v8::Integer>& args) {
v8::Isolate* isolate = args.GetIsolate();
v8::HandleScope scope(isolate);
int32_t rc = -1; // Not found unless proven otherwise.
#ifndef _WIN32
v8::String::Utf8Value key(property);
if (getenv(*key))
rc = 0;
#else // _WIN32
v8::String::Utf8Value key(property);
WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
if (GetEnvironmentVariableW(key_ptr, NULL, 0) > 0 ||
GetLastError() == ERROR_SUCCESS) {
rc = 0;
if (key_ptr[0] == L'=') {
// Environment variables that start with '=' are hidden and read-only.
rc = static_cast<int32_t>(v8::ReadOnly) |
static_cast<int32_t>(v8::DontDelete) |
static_cast<int32_t>(v8::DontEnum);
}
}
#endif
if (rc != -1)
TRI_V8_RETURN(rc);
}
static void EnvDeleter(v8::Local<v8::String> property,
const v8::PropertyCallbackInfo<v8::Boolean>& args) {
v8::Isolate* isolate = args.GetIsolate();
v8::HandleScope scope(isolate);
bool rc = true;
v8::String::Utf8Value key(property);
#ifndef _WIN32
rc = getenv(*key) != NULL;
if (rc)
unsetenv(*key);
#else
WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
if (key_ptr[0] == L'=' || !SetEnvironmentVariableW(key_ptr, NULL)) {
// Deletion failed. Return true if the key wasn't there in the first place,
// false if it is still there.
rc = GetEnvironmentVariableW(key_ptr, NULL, NULL) == 0 &&
GetLastError() != ERROR_SUCCESS;
}
#endif
if (rc) {
TRI_V8_RETURN_TRUE();
}
else {
TRI_V8_RETURN_FALSE();
}
}
static void EnvEnumerator(const v8::PropertyCallbackInfo<v8::Array>& args) {
v8::Isolate* isolate = args.GetIsolate();
v8::HandleScope scope(isolate);
#ifndef _WIN32
int size = 0;
while (environ[size])
size++;
v8::Local<v8::Array> envarr = v8::Array::New(isolate, size);
for (int i = 0; i < size; ++i) {
const char* var = environ[i];
const char* s = strchr(var, '=');
const int length = s ? s - var : strlen(var);
v8::Local<v8::String> name = TRI_V8_PAIR_STRING(var, length);
envarr->Set(i, name);
}
#else // _WIN32
WCHAR* environment = GetEnvironmentStringsW();
if (environment == NULL)
return; // This should not happen.
v8::Local<v8::Array> envarr = v8::Array::New(isolate);
WCHAR* p = environment;
int i = 0;
while (*p != NULL) {
WCHAR *s;
if (*p == L'=') {
// If the key starts with '=' it is a hidden environment variable.
p += wcslen(p) + 1;
continue;
} else {
s = wcschr(p, L'=');
}
if (!s) {
s = p + wcslen(p);
}
const uint16_t* two_byte_buffer = reinterpret_cast<const uint16_t*>(p);
const size_t two_byte_buffer_len = s - p;
v8::Local<v8::String> value = v8::String::NewFromTwoByte(env->isolate(),
two_byte_buffer,
String::kNormalString,
two_byte_buffer_len);
envarr->Set(i++, value);
p = s + wcslen(s) + 1;
}
FreeEnvironmentStringsW(environment);
#endif
TRI_V8_RETURN(envarr);
}
// -----------------------------------------------------------------------------
// --SECTION-- module initialisation
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief stores the V8 utils functions inside the global variable
////////////////////////////////////////////////////////////////////////////////
void TRI_InitV8Env (v8::Isolate* isolate,
v8::Handle<v8::Context> context,
std::string const& startupPath,
std::string const& modules) {
v8::HandleScope scope(isolate);
TRI_v8_global_t* v8g = TRI_GetV8Globals(isolate);
v8::Handle<v8::ObjectTemplate> rt;
v8::Handle<v8::FunctionTemplate> ft;
ft = v8::FunctionTemplate::New(isolate);
ft->SetClassName(TRI_V8_ASCII_STRING("ENV"));
rt = ft->InstanceTemplate();
// rt->SetInternalFieldCount(3);
rt->SetNamedPropertyHandler(EnvGetter,
EnvSetter,
EnvQuery,
EnvDeleter,
EnvEnumerator,
v8::Object::New(isolate));
v8g->EnvTempl.Reset(isolate, rt);
TRI_AddGlobalFunctionVocbase(isolate, context, TRI_V8_ASCII_STRING("ENV"), ft->GetFunction());
}
// -----------------------------------------------------------------------------
// --SECTION-- END-OF-FILE
// -----------------------------------------------------------------------------
// Local Variables:
// mode: outline-minor
// outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @page\\|// --SECTION--\\|/// @\\}"
// End:
<commit_msg>Fix windows compilaton for V8 environment adoption routines.<commit_after>////////////////////////////////////////////////////////////////////////////////
/// @brief map the environment to javascript
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2014 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// heavily inspired by
/// https://github.com/joyent/node/blob/master/src/node.cc
////////////////////////////////////////////////////////////////////////////////
#ifdef _WIN32
#include "Basics/win-utils.h"
#endif
#include "v8-utils.h"
static void EnvGetter(v8::Local<v8::String> property,
const v8::PropertyCallbackInfo<v8::Value>& args) {
v8::Isolate* isolate = args.GetIsolate();
v8::HandleScope scope(isolate);
v8::String::Utf8Value const key(property);
#ifndef _WIN32
const char* val = getenv(*key);
if (val) {
TRI_V8_RETURN_STRING(val);
}
#else // _WIN32
WCHAR buffer[32767]; // The maximum size allowed for environment variables.
DWORD result = GetEnvironmentVariableW(reinterpret_cast<const WCHAR*>(*key),
buffer,
sizeof(buffer));
// If result >= sizeof buffer the buffer was too small. That should never
// happen. If result == 0 and result != ERROR_SUCCESS the variable was not
// not found.
if ((result > 0 || GetLastError() == ERROR_SUCCESS) &&
result < sizeof(buffer)) {
const uint16_t* two_byte_buffer = reinterpret_cast<const uint16_t*>(buffer);
auto rc = TRI_V8_STRING_UTF16(two_byte_buffer, result);
TRI_V8_RETURN(rc);
}
#endif
// Not found. Fetch from prototype.
TRI_V8_RETURN(args.Data().As<v8::Object>()->Get(property));
}
static void EnvSetter(v8::Local<v8::String> property,
v8::Local<v8::Value> value,
const v8::PropertyCallbackInfo<v8::Value>& args) {
v8::Isolate* isolate = args.GetIsolate();
v8::HandleScope scope(isolate);
#ifndef _WIN32
v8::String::Utf8Value key(property);
v8::String::Utf8Value val(value);
setenv(*key, *val, 1);
#else // _WIN32
v8::String::Value key(property);
v8::String::Value val(value);
WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
// Environment variables that start with '=' are read-only.
if (key_ptr[0] != L'=') {
SetEnvironmentVariableW(key_ptr, reinterpret_cast<WCHAR*>(*val));
}
#endif
// Whether it worked or not, always return rval.
TRI_V8_RETURN(value);
}
static void EnvQuery(v8::Local<v8::String> property,
const v8::PropertyCallbackInfo<v8::Integer>& args) {
v8::Isolate* isolate = args.GetIsolate();
v8::HandleScope scope(isolate);
int32_t rc = -1; // Not found unless proven otherwise.
#ifndef _WIN32
v8::String::Utf8Value key(property);
if (getenv(*key))
rc = 0;
#else // _WIN32
v8::String::Utf8Value key(property);
WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
if (GetEnvironmentVariableW(key_ptr, NULL, 0) > 0 ||
GetLastError() == ERROR_SUCCESS) {
rc = 0;
if (key_ptr[0] == L'=') {
// Environment variables that start with '=' are hidden and read-only.
rc = static_cast<int32_t>(v8::ReadOnly) |
static_cast<int32_t>(v8::DontDelete) |
static_cast<int32_t>(v8::DontEnum);
}
}
#endif
if (rc != -1)
TRI_V8_RETURN(rc);
}
static void EnvDeleter(v8::Local<v8::String> property,
const v8::PropertyCallbackInfo<v8::Boolean>& args) {
v8::Isolate* isolate = args.GetIsolate();
v8::HandleScope scope(isolate);
bool rc = true;
v8::String::Utf8Value key(property);
#ifndef _WIN32
rc = getenv(*key) != NULL;
if (rc)
unsetenv(*key);
#else
WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
if (key_ptr[0] == L'=' || !SetEnvironmentVariableW(key_ptr, NULL)) {
// Deletion failed. Return true if the key wasn't there in the first place,
// false if it is still there.
rc = GetEnvironmentVariableW(key_ptr, NULL, NULL) == 0 &&
GetLastError() != ERROR_SUCCESS;
}
#endif
if (rc) {
TRI_V8_RETURN_TRUE();
}
else {
TRI_V8_RETURN_FALSE();
}
}
static void EnvEnumerator(const v8::PropertyCallbackInfo<v8::Array>& args) {
v8::Isolate* isolate = args.GetIsolate();
v8::HandleScope scope(isolate);
#ifndef _WIN32
int size = 0;
while (environ[size])
size++;
v8::Local<v8::Array> envarr = v8::Array::New(isolate, size);
for (int i = 0; i < size; ++i) {
const char* var = environ[i];
const char* s = strchr(var, '=');
const int length = s ? s - var : strlen(var);
v8::Local<v8::String> name = TRI_V8_PAIR_STRING(var, length);
envarr->Set(i, name);
}
#else // _WIN32
WCHAR* environment = GetEnvironmentStringsW();
if (environment == NULL)
return; // This should not happen.
v8::Local<v8::Array> envarr = v8::Array::New(isolate);
WCHAR* p = environment;
int i = 0;
while (*p != NULL) {
WCHAR *s;
if (*p == L'=') {
// If the key starts with '=' it is a hidden environment variable.
p += wcslen(p) + 1;
continue;
} else {
s = wcschr(p, L'=');
}
if (!s) {
s = p + wcslen(p);
}
const uint16_t* two_byte_buffer = reinterpret_cast<const uint16_t*>(p);
const size_t two_byte_buffer_len = s - p;
auto value = TRI_V8_STRING_UTF16(two_byte_buffer, (int)two_byte_buffer_len);
envarr->Set(i++, value);
p = s + wcslen(s) + 1;
}
FreeEnvironmentStringsW(environment);
#endif
TRI_V8_RETURN(envarr);
}
// -----------------------------------------------------------------------------
// --SECTION-- module initialisation
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief stores the V8 utils functions inside the global variable
////////////////////////////////////////////////////////////////////////////////
void TRI_InitV8Env (v8::Isolate* isolate,
v8::Handle<v8::Context> context,
std::string const& startupPath,
std::string const& modules) {
v8::HandleScope scope(isolate);
TRI_v8_global_t* v8g = TRI_GetV8Globals(isolate);
v8::Handle<v8::ObjectTemplate> rt;
v8::Handle<v8::FunctionTemplate> ft;
ft = v8::FunctionTemplate::New(isolate);
ft->SetClassName(TRI_V8_ASCII_STRING("ENV"));
rt = ft->InstanceTemplate();
// rt->SetInternalFieldCount(3);
rt->SetNamedPropertyHandler(EnvGetter,
EnvSetter,
EnvQuery,
EnvDeleter,
EnvEnumerator,
v8::Object::New(isolate));
v8g->EnvTempl.Reset(isolate, rt);
TRI_AddGlobalFunctionVocbase(isolate, context, TRI_V8_ASCII_STRING("ENV"), ft->GetFunction());
}
// -----------------------------------------------------------------------------
// --SECTION-- END-OF-FILE
// -----------------------------------------------------------------------------
// Local Variables:
// mode: outline-minor
// outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @page\\|// --SECTION--\\|/// @\\}"
// End:
<|endoftext|>
|
<commit_before>//===-- BasicBlock.cpp - Implement BasicBlock related methods -------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the BasicBlock class for the VMCore library.
//
//===----------------------------------------------------------------------===//
#include "llvm/BasicBlock.h"
#include "llvm/Constants.h"
#include "llvm/Instructions.h"
#include "llvm/Type.h"
#include "llvm/Support/CFG.h"
#include "llvm/Support/LeakDetector.h"
#include "SymbolTableListTraitsImpl.h"
#include <algorithm>
using namespace llvm;
namespace {
/// DummyInst - An instance of this class is used to mark the end of the
/// instruction list. This is not a real instruction.
struct DummyInst : public Instruction {
DummyInst() : Instruction(Type::VoidTy, OtherOpsEnd, 0, 0) {
// This should not be garbage monitored.
LeakDetector::removeGarbageObject(this);
}
virtual Instruction *clone() const {
assert(0 && "Cannot clone EOL");abort();
return 0;
}
virtual const char *getOpcodeName() const { return "*end-of-list-inst*"; }
// Methods for support type inquiry through isa, cast, and dyn_cast...
static inline bool classof(const DummyInst *) { return true; }
static inline bool classof(const Instruction *I) {
return I->getOpcode() == OtherOpsEnd;
}
static inline bool classof(const Value *V) {
return isa<Instruction>(V) && classof(cast<Instruction>(V));
}
};
}
Instruction *ilist_traits<Instruction>::createSentinel() {
return new DummyInst();
}
iplist<Instruction> &ilist_traits<Instruction>::getList(BasicBlock *BB) {
return BB->getInstList();
}
// Explicit instantiation of SymbolTableListTraits since some of the methods
// are not in the public header file...
template class SymbolTableListTraits<Instruction, BasicBlock, Function>;
BasicBlock::BasicBlock(const std::string &Name, Function *Parent,
BasicBlock *InsertBefore)
: Value(Type::LabelTy, Value::BasicBlockVal, Name) {
// Initialize the instlist...
InstList.setItemParent(this);
// Make sure that we get added to a function
LeakDetector::addGarbageObject(this);
if (InsertBefore) {
assert(Parent &&
"Cannot insert block before another block with no function!");
Parent->getBasicBlockList().insert(InsertBefore, this);
} else if (Parent) {
Parent->getBasicBlockList().push_back(this);
}
}
BasicBlock::~BasicBlock() {
assert(getParent() == 0 && "BasicBlock still linked into the program!");
dropAllReferences();
InstList.clear();
}
void BasicBlock::setParent(Function *parent) {
if (getParent())
LeakDetector::addGarbageObject(this);
InstList.setParent(parent);
if (getParent())
LeakDetector::removeGarbageObject(this);
}
void BasicBlock::removeFromParent() {
getParent()->getBasicBlockList().remove(this);
}
void BasicBlock::eraseFromParent() {
getParent()->getBasicBlockList().erase(this);
}
TerminatorInst *BasicBlock::getTerminator() {
if (InstList.empty()) return 0;
return dyn_cast<TerminatorInst>(&InstList.back());
}
const TerminatorInst *const BasicBlock::getTerminator() const {
if (InstList.empty()) return 0;
return dyn_cast<TerminatorInst>(&InstList.back());
}
void BasicBlock::dropAllReferences() {
for(iterator I = begin(), E = end(); I != E; ++I)
I->dropAllReferences();
}
/// getSinglePredecessor - If this basic block has a single predecessor block,
/// return the block, otherwise return a null pointer.
BasicBlock *BasicBlock::getSinglePredecessor() {
pred_iterator PI = pred_begin(this), E = pred_end(this);
if (PI == E) return 0; // No preds.
BasicBlock *ThePred = *PI;
++PI;
return (PI == E) ? ThePred : 0 /*multiple preds*/;
}
/// removePredecessor - This method is used to notify a BasicBlock that the
/// specified Predecessor of the block is no longer able to reach it. This is
/// actually not used to update the Predecessor list, but is actually used to
/// update the PHI nodes that reside in the block. Note that this should be
/// called while the predecessor still refers to this block.
///
void BasicBlock::removePredecessor(BasicBlock *Pred,
bool DontDeleteUselessPHIs) {
assert((hasNUsesOrMore(16)||// Reduce cost of this assertion for complex CFGs.
find(pred_begin(this), pred_end(this), Pred) != pred_end(this)) &&
"removePredecessor: BB is not a predecessor!");
if (InstList.empty()) return;
PHINode *APN = dyn_cast<PHINode>(&front());
if (!APN) return; // Quick exit.
// If there are exactly two predecessors, then we want to nuke the PHI nodes
// altogether. However, we cannot do this, if this in this case:
//
// Loop:
// %x = phi [X, Loop]
// %x2 = add %x, 1 ;; This would become %x2 = add %x2, 1
// br Loop ;; %x2 does not dominate all uses
//
// This is because the PHI node input is actually taken from the predecessor
// basic block. The only case this can happen is with a self loop, so we
// check for this case explicitly now.
//
unsigned max_idx = APN->getNumIncomingValues();
assert(max_idx != 0 && "PHI Node in block with 0 predecessors!?!?!");
if (max_idx == 2) {
BasicBlock *Other = APN->getIncomingBlock(APN->getIncomingBlock(0) == Pred);
// Disable PHI elimination!
if (this == Other) max_idx = 3;
}
// <= Two predecessors BEFORE I remove one?
if (max_idx <= 2 && !DontDeleteUselessPHIs) {
// Yup, loop through and nuke the PHI nodes
while (PHINode *PN = dyn_cast<PHINode>(&front())) {
// Remove the predecessor first.
PN->removeIncomingValue(Pred, !DontDeleteUselessPHIs);
// If the PHI _HAD_ two uses, replace PHI node with its now *single* value
if (max_idx == 2) {
if (PN->getOperand(0) != PN)
PN->replaceAllUsesWith(PN->getOperand(0));
else
// We are left with an infinite loop with no entries: kill the PHI.
PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
getInstList().pop_front(); // Remove the PHI node
}
// If the PHI node already only had one entry, it got deleted by
// removeIncomingValue.
}
} else {
// Okay, now we know that we need to remove predecessor #pred_idx from all
// PHI nodes. Iterate over each PHI node fixing them up
PHINode *PN;
for (iterator II = begin(); (PN = dyn_cast<PHINode>(II)); ++II) {
PN->removeIncomingValue(Pred, false);
// If all incoming values to the Phi are the same, we can replace the Phi
// with that value.
if (Value *PNV = PN->hasConstantValue())
if (!isa<Instruction>(PNV)) {
PN->replaceAllUsesWith(PNV);
PN->eraseFromParent();
}
}
}
}
/// splitBasicBlock - This splits a basic block into two at the specified
/// instruction. Note that all instructions BEFORE the specified iterator stay
/// as part of the original basic block, an unconditional branch is added to
/// the new BB, and the rest of the instructions in the BB are moved to the new
/// BB, including the old terminator. This invalidates the iterator.
///
/// Note that this only works on well formed basic blocks (must have a
/// terminator), and 'I' must not be the end of instruction list (which would
/// cause a degenerate basic block to be formed, having a terminator inside of
/// the basic block).
///
BasicBlock *BasicBlock::splitBasicBlock(iterator I, const std::string &BBName) {
assert(getTerminator() && "Can't use splitBasicBlock on degenerate BB!");
assert(I != InstList.end() &&
"Trying to get me to create degenerate basic block!");
BasicBlock *New = new BasicBlock(BBName, getParent(), getNext());
// Move all of the specified instructions from the original basic block into
// the new basic block.
New->getInstList().splice(New->end(), this->getInstList(), I, end());
// Add a branch instruction to the newly formed basic block.
new BranchInst(New, this);
// Now we must loop through all of the successors of the New block (which
// _were_ the successors of the 'this' block), and update any PHI nodes in
// successors. If there were PHI nodes in the successors, then they need to
// know that incoming branches will be from New, not from Old.
//
for (succ_iterator I = succ_begin(New), E = succ_end(New); I != E; ++I) {
// Loop over any phi nodes in the basic block, updating the BB field of
// incoming values...
BasicBlock *Successor = *I;
PHINode *PN;
for (BasicBlock::iterator II = Successor->begin();
(PN = dyn_cast<PHINode>(II)); ++II) {
int IDX = PN->getBasicBlockIndex(this);
while (IDX != -1) {
PN->setIncomingBlock((unsigned)IDX, New);
IDX = PN->getBasicBlockIndex(this);
}
}
}
return New;
}
<commit_msg>Now that hasConstantValue is more careful w.r.t. returning values that only dominate the PHI node, this code can go away. This also makes passes more aggressive, e.g. implementing Transforms/CondProp/phisimplify2.ll<commit_after>//===-- BasicBlock.cpp - Implement BasicBlock related methods -------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the BasicBlock class for the VMCore library.
//
//===----------------------------------------------------------------------===//
#include "llvm/BasicBlock.h"
#include "llvm/Constants.h"
#include "llvm/Instructions.h"
#include "llvm/Type.h"
#include "llvm/Support/CFG.h"
#include "llvm/Support/LeakDetector.h"
#include "SymbolTableListTraitsImpl.h"
#include <algorithm>
using namespace llvm;
namespace {
/// DummyInst - An instance of this class is used to mark the end of the
/// instruction list. This is not a real instruction.
struct DummyInst : public Instruction {
DummyInst() : Instruction(Type::VoidTy, OtherOpsEnd, 0, 0) {
// This should not be garbage monitored.
LeakDetector::removeGarbageObject(this);
}
virtual Instruction *clone() const {
assert(0 && "Cannot clone EOL");abort();
return 0;
}
virtual const char *getOpcodeName() const { return "*end-of-list-inst*"; }
// Methods for support type inquiry through isa, cast, and dyn_cast...
static inline bool classof(const DummyInst *) { return true; }
static inline bool classof(const Instruction *I) {
return I->getOpcode() == OtherOpsEnd;
}
static inline bool classof(const Value *V) {
return isa<Instruction>(V) && classof(cast<Instruction>(V));
}
};
}
Instruction *ilist_traits<Instruction>::createSentinel() {
return new DummyInst();
}
iplist<Instruction> &ilist_traits<Instruction>::getList(BasicBlock *BB) {
return BB->getInstList();
}
// Explicit instantiation of SymbolTableListTraits since some of the methods
// are not in the public header file...
template class SymbolTableListTraits<Instruction, BasicBlock, Function>;
BasicBlock::BasicBlock(const std::string &Name, Function *Parent,
BasicBlock *InsertBefore)
: Value(Type::LabelTy, Value::BasicBlockVal, Name) {
// Initialize the instlist...
InstList.setItemParent(this);
// Make sure that we get added to a function
LeakDetector::addGarbageObject(this);
if (InsertBefore) {
assert(Parent &&
"Cannot insert block before another block with no function!");
Parent->getBasicBlockList().insert(InsertBefore, this);
} else if (Parent) {
Parent->getBasicBlockList().push_back(this);
}
}
BasicBlock::~BasicBlock() {
assert(getParent() == 0 && "BasicBlock still linked into the program!");
dropAllReferences();
InstList.clear();
}
void BasicBlock::setParent(Function *parent) {
if (getParent())
LeakDetector::addGarbageObject(this);
InstList.setParent(parent);
if (getParent())
LeakDetector::removeGarbageObject(this);
}
void BasicBlock::removeFromParent() {
getParent()->getBasicBlockList().remove(this);
}
void BasicBlock::eraseFromParent() {
getParent()->getBasicBlockList().erase(this);
}
TerminatorInst *BasicBlock::getTerminator() {
if (InstList.empty()) return 0;
return dyn_cast<TerminatorInst>(&InstList.back());
}
const TerminatorInst *const BasicBlock::getTerminator() const {
if (InstList.empty()) return 0;
return dyn_cast<TerminatorInst>(&InstList.back());
}
void BasicBlock::dropAllReferences() {
for(iterator I = begin(), E = end(); I != E; ++I)
I->dropAllReferences();
}
/// getSinglePredecessor - If this basic block has a single predecessor block,
/// return the block, otherwise return a null pointer.
BasicBlock *BasicBlock::getSinglePredecessor() {
pred_iterator PI = pred_begin(this), E = pred_end(this);
if (PI == E) return 0; // No preds.
BasicBlock *ThePred = *PI;
++PI;
return (PI == E) ? ThePred : 0 /*multiple preds*/;
}
/// removePredecessor - This method is used to notify a BasicBlock that the
/// specified Predecessor of the block is no longer able to reach it. This is
/// actually not used to update the Predecessor list, but is actually used to
/// update the PHI nodes that reside in the block. Note that this should be
/// called while the predecessor still refers to this block.
///
void BasicBlock::removePredecessor(BasicBlock *Pred,
bool DontDeleteUselessPHIs) {
assert((hasNUsesOrMore(16)||// Reduce cost of this assertion for complex CFGs.
find(pred_begin(this), pred_end(this), Pred) != pred_end(this)) &&
"removePredecessor: BB is not a predecessor!");
if (InstList.empty()) return;
PHINode *APN = dyn_cast<PHINode>(&front());
if (!APN) return; // Quick exit.
// If there are exactly two predecessors, then we want to nuke the PHI nodes
// altogether. However, we cannot do this, if this in this case:
//
// Loop:
// %x = phi [X, Loop]
// %x2 = add %x, 1 ;; This would become %x2 = add %x2, 1
// br Loop ;; %x2 does not dominate all uses
//
// This is because the PHI node input is actually taken from the predecessor
// basic block. The only case this can happen is with a self loop, so we
// check for this case explicitly now.
//
unsigned max_idx = APN->getNumIncomingValues();
assert(max_idx != 0 && "PHI Node in block with 0 predecessors!?!?!");
if (max_idx == 2) {
BasicBlock *Other = APN->getIncomingBlock(APN->getIncomingBlock(0) == Pred);
// Disable PHI elimination!
if (this == Other) max_idx = 3;
}
// <= Two predecessors BEFORE I remove one?
if (max_idx <= 2 && !DontDeleteUselessPHIs) {
// Yup, loop through and nuke the PHI nodes
while (PHINode *PN = dyn_cast<PHINode>(&front())) {
// Remove the predecessor first.
PN->removeIncomingValue(Pred, !DontDeleteUselessPHIs);
// If the PHI _HAD_ two uses, replace PHI node with its now *single* value
if (max_idx == 2) {
if (PN->getOperand(0) != PN)
PN->replaceAllUsesWith(PN->getOperand(0));
else
// We are left with an infinite loop with no entries: kill the PHI.
PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
getInstList().pop_front(); // Remove the PHI node
}
// If the PHI node already only had one entry, it got deleted by
// removeIncomingValue.
}
} else {
// Okay, now we know that we need to remove predecessor #pred_idx from all
// PHI nodes. Iterate over each PHI node fixing them up
PHINode *PN;
for (iterator II = begin(); (PN = dyn_cast<PHINode>(II)); ++II) {
PN->removeIncomingValue(Pred, false);
// If all incoming values to the Phi are the same, we can replace the Phi
// with that value.
if (Value *PNV = PN->hasConstantValue()) {
PN->replaceAllUsesWith(PNV);
PN->eraseFromParent();
}
}
}
}
/// splitBasicBlock - This splits a basic block into two at the specified
/// instruction. Note that all instructions BEFORE the specified iterator stay
/// as part of the original basic block, an unconditional branch is added to
/// the new BB, and the rest of the instructions in the BB are moved to the new
/// BB, including the old terminator. This invalidates the iterator.
///
/// Note that this only works on well formed basic blocks (must have a
/// terminator), and 'I' must not be the end of instruction list (which would
/// cause a degenerate basic block to be formed, having a terminator inside of
/// the basic block).
///
BasicBlock *BasicBlock::splitBasicBlock(iterator I, const std::string &BBName) {
assert(getTerminator() && "Can't use splitBasicBlock on degenerate BB!");
assert(I != InstList.end() &&
"Trying to get me to create degenerate basic block!");
BasicBlock *New = new BasicBlock(BBName, getParent(), getNext());
// Move all of the specified instructions from the original basic block into
// the new basic block.
New->getInstList().splice(New->end(), this->getInstList(), I, end());
// Add a branch instruction to the newly formed basic block.
new BranchInst(New, this);
// Now we must loop through all of the successors of the New block (which
// _were_ the successors of the 'this' block), and update any PHI nodes in
// successors. If there were PHI nodes in the successors, then they need to
// know that incoming branches will be from New, not from Old.
//
for (succ_iterator I = succ_begin(New), E = succ_end(New); I != E; ++I) {
// Loop over any phi nodes in the basic block, updating the BB field of
// incoming values...
BasicBlock *Successor = *I;
PHINode *PN;
for (BasicBlock::iterator II = Successor->begin();
(PN = dyn_cast<PHINode>(II)); ++II) {
int IDX = PN->getBasicBlockIndex(this);
while (IDX != -1) {
PN->setIncomingBlock((unsigned)IDX, New);
IDX = PN->getBasicBlockIndex(this);
}
}
}
return New;
}
<|endoftext|>
|
<commit_before>#include <boost/version.hpp>
#include <boost/detail/lightweight_test.hpp>
#include <iostream>
#include <mapnik/memory_datasource.hpp>
#include <mapnik/feature.hpp>
#include <mapnik/feature_factory.hpp>
#include <mapnik/unicode.hpp>
#include <mapnik/geometry.hpp>
#include <mapnik/map.hpp>
#include <mapnik/params.hpp>
#include <mapnik/expression.hpp>
#include <mapnik/layer.hpp>
#include <mapnik/rule.hpp>
#include <mapnik/feature_type_style.hpp>
#include <mapnik/agg_renderer.hpp>
#include <mapnik/graphics.hpp>
#include <mapnik/image_util.hpp>
#include <mapnik/color_factory.hpp>
#include <mapnik/save_map.hpp>
#include <vector>
#include <algorithm>
#include "utils.hpp"
int main(int argc, char** argv)
{
std::vector<std::string> args;
for (int i=1;i<argc;++i)
{
args.push_back(argv[i]);
}
bool quiet = std::find(args.begin(), args.end(), "-q")!=args.end();
try {
BOOST_TEST(set_working_dir(args));
// create a renderable map with a fontset and a text symbolizer
// and do not register any fonts, to ensure the error thrown is reasonable
mapnik::context_ptr ctx = boost::make_shared<mapnik::context_type>();
ctx->push("name");
mapnik::feature_ptr feature(mapnik::feature_factory::create(ctx,1));
mapnik::transcoder tr("utf-8");
UnicodeString ustr = tr.transcode("hello world!");
feature->put("name",ustr);
mapnik::geometry_type * pt = new mapnik::geometry_type(mapnik::Point);
pt->move_to(128,128);
feature->add_geometry(pt);
mapnik::datasource_ptr memory_ds = boost::make_shared<mapnik::memory_datasource>();
mapnik::memory_datasource *cache = dynamic_cast<mapnik::memory_datasource *>(memory_ds.get());
cache->push(feature);
mapnik::Map m(256,256);
mapnik::font_set fontset("fontset");
// NOTE: this is a valid font, but will fail because none are registered
fontset.add_face_name("DejaVu Sans Book");
m.insert_fontset("fontset", fontset);
mapnik::layer lyr("layer");
lyr.set_datasource(memory_ds);
lyr.add_style("style");
m.addLayer(lyr);
mapnik::feature_type_style the_style;
mapnik::rule the_rule;
mapnik::text_symbolizer text_sym(mapnik::parse_expression("[name]"),10,mapnik::color(0,0,0));
text_sym.set_fontset(fontset);
the_rule.append(text_sym);
the_style.add_rule(the_rule);
m.insert_style("style",the_style );
m.zoom_to_box(mapnik::box2d<double>(-256,-256,
256,256));
mapnik::image_32 buf(m.width(),m.height());
mapnik::agg_renderer<mapnik::image_32> ren(m,buf);
ren.apply();
} catch (std::exception const& ex) {
BOOST_TEST_EQ(std::string(ex.what()),std::string("No valid font face could be loaded for font set: 'fontset'"));
}
if (!::boost::detail::test_errors()) {
if (quiet) std::clog << "\x1b[1;32m.\x1b[0m";
else std::clog << "C++ fontset runtime: \x1b[1;32m✓ \x1b[0m\n";
#if BOOST_VERSION >= 104600
::boost::detail::report_errors_remind().called_report_errors_function = true;
#endif
} else {
return ::boost::report_errors();
}
}
<commit_msg>cpp_tests: no need for dynamic_cast<commit_after>#include <boost/version.hpp>
#include <boost/detail/lightweight_test.hpp>
#include <iostream>
#include <mapnik/memory_datasource.hpp>
#include <mapnik/feature.hpp>
#include <mapnik/feature_factory.hpp>
#include <mapnik/unicode.hpp>
#include <mapnik/geometry.hpp>
#include <mapnik/map.hpp>
#include <mapnik/params.hpp>
#include <mapnik/expression.hpp>
#include <mapnik/layer.hpp>
#include <mapnik/rule.hpp>
#include <mapnik/feature_type_style.hpp>
#include <mapnik/agg_renderer.hpp>
#include <mapnik/graphics.hpp>
#include <mapnik/image_util.hpp>
#include <mapnik/color_factory.hpp>
#include <mapnik/save_map.hpp>
#include <vector>
#include <algorithm>
#include "utils.hpp"
int main(int argc, char** argv)
{
std::vector<std::string> args;
for (int i=1;i<argc;++i)
{
args.push_back(argv[i]);
}
bool quiet = std::find(args.begin(), args.end(), "-q")!=args.end();
try {
BOOST_TEST(set_working_dir(args));
// create a renderable map with a fontset and a text symbolizer
// and do not register any fonts, to ensure the error thrown is reasonable
mapnik::context_ptr ctx = boost::make_shared<mapnik::context_type>();
ctx->push("name");
mapnik::feature_ptr feature(mapnik::feature_factory::create(ctx,1));
mapnik::transcoder tr("utf-8");
UnicodeString ustr = tr.transcode("hello world!");
feature->put("name",ustr);
mapnik::geometry_type * pt = new mapnik::geometry_type(mapnik::Point);
pt->move_to(128,128);
feature->add_geometry(pt);
boost::shared_ptr<mapnik::memory_datasource> ds = boost::make_shared<mapnik::memory_datasource>();
ds->push(feature);
mapnik::Map m(256,256);
mapnik::font_set fontset("fontset");
// NOTE: this is a valid font, but will fail because none are registered
fontset.add_face_name("DejaVu Sans Book");
m.insert_fontset("fontset", fontset);
mapnik::layer lyr("layer");
lyr.set_datasource(ds);
lyr.add_style("style");
m.addLayer(lyr);
mapnik::feature_type_style the_style;
mapnik::rule the_rule;
mapnik::text_symbolizer text_sym(mapnik::parse_expression("[name]"),10,mapnik::color(0,0,0));
text_sym.set_fontset(fontset);
the_rule.append(text_sym);
the_style.add_rule(the_rule);
m.insert_style("style",the_style );
m.zoom_to_box(mapnik::box2d<double>(-256,-256,
256,256));
mapnik::image_32 buf(m.width(),m.height());
mapnik::agg_renderer<mapnik::image_32> ren(m,buf);
ren.apply();
} catch (std::exception const& ex) {
BOOST_TEST_EQ(std::string(ex.what()),std::string("No valid font face could be loaded for font set: 'fontset'"));
}
if (!::boost::detail::test_errors()) {
if (quiet) std::clog << "\x1b[1;32m.\x1b[0m";
else std::clog << "C++ fontset runtime: \x1b[1;32m✓ \x1b[0m\n";
#if BOOST_VERSION >= 104600
::boost::detail::report_errors_remind().called_report_errors_function = true;
#endif
} else {
return ::boost::report_errors();
}
}
<|endoftext|>
|
<commit_before>#include "training/species_manager.hpp"
#include "utility/random.hpp"
using namespace Hippocrates;
using namespace Hippocrates::Training;
auto SpeciesManager::CreateInitialOrganisms(Bodies& bodies) -> void {
species.clear();
for (auto& currTrainer : bodies) {
Genotype::Genome standardGenes(currTrainer.get().GetInputCount(), currTrainer.get().GetOutputCount());
currGenerationInnovations.AssignAndCacheHistoricalMarkings(standardGenes);
Phenotype::NeuralNetwork network(std::move(standardGenes));
Phenotype::Organism organism(currTrainer, std::move(network));
FillOrganismIntoSpecies(std::move(organism));
}
}
auto SpeciesManager::Repopulate(Bodies& bodies) -> void {
auto populationCount = GetPopulationCount();
auto averageFitness = GetAverageFitness();
std::vector<Phenotype::Organism> newGeneration;
newGeneration.reserve(bodies.size());
auto currBody = bodies.begin();
auto EmplaceChild = [&](Phenotype::NeuralNetwork && network) {
newGeneration.emplace_back(*currBody, std::forward<decltype(network)>(network));
++currBody;
};
auto Breed = [&](const Species & species) {
auto child = BreedInSpecies(species);
EmplaceChild(std::move(child));
};
auto CloneChamp = [&](const Species & species) {
auto champNetwork = species.GetFittestOrganism().GetNeuralNetwork();
EmplaceChild(std::move(champNetwork));
};
currGenerationInnovations.Clear();
// In the original implementation the offspring were tossed directly into their new species and, as a result, in the mating pool.
// We instead separate the generations
for (auto& s : species) {
auto offspringCount = s.GetOffspringCount(averageFitness);
offspringCount = std::min(offspringCount, s.GetSize());
s.RemoveWorst();
if (offspringCount >= 1
&& s.GetSize() > GetParameters().reproduction.minSpeciesSizeForChampConservation) {
CloneChamp(s);
offspringCount--;
}
for (std::size_t i = 0; i < offspringCount; ++i) {
Breed(s);
}
}
// Account for rounding Errors
while (newGeneration.size() < populationCount) {
Breed(GetFittestSpecies());
}
ClearSpeciesPopulation();
for (auto&& child : newGeneration) {
FillOrganismIntoSpecies(std::move(child));
}
DeleteEmptySpecies();
}
auto SpeciesManager::BreedInSpecies(const Species& species) -> Phenotype::NeuralNetwork {
const auto& mother = species.GetOrganismToBreed();
// Note that the father can be the same as the mother
const Phenotype::Organism* father = nullptr;
if (Utility::Random::DidChanceOccure(GetParameters().reproduction.chanceForInterspecialReproduction))
father = &Utility::Random::Element(this->species)->GetFittestOrganism();
else
father = &species.GetOrganismToBreed();
return father->BreedWith(mother, currGenerationInnovations);
}
auto SpeciesManager::GetFittestSpecies() -> const Species & {
if (species.empty()) {
throw std::out_of_range("Your population is empty");
}
SortSpeciesIfNeeded();
return species.front();
}
auto SpeciesManager::DeleteEmptySpecies() -> void {
species.erase(
std::remove_if(species.begin(), species.end(), [](const Species& s) {return s.IsEmpty(); }),
species.end()
);
}
auto SpeciesManager::FillOrganismIntoSpecies(Phenotype::Organism&& organism) -> void {
areSpeciesSortedByFitness = false;
auto isCompatibleWithExistingSpecies = false;
for (auto& currSpecies : species) {
if (currSpecies.IsCompatible(organism.GetGenome())) {
currSpecies.AddOrganism(std::move(organism));
isCompatibleWithExistingSpecies = true;
break;
}
}
if (!isCompatibleWithExistingSpecies) {
species.emplace_back(std::move(organism));
}
}
auto SpeciesManager::ClearSpeciesPopulation() -> void {
for (auto& sp : species)
sp.ClearPopulation();
}
auto SpeciesManager::GetAverageFitness() const -> Type::fitness_t {
return GetTotalFitness() / GetPopulationCount();
}
auto SpeciesManager::GetPopulationCount() const -> std::size_t {
std::size_t populationCount = 0;
for (const auto & s : species)
populationCount += s.GetSize();
return populationCount;
}
auto SpeciesManager::GetTotalFitness() const -> Type::fitness_t {
auto totalFitness = 0.0;
for (auto & s : species)
totalFitness += s.GetTotalFitness();
return totalFitness;
}
auto SpeciesManager::GetFittestOrganism() -> const Phenotype::Organism& {
return GetFittestSpecies().GetFittestOrganism();
}
auto SpeciesManager::SortSpeciesIfNeeded() -> void {
if (!areSpeciesSortedByFitness) {
auto CompareSpecies = [](const Species& lhs, const Species& rhs) {
return lhs.GetFittestOrganism().GetOrCalculateFitness() < rhs.GetFittestOrganism().GetOrCalculateFitness();
};
std::sort(species.begin(), species.end(), CompareSpecies);
areSpeciesSortedByFitness = true;
}
}
auto SpeciesManager::Update() -> void {
didLastUpdateFinishTask = true;
for (auto& sp : species) {
sp.Update();
if (didLastUpdateFinishTask)
didLastUpdateFinishTask = sp.DidLastUpdateFinishTask();
}
areSpeciesSortedByFitness = false;
}
auto SpeciesManager::Reset() -> void {
for (auto& sp : species)
sp.Reset();
}
<commit_msg>Fix endless loop<commit_after>#include "training/species_manager.hpp"
#include "utility/random.hpp"
using namespace Hippocrates;
using namespace Hippocrates::Training;
auto SpeciesManager::CreateInitialOrganisms(Bodies& bodies) -> void {
species.clear();
for (auto& currTrainer : bodies) {
Genotype::Genome standardGenes(currTrainer.get().GetInputCount(), currTrainer.get().GetOutputCount());
currGenerationInnovations.AssignAndCacheHistoricalMarkings(standardGenes);
Phenotype::NeuralNetwork network(std::move(standardGenes));
Phenotype::Organism organism(currTrainer, std::move(network));
FillOrganismIntoSpecies(std::move(organism));
}
}
auto SpeciesManager::Repopulate(Bodies& bodies) -> void {
auto populationCount = GetPopulationCount();
auto averageFitness = GetAverageFitness();
std::vector<Phenotype::Organism> newGeneration;
newGeneration.reserve(bodies.size());
auto currBody = bodies.begin();
auto EmplaceChild = [&](Phenotype::NeuralNetwork && network) {
newGeneration.emplace_back(*currBody, std::forward<decltype(network)>(network));
++currBody;
};
auto Breed = [&](const Species & species) {
auto child = BreedInSpecies(species);
EmplaceChild(std::move(child));
};
auto CloneChamp = [&](const Species & species) {
auto champNetwork = species.GetFittestOrganism().GetNeuralNetwork();
EmplaceChild(std::move(champNetwork));
};
currGenerationInnovations.Clear();
// In the original implementation the offspring were tossed directly into their new species and, as a result, in the mating pool.
// We instead separate the generations
for (auto& s : species) {
auto offspringCount = s.GetOffspringCount(averageFitness);
offspringCount = std::min(offspringCount, s.GetSize());
s.RemoveWorst();
if (offspringCount >= 1
&& s.GetSize() > GetParameters().reproduction.minSpeciesSizeForChampConservation) {
CloneChamp(s);
offspringCount--;
}
for (std::size_t i = 0; i < offspringCount; ++i) {
Breed(s);
}
}
// Account for rounding Errors
while (newGeneration.size() < populationCount) {
Breed(GetFittestSpecies());
}
ClearSpeciesPopulation();
for (auto&& child : newGeneration) {
FillOrganismIntoSpecies(std::move(child));
}
DeleteEmptySpecies();
}
auto SpeciesManager::BreedInSpecies(const Species& species) -> Phenotype::NeuralNetwork {
const auto& mother = species.GetOrganismToBreed();
// Note that the father can be the same as the mother
const Phenotype::Organism* father = nullptr;
if (Utility::Random::DidChanceOccure(GetParameters().reproduction.chanceForInterspecialReproduction))
father = &Utility::Random::Element(this->species)->GetFittestOrganism();
else
father = &species.GetOrganismToBreed();
return father->BreedWith(mother, currGenerationInnovations);
}
auto SpeciesManager::GetFittestSpecies() -> const Species & {
if (species.empty()) {
throw std::out_of_range("Your population is empty");
}
SortSpeciesIfNeeded();
return species.front();
}
auto SpeciesManager::DeleteEmptySpecies() -> void {
species.erase(
std::remove_if(species.begin(), species.end(), [](const Species& s) {return s.IsEmpty(); }),
species.end()
);
}
auto SpeciesManager::FillOrganismIntoSpecies(Phenotype::Organism&& organism) -> void {
areSpeciesSortedByFitness = false;
auto isCompatibleWithExistingSpecies = false;
for (auto& currSpecies : species) {
if (currSpecies.IsCompatible(organism.GetGenome())) {
currSpecies.AddOrganism(std::move(organism));
isCompatibleWithExistingSpecies = true;
break;
}
}
if (!isCompatibleWithExistingSpecies) {
species.emplace_back(std::move(organism));
}
}
auto SpeciesManager::ClearSpeciesPopulation() -> void {
for (auto& sp : species)
sp.ClearPopulation();
}
auto SpeciesManager::GetAverageFitness() const -> Type::fitness_t {
return GetTotalFitness() / GetPopulationCount();
}
auto SpeciesManager::GetPopulationCount() const -> std::size_t {
std::size_t populationCount = 0;
for (const auto & s : species)
populationCount += s.GetSize();
return populationCount;
}
auto SpeciesManager::GetTotalFitness() const -> Type::fitness_t {
auto totalFitness = 0.0;
for (auto & s : species)
totalFitness += s.GetTotalFitness();
return totalFitness;
}
auto SpeciesManager::GetFittestOrganism() -> const Phenotype::Organism& {
return GetFittestSpecies().GetFittestOrganism();
}
auto SpeciesManager::SortSpeciesIfNeeded() -> void {
if (!areSpeciesSortedByFitness) {
auto CompareSpecies = [](const Species& lhs, const Species& rhs) {
return lhs.GetFittestOrganism().GetOrCalculateFitness() < rhs.GetFittestOrganism().GetOrCalculateFitness();
};
std::sort(species.begin(), species.end(), CompareSpecies);
areSpeciesSortedByFitness = true;
}
}
auto SpeciesManager::Update() -> void {
didLastUpdateFinishTask = true;
for (auto& sp : species) {
sp.Update();
if (didLastUpdateFinishTask)
didLastUpdateFinishTask = sp.DidLastUpdateFinishTask();
}
areSpeciesSortedByFitness = false;
}
auto SpeciesManager::Reset() -> void {
for (auto& sp : species)
sp.Reset();
didLastUpdateFinishTask = false;
}
<|endoftext|>
|
<commit_before>/* This file is part of the KDE project
Copyright (C) 2006 Matthias Kretz <[email protected]>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License version 2 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
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 "audiodevice.h"
#include <QString>
#include "audiodevice_p.h"
#include "audiodeviceenumerator.h"
#include <kdebug.h>
#include <solid/device.h>
#include <solid/audiohw.h>
#include <kconfiggroup.h>
namespace Phonon
{
AudioDevice::AudioDevice()
: d(new AudioDevicePrivate)
{
}
AudioDevice::AudioDevice(Solid::Device audioDevice, KSharedConfig::Ptr config)
: d(new AudioDevicePrivate)
{
Solid::AudioHw *audioHw = audioDevice.as<Solid::AudioHw>();
kDebug(603) << k_funcinfo << audioHw->driverHandles() << endl;
d->udi = audioDevice.udi();
d->cardName = audioHw->name();
d->deviceIds = audioHw->driverHandles();
switch (audioHw->soundcardType()) {
case Solid::AudioHw::InternalSoundcard:
d->icon = QLatin1String("pci-card");
break;
case Solid::AudioHw::UsbSoundcard:
d->icon = QLatin1String("usb-device");
break;
case Solid::AudioHw::FirewireSoundcard:
d->icon = QLatin1String("firewire-device");
break;
case Solid::AudioHw::Headset:
d->icon = QLatin1String("headset");
break;
case Solid::AudioHw::Modem:
d->icon = QLatin1String("modem");
// should a modem be a valid device so that it's shown to the user?
d->valid = false;
return;
}
d->driver = audioHw->driver();
d->available = true;
d->valid = true;
QString groupName;
Solid::AudioHw::AudioHwTypes deviceType = audioHw->deviceType();
if (deviceType == Solid::AudioHw::AudioInput) {
d->captureDevice = true;
groupName = QLatin1String("AudioCaptureDevice_");
} else {
if (deviceType == Solid::AudioHw::AudioOutput) {
d->playbackDevice = true;
groupName = QLatin1String("AudioOutputDevice_");
} else {
Q_ASSERT(deviceType == Solid::AudioHw::AudioOutput | Solid::AudioHw::AudioInput);
d->captureDevice = true;
d->playbackDevice = true;
groupName = QLatin1String("AudioIODevice_");
}
}
groupName += d->cardName;
KConfigGroup deviceGroup(config.data(), groupName);
if (config->hasGroup(groupName)) {
d->index = deviceGroup.readEntry("index", -1);
}
if (d->index == -1) {
KConfigGroup globalGroup(config.data(), "Globals");
int nextIndex = globalGroup.readEntry("nextIndex", 0);
d->index = nextIndex++;
globalGroup.writeEntry("nextIndex", nextIndex);
deviceGroup.writeEntry("index", d->index);
deviceGroup.writeEntry("cardName", d->cardName);
deviceGroup.writeEntry("icon", d->icon);
deviceGroup.writeEntry("driver", static_cast<int>(d->driver));
deviceGroup.writeEntry("captureDevice", d->captureDevice);
deviceGroup.writeEntry("playbackDevice", d->playbackDevice);
deviceGroup.writeEntry("udi", d->udi);
config->sync();
} else if (!deviceGroup.hasKey("udi")) {
deviceGroup.writeEntry("udi", d->udi);
config->sync();
}
kDebug(603) << deviceGroup.readEntry("udi", d->udi) << " == " << d->udi << endl;
//Q_ASSERT(deviceGroup.readEntry("udi", d->udi) == d->udi);
}
AudioDevice::AudioDevice(KConfigGroup &deviceGroup)
: d(new AudioDevicePrivate)
{
d->index = deviceGroup.readEntry("index", d->index);
d->cardName = deviceGroup.readEntry("cardName", d->cardName);
d->icon = deviceGroup.readEntry("icon", d->icon);
d->driver = static_cast<Solid::AudioHw::AudioDriver>(deviceGroup.readEntry("driver", static_cast<int>(d->driver)));
d->captureDevice = deviceGroup.readEntry("captureDevice", d->captureDevice);
d->playbackDevice = deviceGroup.readEntry("playbackDevice", d->playbackDevice);
d->udi = deviceGroup.readEntry("udi", d->udi);
d->valid = true;
d->available = false;
// deviceIds stays empty because it's not available
}
#if 0
void AudioDevicePrivate::deviceInfoFromControlDevice(const QString &deviceName)
{
snd_ctl_card_info_t *cardInfo;
snd_ctl_card_info_malloc(&cardInfo);
snd_ctl_t *ctl;
if (0 == snd_ctl_open(&ctl, deviceName.toLatin1().constData(), 0 /*open mode: blocking, sync*/)) {
if (0 == snd_ctl_card_info(ctl, cardInfo)) {
//Get card identifier from a CTL card info.
internalId = snd_ctl_card_info_get_id(cardInfo);
kDebug(603) << k_funcinfo << internalId << endl;
if (!deviceIds.contains(deviceName)) {
deviceIds << deviceName;
}
//Get card name from a CTL card info.
cardName = QString(snd_ctl_card_info_get_name(cardInfo)).trimmed();
valid = true;
if (cardName.contains("headset", Qt::CaseInsensitive) ||
cardName.contains("headphone", Qt::CaseInsensitive)) {
// it's a headset
icon = QLatin1String("headset");
} else {
//Get card driver name from a CTL card info.
QString driver = snd_ctl_card_info_get_driver(cardInfo);
if (driver.contains("usb", Qt::CaseInsensitive)) {
// it's an external USB device
icon = QLatin1String("usb-device");
} else {
icon = QLatin1String("pci-card");
}
}
}
snd_ctl_close(ctl);
}
snd_ctl_card_info_free(cardInfo);
}
void AudioDevicePrivate::deviceInfoFromPcmDevice(const QString &deviceName)
{
snd_pcm_info_t *pcmInfo;
snd_pcm_info_malloc(&pcmInfo);
snd_pcm_t *pcm;
if (0 == snd_pcm_open(&pcm, deviceName.toLatin1().constData(), SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK /*open mode: non-blocking, sync*/)) {
if (0 == snd_pcm_info(pcm, pcmInfo)) {
if (internalId.isNull()) {
internalId = snd_pcm_info_get_id(pcmInfo);
}
if (!deviceIds.contains(deviceName)) {
deviceIds << deviceName;
}
}
snd_pcm_close(pcm);
}
snd_pcm_info_free(pcmInfo);
}
#endif
const QString &AudioDevice::udi() const
{
return d->udi;
}
int AudioDevice::index() const
{
return d->index;
}
bool AudioDevice::isAvailable() const
{
return d->available;
}
bool AudioDevice::ceaseToExist()
{
if (d->available) {
return false; // you cannot remove devices that are plugged in
}
d->valid = false;
KSharedConfig::Ptr config = KSharedConfig::openConfig("phonondevicesrc", KConfig::NoGlobals );
QString groupName;
if (d->captureDevice) {
if (d->playbackDevice) {
groupName = QLatin1String("AudioIODevice_");
} else {
groupName = QLatin1String("AudioCaptureDevice_");
}
} else {
groupName = QLatin1String("AudioOutputDevice_");
}
groupName += d->cardName;
config->deleteGroup(groupName);
config->sync();
return true;
}
bool AudioDevice::isValid() const
{
return d->valid;
}
bool AudioDevice::isCaptureDevice() const
{
return d->captureDevice;
}
bool AudioDevice::isPlaybackDevice() const
{
return d->playbackDevice;
}
AudioDevice::AudioDevice(const AudioDevice& rhs)
: d(rhs.d)
{
++d->refCount;
}
AudioDevice::~AudioDevice()
{
--d->refCount;
if (d->refCount == 0) {
delete d;
d = 0;
}
}
AudioDevice &AudioDevice::operator=(const AudioDevice &rhs)
{
--d->refCount;
if (d->refCount == 0) {
delete d;
d = 0;
}
d = rhs.d;
++d->refCount;
return *this;
}
bool AudioDevice::operator==(const AudioDevice &rhs) const
{
return d->udi == rhs.d->udi;
/*
return (d->cardName == rhs.d->cardName &&
d->icon == rhs.d->icon &&
d->deviceIds == rhs.d->deviceIds &&
d->captureDevice == rhs.d->captureDevice &&
d->playbackDevice == rhs.d->playbackDevice);
*/
}
QString AudioDevice::cardName() const
{
return d->cardName;
}
QStringList AudioDevice::deviceIds() const
{
return d->deviceIds;
}
QString AudioDevice::iconName() const
{
return d->icon;
}
Solid::AudioHw::AudioDriver AudioDevice::driver() const
{
return d->driver;
}
} // namespace Phonon
// vim: sw=4 sts=4 et tw=100
<commit_msg>warning--<commit_after>/* This file is part of the KDE project
Copyright (C) 2006 Matthias Kretz <[email protected]>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License version 2 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
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 "audiodevice.h"
#include <QString>
#include "audiodevice_p.h"
#include "audiodeviceenumerator.h"
#include <kdebug.h>
#include <solid/device.h>
#include <solid/audiohw.h>
#include <kconfiggroup.h>
namespace Phonon
{
AudioDevice::AudioDevice()
: d(new AudioDevicePrivate)
{
}
AudioDevice::AudioDevice(Solid::Device audioDevice, KSharedConfig::Ptr config)
: d(new AudioDevicePrivate)
{
Solid::AudioHw *audioHw = audioDevice.as<Solid::AudioHw>();
kDebug(603) << k_funcinfo << audioHw->driverHandles() << endl;
d->udi = audioDevice.udi();
d->cardName = audioHw->name();
d->deviceIds = audioHw->driverHandles();
switch (audioHw->soundcardType()) {
case Solid::AudioHw::InternalSoundcard:
d->icon = QLatin1String("pci-card");
break;
case Solid::AudioHw::UsbSoundcard:
d->icon = QLatin1String("usb-device");
break;
case Solid::AudioHw::FirewireSoundcard:
d->icon = QLatin1String("firewire-device");
break;
case Solid::AudioHw::Headset:
d->icon = QLatin1String("headset");
break;
case Solid::AudioHw::Modem:
d->icon = QLatin1String("modem");
// should a modem be a valid device so that it's shown to the user?
d->valid = false;
return;
}
d->driver = audioHw->driver();
d->available = true;
d->valid = true;
QString groupName;
Solid::AudioHw::AudioHwTypes deviceType = audioHw->deviceType();
if (deviceType == Solid::AudioHw::AudioInput) {
d->captureDevice = true;
groupName = QLatin1String("AudioCaptureDevice_");
} else {
if (deviceType == Solid::AudioHw::AudioOutput) {
d->playbackDevice = true;
groupName = QLatin1String("AudioOutputDevice_");
} else {
Q_ASSERT(deviceType == (Solid::AudioHw::AudioOutput | Solid::AudioHw::AudioInput));
d->captureDevice = true;
d->playbackDevice = true;
groupName = QLatin1String("AudioIODevice_");
}
}
groupName += d->cardName;
KConfigGroup deviceGroup(config.data(), groupName);
if (config->hasGroup(groupName)) {
d->index = deviceGroup.readEntry("index", -1);
}
if (d->index == -1) {
KConfigGroup globalGroup(config.data(), "Globals");
int nextIndex = globalGroup.readEntry("nextIndex", 0);
d->index = nextIndex++;
globalGroup.writeEntry("nextIndex", nextIndex);
deviceGroup.writeEntry("index", d->index);
deviceGroup.writeEntry("cardName", d->cardName);
deviceGroup.writeEntry("icon", d->icon);
deviceGroup.writeEntry("driver", static_cast<int>(d->driver));
deviceGroup.writeEntry("captureDevice", d->captureDevice);
deviceGroup.writeEntry("playbackDevice", d->playbackDevice);
deviceGroup.writeEntry("udi", d->udi);
config->sync();
} else if (!deviceGroup.hasKey("udi")) {
deviceGroup.writeEntry("udi", d->udi);
config->sync();
}
kDebug(603) << deviceGroup.readEntry("udi", d->udi) << " == " << d->udi << endl;
//Q_ASSERT(deviceGroup.readEntry("udi", d->udi) == d->udi);
}
AudioDevice::AudioDevice(KConfigGroup &deviceGroup)
: d(new AudioDevicePrivate)
{
d->index = deviceGroup.readEntry("index", d->index);
d->cardName = deviceGroup.readEntry("cardName", d->cardName);
d->icon = deviceGroup.readEntry("icon", d->icon);
d->driver = static_cast<Solid::AudioHw::AudioDriver>(deviceGroup.readEntry("driver", static_cast<int>(d->driver)));
d->captureDevice = deviceGroup.readEntry("captureDevice", d->captureDevice);
d->playbackDevice = deviceGroup.readEntry("playbackDevice", d->playbackDevice);
d->udi = deviceGroup.readEntry("udi", d->udi);
d->valid = true;
d->available = false;
// deviceIds stays empty because it's not available
}
#if 0
void AudioDevicePrivate::deviceInfoFromControlDevice(const QString &deviceName)
{
snd_ctl_card_info_t *cardInfo;
snd_ctl_card_info_malloc(&cardInfo);
snd_ctl_t *ctl;
if (0 == snd_ctl_open(&ctl, deviceName.toLatin1().constData(), 0 /*open mode: blocking, sync*/)) {
if (0 == snd_ctl_card_info(ctl, cardInfo)) {
//Get card identifier from a CTL card info.
internalId = snd_ctl_card_info_get_id(cardInfo);
kDebug(603) << k_funcinfo << internalId << endl;
if (!deviceIds.contains(deviceName)) {
deviceIds << deviceName;
}
//Get card name from a CTL card info.
cardName = QString(snd_ctl_card_info_get_name(cardInfo)).trimmed();
valid = true;
if (cardName.contains("headset", Qt::CaseInsensitive) ||
cardName.contains("headphone", Qt::CaseInsensitive)) {
// it's a headset
icon = QLatin1String("headset");
} else {
//Get card driver name from a CTL card info.
QString driver = snd_ctl_card_info_get_driver(cardInfo);
if (driver.contains("usb", Qt::CaseInsensitive)) {
// it's an external USB device
icon = QLatin1String("usb-device");
} else {
icon = QLatin1String("pci-card");
}
}
}
snd_ctl_close(ctl);
}
snd_ctl_card_info_free(cardInfo);
}
void AudioDevicePrivate::deviceInfoFromPcmDevice(const QString &deviceName)
{
snd_pcm_info_t *pcmInfo;
snd_pcm_info_malloc(&pcmInfo);
snd_pcm_t *pcm;
if (0 == snd_pcm_open(&pcm, deviceName.toLatin1().constData(), SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK /*open mode: non-blocking, sync*/)) {
if (0 == snd_pcm_info(pcm, pcmInfo)) {
if (internalId.isNull()) {
internalId = snd_pcm_info_get_id(pcmInfo);
}
if (!deviceIds.contains(deviceName)) {
deviceIds << deviceName;
}
}
snd_pcm_close(pcm);
}
snd_pcm_info_free(pcmInfo);
}
#endif
const QString &AudioDevice::udi() const
{
return d->udi;
}
int AudioDevice::index() const
{
return d->index;
}
bool AudioDevice::isAvailable() const
{
return d->available;
}
bool AudioDevice::ceaseToExist()
{
if (d->available) {
return false; // you cannot remove devices that are plugged in
}
d->valid = false;
KSharedConfig::Ptr config = KSharedConfig::openConfig("phonondevicesrc", KConfig::NoGlobals );
QString groupName;
if (d->captureDevice) {
if (d->playbackDevice) {
groupName = QLatin1String("AudioIODevice_");
} else {
groupName = QLatin1String("AudioCaptureDevice_");
}
} else {
groupName = QLatin1String("AudioOutputDevice_");
}
groupName += d->cardName;
config->deleteGroup(groupName);
config->sync();
return true;
}
bool AudioDevice::isValid() const
{
return d->valid;
}
bool AudioDevice::isCaptureDevice() const
{
return d->captureDevice;
}
bool AudioDevice::isPlaybackDevice() const
{
return d->playbackDevice;
}
AudioDevice::AudioDevice(const AudioDevice& rhs)
: d(rhs.d)
{
++d->refCount;
}
AudioDevice::~AudioDevice()
{
--d->refCount;
if (d->refCount == 0) {
delete d;
d = 0;
}
}
AudioDevice &AudioDevice::operator=(const AudioDevice &rhs)
{
--d->refCount;
if (d->refCount == 0) {
delete d;
d = 0;
}
d = rhs.d;
++d->refCount;
return *this;
}
bool AudioDevice::operator==(const AudioDevice &rhs) const
{
return d->udi == rhs.d->udi;
/*
return (d->cardName == rhs.d->cardName &&
d->icon == rhs.d->icon &&
d->deviceIds == rhs.d->deviceIds &&
d->captureDevice == rhs.d->captureDevice &&
d->playbackDevice == rhs.d->playbackDevice);
*/
}
QString AudioDevice::cardName() const
{
return d->cardName;
}
QStringList AudioDevice::deviceIds() const
{
return d->deviceIds;
}
QString AudioDevice::iconName() const
{
return d->icon;
}
Solid::AudioHw::AudioDriver AudioDevice::driver() const
{
return d->driver;
}
} // namespace Phonon
// vim: sw=4 sts=4 et tw=100
<|endoftext|>
|
<commit_before>/*
MIT License
Copyright (c) 2017 Alan Tonks
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 "serial.h"
#include <errno.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
int checkPort(std::string port)
{
struct stat stat_buf;
if (stat(port.c_str(), &stat_buf) == 0) return 0;
else return -1;
}
Serial::Serial():Serial(4800, "/dev/ttyUSB0") { } // Delegating constructor
Serial::Serial(speed_t baud, std::string port):Serial(baud,port,true){ } // Delegating constructor
Serial::Serial(speed_t baud, std::string port, bool canon) // Target constructor
{
if (setBaud(baud) != 0) setBaud(4800);
if (checkPort(port) == 0) PORT = port;
else PORT = "/dev/ttyUSB0";
isCanonical = canon;
init();
}
// Open and configure the port
void Serial::init()
{
dev_fd = open(PORT.c_str(), O_RDWR | O_NOCTTY);
if (dev_fd < 0) {
perror("Failed to open device: ");
exit(-1);
}
else isOpen = true;
tcgetattr(dev_fd, &oldConfig);
memset(&terminalConfiguration, 0, sizeof(terminalConfiguration)); // Clear junk from location of terminalConfiguration to start with clean slate
tcgetattr(dev_fd, &terminalConfiguration);
// TERMIOS CONFIGURATION
// BAUDRATE: Integer multiple of 2400
// CRTSCTS: Hardware flow control
// CS8: 8N1
// CLOCAL: No modem control. (local device)
// HUPCL: Generates modem disconnect when port is closed
// CREAD: Receive chars
terminalConfiguration.c_cflag |= (BAUDRATE | CS8 | CLOCAL | HUPCL | CREAD);
// IGNPAR: Ignore parity errors
terminalConfiguration.c_iflag |= IGNPAR;
// 0 for raw output
terminalConfiguration.c_oflag = 0;
// Setting input mode
if (isCanonical == true) {
terminalConfiguration.c_lflag |= (ICANON | ECHO | ECHOE); // Canonical input
}
else {
//Configure non-canonical mode
terminalConfiguration.c_lflag &= ~(ICANON | ECHO | ECHOE); // Disable canonical mode and echo
terminalConfiguration.c_cc[VMIN] = 1; // Minimum number of chars to read before returning
terminalConfiguration.c_cc[VTIME] = 0; // Timeout in deciseconds. 0 to disregard timing between bytes
}
tcflush(dev_fd, TCIFLUSH);
applyNewConfig();
}
int Serial::setBaud(speed_t baud)
{
int status = -1;
switch (baud) {
case 2400:
status = cfsetspeed(&terminalConfiguration, B2400);
BAUDRATE = B2400;
break;
case 4800:
status = cfsetspeed(&terminalConfiguration, B4800);
BAUDRATE = B4800;
break;
case 9600:
status = cfsetspeed(&terminalConfiguration, B9600);
BAUDRATE = B9600;
break;
case 19200:
status = cfsetspeed(&terminalConfiguration, B19200);
BAUDRATE = B19200;
break;
case 38400:
status = cfsetspeed(&terminalConfiguration, B38400);
BAUDRATE = B38400;
break;
case 57600:
status = cfsetspeed(&terminalConfiguration, B57600);
BAUDRATE = B57600;
break;
case 115200:
status = cfsetspeed(&terminalConfiguration, B115200);
BAUDRATE = B115200;
break;
case 230400:
status = cfsetspeed(&terminalConfiguration, B230400);
BAUDRATE = B230400;
break;
default:
std::cout << "Invalid baudrate requested.\n";
return -1;
}
if (status < 0) {
perror("In function setBaud() failed to set requested baudrate: ");
return -1;
}
else {
return status;
}
}
int Serial::applyNewConfig()
{
if (tcsetattr(dev_fd, TCSANOW, &terminalConfiguration) < 0) perror("Could not apply configuration: ");
else return 0;
}
speed_t Serial::getBaud()
{
return cfgetispeed(&terminalConfiguration);
}
termios Serial::getConfig()
{
return terminalConfiguration;
}
// Helper function checks if port is open,
// then flushes the serial line.
int Serial::setupRead()
{
if (!isOpen) return -1;
if (tcflush(dev_fd, TCIOFLUSH < 0)) {
perror("Could not flush line: ");
return -1;
}
else return 0;
}
int Serial::serialRead()
{
return serialRead(255);
}
int Serial::serialRead(int bytes)
{
if (setupRead() < 0) return -1;
int buf_size = bytes;
char buf[buf_size];
bytesReceived = read(dev_fd, buf, bytes);
if (bytesReceived < 0) perror("Read failed: ");
else buf[bytesReceived] = '\0'; // Null terminated
serialData.assign(buf); // Store as std::string
return bytesReceived;
}
int Serial::flush()
{
return tcflush(dev_fd, TCIOFLUSH);
}
int Serial::serialWrite(std::string str)
{
if (!isOpen) return -1;
int write_status = write(dev_fd, str.c_str(), str.length());
if (write_status < 0) {
perror("Failed to write to port: ");
return -1;
}
else return write_status;
}
std::string Serial::getData()
{
return serialData;
}
Serial::~Serial()
{
tcsetattr(dev_fd, TCSANOW, &oldConfig); // Leave port how we found it
close(dev_fd);
}
<commit_msg>Commenting<commit_after>/*
MIT License
Copyright (c) 2017 Alan Tonks
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 "serial.h"
#include <errno.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
int checkPort(std::string port)
{
struct stat stat_buf;
if (stat(port.c_str(), &stat_buf) == 0) return 0;
else return -1;
}
Serial::Serial():Serial(4800, "/dev/ttyUSB0") { } // Delegating constructor
Serial::Serial(speed_t baud, std::string port):Serial(baud,port,true){ } // Delegating constructor
Serial::Serial(speed_t baud, std::string port, bool canon) // Target constructor
{
if (setBaud(baud) != 0) setBaud(4800);
if (checkPort(port) == 0) PORT = port;
else PORT = "/dev/ttyUSB0";
isCanonical = canon;
init();
}
// Open and configure the port
void Serial::init()
{
dev_fd = open(PORT.c_str(), O_RDWR | O_NOCTTY);
if (dev_fd < 0) {
perror("Failed to open device: ");
exit(-1);
}
else isOpen = true;
tcgetattr(dev_fd, &oldConfig);
memset(&terminalConfiguration, 0, sizeof(terminalConfiguration)); // Clear junk from location of terminalConfiguration to start with clean slate
tcgetattr(dev_fd, &terminalConfiguration);
// TERMIOS CONFIGURATION
// BAUDRATE: Integer multiple of 2400
// CRTSCTS: Hardware flow control
// CS8: 8N1
// CLOCAL: No modem control. (local device)
// HUPCL: Generates modem disconnect when port is closed
// CREAD: Receive chars
terminalConfiguration.c_cflag |= (BAUDRATE | CS8 | CLOCAL | HUPCL | CREAD);
// IGNPAR: Ignore parity errors
terminalConfiguration.c_iflag |= IGNPAR;
// 0 for raw output
terminalConfiguration.c_oflag = 0;
// Setting input mode
if (isCanonical == true) {
terminalConfiguration.c_lflag |= (ICANON | ECHO | ECHOE); // Canonical input
}
else {
//Configure non-canonical mode
terminalConfiguration.c_lflag &= ~(ICANON | ECHO | ECHOE); // Disable canonical mode and echo
terminalConfiguration.c_cc[VMIN] = 1; // Minimum number of chars to read before returning
terminalConfiguration.c_cc[VTIME] = 0; // Timeout in deciseconds. 0 to disregard timing between bytes
}
tcflush(dev_fd, TCIFLUSH);
applyNewConfig();
}
int Serial::setBaud(speed_t baud)
{
int status = -1;
switch (baud) {
case 2400:
status = cfsetspeed(&terminalConfiguration, B2400);
BAUDRATE = B2400;
break;
case 4800:
status = cfsetspeed(&terminalConfiguration, B4800);
BAUDRATE = B4800;
break;
case 9600:
status = cfsetspeed(&terminalConfiguration, B9600);
BAUDRATE = B9600;
break;
case 19200:
status = cfsetspeed(&terminalConfiguration, B19200);
BAUDRATE = B19200;
break;
case 38400:
status = cfsetspeed(&terminalConfiguration, B38400);
BAUDRATE = B38400;
break;
case 57600:
status = cfsetspeed(&terminalConfiguration, B57600);
BAUDRATE = B57600;
break;
case 115200:
status = cfsetspeed(&terminalConfiguration, B115200);
BAUDRATE = B115200;
break;
case 230400:
status = cfsetspeed(&terminalConfiguration, B230400);
BAUDRATE = B230400;
break;
default:
std::cout << "Invalid baudrate requested.\n";
return -1;
}
if (status < 0) {
perror("In function setBaud() failed to set requested baudrate: ");
return -1;
}
else {
return status;
}
}
int Serial::applyNewConfig()
{
if (tcsetattr(dev_fd, TCSANOW, &terminalConfiguration) < 0) perror("Could not apply configuration: ");
else return 0;
}
speed_t Serial::getBaud()
{
return cfgetispeed(&terminalConfiguration);
}
termios Serial::getConfig()
{
return terminalConfiguration;
}
// Helper function checks if port is open,
// then flushes the serial line.
int Serial::setupRead()
{
if (!isOpen) return -1;
if (tcflush(dev_fd, TCIOFLUSH < 0)) {
perror("Could not flush line: ");
return -1;
}
else return 0;
}
int Serial::serialRead()
{
return serialRead(255); // Request 255 bytes. Will return when \n is received.
}
int Serial::serialRead(int bytes)
{
if (setupRead() < 0) return -1;
int buf_size = bytes;
char buf[buf_size];
bytesReceived = read(dev_fd, buf, bytes);
if (bytesReceived < 0) perror("Read failed: ");
else buf[bytesReceived] = '\0'; // Null terminated
serialData.assign(buf); // Store as std::string
return bytesReceived;
}
int Serial::flush()
{
return tcflush(dev_fd, TCIOFLUSH);
}
int Serial::serialWrite(std::string str)
{
if (!isOpen) return -1;
int write_status = write(dev_fd, str.c_str(), str.length());
if (write_status < 0) {
perror("Failed to write to port: ");
return -1;
}
else return write_status;
}
std::string Serial::getData()
{
return serialData;
}
Serial::~Serial()
{
tcsetattr(dev_fd, TCSANOW, &oldConfig); // Leave port how we found it
close(dev_fd);
}
<|endoftext|>
|
<commit_before>/*
MIT License
Copyright (c) 2017 Alan Tonks
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 "serial.h"
#include <errno.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
Serial::Serial() {
PORT = "/dev/ttyUSB0";
Serial(4800, PORT, true);
}
Serial::Serial(speed_t baud, std::string port)
{
Serial(baud, port, true);
}
Serial::Serial(speed_t baud, std::string port, bool canon)
{
// Make a copy of the current configuration so it can be
// restored in destructor.
isCanonical = canon;
if (setBaud(baud) == 0) BAUDRATE = baud; // baudrate must be multiple of 2400
isOpen = false;
struct stat stat_buf; // See if specified port exists
if (stat(port.c_str(), &stat_buf) == 0) PORT = port;
else { // Port doesn't exist
std::cout << "Device not found." << std::endl;
exit(-1);
}
// open port for read and write, not controlling, ignore DCD line
dev_fd = open(PORT.c_str(), O_RDWR | O_NOCTTY);
if (dev_fd < 0) {
perror("In function: Serial()\n Failed to open device: ");
exit(-1);
}
else {
std::cout << "dev_fd: " << dev_fd << std::endl;
isOpen = true;
}
init();
}
// Open and configure the port
void Serial::init()
{
tcgetattr(dev_fd, &oldConfig);
// memset(&terminalConfiguration, 0, sizeof(terminalConfiguration)); // Clear junk from location of terminalConfiguration to start with clean slate
tcgetattr(dev_fd, &terminalConfiguration);
// TERMIOS CONFIGURATION
// BAUDRATE: Integer multiple of 2400
// CRTSCTS: Hardware flow control
// CS8: 8N1
// CLOCAL: No modem control. (local device)
// CREAD: Receive chars
terminalConfiguration.c_cflag |= (BAUDRATE | CS8 | CLOCAL | CREAD);
// IGNPAR: Ignore parity errors
terminalConfiguration.c_iflag |= IGNPAR;
// 0 for raw output
terminalConfiguration.c_oflag = 0;
// Setting input mode
if (isCanonical) terminalConfiguration.c_lflag |= (ICANON | ECHO | ECHOE); // Canonical input
else {
//Configure non-canonical mode
terminalConfiguration.c_lflag &= ~(ICANON | ECHO | ECHOE); // Disable canonical mode and echo
terminalConfiguration.c_cc[VMIN] = 1; // Minimum number of chars to read before returning
terminalConfiguration.c_cc[VTIME] = 0; // Timeout in deciseconds. 0 to disregard timing between bytes
}
tcflush(dev_fd, TCIFLUSH);
applyNewConfig();
}
int Serial::setBaud(speed_t baud)
{
int status_i = -1;
int status_o = -1;
switch (baud) {
case 2400:
status_i = cfsetispeed(&terminalConfiguration, B2400);
status_o = cfsetospeed(&terminalConfiguration, B2400);
break;
case 4800:
status_i = cfsetispeed(&terminalConfiguration, B4800);
status_o = cfsetospeed(&terminalConfiguration, B4800);
break;
case 9600:
status_i = cfsetispeed(&terminalConfiguration, B9600);
status_o = cfsetospeed(&terminalConfiguration, B9600);
break;
case 19200:
status_i = cfsetispeed(&terminalConfiguration, B19200);
status_o = cfsetospeed(&terminalConfiguration, B19200);
break;
case 38400:
status_i = cfsetispeed(&terminalConfiguration, B38400);
status_o = cfsetospeed(&terminalConfiguration, B38400);
break;
case 57600:
status_i = cfsetispeed(&terminalConfiguration, B57600);
status_o = cfsetospeed(&terminalConfiguration, B57600);
break;
case 115200:
status_i = cfsetispeed(&terminalConfiguration, B115200);
status_o = cfsetospeed(&terminalConfiguration, B115200);
break;
case 230400:
status_i = cfsetispeed(&terminalConfiguration, B230400);
status_o = cfsetospeed(&terminalConfiguration, B230400);
break;
default:
std::cout << "Invalid baudrate requested.\n";
return -1;
}
if (status_i < 0 || status_o < 0) {
perror("In function: setBaud()\nFailed to set requested baudrate: ");
return -1;
}
else return status_i;
}
int Serial::applyNewConfig()
{
if (isOpen) {
if (tcsetattr(dev_fd, TCSANOW, &terminalConfiguration) < 0) perror("Could not apply configuration: ");
else return 0;
}
else return -1;
}
speed_t Serial::getBaud()
{
return cfgetispeed(&terminalConfiguration);
}
termios Serial::getConfig()
{
return terminalConfiguration;
}
// Helper function checks if port is open,
// then flushes the serial line.
int Serial::setupRead()
{
if (!isOpen) return -1;
if (tcflush(dev_fd, TCIOFLUSH < 0)) {
perror("Could not flush line: ");
return -1;
}
else return 0;
}
int Serial::serialRead()
{
if (setupRead() < 0) return -1;
int buf_size = 255; // 82 is longest NMEA Sentence
char buf[buf_size];
bytesReceived = read(dev_fd, buf, buf_size);
if (bytesReceived < 0) perror("In function serialRead()\nRead failed: ");
else buf[bytesReceived] = '\0'; // Null terminate the string
serialData.assign(buf); // store serialData as std::string
return bytesReceived;
}
int Serial::serialRead(int bytes)
{
if (setupRead() < 0) return -1;
int buf_size = bytes;
char buf[buf_size];
bytesReceived = read(dev_fd, buf, bytes);
if (bytesReceived < 0) perror("Read failed: ");
else buf[bytesReceived] = '\0'; // Null terminated
serialData.assign(buf); // Store as std::string
return bytesReceived;
}
int Serial::flush()
{
return tcflush(dev_fd, TCIOFLUSH);
}
int Serial::serialWrite(std::string str)
{
if (!isOpen) return -1;
int write_status = write(dev_fd, str.c_str(), str.length());
if (write_status < 0) {
perror("Failed to write to port: ");
return -1;
}
else return write_status;
}
std::string Serial::getData()
{
return serialData;
}
Serial::~Serial()
{
tcsetattr(dev_fd, TCSANOW, &oldConfig); /* Leave port how we found it. */
close(dev_fd); /* close the port */
}<commit_msg>Added debug output<commit_after>/*
MIT License
Copyright (c) 2017 Alan Tonks
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 "serial.h"
#include <errno.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
Serial::Serial() {
PORT = "/dev/ttyUSB0";
Serial(4800, PORT, true);
}
Serial::Serial(speed_t baud, std::string port)
{
Serial(baud, port, true);
}
Serial::Serial(speed_t baud, std::string port, bool canon)
{
// Make a copy of the current configuration so it can be
// restored in destructor.
isCanonical = canon;
if (setBaud(baud) == 0) BAUDRATE = baud; // baudrate must be multiple of 2400
isOpen = false;
struct stat stat_buf; // See if specified port exists
if (stat(port.c_str(), &stat_buf) == 0) PORT = port;
else { // Port doesn't exist
std::cout << "Device not found." << std::endl;
exit(-1);
}
// open port for read and write, not controlling, ignore DCD line
dev_fd = open(PORT.c_str(), O_RDWR | O_NOCTTY);
if (dev_fd < 0) {
perror("In function: Serial()\n Failed to open device: ");
exit(-1);
}
else {
std::cout << "dev_fd: " << dev_fd << std::endl;
isOpen = true;
}
init();
}
// Open and configure the port
void Serial::init()
{
tcgetattr(dev_fd, &oldConfig);
// memset(&terminalConfiguration, 0, sizeof(terminalConfiguration)); // Clear junk from location of terminalConfiguration to start with clean slate
tcgetattr(dev_fd, &terminalConfiguration);
// TERMIOS CONFIGURATION
// BAUDRATE: Integer multiple of 2400
// CRTSCTS: Hardware flow control
// CS8: 8N1
// CLOCAL: No modem control. (local device)
// CREAD: Receive chars
terminalConfiguration.c_cflag |= (BAUDRATE | CS8 | CLOCAL | CREAD);
// IGNPAR: Ignore parity errors
terminalConfiguration.c_iflag |= IGNPAR;
// 0 for raw output
terminalConfiguration.c_oflag = 0;
// Setting input mode
if (isCanonical) terminalConfiguration.c_lflag |= (ICANON | ECHO | ECHOE); // Canonical input
else {
//Configure non-canonical mode
terminalConfiguration.c_lflag &= ~(ICANON | ECHO | ECHOE); // Disable canonical mode and echo
terminalConfiguration.c_cc[VMIN] = 1; // Minimum number of chars to read before returning
terminalConfiguration.c_cc[VTIME] = 0; // Timeout in deciseconds. 0 to disregard timing between bytes
}
tcflush(dev_fd, TCIFLUSH);
applyNewConfig();
}
int Serial::setBaud(speed_t baud)
{
int status_i = -1;
int status_o = -1;
switch (baud) {
case 2400:
status_i = cfsetispeed(&terminalConfiguration, B2400);
status_o = cfsetospeed(&terminalConfiguration, B2400);
break;
case 4800:
status_i = cfsetispeed(&terminalConfiguration, B4800);
status_o = cfsetospeed(&terminalConfiguration, B4800);
break;
case 9600:
status_i = cfsetispeed(&terminalConfiguration, B9600);
status_o = cfsetospeed(&terminalConfiguration, B9600);
break;
case 19200:
status_i = cfsetispeed(&terminalConfiguration, B19200);
status_o = cfsetospeed(&terminalConfiguration, B19200);
break;
case 38400:
status_i = cfsetispeed(&terminalConfiguration, B38400);
status_o = cfsetospeed(&terminalConfiguration, B38400);
break;
case 57600:
status_i = cfsetispeed(&terminalConfiguration, B57600);
status_o = cfsetospeed(&terminalConfiguration, B57600);
break;
case 115200:
status_i = cfsetispeed(&terminalConfiguration, B115200);
status_o = cfsetospeed(&terminalConfiguration, B115200);
break;
case 230400:
status_i = cfsetispeed(&terminalConfiguration, B230400);
status_o = cfsetospeed(&terminalConfiguration, B230400);
break;
default:
std::cout << "Invalid baudrate requested.\n";
return -1;
}
if (status_i < 0 || status_o < 0) {
perror("In function: setBaud()\nFailed to set requested baudrate: ");
return -1;
}
else return status_i;
}
int Serial::applyNewConfig()
{
if (tcsetattr(dev_fd, TCSANOW, &terminalConfiguration) < 0) perror("Could not apply configuration: ");
else return 0;
}
speed_t Serial::getBaud()
{
return cfgetispeed(&terminalConfiguration);
}
termios Serial::getConfig()
{
return terminalConfiguration;
}
// Helper function checks if port is open,
// then flushes the serial line.
int Serial::setupRead()
{
if (!isOpen) return -1;
if (tcflush(dev_fd, TCIOFLUSH < 0)) {
perror("Could not flush line: ");
return -1;
}
else return 0;
}
int Serial::serialRead()
{
if (setupRead() < 0) return -1;
int buf_size = 255; // 82 is longest NMEA Sentence
char buf[buf_size];
bytesReceived = read(dev_fd, buf, buf_size);
if (bytesReceived < 0) perror("In function serialRead()\nRead failed: ");
else buf[bytesReceived] = '\0'; // Null terminate the string
serialData.assign(buf); // store serialData as std::string
return bytesReceived;
}
int Serial::serialRead(int bytes)
{
if (setupRead() < 0) return -1;
int buf_size = bytes;
char buf[buf_size];
bytesReceived = read(dev_fd, buf, bytes);
if (bytesReceived < 0) perror("Read failed: ");
else buf[bytesReceived] = '\0'; // Null terminated
serialData.assign(buf); // Store as std::string
return bytesReceived;
}
int Serial::flush()
{
return tcflush(dev_fd, TCIOFLUSH);
}
int Serial::serialWrite(std::string str)
{
if (!isOpen) return -1;
int write_status = write(dev_fd, str.c_str(), str.length());
if (write_status < 0) {
perror("Failed to write to port: ");
return -1;
}
else return write_status;
}
std::string Serial::getData()
{
return serialData;
}
Serial::~Serial()
{
tcsetattr(dev_fd, TCSANOW, &oldConfig); /* Leave port how we found it. */
close(dev_fd); /* close the port */
}<|endoftext|>
|
<commit_before>#include <stdlib.h>
#include <sys/socket.h>
#include <string.h>
#include <netinet/in.h>
#include <cstring>
#include <stdio.h>
#include <string>
#include <iostream>
#include <list>
#include <map>
#include "server.h"
#include "duckchat.h"
// TODO Server can accept connections.
// TODO Server handles Login and Logout from users, and keeps records of which users are logged in.
// TODO Server handles Join and Leave from users, keeps records of which channels a user belongs to,
// and keeps records of which users are in a channel.
// TODO Server handles the Say message.
// TODO Server correctly handles List and Who.
// TODO Create copies of your client and server source. Modify them to send invalid packets to your good client
// and server, to see if you can make your client or server crash. Fix any bugs you find.
//std::string user;
class Channel {
public:
std::string name;
std::list<User *> users;
Channel(std::string name): name(name) {};
};
class User {
public:
std::string name;
struct sockaddr_in *address;
std::list<Channel *> channels;
User(std::string name, struct sockaddr_in *address): name(name), address(address) {};
};
std::map<std::string, User *> users;
std::map<std::string, Channel *> channels;
void Error(const char *msg) {
perror(msg);
exit(1);
}
void ProcessRequest(void *buffer, struct sockaddr_in *address) {
struct request current_request;
User *new_user;
std::map<std::string, User *>::iterator it;
memcpy(¤t_request, buffer, sizeof(struct request));
std::cout << "request type: " << current_request.req_type << std::endl;
request_t request_type = current_request.req_type;
switch(request_type) {
case REQ_LOGIN:
struct request_login login_request;
memcpy(&login_request, buffer, sizeof(struct request_login));
new_user = new User(login_request.req_username, address);
users.insert({std::string(login_request.req_username), new_user});
std::cout << "server: " << login_request.req_username << " logs in" << std::endl;
break;
case REQ_LOGOUT:
struct request_logout logout_request;
memcpy(&logout_request, buffer, sizeof(struct request_logout));
for (auto user : users) {
unsigned short user_port = user.second->address->sin_port;
in_addr_t user_address = user.second->address->sin_addr.s_addr;
unsigned short request_port = address->sin_port;
in_addr_t request_address = address->sin_addr.s_addr;
if (user_port == request_port && user_address == request_address) {
std::cout << "server: " << user.first << " logs out" << std::endl;
users.erase(user.first);
break;
}
}
break;
case REQ_JOIN:
struct request_join join_request;
memcpy(&join_request, buffer, sizeof(struct request_join));
// std::cout << "server: " << username << " joins channel " << join_request.req_channel << std::endl;
break;
default:
break;
}
for (auto user : users) {
unsigned short user_port = user.second->address->sin_port;
in_addr_t user_address = user.second->address->sin_addr.s_addr;
std::cout << user.first << " " << user_address << ":" << user_port << std::endl;
}
}
int main(int argc, char *argv[]) {
struct sockaddr_in server_addr;
int server_socket;
int receive_len;
void* buffer[kBufferSize];
int port;
// user = "";
if (argc < 2) {
std::cerr << "server: no port provided" << std::endl;
exit(1);
}
port = atoi(argv[1]);
memset((char *) &server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
server_addr.sin_port = htons(port);
if ((server_socket = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
Error("server: can't open socket\n");
}
if (bind(server_socket, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0) {
Error("server: bind failed\n");
}
printf("server: waiting on port %d\n", port);
while (1) {
struct sockaddr_in client_addr;
socklen_t client_addr_len = sizeof(client_addr);
// std::cout << "before recvfrom" << std::endl;
receive_len = recvfrom(server_socket, buffer, kBufferSize, 0, (struct sockaddr *) &client_addr, &client_addr_len);
if (receive_len > 0) {
buffer[receive_len] = 0;
ProcessRequest(buffer, &client_addr);
}
}
}
<commit_msg>more printing test logout<commit_after>#include <stdlib.h>
#include <sys/socket.h>
#include <string.h>
#include <netinet/in.h>
#include <cstring>
#include <stdio.h>
#include <string>
#include <iostream>
#include <list>
#include <map>
#include "server.h"
#include "duckchat.h"
// TODO Server can accept connections.
// TODO Server handles Login and Logout from users, and keeps records of which users are logged in.
// TODO Server handles Join and Leave from users, keeps records of which channels a user belongs to,
// and keeps records of which users are in a channel.
// TODO Server handles the Say message.
// TODO Server correctly handles List and Who.
// TODO Create copies of your client and server source. Modify them to send invalid packets to your good client
// and server, to see if you can make your client or server crash. Fix any bugs you find.
//std::string user;
class Channel {
public:
std::string name;
std::list<User *> users;
Channel(std::string name): name(name) {};
};
class User {
public:
std::string name;
struct sockaddr_in *address;
std::list<Channel *> channels;
User(std::string name, struct sockaddr_in *address): name(name), address(address) {};
};
std::map<std::string, User *> users;
std::map<std::string, Channel *> channels;
void Error(const char *msg) {
perror(msg);
exit(1);
}
void ProcessRequest(void *buffer, struct sockaddr_in *address) {
struct request current_request;
User *new_user;
std::map<std::string, User *>::iterator it;
memcpy(¤t_request, buffer, sizeof(struct request));
std::cout << "request type: " << current_request.req_type << std::endl;
request_t request_type = current_request.req_type;
switch(request_type) {
case REQ_LOGIN:
struct request_login login_request;
memcpy(&login_request, buffer, sizeof(struct request_login));
new_user = new User(login_request.req_username, address);
users.insert({std::string(login_request.req_username), new_user});
std::cout << "server: " << login_request.req_username << " logs in" << std::endl;
break;
case REQ_LOGOUT:
struct request_logout logout_request;
memcpy(&logout_request, buffer, sizeof(struct request_logout));
for (auto user : users) {
unsigned short user_port = user.second->address->sin_port;
in_addr_t user_address = user.second->address->sin_addr.s_addr;
unsigned short request_port = address->sin_port;
in_addr_t request_address = address->sin_addr.s_addr;
std::cout << user_port << " == " << request_port << " && " << user_address << " == " << request_address << std::endl;
if (user_port == request_port && user_address == request_address) {
std::cout << "server: " << user.first << " logs out" << std::endl;
users.erase(user.first);
break;
}
}
break;
case REQ_JOIN:
struct request_join join_request;
memcpy(&join_request, buffer, sizeof(struct request_join));
// std::cout << "server: " << username << " joins channel " << join_request.req_channel << std::endl;
break;
default:
break;
}
//
// for (auto user : users) {
// unsigned short user_port = user.second->address->sin_port;
// in_addr_t user_address = user.second->address->sin_addr.s_addr;
//
// std::cout << user.first << " " << user_address << ":" << user_port << std::endl;
// }
}
int main(int argc, char *argv[]) {
struct sockaddr_in server_addr;
int server_socket;
int receive_len;
void* buffer[kBufferSize];
int port;
// user = "";
if (argc < 2) {
std::cerr << "server: no port provided" << std::endl;
exit(1);
}
port = atoi(argv[1]);
memset((char *) &server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
server_addr.sin_port = htons(port);
if ((server_socket = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
Error("server: can't open socket\n");
}
if (bind(server_socket, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0) {
Error("server: bind failed\n");
}
printf("server: waiting on port %d\n", port);
while (1) {
struct sockaddr_in client_addr;
socklen_t client_addr_len = sizeof(client_addr);
// std::cout << "before recvfrom" << std::endl;
receive_len = recvfrom(server_socket, buffer, kBufferSize, 0, (struct sockaddr *) &client_addr, &client_addr_len);
if (receive_len > 0) {
buffer[receive_len] = 0;
ProcessRequest(buffer, &client_addr);
}
}
}
<|endoftext|>
|
<commit_before>#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/time.h>
#include <string.h>
#include <iostream>
#include <fstream>
#include <boost/lexical_cast.hpp>
#include "packet.h"
#define USAGE "Usage:\r\nc \r\n[tux machine number] \r\n[probability of packet corruption in int form] \r\n[probability of packet loss in int form] \r\n[probability of packet delay] \r\n[length of delay in ms] \r\n"
#define PORT 10038
#define PAKSIZE 512
#define ACK 0
#define NAK 1
#define BUFSIZE 505
#define FILENAME "Testfile"
#define TIMEOUT 100 //in ms
#define WIN_SIZE 16
using namespace std;
bool isvpack(unsigned char * p);
bool init(int argc, char** argv);
bool loadFile();
bool getFile();
bool sendFile();
bool isAck();
void handleAck();
void handleNak(int& x);
bool* gremlin(Packet * pack, int corruptProb, int lossProb, int delayProb);
Packet createPacket(int index);
void loadWindow();
bool sendPacket();
bool getGet();
struct sockaddr_in a;
struct sockaddr_in ca;
socklen_t calen;
int rlen;
int s;
bool ack;
string fstr;
char * file;
int probCorrupt;
int probLoss;
int probDelay;
int delayT;
Packet p;
Packet window[16];
int length;
bool dropPck;
bool delayPck;
int toms;
unsigned char b[BUFSIZE];
int base;
int main(int argc, char** argv) {
if(!init(argc, argv)) return -1;
sendFile();
return 0;
}
bool init(int argc, char** argv){
if(argc != 6) {
cout << USAGE << endl;
return false;
}
char * probCorruptStr = argv[2];
probCorrupt = boost::lexical_cast<int>(probCorruptStr);
char * probLossStr = argv[3];
probLoss = boost::lexical_cast<int>(probLossStr);
char * probDelayStr = argv[4];
probDelay = boost::lexical_cast<int>(probDelayStr);
char* delayTStr = argv[5];
delayT = boost::lexical_cast<int>(delayTStr);
struct timeval timeout;
timeout.tv_usec = TIMEOUT * 1000;
toms = TIMEOUT;
/* Create our socket. */
if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
cout << "Socket creation failed. (socket s)" << endl;
return 0;
}
setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout, sizeof(timeout));
/*
* Bind our socket to an IP (whatever the computer decides)
* and a specified port.
*
*/
if (!loadFile()) {
cout << "Loading file failed. (filename FILENAME)" << endl;
return false;
}
memset((char *)&a, 0, sizeof(a));
a.sin_family = AF_INET;
a.sin_addr.s_addr = htonl(INADDR_ANY);
a.sin_port = htons(PORT);
if (bind(s, (struct sockaddr *)&a, sizeof(a)) < 0) {
cout << "Socket binding failed. (socket s, address a)" << endl;
return 0;
}
fstr = string(file);
cout << "File: " << endl << fstr << endl;
base = 0;
dropPck = false;
calen = sizeof(ca);
getGet();
return true;
}
bool getGet(){
unsigned char packet[PAKSIZE + 1];
rlen = recvfrom(s, packet, PAKSIZE, 0, (struct sockaddr *)&ca, &calen);
return (rlen > 0) ? true : false;
}
bool isvpack(unsigned char * p) {
cout << endl << "=== IS VALID PACKET TESTING" << endl;
char * sns = new char[2];
memcpy(sns, &p[0], 1);
sns[1] = '\0';
char * css = new char[7];
memcpy(css, &p[1], 6);
css[6] = '\0';
char * db = new char[121 + 1];
memcpy(db, &p[2], 121);
db[121] = '\0';
cout << "Seq. num: " << sns << endl;
cout << "Checksum: " << css << endl;
cout << "Message: " << db << endl;
int sn = boost::lexical_cast<int>(sns);
int cs = boost::lexical_cast<int>(css);
Packet pk (0, db);
pk.setSequenceNum(sn);
// change to validate based on checksum and sequence number
if(sn == 0) return false; //doesn't matter, only for the old version (netwark)
if(cs != pk.generateCheckSum()) return false;
return true;
}
bool getFile(){
/* Loop forever, waiting for messages from a client. */
cout << "Waiting on port " << PORT << "..." << endl;
ofstream file("Dumpfile");
for (;;) {
unsigned char packet[PAKSIZE + 1];
unsigned char dataPull[PAKSIZE - 7 + 1];
rlen = recvfrom(s, packet, PAKSIZE, 0, (struct sockaddr *)&ca, &calen);
for(int x = 0; x < PAKSIZE - 7; x++) {
dataPull[x] = packet[x + 7];
}
dataPull[PAKSIZE - 7] = '\0';
packet[PAKSIZE] = '\0';
if (rlen > 0) {
char * css = new char[6];
memcpy(css, &packet[1], 5);
css[5] = '\0';
cout << endl << endl << "=== RECEIPT" << endl;
cout << "Seq. num: " << packet[0] << endl;
cout << "Checksum: " << css << endl;
cout << "Received message: " << dataPull << endl;
cout << "Sent response: ";
if(isvpack(packet)) {
ack = ACK;
//seqNum = (seqNum) ? false : true;
file << dataPull;
} else {
ack = NAK;
}
cout << ((ack == ACK) ? "ACK" : "NAK") << endl;
Packet p (false, reinterpret_cast<const char *>(dataPull));
p.setCheckSum(boost::lexical_cast<int>(css));
p.setAckNack(ack);
if(sendto(s, p.str(), PAKSIZE, 0, (struct sockaddr *)&ca, calen) < 0) {
cout << "Acknowledgement failed. (socket s, acknowledgement message ack, client address ca, client address length calen)" << endl;
return 0;
}
delete css;
}
}
file.close();
return true;
}
bool loadFile() {
ifstream is (FILENAME, ifstream::binary);
if(is) {
is.seekg(0, is.end);
length = is.tellg();
is.seekg(0, is.beg);
file = new char[length];
cout << "Reading " << length << " characters..." << endl;
is.read(file, length);
if(!is) { cout << "File reading failed. (filename " << FILENAME << "). Only " << is.gcount() << " could be read."; return false; }
is.close();
}
return true;
}
void loadWindow(){
for(int i = base; i < base + WIN_SIZE; i++) {
window[i-base] = createPacket(i);
if(strlen(window[i-base].getDataBuffer()) < BUFSIZE - 1 && window[i-base].getDataBuffer()[0] != 'G') {
for(++i; i < base + WIN_SIZE; i++){
window[i-base].loadDataBuffer("\0");
}
return;
}
cout << "window[i-base] seq. num: " << window[i-base].getSequenceNum() << endl;
}
}
bool sendFile() {
/*Currently causes the program to only send the first 16 packets of file out
requires additional code later to sendFile again with updated window*/
base = 0;
while(base * BUFSIZE < length) {
loadWindow();
cout << "packet " << base << ": " << window[0].str() << endl;
for(int x = 0; x < WIN_SIZE; x++) {
p = window[x];
if(!sendPacket()) continue;
}
if(p.str()[0] == '\0') break;
for(int x = 0; x < WIN_SIZE; x++) {
if(recvfrom(s, b, BUFSIZE + 7, 0, (struct sockaddr *)&ca, &calen) < 0) {
cout << "=== ACK TIMEOUT" << endl;
x--;
continue;
}
if(isAck()) {
handleAck();
} else {
handleAck();
//handleNak(x);
}
memset(b, 0, BUFSIZE);
}
}
if(sendto(s, "\0", BUFSIZE, 0, (struct sockaddr *)&ca, sizeof(ca)) < 0) {
cout << "Final package sending failed. (socket s, server address sa, message m)" << endl;
return false;
}
return true;
}
Packet createPacket(int index){
string mstr = fstr.substr(index * BUFSIZE, BUFSIZE);
if(mstr.length() < BUFSIZE) {
cout << "Null terminated mstr." << endl;
mstr[length - (index * BUFSIZE)] = '\0';
}
cout << "index: " << index << endl;
return Packet (index, mstr.c_str());
}
bool sendPacket(){
cout << endl;
cout << "=== TRANSMISSION START" << endl;
cout << "Sequence number before gremlin function: " << p.getSequenceNum() << endl;
int pc = probCorrupt; int pl = probLoss; int pd = probDelay;
bool* pckStatus = gremlin(&p, pc, pl, pd);
dropPck = pckStatus[0];
delayPck = pckStatus[1];
if (dropPck == true) return false;
if (delayPck == true) p.setAckNack(1);
if(sendto(s, p.str(), BUFSIZE + 8, 0, (struct sockaddr *)&ca, sizeof(ca)) < 0) {
cout << "Package sending failed. (socket s, server address sa, message m)" << endl;
return false;
}
return true;
}
bool isAck() {
cout << endl << "=== SERVER RESPONSE TEST" << endl;
cout << "Data: " << b << endl;
if(b[6] == '0') return true;
else return false;
}
void handleAck() {
int ack = boost::lexical_cast<int>(b);
if(base < ack) base = ack;
cout << "Window base: " << base << endl;
}
void handleNak(int& x) {
char * sns = new char[2];
memcpy(sns, &b[0], 1);
sns[1] = '\0';
char * css = new char[5];
memcpy(css, &b[1], 5);
char * db = new char[BUFSIZE + 1];
memcpy(db, &b[2], BUFSIZE);
db[BUFSIZE] = '\0';
cout << "Sequence number: " << sns << endl;
cout << "Checksum: " << css << endl;
Packet pk (0, db);
pk.setSequenceNum(boost::lexical_cast<int>(sns));
pk.setCheckSum(boost::lexical_cast<int>(css));
if(!pk.chksm()) x--;
else x = (x - 2 > 0) ? x - 2 : 0;
}
bool* gremlin(Packet * pack, int corruptProb, int lossProb, int delayProb){
bool* packStatus = new bool[2];
int r = rand() % 100;
cout << "Corruption probability: " << corruptProb << endl;
cout << "Random number: " << r << endl;
packStatus[0] = false;
packStatus[1] = false;
if(r <= (lossProb)){
packStatus[0] = true;
cout << "Dropped!" << endl;
}
else if(r <= (delayProb)){
packStatus[1] = true;
cout << "Delayed!" << endl;
}
else if(r <= (corruptProb)){
cout << "Corrupted!" << endl;
cout << "Seq. num (pre-gremlin): " << pack->getSequenceNum() << endl;
pack->loadDataBuffer((char*)"GREMLIN LOL");
}
cout << "Seq. num: " << pack->getSequenceNum() << endl;
cout << "Checksum: " << pack->getCheckSum() << endl;
//cout << "Message: " << pack->getDataBuffer() << endl;
return packStatus;
}<commit_msg>Change testing 2<commit_after>#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/time.h>
#include <string.h>
#include <iostream>
#include <fstream>
#include <boost/lexical_cast.hpp>
#include "packet.h"
#define USAGE "Usage:\r\nc \r\n[tux machine number] \r\n[probability of packet corruption in int form] \r\n[probability of packet loss in int form] \r\n[probability of packet delay] \r\n[length of delay in ms] \r\n"
#define PORT 10038
#define PAKSIZE 512
#define ACK 0
#define NAK 1
#define BUFSIZE 505
#define FILENAME "Testfile"
#define TIMEOUT 100 //in ms
#define WIN_SIZE 16
using namespace std;
bool isvpack(unsigned char * p);
bool init(int argc, char** argv);
bool loadFile();
bool getFile();
bool sendFile();
bool isAck();
void handleAck();
void handleNak(int& x);
bool* gremlin(Packet * pack, int corruptProb, int lossProb, int delayProb);
Packet createPacket(int index);
void loadWindow();
bool sendPacket();
bool getGet();
struct sockaddr_in a;
struct sockaddr_in ca;
socklen_t calen;
int rlen;
int s;
bool ack;
string fstr;
char * file;
int probCorrupt;
int probLoss;
int probDelay;
int delayT;
Packet p;
Packet window[16];
int length;
bool dropPck;
bool delayPck;
int toms;
unsigned char b[BUFSIZE];
int base;
int main(int argc, char** argv) {
if(!init(argc, argv)) return -1;
sendFile();
return 0;
}
bool init(int argc, char** argv){
if(argc != 6) {
cout << USAGE << endl;
return false;
}
char * probCorruptStr = argv[2];
probCorrupt = boost::lexical_cast<int>(probCorruptStr);
char * probLossStr = argv[3];
probLoss = boost::lexical_cast<int>(probLossStr);
char * probDelayStr = argv[4];
probDelay = boost::lexical_cast<int>(probDelayStr);
char* delayTStr = argv[5];
delayT = boost::lexical_cast<int>(delayTStr);
struct timeval timeout;
timeout.tv_usec = TIMEOUT * 1000;
toms = TIMEOUT;
/* Create our socket. */
if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
cout << "Socket creation failed. (socket s)" << endl;
return 0;
}
setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout, sizeof(timeout));
/*
* Bind our socket to an IP (whatever the computer decides)
* and a specified port.
*
*/
if (!loadFile()) {
cout << "Loading file failed. (filename FILENAME)" << endl;
return false;
}
memset((char *)&a, 0, sizeof(a));
a.sin_family = AF_INET;
a.sin_addr.s_addr = htonl(INADDR_ANY);
a.sin_port = htons(PORT);
if (bind(s, (struct sockaddr *)&a, sizeof(a)) < 0) {
cout << "Socket binding failed. (socket s, address a)" << endl;
return 0;
}
fstr = string(file);
cout << "File: " << endl << fstr << endl;
base = 0;
dropPck = false;
calen = sizeof(ca);
getGet();
return true;
}
bool getGet(){
unsigned char packet[PAKSIZE + 1];
rlen = recvfrom(s, packet, PAKSIZE, 0, (struct sockaddr *)&ca, &calen);
return (rlen > 0) ? true : false;
}
bool isvpack(unsigned char * p) {
cout << endl << "=== IS VALID PACKET TESTING" << endl;
char * sns = new char[2];
memcpy(sns, &p[0], 1);
sns[1] = '\0';
char * css = new char[7];
memcpy(css, &p[1], 6);
css[6] = '\0';
char * db = new char[121 + 1];
memcpy(db, &p[2], 121);
db[121] = '\0';
cout << "Seq. num: " << sns << endl;
cout << "Checksum: " << css << endl;
cout << "Message: " << db << endl;
int sn = boost::lexical_cast<int>(sns);
int cs = boost::lexical_cast<int>(css);
Packet pk (0, db);
pk.setSequenceNum(sn);
// change to validate based on checksum and sequence number
if(sn == 0) return false; //doesn't matter, only for the old version (netwark)
if(cs != pk.generateCheckSum()) return false;
return true;
}
bool getFile(){
/* Loop forever, waiting for messages from a client. */
cout << "Waiting on port " << PORT << "..." << endl;
ofstream file("Dumpfile");
for (;;) {
unsigned char packet[PAKSIZE + 1];
unsigned char dataPull[PAKSIZE - 7 + 1];
rlen = recvfrom(s, packet, PAKSIZE, 0, (struct sockaddr *)&ca, &calen);
for(int x = 0; x < PAKSIZE - 7; x++) {
dataPull[x] = packet[x + 7];
}
dataPull[PAKSIZE - 7] = '\0';
packet[PAKSIZE] = '\0';
if (rlen > 0) {
char * css = new char[6];
memcpy(css, &packet[1], 5);
css[5] = '\0';
cout << endl << endl << "=== RECEIPT" << endl;
cout << "Seq. num: " << packet[0] << endl;
cout << "Checksum: " << css << endl;
cout << "Received message: " << dataPull << endl;
cout << "Sent response: ";
if(isvpack(packet)) {
ack = ACK;
//seqNum = (seqNum) ? false : true;
file << dataPull;
} else {
ack = NAK;
}
cout << ((ack == ACK) ? "ACK" : "NAK") << endl;
Packet p (false, reinterpret_cast<const char *>(dataPull));
p.setCheckSum(boost::lexical_cast<int>(css));
p.setAckNack(ack);
if(sendto(s, p.str(), PAKSIZE, 0, (struct sockaddr *)&ca, calen) < 0) {
cout << "Acknowledgement failed. (socket s, acknowledgement message ack, client address ca, client address length calen)" << endl;
return 0;
}
delete css;
}
}
file.close();
return true;
}
bool loadFile() {
ifstream is (FILENAME, ifstream::binary);
if(is) {
is.seekg(0, is.end);
length = is.tellg();
is.seekg(0, is.beg);
file = new char[length];
cout << "Reading " << length << " characters..." << endl;
is.read(file, length);
if(!is) { cout << "File reading failed. (filename " << FILENAME << "). Only " << is.gcount() << " could be read."; return false; }
is.close();
}
return true;
}
void loadWindow(){
for(int i = base; i < base + WIN_SIZE; i++) {
window[i-base] = createPacket(i);
if(strlen(window[i-base].getDataBuffer()) < BUFSIZE - 1 && window[i-base].getDataBuffer()[0] != 'G') {
for(++i; i < base + WIN_SIZE; i++){
window[i-base].loadDataBuffer("\0");
}
return;
}
cout << "window[i-base] seq. num: " << window[i-base].getSequenceNum() << endl;
}
}
bool sendFile() {
/*Currently causes the program to only send the first 16 packets of file out
requires additional code later to sendFile again with updated window*/
base = 0;
while(base * BUFSIZE < length) {
loadWindow();
cout << "packet " << base + 1 << ": " << window[1].str() << endl;
for(int x = 0; x < WIN_SIZE; x++) {
p = window[x];
if(!sendPacket()) continue;
}
if(p.str()[0] == '\0') break;
for(int x = 0; x < WIN_SIZE; x++) {
if(recvfrom(s, b, BUFSIZE + 7, 0, (struct sockaddr *)&ca, &calen) < 0) {
cout << "=== ACK TIMEOUT" << endl;
x--;
continue;
}
if(isAck()) {
handleAck();
} else {
handleAck();
//handleNak(x);
}
memset(b, 0, BUFSIZE);
}
}
if(sendto(s, "\0", BUFSIZE, 0, (struct sockaddr *)&ca, sizeof(ca)) < 0) {
cout << "Final package sending failed. (socket s, server address sa, message m)" << endl;
return false;
}
return true;
}
Packet createPacket(int index){
string mstr = fstr.substr(index * BUFSIZE, BUFSIZE);
if(mstr.length() < BUFSIZE) {
cout << "Null terminated mstr." << endl;
mstr[length - (index * BUFSIZE)] = '\0';
}
cout << "index: " << index << endl;
return Packet (index, mstr.c_str());
}
bool sendPacket(){
cout << endl;
cout << "=== TRANSMISSION START" << endl;
cout << "Sequence number before gremlin function: " << p.getSequenceNum() << endl;
int pc = probCorrupt; int pl = probLoss; int pd = probDelay;
bool* pckStatus = gremlin(&p, pc, pl, pd);
dropPck = pckStatus[0];
delayPck = pckStatus[1];
if (dropPck == true) return false;
if (delayPck == true) p.setAckNack(1);
if(sendto(s, p.str(), BUFSIZE + 8, 0, (struct sockaddr *)&ca, sizeof(ca)) < 0) {
cout << "Package sending failed. (socket s, server address sa, message m)" << endl;
return false;
}
return true;
}
bool isAck() {
cout << endl << "=== SERVER RESPONSE TEST" << endl;
cout << "Data: " << b << endl;
if(b[6] == '0') return true;
else return false;
}
void handleAck() {
int ack = boost::lexical_cast<int>(b);
if(base < ack) base = ack;
cout << "Window base: " << base << endl;
}
void handleNak(int& x) {
char * sns = new char[2];
memcpy(sns, &b[0], 1);
sns[1] = '\0';
char * css = new char[5];
memcpy(css, &b[1], 5);
char * db = new char[BUFSIZE + 1];
memcpy(db, &b[2], BUFSIZE);
db[BUFSIZE] = '\0';
cout << "Sequence number: " << sns << endl;
cout << "Checksum: " << css << endl;
Packet pk (0, db);
pk.setSequenceNum(boost::lexical_cast<int>(sns));
pk.setCheckSum(boost::lexical_cast<int>(css));
if(!pk.chksm()) x--;
else x = (x - 2 > 0) ? x - 2 : 0;
}
bool* gremlin(Packet * pack, int corruptProb, int lossProb, int delayProb){
bool* packStatus = new bool[2];
int r = rand() % 100;
cout << "Corruption probability: " << corruptProb << endl;
cout << "Random number: " << r << endl;
packStatus[0] = false;
packStatus[1] = false;
if(r <= (lossProb)){
packStatus[0] = true;
cout << "Dropped!" << endl;
}
else if(r <= (delayProb)){
packStatus[1] = true;
cout << "Delayed!" << endl;
}
else if(r <= (corruptProb)){
cout << "Corrupted!" << endl;
cout << "Seq. num (pre-gremlin): " << pack->getSequenceNum() << endl;
pack->loadDataBuffer((char*)"GREMLIN LOL");
}
cout << "Seq. num: " << pack->getSequenceNum() << endl;
cout << "Checksum: " << pack->getCheckSum() << endl;
//cout << "Message: " << pack->getDataBuffer() << endl;
return packStatus;
}<|endoftext|>
|
<commit_before>/* Copyright 2015-2018 Egor Yusov
*
* 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
*
* 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 OF ANY PROPRIETARY RIGHTS.
*
* In no event and under no legal theory, whether in tort (including negligence),
* contract, or otherwise, unless required by applicable law (such as deliberate
* and grossly negligent acts) or agreed to in writing, shall any Contributor be
* liable for any damages, including any direct, indirect, special, incidental,
* or consequential damages of any character arising as a result of this License or
* out of the use or inability to use the software (including but not limited to damages
* for loss of goodwill, work stoppage, computer failure or malfunction, or any and
* all other commercial damages or losses), even if such Contributor has been advised
* of the possibility of such damages.
*/
#include "pch.h"
#include "GLContextWindows.h"
#include "DeviceCaps.h"
#include "GLTypeConversions.h"
#include "EngineGLAttribs.h"
namespace Diligent
{
void APIENTRY openglCallbackFunction( GLenum source,
GLenum type,
GLuint id,
GLenum severity,
GLsizei length,
const GLchar* message,
const void* userParam )
{
// We are trying to disable flood of notifications through glDebugMessageControl(), but it has no effect,
// so we have to filter them out here
if (type == GL_DEBUG_TYPE_OTHER && severity == GL_DEBUG_SEVERITY_NOTIFICATION)
return;
std::stringstream MessageSS;
MessageSS << "OpenGL debug message (";
switch( type )
{
case GL_DEBUG_TYPE_ERROR:
MessageSS << "ERROR";
break;
case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR:
MessageSS << "DEPRECATED_BEHAVIOR";
break;
case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR:
MessageSS << "UNDEFINED_BEHAVIOR";
break;
case GL_DEBUG_TYPE_PORTABILITY:
MessageSS << "PORTABILITY";
break;
case GL_DEBUG_TYPE_PERFORMANCE:
MessageSS << "PERFORMANCE";
break;
case GL_DEBUG_TYPE_OTHER:
MessageSS << "OTHER";
break;
}
switch( severity )
{
case GL_DEBUG_SEVERITY_LOW:
MessageSS << ", low severity";
break;
case GL_DEBUG_SEVERITY_MEDIUM:
MessageSS << ", medium severity";
break;
case GL_DEBUG_SEVERITY_HIGH:
MessageSS << ", HIGH severity";
break;
case GL_DEBUG_SEVERITY_NOTIFICATION:
MessageSS << ", notification";
break;
}
MessageSS << ")" << std::endl << message << std::endl;
LOG_INFO_MESSAGE( MessageSS.str().c_str() );
}
GLContext::GLContext(const EngineGLAttribs &InitAttribs, DeviceCaps &DeviceCaps ) :
m_Context(0),
m_WindowHandleToDeviceContext(0)
{
Int32 MajorVersion = 0, MinorVersion = 0;
if(InitAttribs.pNativeWndHandle != nullptr)
{
HWND hWnd = reinterpret_cast<HWND>(InitAttribs.pNativeWndHandle);
// See http://www.opengl.org/wiki/Tutorial:_OpenGL_3.1_The_First_Triangle_(C%2B%2B/Win)
// http://www.opengl.org/wiki/Creating_an_OpenGL_Context_(WGL)
PIXELFORMATDESCRIPTOR pfd;
memset( &pfd, 0, sizeof( PIXELFORMATDESCRIPTOR ) );
pfd.nSize = sizeof( PIXELFORMATDESCRIPTOR );
pfd.nVersion = 1;
pfd.dwFlags = PFD_DOUBLEBUFFER | PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW;
pfd.iPixelType = PFD_TYPE_RGBA;
pfd.cColorBits = 32;
pfd.cDepthBits = 32;
pfd.iLayerType = PFD_MAIN_PLANE;
m_WindowHandleToDeviceContext = GetDC( hWnd );
int nPixelFormat = ChoosePixelFormat( m_WindowHandleToDeviceContext, &pfd );
if( nPixelFormat == 0 )
LOG_ERROR_AND_THROW( "Invalid Pixel Format" );
BOOL bResult = SetPixelFormat( m_WindowHandleToDeviceContext, nPixelFormat, &pfd );
if( !bResult )
LOG_ERROR_AND_THROW( "Failed to set Pixel Format" );
// Create standard OpenGL (2.1) rendering context which will be used only temporarily,
HGLRC tempContext = wglCreateContext( m_WindowHandleToDeviceContext );
// and make it current
wglMakeCurrent( m_WindowHandleToDeviceContext, tempContext );
// Initialize GLEW
GLenum err = glewInit();
if( GLEW_OK != err )
LOG_ERROR_AND_THROW( "Failed to initialize GLEW" );
if( wglewIsSupported( "WGL_ARB_create_context" ) == 1 )
{
MajorVersion = 4;
MinorVersion = 4;
// Setup attributes for a new OpenGL rendering context
int attribs[] =
{
WGL_CONTEXT_MAJOR_VERSION_ARB, MajorVersion,
WGL_CONTEXT_MINOR_VERSION_ARB, MinorVersion,
WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB,
GL_CONTEXT_PROFILE_MASK, GL_CONTEXT_CORE_PROFILE_BIT,
0, 0
};
#ifdef _DEBUG
attribs[5] |= WGL_CONTEXT_DEBUG_BIT_ARB;
#endif
// Create new rendering context
// In order to create new OpenGL rendering context we have to call function wglCreateContextAttribsARB(),
// which is an OpenGL function and requires OpenGL to be active when it is called.
// The only way is to create an old context, activate it, and while it is active create a new one.
// Very inconsistent, but we have to live with it!
m_Context = wglCreateContextAttribsARB( m_WindowHandleToDeviceContext, 0, attribs );
// Delete tempContext
wglMakeCurrent( NULL, NULL );
wglDeleteContext( tempContext );
// Make new context current
wglMakeCurrent( m_WindowHandleToDeviceContext, m_Context );
wglSwapIntervalEXT( 0 );
}
else
{ //It's not possible to make a GL 4.x context. Use the old style context (GL 2.1 and before)
m_Context = tempContext;
}
if( glDebugMessageCallback )
{
glEnable( GL_DEBUG_OUTPUT_SYNCHRONOUS );
glDebugMessageCallback( openglCallbackFunction, nullptr );
GLuint unusedIds = 0;
glDebugMessageControl(
GL_DONT_CARE, // Source of debug messages to enable or disable
GL_DONT_CARE, // Type of debug messages to enable or disable
GL_DONT_CARE, // Severity of debug messages to enable or disable
0, // The length of the array ids
&unusedIds, // Array of unsigned integers contianing the ids of the messages to enable or disable
GL_TRUE // Flag determining whether the selected messages should be enabled or disabled
);
if( glGetError() != GL_NO_ERROR )
LOG_ERROR_MESSAGE("Failed to enable debug messages");
// Disable notifications as they flood the output
// Note: quite commonly for OpenGL, this call does not work as described and has no effect.
// Even disabling all messages does not disable them
glDebugMessageControl(
GL_DONT_CARE, // Source of debug messages to enable or disable
GL_DEBUG_TYPE_OTHER, // Type of debug messages to enable or disable
GL_DEBUG_SEVERITY_NOTIFICATION, // Severity of debug messages to enable or disable
0, // The length of the array ids
&unusedIds, // Array of unsigned integers contianing the ids of the messages to enable or disable
GL_FALSE // Flag determining whether the selected messages should be enabled or disabled
);
if( glGetError() != GL_NO_ERROR )
LOG_ERROR_MESSAGE("Failed to disable debug notification messages");
}
}
else
{
auto CurrentCtx = wglGetCurrentContext();
if (CurrentCtx == 0)
{
LOG_ERROR_AND_THROW("No current GL context found! Provide non-null handle to a native Window to create a GL context");
}
// Initialize GLEW
GLenum err = glewInit();
if( GLEW_OK != err )
LOG_ERROR_AND_THROW( "Failed to initialize GLEW" );
}
//Checking GL version
const GLubyte *GLVersionString = glGetString( GL_VERSION );
//Or better yet, use the GL3 way to get the version number
glGetIntegerv( GL_MAJOR_VERSION, &MajorVersion );
glGetIntegerv( GL_MINOR_VERSION, &MinorVersion );
LOG_INFO_MESSAGE(InitAttribs.pNativeWndHandle != nullptr ? "Initialized OpenGL " : "Attached to OpenGL ", MajorVersion, '.', MinorVersion, " context (", GLVersionString, ')');
// Under the standard filtering rules for cubemaps, filtering does not work across faces of the cubemap.
// This results in a seam across the faces of a cubemap. This was a hardware limitation in the past, but
// modern hardware is capable of interpolating across a cube face boundary.
// GL_TEXTURE_CUBE_MAP_SEAMLESS is not defined in OpenGLES
glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS);
if( glGetError() != GL_NO_ERROR )
LOG_ERROR_MESSAGE("Failed to enable seamless cubemap filtering");
// When GL_FRAMEBUFFER_SRGB is enabled, and if the destination image is in the sRGB colorspace
// then OpenGL will assume the shader's output is in the linear RGB colorspace. It will therefore
// convert the output from linear RGB to sRGB.
// Any writes to images that are not in the sRGB format should not be affected.
// Thus this setting should be just set once and left that way
glEnable(GL_FRAMEBUFFER_SRGB);
if( glGetError() != GL_NO_ERROR )
LOG_ERROR_MESSAGE("Failed to enable SRGB framebuffers");
DeviceCaps.DevType = DeviceType::OpenGL;
DeviceCaps.MajorVersion = MajorVersion;
DeviceCaps.MinorVersion = MinorVersion;
bool IsGL43OrAbove = MajorVersion >= 5 || MajorVersion == 4 && MinorVersion >= 3;
auto &TexCaps = DeviceCaps.TexCaps;
TexCaps.bTexture2DMSSupported = IsGL43OrAbove;
TexCaps.bTexture2DMSArraySupported = IsGL43OrAbove;
TexCaps.bTextureViewSupported = IsGL43OrAbove;
TexCaps.bCubemapArraysSupported = IsGL43OrAbove;
DeviceCaps.bMultithreadedResourceCreationSupported = False;
}
GLContext::~GLContext()
{
// Do not destroy context if it was created by the app.
if( m_Context )
{
wglMakeCurrent( m_WindowHandleToDeviceContext, 0 );
wglDeleteContext( m_Context );
}
}
void GLContext::SwapBuffers()
{
if (m_WindowHandleToDeviceContext)
::SwapBuffers(m_WindowHandleToDeviceContext);
else
LOG_ERROR("Swap buffer failed because window handle to device context is not initialized");
}
GLContext::NativeGLContextType GLContext::GetCurrentNativeGLContext()
{
return wglGetCurrentContext();
}
}
<commit_msg>Updated OpenGL debug message output<commit_after>/* Copyright 2015-2018 Egor Yusov
*
* 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
*
* 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 OF ANY PROPRIETARY RIGHTS.
*
* In no event and under no legal theory, whether in tort (including negligence),
* contract, or otherwise, unless required by applicable law (such as deliberate
* and grossly negligent acts) or agreed to in writing, shall any Contributor be
* liable for any damages, including any direct, indirect, special, incidental,
* or consequential damages of any character arising as a result of this License or
* out of the use or inability to use the software (including but not limited to damages
* for loss of goodwill, work stoppage, computer failure or malfunction, or any and
* all other commercial damages or losses), even if such Contributor has been advised
* of the possibility of such damages.
*/
#include "pch.h"
#include "GLContextWindows.h"
#include "DeviceCaps.h"
#include "GLTypeConversions.h"
#include "EngineGLAttribs.h"
namespace Diligent
{
void APIENTRY openglCallbackFunction( GLenum source,
GLenum type,
GLuint id,
GLenum severity,
GLsizei length,
const GLchar* message,
const void* userParam )
{
// Note: disabling flood of notifications through glDebugMessageControl() has no effect,
// so we have to filter them out here
if (id == 131185 || // Buffer detailed info: Buffer object <X> (bound to GL_XXXX ... , usage hint is GL_DYNAMIC_DRAW)
// will use VIDEO memory as the source for buffer object operations.
id == 131186 // Buffer object <X> (bound to GL_XXXX, usage hint is GL_DYNAMIC_DRAW) is being copied/moved from VIDEO memory to HOST memory.
)
return;
std::stringstream MessageSS;
MessageSS << "OpenGL debug message " << id << " (";
switch (source)
{
case GL_DEBUG_SOURCE_API: MessageSS << "Source: API."; break;
case GL_DEBUG_SOURCE_WINDOW_SYSTEM: MessageSS << "Source: Window System."; break;
case GL_DEBUG_SOURCE_SHADER_COMPILER: MessageSS << "Source: Shader Compiler."; break;
case GL_DEBUG_SOURCE_THIRD_PARTY: MessageSS << "Source: Third Party."; break;
case GL_DEBUG_SOURCE_APPLICATION: MessageSS << "Source: Application."; break;
case GL_DEBUG_SOURCE_OTHER: MessageSS << "Source: Other."; break;
default: MessageSS << "Source: Unknown (" << source << ").";
}
switch (type)
{
case GL_DEBUG_TYPE_ERROR: MessageSS << " Type: ERROR."; break;
case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR: MessageSS << " Type: Deprecated Behaviour."; break;
case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR: MessageSS << " Type: UNDEFINED BEHAVIOUR."; break;
case GL_DEBUG_TYPE_PORTABILITY: MessageSS << " Type: Portability."; break;
case GL_DEBUG_TYPE_PERFORMANCE: MessageSS << " Type: PERFORMANCE."; break;
case GL_DEBUG_TYPE_MARKER: MessageSS << " Type: Marker."; break;
case GL_DEBUG_TYPE_PUSH_GROUP: MessageSS << " Type: Push Group."; break;
case GL_DEBUG_TYPE_POP_GROUP: MessageSS << " Type: Pop Group."; break;
case GL_DEBUG_TYPE_OTHER: MessageSS << " Type: Other."; break;
default: MessageSS << " Type: Unknown (" << type << ").";
}
switch (severity)
{
case GL_DEBUG_SEVERITY_HIGH: MessageSS << " Severity: HIGH"; break;
case GL_DEBUG_SEVERITY_MEDIUM: MessageSS << " Severity: Medium"; break;
case GL_DEBUG_SEVERITY_LOW: MessageSS << " Severity: Low"; break;
case GL_DEBUG_SEVERITY_NOTIFICATION: MessageSS << " Severity: Notification"; break;
default: MessageSS << " Severity: Unknown (" << severity << ")"; break;
}
MessageSS << "): " << message;
LOG_INFO_MESSAGE( MessageSS.str().c_str() );
}
GLContext::GLContext(const EngineGLAttribs &InitAttribs, DeviceCaps &DeviceCaps ) :
m_Context(0),
m_WindowHandleToDeviceContext(0)
{
Int32 MajorVersion = 0, MinorVersion = 0;
if(InitAttribs.pNativeWndHandle != nullptr)
{
HWND hWnd = reinterpret_cast<HWND>(InitAttribs.pNativeWndHandle);
// See http://www.opengl.org/wiki/Tutorial:_OpenGL_3.1_The_First_Triangle_(C%2B%2B/Win)
// http://www.opengl.org/wiki/Creating_an_OpenGL_Context_(WGL)
PIXELFORMATDESCRIPTOR pfd;
memset( &pfd, 0, sizeof( PIXELFORMATDESCRIPTOR ) );
pfd.nSize = sizeof( PIXELFORMATDESCRIPTOR );
pfd.nVersion = 1;
pfd.dwFlags = PFD_DOUBLEBUFFER | PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW;
pfd.iPixelType = PFD_TYPE_RGBA;
pfd.cColorBits = 32;
pfd.cDepthBits = 32;
pfd.iLayerType = PFD_MAIN_PLANE;
m_WindowHandleToDeviceContext = GetDC( hWnd );
int nPixelFormat = ChoosePixelFormat( m_WindowHandleToDeviceContext, &pfd );
if( nPixelFormat == 0 )
LOG_ERROR_AND_THROW( "Invalid Pixel Format" );
BOOL bResult = SetPixelFormat( m_WindowHandleToDeviceContext, nPixelFormat, &pfd );
if( !bResult )
LOG_ERROR_AND_THROW( "Failed to set Pixel Format" );
// Create standard OpenGL (2.1) rendering context which will be used only temporarily,
HGLRC tempContext = wglCreateContext( m_WindowHandleToDeviceContext );
// and make it current
wglMakeCurrent( m_WindowHandleToDeviceContext, tempContext );
// Initialize GLEW
GLenum err = glewInit();
if( GLEW_OK != err )
LOG_ERROR_AND_THROW( "Failed to initialize GLEW" );
if( wglewIsSupported( "WGL_ARB_create_context" ) == 1 )
{
MajorVersion = 4;
MinorVersion = 4;
// Setup attributes for a new OpenGL rendering context
int attribs[] =
{
WGL_CONTEXT_MAJOR_VERSION_ARB, MajorVersion,
WGL_CONTEXT_MINOR_VERSION_ARB, MinorVersion,
WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB,
GL_CONTEXT_PROFILE_MASK, GL_CONTEXT_CORE_PROFILE_BIT,
0, 0
};
#ifdef _DEBUG
attribs[5] |= WGL_CONTEXT_DEBUG_BIT_ARB;
#endif
// Create new rendering context
// In order to create new OpenGL rendering context we have to call function wglCreateContextAttribsARB(),
// which is an OpenGL function and requires OpenGL to be active when it is called.
// The only way is to create an old context, activate it, and while it is active create a new one.
// Very inconsistent, but we have to live with it!
m_Context = wglCreateContextAttribsARB( m_WindowHandleToDeviceContext, 0, attribs );
// Delete tempContext
wglMakeCurrent( NULL, NULL );
wglDeleteContext( tempContext );
// Make new context current
wglMakeCurrent( m_WindowHandleToDeviceContext, m_Context );
wglSwapIntervalEXT( 0 );
}
else
{ //It's not possible to make a GL 4.x context. Use the old style context (GL 2.1 and before)
m_Context = tempContext;
}
if( glDebugMessageCallback )
{
glEnable( GL_DEBUG_OUTPUT_SYNCHRONOUS );
glDebugMessageCallback( openglCallbackFunction, nullptr );
GLuint unusedIds = 0;
glDebugMessageControl(
GL_DONT_CARE, // Source of debug messages to enable or disable
GL_DONT_CARE, // Type of debug messages to enable or disable
GL_DONT_CARE, // Severity of debug messages to enable or disable
0, // The length of the array ids
&unusedIds, // Array of unsigned integers contianing the ids of the messages to enable or disable
GL_TRUE // Flag determining whether the selected messages should be enabled or disabled
);
if( glGetError() != GL_NO_ERROR )
LOG_ERROR_MESSAGE("Failed to enable debug messages");
}
}
else
{
auto CurrentCtx = wglGetCurrentContext();
if (CurrentCtx == 0)
{
LOG_ERROR_AND_THROW("No current GL context found! Provide non-null handle to a native Window to create a GL context");
}
// Initialize GLEW
GLenum err = glewInit();
if( GLEW_OK != err )
LOG_ERROR_AND_THROW( "Failed to initialize GLEW" );
}
//Checking GL version
const GLubyte *GLVersionString = glGetString( GL_VERSION );
//Or better yet, use the GL3 way to get the version number
glGetIntegerv( GL_MAJOR_VERSION, &MajorVersion );
glGetIntegerv( GL_MINOR_VERSION, &MinorVersion );
LOG_INFO_MESSAGE(InitAttribs.pNativeWndHandle != nullptr ? "Initialized OpenGL " : "Attached to OpenGL ", MajorVersion, '.', MinorVersion, " context (", GLVersionString, ')');
// Under the standard filtering rules for cubemaps, filtering does not work across faces of the cubemap.
// This results in a seam across the faces of a cubemap. This was a hardware limitation in the past, but
// modern hardware is capable of interpolating across a cube face boundary.
// GL_TEXTURE_CUBE_MAP_SEAMLESS is not defined in OpenGLES
glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS);
if( glGetError() != GL_NO_ERROR )
LOG_ERROR_MESSAGE("Failed to enable seamless cubemap filtering");
// When GL_FRAMEBUFFER_SRGB is enabled, and if the destination image is in the sRGB colorspace
// then OpenGL will assume the shader's output is in the linear RGB colorspace. It will therefore
// convert the output from linear RGB to sRGB.
// Any writes to images that are not in the sRGB format should not be affected.
// Thus this setting should be just set once and left that way
glEnable(GL_FRAMEBUFFER_SRGB);
if( glGetError() != GL_NO_ERROR )
LOG_ERROR_MESSAGE("Failed to enable SRGB framebuffers");
DeviceCaps.DevType = DeviceType::OpenGL;
DeviceCaps.MajorVersion = MajorVersion;
DeviceCaps.MinorVersion = MinorVersion;
bool IsGL43OrAbove = MajorVersion >= 5 || MajorVersion == 4 && MinorVersion >= 3;
auto &TexCaps = DeviceCaps.TexCaps;
TexCaps.bTexture2DMSSupported = IsGL43OrAbove;
TexCaps.bTexture2DMSArraySupported = IsGL43OrAbove;
TexCaps.bTextureViewSupported = IsGL43OrAbove;
TexCaps.bCubemapArraysSupported = IsGL43OrAbove;
DeviceCaps.bMultithreadedResourceCreationSupported = False;
}
GLContext::~GLContext()
{
// Do not destroy context if it was created by the app.
if( m_Context )
{
wglMakeCurrent( m_WindowHandleToDeviceContext, 0 );
wglDeleteContext( m_Context );
}
}
void GLContext::SwapBuffers()
{
if (m_WindowHandleToDeviceContext)
::SwapBuffers(m_WindowHandleToDeviceContext);
else
LOG_ERROR("Swap buffer failed because window handle to device context is not initialized");
}
GLContext::NativeGLContextType GLContext::GetCurrentNativeGLContext()
{
return wglGetCurrentContext();
}
}
<|endoftext|>
|
<commit_before>#include <Beacon.h>
#include <sys/time.h>
#include "HCIDumpParser.h"
// Uncomment to publish the raw byte[] for the beacon, otherwise, properties are sent
//#define SEND_BINARY_DATA
static int64_t currentMilliseconds() {
timeval now;
gettimeofday(&now, nullptr);
int64_t nowMS = now.tv_sec;
nowMS *= 1000;
nowMS += now.tv_usec/1000;
return nowMS;
}
void HCIDumpParser::processHCI(HCIDumpCommand& parseCommand) {
HCIDumpParser::parseCommand = &parseCommand;
string clientID(parseCommand.getClientID());
if(clientID.empty())
clientID = parseCommand.getScannerID();
publisher = MsgPublisher::create(parseCommand.getPubType(), parseCommand.getBrokerURL(), clientID, "", "");
if(parseCommand.isAnalyzeMode()) {
begin = currentMilliseconds();
end += parseCommand.getAnalyzeWindow();
printf("Running in analyze mode, window=%d seconds\n", parseCommand.getAnalyzeWindow());
}
else if(!parseCommand.isSkipPublish()) {
publisher->setUseTopics(!parseCommand.isUseQueues());
publisher->setDestinationName(parseCommand.getDestinationName());
if(batchCount > 0) {
publisher->setUseTransactions(true);
printf("Enabled transactions\n");
}
publisher->start(parseCommand.isAsyncMode());
}
else {
printf("Skipping publish of parsed beacons\n");
}
char cdev = parseCommand.getHciDev().at(parseCommand.getHciDev().size()-1);
int device = cdev - '0';
scan_frames(device, beacon_event_callback);
}
void HCIDumpParser::beaconEvent(const beacon_info *info) {
Beacon beacon(parseCommand->getScannerID(), info->uuid, info->code, info->manufacturer, info->major, info->minor,
info->power, info->calibrated_power, info->rssi, info->time);
vector<byte> msg = beacon.toByteMsg();
// Check for heartbeat
bool isHeartbeat = scannerUUID.compare(info->uuid) == 0;
if(isHeartbeat)
beacon.setMessageType(BeconEventType::SCANNER_HEARTBEAT);
if(parseCommand->isAnalyzeMode()) {
updateBeaconCounts(info);
}
else if(!parseCommand->isSkipPublish()) {
if(batchCount > 0) {
// Overwrite last event if it is a heartbeat and this is as well
if(isHeartbeat && events.size() > 0 && events.back().getMessageType() == BeconEventType::SCANNER_HEARTBEAT)
events.pop_back();
events.push_back(beacon);
if(shouldSendMessages()) {
#ifdef PRINT_DEBUG
printf("Sending msg batch, size=%d\n", events.size());
#endif
publisher->publish(events);
events.clear();
} else {
#ifdef PRINT_DEBUG
printf("Batched msg, size=%d\n", events.size());
#endif
}
} else if(isHeartbeat) {
#ifdef PRINT_DEBUG
printf("Sending heartbeat, %s\n", !parseCommand->isSkipHeartbeat());
#endif
if(!parseCommand->isSkipHeartbeat())
publisher->publishStatus(beacon);
} else {
#ifdef PRINT_DEBUG
printf("Sending msg\n");
#endif
#ifdef SEND_BINARY_DATA
publisher->publish("", MqttQOS::AT_MOST_ONCE, msg.data(), msg.size());
#else
publisher->publish("", beacon);
#endif
}
}
else {
const char *info = isHeartbeat ? "heartbeat" : "event";
if(!isHeartbeat || (isHeartbeat && !parseCommand->isSkipHeartbeat()))
printf("Parsed(%s): %s\n", info, beacon.toString().c_str());
}
}
void HCIDumpParser::cleanup() {
if(publisher != nullptr)
publisher->stop();
publisher = nullptr;
}
void HCIDumpParser::updateBeaconCounts(beacon_info const *info) {
#ifdef PRINT_DEBUG
printf("updateBeaconCounts(begin=%lld, end=%lld, info.time=%lld\n", begin, end, info->time);
#endif
if(info->time < end) {
// Update the beacon event counts
beaconCounts[info->minor] ++;
} else {
char timestr[256];
struct timeval tv;
tv.tv_sec = begin/1000;
tv.tv_usec = 0;
struct tm tm;
localtime_r(&tv.tv_sec, &tm);
strftime(timestr, 128, "%r", &tm);
// Report the stats for this time window and then reset
printf("+++ Beacon counts for window(%d): %s\n", parseCommand->getAnalyzeWindow(), timestr);
for(map<int32_t, int32_t>::iterator iter = beaconCounts.begin(); iter != beaconCounts.end(); iter++) {
printf("\t%2d: %2d", iter->first, iter->second);
}
begin = end;
end += 1000*parseCommand->getAnalyzeWindow();
beaconCounts.clear();
}
}
<commit_msg>fix int format in print statement<commit_after>#include <Beacon.h>
#include <sys/time.h>
#include "HCIDumpParser.h"
// Uncomment to publish the raw byte[] for the beacon, otherwise, properties are sent
//#define SEND_BINARY_DATA
static int64_t currentMilliseconds() {
timeval now;
gettimeofday(&now, nullptr);
int64_t nowMS = now.tv_sec;
nowMS *= 1000;
nowMS += now.tv_usec/1000;
return nowMS;
}
void HCIDumpParser::processHCI(HCIDumpCommand& parseCommand) {
HCIDumpParser::parseCommand = &parseCommand;
string clientID(parseCommand.getClientID());
if(clientID.empty())
clientID = parseCommand.getScannerID();
publisher = MsgPublisher::create(parseCommand.getPubType(), parseCommand.getBrokerURL(), clientID, "", "");
if(parseCommand.isAnalyzeMode()) {
begin = currentMilliseconds();
end += parseCommand.getAnalyzeWindow();
printf("Running in analyze mode, window=%d seconds\n", parseCommand.getAnalyzeWindow());
}
else if(!parseCommand.isSkipPublish()) {
publisher->setUseTopics(!parseCommand.isUseQueues());
publisher->setDestinationName(parseCommand.getDestinationName());
if(batchCount > 0) {
publisher->setUseTransactions(true);
printf("Enabled transactions\n");
}
publisher->start(parseCommand.isAsyncMode());
}
else {
printf("Skipping publish of parsed beacons\n");
}
char cdev = parseCommand.getHciDev().at(parseCommand.getHciDev().size()-1);
int device = cdev - '0';
scan_frames(device, beacon_event_callback);
}
void HCIDumpParser::beaconEvent(const beacon_info *info) {
Beacon beacon(parseCommand->getScannerID(), info->uuid, info->code, info->manufacturer, info->major, info->minor,
info->power, info->calibrated_power, info->rssi, info->time);
vector<byte> msg = beacon.toByteMsg();
// Check for heartbeat
bool isHeartbeat = scannerUUID.compare(info->uuid) == 0;
if(isHeartbeat)
beacon.setMessageType(BeconEventType::SCANNER_HEARTBEAT);
if(parseCommand->isAnalyzeMode()) {
updateBeaconCounts(info);
}
else if(!parseCommand->isSkipPublish()) {
if(batchCount > 0) {
// Overwrite last event if it is a heartbeat and this is as well
if(isHeartbeat && events.size() > 0 && events.back().getMessageType() == BeconEventType::SCANNER_HEARTBEAT)
events.pop_back();
events.push_back(beacon);
if(shouldSendMessages()) {
#ifdef PRINT_DEBUG
printf("Sending msg batch, size=%d\n", events.size());
#endif
publisher->publish(events);
events.clear();
} else {
#ifdef PRINT_DEBUG
printf("Batched msg, size=%d\n", events.size());
#endif
}
} else if(isHeartbeat) {
#ifdef PRINT_DEBUG
printf("Sending heartbeat, %s\n", !parseCommand->isSkipHeartbeat());
#endif
if(!parseCommand->isSkipHeartbeat())
publisher->publishStatus(beacon);
} else {
#ifdef PRINT_DEBUG
printf("Sending msg\n");
#endif
#ifdef SEND_BINARY_DATA
publisher->publish("", MqttQOS::AT_MOST_ONCE, msg.data(), msg.size());
#else
publisher->publish("", beacon);
#endif
}
}
else {
const char *info = isHeartbeat ? "heartbeat" : "event";
if(!isHeartbeat || (isHeartbeat && !parseCommand->isSkipHeartbeat()))
printf("Parsed(%s): %s\n", info, beacon.toString().c_str());
}
}
void HCIDumpParser::cleanup() {
if(publisher != nullptr)
publisher->stop();
publisher = nullptr;
}
void HCIDumpParser::updateBeaconCounts(beacon_info const *info) {
#ifdef PRINT_DEBUG
printf("updateBeaconCounts(%d); begin=%lld, end=%lld, info.time=%lld\n", beaconCounts.size(), begin, end, info->time);
#endif
if(info->time < end) {
// Update the beacon event counts
beaconCounts[info->minor] ++;
} else {
char timestr[256];
struct timeval tv;
tv.tv_sec = begin/1000;
tv.tv_usec = 0;
struct tm tm;
localtime_r(&tv.tv_sec, &tm);
strftime(timestr, 128, "%r", &tm);
// Report the stats for this time window and then reset
printf("+++ Beacon counts for window(%d): %s\n", parseCommand->getAnalyzeWindow(), timestr);
for(map<int32_t, int32_t>::iterator iter = beaconCounts.begin(); iter != beaconCounts.end(); iter++) {
printf("\t%2d: %2d", iter->first, iter->second);
}
begin = end;
end += 1000*parseCommand->getAnalyzeWindow();
beaconCounts.clear();
}
}
<|endoftext|>
|
<commit_before>/*******************************************************************************
*
* MIT License
*
* Copyright (c) 2019 Advanced Micro Devices, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*******************************************************************************/
#include "driver.hpp"
#include "dropout_util.hpp"
#include "get_handle.hpp"
#include "tensor_holder.hpp"
#include "test.hpp"
#include "verify.hpp"
#include "random.hpp"
#define DROPOUT_DEBUG_CTEST 0
#define DROPOUT_LARGE_CTEST 0
// OpenCL error creating buffer: 0 Invalid Buffer Size
#define WORKAROUND_MLOPEN_ISSUE_2335 \
((HIP_PACKAGE_VERSION_FLAT < 3007000000ULL) && MIOPEN_BACKEND_OPENCL)
template <class T>
struct verify_forward_dropout
{
tensor<T> input;
tensor<T> output;
std::vector<unsigned char> rsvsp;
miopen::DropoutDescriptor DropoutDesc;
miopen::TensorDescriptor noise_shape;
size_t in_offset;
size_t out_offset;
size_t rsvsp_offset;
bool use_rsvsp;
typename std::vector<unsigned char>::iterator rsvsp_ptr;
verify_forward_dropout(const miopen::DropoutDescriptor& pDropoutDesc,
const miopen::TensorDescriptor& pNoiseShape,
const tensor<T>& pinput,
const tensor<T>& poutput,
std::vector<unsigned char>& prsvsp,
size_t pin_offset,
size_t pout_offset,
size_t prsvsp_offset,
bool puse_rsvsp = true)
{
DropoutDesc = pDropoutDesc;
noise_shape = pNoiseShape;
input = pinput;
output = poutput;
rsvsp = prsvsp;
in_offset = pin_offset;
out_offset = pout_offset;
rsvsp_offset = prsvsp_offset;
use_rsvsp = puse_rsvsp;
rsvsp_ptr = prsvsp.begin();
}
tensor<T> cpu() const
{
auto states_cpu = std::vector<prngStates>(DropoutDesc.stateSizeInBytes);
InitKernelStateEmulator(states_cpu, DropoutDesc);
auto out_cpu = output;
auto rsvsp_cpu = rsvsp;
DropoutForwardVerify<T>(get_handle(),
DropoutDesc,
input.desc,
input.data,
out_cpu.desc,
out_cpu.data,
rsvsp_cpu,
states_cpu,
in_offset,
out_offset,
rsvsp_offset);
return out_cpu;
}
tensor<T> gpu() const
{
auto&& handle = get_handle();
auto out_gpu = output;
auto rsvsp_dev = handle.Write(rsvsp);
auto in_dev = handle.Write(input.data);
auto out_dev = handle.Write(output.data);
DropoutDesc.DropoutForward(handle,
input.desc,
input.desc,
in_dev.get(),
output.desc,
out_dev.get(),
use_rsvsp ? rsvsp_dev.get() : nullptr,
rsvsp.size(),
in_offset,
out_offset,
rsvsp_offset);
out_gpu.data = handle.Read<T>(out_dev, output.data.size());
auto rsvsp_gpu = handle.Read<unsigned char>(rsvsp_dev, rsvsp.size());
std::copy(rsvsp_gpu.begin(), rsvsp_gpu.end(), rsvsp_ptr);
return out_gpu;
}
void fail(int badtensor) const
{
std::cout << "Forward Dropout: " << std::endl;
std::cout << "Input tensor: " << input.desc.ToString() << std::endl;
switch(badtensor)
{
case(0): std::cout << "Output tensor failed verification." << std::endl; break;
case(1): std::cout << "Reservespace failed verification." << std::endl; break;
default: break;
}
}
};
template <class T>
struct verify_backward_dropout
{
tensor<T> din;
tensor<T> dout;
std::vector<unsigned char> rsvsp;
miopen::DropoutDescriptor DropoutDesc;
size_t in_offset;
size_t out_offset;
size_t rsvsp_offset;
bool use_rsvsp;
verify_backward_dropout(const miopen::DropoutDescriptor& pDropoutDesc,
const tensor<T>& pdin,
const tensor<T>& pdout,
const std::vector<unsigned char>& prsvsp,
size_t pin_offset,
size_t pout_offset,
size_t prsvsp_offset,
bool puse_rsvsp = true)
{
DropoutDesc = pDropoutDesc;
din = pdin;
dout = pdout;
rsvsp = prsvsp;
in_offset = pin_offset;
out_offset = pout_offset;
rsvsp_offset = prsvsp_offset;
use_rsvsp = puse_rsvsp;
}
tensor<T> cpu() const
{
auto din_cpu = din;
auto rsvsp_cpu = rsvsp;
DropoutBackwardVerify<T>(DropoutDesc,
dout.desc,
dout.data,
din_cpu.desc,
din_cpu.data,
rsvsp_cpu,
in_offset,
out_offset,
rsvsp_offset);
return din_cpu;
}
tensor<T> gpu() const
{
auto&& handle = get_handle();
auto din_gpu = din;
auto din_dev = handle.Write(din.data);
auto dout_dev = handle.Write(dout.data);
auto rsvsp_dev = handle.Write(rsvsp);
DropoutDesc.DropoutBackward(handle,
din.desc,
dout.desc,
dout_dev.get(),
din.desc,
din_dev.get(),
use_rsvsp ? rsvsp_dev.get() : nullptr,
rsvsp.size(),
in_offset,
out_offset,
rsvsp_offset);
din_gpu.data = handle.Read<T>(din_dev, din.data.size());
return din_gpu;
}
void fail(int = 0) const
{
std::cout << "Backward Dropout: " << std::endl;
std::cout << "Doutput tensor: " << dout.desc.ToString() << std::endl;
}
};
template <class T>
struct dropout_driver : test_driver
{
std::vector<std::vector<int>> input_dims;
float dropout_rate{};
unsigned long long seed{};
bool mask{};
std::vector<int> in_dim{};
int rng_mode_cmd = 0;
dropout_driver()
{
input_dims = get_sub_tensor();
std::set<std::vector<int>> get_inputs_set = get_inputs(1);
std::set<std::vector<int>> get_3d_conv_input_shapes_set = get_3d_conv_input_shapes(1);
#if DROPOUT_LARGE_CTEST
input_dims.insert(input_dims.end(), get_inputs_set.begin(), get_inputs_set.end());
input_dims.insert(input_dims.end(),
get_3d_conv_input_shapes_set.begin(),
get_3d_conv_input_shapes_set.end());
#else
auto itr = get_inputs_set.begin();
for(std::size_t i = 0; i < get_inputs_set.size(); itr++, i++)
if(i % 6 == 0)
input_dims.push_back(*itr);
itr = get_3d_conv_input_shapes_set.begin();
for(std::size_t i = 0; i < get_3d_conv_input_shapes_set.size(); itr++, i++)
if(i % 3 == 0)
input_dims.push_back(*itr);
#endif
add(in_dim, "input-dim", generate_data(input_dims));
add(dropout_rate, "dropout", generate_data({float(0.0), float(0.5), float(1.0)}));
add(seed, "seed", generate_data({0x0ULL, 0xFFFFFFFFFFFFFFFFULL}));
add(mask, "use-mask", generate_data({false, true}));
add(rng_mode_cmd, "rng-mode", generate_data({0}));
}
void run()
{
// Workaround for issue #2335.
// OpenCL error creating buffer: 0 Invalid Buffer Size
#if WORKAROUND_MLOPEN_ISSUE_2335
std::cout << "Skip test for Issue #2335: " << std::endl;
return;
#endif
miopen::DropoutDescriptor DropoutDesc;
unsigned long max_value = miopen_type<T>{} == miopenHalf ? 5 : 17;
auto&& handle = get_handle();
auto in = tensor<T>{in_dim}.generate(tensor_elem_gen_integer{max_value});
miopenRNGType_t rng_mode = miopenRNGType_t(rng_mode_cmd);
size_t stateSizeInBytes =
std::min(size_t(MAX_PRNG_STATE), handle.GetImage3dMaxWidth()) * sizeof(prngStates);
size_t reserveSpaceSizeInBytes = in.desc.GetElementSize() * sizeof(bool);
size_t total_mem =
2 * (2 * in.desc.GetNumBytes() + reserveSpaceSizeInBytes) + stateSizeInBytes;
size_t device_mem = handle.GetGlobalMemorySize();
#if !DROPOUT_DEBUG_CTEST
if(total_mem >= device_mem)
{
#endif
show_command();
std::cout << "Config requires " << total_mem
<< " Bytes to write all necessary tensors to GPU. GPU has " << device_mem
<< " Bytes of memory." << std::endl;
#if !DROPOUT_DEBUG_CTEST
}
#else
std::cout << "Input tensor requires " << in.desc.GetElementSize() << " Bytes of memory."
<< std::endl;
std::cout << "Output tensor requires " << in.desc.GetElementSize() << " Bytes of memory."
<< std::endl;
std::cout << "reserveSpace requires " << reserveSpaceSizeInBytes << " Bytes of memory."
<< std::endl;
std::cout << "PRNG state space requires " << stateSizeInBytes << " Bytes of memory."
<< std::endl;
#endif
if(total_mem >= device_mem)
{
return;
}
auto reserveSpace = std::vector<unsigned char>(in.desc.GetElementSize());
if(mask)
{
srand(0);
for(size_t i = 0; i < in.desc.GetElementSize(); i++)
reserveSpace[i] =
static_cast<unsigned char>(float(GET_RAND()) / float(RAND_MAX) > dropout_rate);
}
DropoutDesc.dropout = dropout_rate;
DropoutDesc.stateSizeInBytes = stateSizeInBytes;
DropoutDesc.seed = seed;
DropoutDesc.use_mask = mask;
DropoutDesc.rng_mode = rng_mode;
auto state_buf = handle.Create<unsigned char>(stateSizeInBytes);
DropoutDesc.pstates = state_buf.get();
DropoutDesc.InitPRNGState(
handle, DropoutDesc.pstates, DropoutDesc.stateSizeInBytes, DropoutDesc.seed);
#if DROPOUT_DEBUG_CTEST
std::cout <<
#if MIOPEN_BACKEND_OPENCL
"Use OpenCL backend."
#elif MIOPEN_BACKEND_HIP
"Use HIP backend."
#endif
<< std::endl;
#endif
auto out = tensor<T>{in_dim};
verify(verify_forward_dropout<T>{DropoutDesc, in.desc, in, out, reserveSpace, 0, 0, 0});
auto dout = tensor<T>{in_dim}.generate(tensor_elem_gen_integer{max_value});
auto din = tensor<T>{in_dim};
verify(verify_backward_dropout<T>{DropoutDesc, din, dout, reserveSpace, 0, 0, 0});
if(!mask)
{
verify(verify_forward_dropout<T>{
DropoutDesc, in.desc, in, out, reserveSpace, 0, 0, 0, false});
verify(
verify_backward_dropout<T>{DropoutDesc, din, dout, reserveSpace, 0, 0, 0, false});
}
}
};
int main(int argc, const char* argv[]) { test_drive<dropout_driver>(argc, argv); }
<commit_msg>[CI][Test] Fix #1128: reduce number of cases in test_dropout (#1129)<commit_after>/*******************************************************************************
*
* MIT License
*
* Copyright (c) 2019 Advanced Micro Devices, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*******************************************************************************/
#include "driver.hpp"
#include "dropout_util.hpp"
#include "get_handle.hpp"
#include "tensor_holder.hpp"
#include "test.hpp"
#include "verify.hpp"
#include "random.hpp"
#define DROPOUT_DEBUG_CTEST 0
// Workaround for issue #1128
#define DROPOUT_SINGLE_CTEST 1
// OpenCL error creating buffer: 0 Invalid Buffer Size
#define WORKAROUND_MLOPEN_ISSUE_2335 \
((HIP_PACKAGE_VERSION_FLAT < 3007000000ULL) && MIOPEN_BACKEND_OPENCL)
template <class T>
struct verify_forward_dropout
{
tensor<T> input;
tensor<T> output;
std::vector<unsigned char> rsvsp;
miopen::DropoutDescriptor DropoutDesc;
miopen::TensorDescriptor noise_shape;
size_t in_offset;
size_t out_offset;
size_t rsvsp_offset;
bool use_rsvsp;
typename std::vector<unsigned char>::iterator rsvsp_ptr;
verify_forward_dropout(const miopen::DropoutDescriptor& pDropoutDesc,
const miopen::TensorDescriptor& pNoiseShape,
const tensor<T>& pinput,
const tensor<T>& poutput,
std::vector<unsigned char>& prsvsp,
size_t pin_offset,
size_t pout_offset,
size_t prsvsp_offset,
bool puse_rsvsp = true)
{
DropoutDesc = pDropoutDesc;
noise_shape = pNoiseShape;
input = pinput;
output = poutput;
rsvsp = prsvsp;
in_offset = pin_offset;
out_offset = pout_offset;
rsvsp_offset = prsvsp_offset;
use_rsvsp = puse_rsvsp;
rsvsp_ptr = prsvsp.begin();
}
tensor<T> cpu() const
{
auto states_cpu = std::vector<prngStates>(DropoutDesc.stateSizeInBytes);
InitKernelStateEmulator(states_cpu, DropoutDesc);
auto out_cpu = output;
auto rsvsp_cpu = rsvsp;
DropoutForwardVerify<T>(get_handle(),
DropoutDesc,
input.desc,
input.data,
out_cpu.desc,
out_cpu.data,
rsvsp_cpu,
states_cpu,
in_offset,
out_offset,
rsvsp_offset);
return out_cpu;
}
tensor<T> gpu() const
{
auto&& handle = get_handle();
auto out_gpu = output;
auto rsvsp_dev = handle.Write(rsvsp);
auto in_dev = handle.Write(input.data);
auto out_dev = handle.Write(output.data);
DropoutDesc.DropoutForward(handle,
input.desc,
input.desc,
in_dev.get(),
output.desc,
out_dev.get(),
use_rsvsp ? rsvsp_dev.get() : nullptr,
rsvsp.size(),
in_offset,
out_offset,
rsvsp_offset);
out_gpu.data = handle.Read<T>(out_dev, output.data.size());
auto rsvsp_gpu = handle.Read<unsigned char>(rsvsp_dev, rsvsp.size());
std::copy(rsvsp_gpu.begin(), rsvsp_gpu.end(), rsvsp_ptr);
return out_gpu;
}
void fail(int badtensor) const
{
std::cout << "Forward Dropout: " << std::endl;
std::cout << "Input tensor: " << input.desc.ToString() << std::endl;
switch(badtensor)
{
case(0): std::cout << "Output tensor failed verification." << std::endl; break;
case(1): std::cout << "Reservespace failed verification." << std::endl; break;
default: break;
}
}
};
template <class T>
struct verify_backward_dropout
{
tensor<T> din;
tensor<T> dout;
std::vector<unsigned char> rsvsp;
miopen::DropoutDescriptor DropoutDesc;
size_t in_offset;
size_t out_offset;
size_t rsvsp_offset;
bool use_rsvsp;
verify_backward_dropout(const miopen::DropoutDescriptor& pDropoutDesc,
const tensor<T>& pdin,
const tensor<T>& pdout,
const std::vector<unsigned char>& prsvsp,
size_t pin_offset,
size_t pout_offset,
size_t prsvsp_offset,
bool puse_rsvsp = true)
{
DropoutDesc = pDropoutDesc;
din = pdin;
dout = pdout;
rsvsp = prsvsp;
in_offset = pin_offset;
out_offset = pout_offset;
rsvsp_offset = prsvsp_offset;
use_rsvsp = puse_rsvsp;
}
tensor<T> cpu() const
{
auto din_cpu = din;
auto rsvsp_cpu = rsvsp;
DropoutBackwardVerify<T>(DropoutDesc,
dout.desc,
dout.data,
din_cpu.desc,
din_cpu.data,
rsvsp_cpu,
in_offset,
out_offset,
rsvsp_offset);
return din_cpu;
}
tensor<T> gpu() const
{
auto&& handle = get_handle();
auto din_gpu = din;
auto din_dev = handle.Write(din.data);
auto dout_dev = handle.Write(dout.data);
auto rsvsp_dev = handle.Write(rsvsp);
DropoutDesc.DropoutBackward(handle,
din.desc,
dout.desc,
dout_dev.get(),
din.desc,
din_dev.get(),
use_rsvsp ? rsvsp_dev.get() : nullptr,
rsvsp.size(),
in_offset,
out_offset,
rsvsp_offset);
din_gpu.data = handle.Read<T>(din_dev, din.data.size());
return din_gpu;
}
void fail(int = 0) const
{
std::cout << "Backward Dropout: " << std::endl;
std::cout << "Doutput tensor: " << dout.desc.ToString() << std::endl;
}
};
template <class T>
struct dropout_driver : test_driver
{
std::vector<std::vector<int>> input_dims;
float dropout_rate{};
unsigned long long seed{};
bool mask{};
std::vector<int> in_dim{};
int rng_mode_cmd = 0;
dropout_driver()
{
input_dims = get_sub_tensor();
std::set<std::vector<int>> get_inputs_set = get_inputs(1);
std::set<std::vector<int>> get_3d_conv_input_shapes_set = get_3d_conv_input_shapes(1);
// Workaround for issue #1128
#if DROPOUT_SINGLE_CTEST
input_dims.resize(1);
add(in_dim, "input-dim", generate_data(input_dims));
add(dropout_rate, "dropout", generate_data({float(0.5)}));
add(seed, "seed", generate_data({0x0ULL}));
add(mask, "use-mask", generate_data({false}));
add(rng_mode_cmd, "rng-mode", generate_data({0}));
#else
#define DROPOUT_LARGE_CTEST 0
#if DROPOUT_LARGE_CTEST
input_dims.insert(input_dims.end(), get_inputs_set.begin(), get_inputs_set.end());
input_dims.insert(input_dims.end(),
get_3d_conv_input_shapes_set.begin(),
get_3d_conv_input_shapes_set.end());
#else
auto itr = get_inputs_set.begin();
for(std::size_t i = 0; i < get_inputs_set.size(); itr++, i++)
if(i % 6 == 0)
input_dims.push_back(*itr);
itr = get_3d_conv_input_shapes_set.begin();
for(std::size_t i = 0; i < get_3d_conv_input_shapes_set.size(); itr++, i++)
if(i % 3 == 0)
input_dims.push_back(*itr);
#endif
add(in_dim, "input-dim", generate_data(input_dims));
add(dropout_rate, "dropout", generate_data({float(0.0), float(0.5), float(1.0)}));
add(seed, "seed", generate_data({0x0ULL, 0xFFFFFFFFFFFFFFFFULL}));
add(mask, "use-mask", generate_data({false, true}));
add(rng_mode_cmd, "rng-mode", generate_data({0}));
#endif
}
void run()
{
// Workaround for issue #2335.
// OpenCL error creating buffer: 0 Invalid Buffer Size
#if WORKAROUND_MLOPEN_ISSUE_2335
std::cout << "Skip test for Issue #2335: " << std::endl;
return;
#endif
miopen::DropoutDescriptor DropoutDesc;
unsigned long max_value = miopen_type<T>{} == miopenHalf ? 5 : 17;
auto&& handle = get_handle();
auto in = tensor<T>{in_dim}.generate(tensor_elem_gen_integer{max_value});
miopenRNGType_t rng_mode = miopenRNGType_t(rng_mode_cmd);
size_t stateSizeInBytes =
std::min(size_t(MAX_PRNG_STATE), handle.GetImage3dMaxWidth()) * sizeof(prngStates);
size_t reserveSpaceSizeInBytes = in.desc.GetElementSize() * sizeof(bool);
size_t total_mem =
2 * (2 * in.desc.GetNumBytes() + reserveSpaceSizeInBytes) + stateSizeInBytes;
size_t device_mem = handle.GetGlobalMemorySize();
#if !DROPOUT_DEBUG_CTEST
if(total_mem >= device_mem)
{
#endif
show_command();
std::cout << "Config requires " << total_mem
<< " Bytes to write all necessary tensors to GPU. GPU has " << device_mem
<< " Bytes of memory." << std::endl;
#if !DROPOUT_DEBUG_CTEST
}
#else
std::cout << "Input tensor requires " << in.desc.GetElementSize() << " Bytes of memory."
<< std::endl;
std::cout << "Output tensor requires " << in.desc.GetElementSize() << " Bytes of memory."
<< std::endl;
std::cout << "reserveSpace requires " << reserveSpaceSizeInBytes << " Bytes of memory."
<< std::endl;
std::cout << "PRNG state space requires " << stateSizeInBytes << " Bytes of memory."
<< std::endl;
#endif
if(total_mem >= device_mem)
{
return;
}
auto reserveSpace = std::vector<unsigned char>(in.desc.GetElementSize());
if(mask)
{
srand(0);
for(size_t i = 0; i < in.desc.GetElementSize(); i++)
reserveSpace[i] =
static_cast<unsigned char>(float(GET_RAND()) / float(RAND_MAX) > dropout_rate);
}
DropoutDesc.dropout = dropout_rate;
DropoutDesc.stateSizeInBytes = stateSizeInBytes;
DropoutDesc.seed = seed;
DropoutDesc.use_mask = mask;
DropoutDesc.rng_mode = rng_mode;
auto state_buf = handle.Create<unsigned char>(stateSizeInBytes);
DropoutDesc.pstates = state_buf.get();
DropoutDesc.InitPRNGState(
handle, DropoutDesc.pstates, DropoutDesc.stateSizeInBytes, DropoutDesc.seed);
#if DROPOUT_DEBUG_CTEST
std::cout <<
#if MIOPEN_BACKEND_OPENCL
"Use OpenCL backend."
#elif MIOPEN_BACKEND_HIP
"Use HIP backend."
#endif
<< std::endl;
#endif
auto out = tensor<T>{in_dim};
verify(verify_forward_dropout<T>{DropoutDesc, in.desc, in, out, reserveSpace, 0, 0, 0});
auto dout = tensor<T>{in_dim}.generate(tensor_elem_gen_integer{max_value});
auto din = tensor<T>{in_dim};
verify(verify_backward_dropout<T>{DropoutDesc, din, dout, reserveSpace, 0, 0, 0});
if(!mask)
{
verify(verify_forward_dropout<T>{
DropoutDesc, in.desc, in, out, reserveSpace, 0, 0, 0, false});
verify(
verify_backward_dropout<T>{DropoutDesc, din, dout, reserveSpace, 0, 0, 0, false});
}
}
};
int main(int argc, const char* argv[]) { test_drive<dropout_driver>(argc, argv); }
<|endoftext|>
|
<commit_before>#include "gtest/gtest.h"
#include "tcframe/io.hpp"
#include <set>
#include <sstream>
#include <string>
#include <vector>
using std::ostringstream;
using std::set;
using std::string;
using std::vector;
using tcframe::IOFormat;
using tcframe::IOFormatException;
using tcframe::IOFormatsCollector;
using tcframe::IOMode;
using tcframe::GridIOSegment;
using tcframe::LineIOSegment;
using tcframe::LinesIOSegment;
TEST(LineIOSegmentTest, UnsupportedTypes) {
set<int> s;
LineIOSegment segment("s");
try {
segment, s;
FAIL();
} catch (IOFormatException& e) {
EXPECT_TRUE(string(e.getMessage()).find("is only supported") != string::npos);
}
}
TEST(LineIOSegmentTest, EmptyLinePrinting) {
LineIOSegment segment("");
ostringstream sout;
segment.printTo(sout);
EXPECT_EQ("\n", sout.str());
}
TEST(LineIOSegmentTest, SingleScalarPrinting) {
int X;
LineIOSegment segment("X");
segment, X;
X = 42;
ostringstream sout;
segment.printTo(sout);
EXPECT_EQ("42\n", sout.str());
}
TEST(LineIOSegmentTest, MultipleScalarsPrinting) {
int A, B, C;
LineIOSegment segment("A, B, C");
segment, A, B, C;
A = 42;
B = 7;
C = 123;
ostringstream sout;
segment.printTo(sout);
EXPECT_EQ("42 7 123\n", sout.str());
}
TEST(LineIOSegmentTest, SingleVectorPrinting) {
vector<int> V;
LineIOSegment segment("V");
segment, V;
V = vector<int>{1, 2, 3};
ostringstream sout;
segment.printTo(sout);
EXPECT_EQ("1 2 3\n", sout.str());
}
TEST(LineIOSegmentTest, MultipleVectorsPrinting) {
vector<int> V, W;
LineIOSegment segment("V, W");
segment, V, W;
V = vector<int>{1, 2, 3};
W = vector<int>{4, 5, 6};
ostringstream sout;
segment.printTo(sout);
EXPECT_EQ("1 2 3 4 5 6\n", sout.str());
}
TEST(LineIOSegmentTest, MixedVariablesPrinting) {
vector<int> V, W;
int A, B;
LineIOSegment segment("A, V, B, W");
segment, A, V, B, W;
V = vector<int>{1, 2, 3};
W = vector<int>{4, 5, 6, 7};
A = V.size();
B = W.size();
ostringstream sout;
segment.printTo(sout);
EXPECT_EQ("3 1 2 3 4 4 5 6 7\n", sout.str());
}
TEST(LinesIOSegmentTest, UnsupportedTypes) {
int X;
LinesIOSegment segment("X");
try {
segment, X;
FAIL();
} catch (IOFormatException& e) {
EXPECT_TRUE(string(e.getMessage()).find("is only supported for vector") != string::npos);
}
vector<vector<int>> V;
segment = LinesIOSegment("V");
try {
segment, V;
FAIL();
} catch (IOFormatException& e) {
EXPECT_TRUE(string(e.getMessage()).find("is only supported for vector of basic scalars") != string::npos);
}
}
TEST(LinesIOSegmentTest, IncompatibleVectorSizes) {
vector<int> V, W;
LinesIOSegment segment("V, W");
segment, V, W;
V = vector<int>{1, 2, 3};
W = vector<int>{4, 5, 6, 7};
ostringstream sout;
try {
segment.printTo(sout);
FAIL();
} catch (IOFormatException& e) {
EXPECT_TRUE(string(e.getMessage()).find("must have equal sizes") != string::npos);
}
}
TEST(LinesIOSegmentTest, NoVariables) {
LinesIOSegment segment("");
ostringstream sout;
try {
segment.printTo(sout);
FAIL();
} catch (IOFormatException& e) {
EXPECT_TRUE(string(e.getMessage()).find("must have at least one variable"));
}
}
TEST(LinesIOSegmentTest, SingleVectorPrinting) {
vector<int> V;
LinesIOSegment segment("V");
segment, V;
V = vector<int>{1, 2, 3};
ostringstream sout;
segment.printTo(sout);
EXPECT_EQ("1\n2\n3\n", sout.str());
}
TEST(LinesIOSegmentTest, MultipleVectorsPrinting) {
vector<int> V;
vector<string> W;
LinesIOSegment segment("V, W");
segment, V, W;
V = vector<int>{1, 2, 3};
W = vector<string>{"a", "bb", "ccc"};
ostringstream sout;
segment.printTo(sout);
EXPECT_EQ("1 a\n2 bb\n3 ccc\n", sout.str());
}
TEST(GridIOSegmentTest, UnsupportedTypes) {
int X;
GridIOSegment segment("X");
try {
segment, X;
FAIL();
} catch (IOFormatException& e) {
EXPECT_TRUE(string(e.getMessage()).find("is only supported for matrix") != string::npos);
}
vector<vector<vector<int>>> V;
segment = GridIOSegment("V");
try {
segment, V;
FAIL();
} catch (IOFormatException& e) {
EXPECT_TRUE(string(e.getMessage()).find("is only supported for matrix of basic scalars") != string::npos);
}
}
TEST(GridIOSegmentTest, IncompatibleDimensionSizes) {
vector<vector<int>> V;
GridIOSegment segment("V");
segment, V;
V = vector<vector<int>>{ {1, 2}, {3, 4, 5} };
ostringstream sout;
try {
segment.printTo(sout);
FAIL();
} catch (IOFormatException& e) {
EXPECT_TRUE(string(e.getMessage()).find("must have equal number of columns") != string::npos);
}
}
TEST(GridIOSegmentTest, NonSingularVariables) {
GridIOSegment segment("");
ostringstream sout;
try {
segment.printTo(sout);
FAIL();
} catch (IOFormatException& e) {
EXPECT_TRUE(string(e.getMessage()).find("must have exactly one variable") != string::npos);
}
vector<vector<int>> V, W;
segment = GridIOSegment("V, W");
try {
segment, V, W;
FAIL();
} catch (IOFormatException& e) {
EXPECT_TRUE(string(e.getMessage()).find("must have exactly one variable") != string::npos);
}
}
TEST(GridIOSegmentTest, CharPrinting) {
vector<vector<char>> C;
GridIOSegment segment("C");
segment, C;
C = vector<vector<char>>{ {'a', 'b'}, {'c', 'd'} };
ostringstream sout;
segment.printTo(sout);
EXPECT_EQ("ab\ncd\n", sout.str());
}
TEST(GridIOSegmentTest, NonCharPrinting) {
vector<vector<int>> C;
GridIOSegment segment("C");
segment, C;
C = vector<vector<int>>{ {1, 2}, {3, 4} };
ostringstream sout;
segment.printTo(sout);
EXPECT_EQ("1 2\n3 4\n", sout.str());
}
TEST(IOFormatTest, MultipleLinesPrinting) {
int A, B;
int K;
vector<int> V;
vector<int> W;
vector<string> Z;
vector<vector<char>> C;
vector<vector<int>> P;
IOFormat format;
format.addSegment(&((*(new LineIOSegment("A, B"))), A, B));
format.addSegment(&((*(new LineIOSegment("K"))), K));
format.addSegment(&((*(new LineIOSegment("V"))), V));
format.addSegment(&((*(new LinesIOSegment("W, Z"))), W, Z));
format.addSegment(&((*(new GridIOSegment("C"))), C));
format.addSegment(&((*(new GridIOSegment("P"))), P));
A = 1;
B = 2;
K = 77;
V = vector<int>{11, 22, 33};
W = vector<int>{10, 20};
Z = vector<string>{"x", "y"};
C = vector<vector<char>>{ {'a', 'b'}, {'c', 'd'} };
P = vector<vector<int>>{ {1, 2}, {3, 4} };
ostringstream sout;
format.printTo(sout);
EXPECT_EQ("1 2\n77\n11 22 33\n10 x\n20 y\nab\ncd\n1 2\n3 4\n", sout.str());
}
TEST(IOFormatsCollectorTest, InputFormatCollection) {
int A, B;
int K;
vector<int> V;
vector<int> W;
vector<string> Z;
vector<vector<char>> C;
vector<vector<int>> P;
IOFormatsCollector collector;
collector.addLineSegment("A, B"), A, B;
collector.addLineSegment("K"), K;
collector.addLineSegment("V"), V;
collector.addLinesSegment("W, Z"), W, Z;
collector.addGridSegment("C"), C;
collector.addGridSegment("P"), P;
A = 1;
B = 2;
K = 77;
V = vector<int>{11, 22, 33};
W = vector<int>{10, 20};
Z = vector<string>{"x", "y"};
C = vector<vector<char>>{ {'a', 'b'}, {'c', 'd'} };
P = vector<vector<int>>{ {1, 2}, {3, 4} };
IOFormat* format = collector.collectFormat(IOMode::INPUT);
ostringstream sout;
format->printTo(sout);
EXPECT_EQ("1 2\n77\n11 22 33\n10 x\n20 y\nab\ncd\n1 2\n3 4\n", sout.str());
}
<commit_msg>Simplify redundant io tests<commit_after>#include "gtest/gtest.h"
#include "tcframe/io.hpp"
#include <set>
#include <sstream>
#include <string>
#include <vector>
using std::ostringstream;
using std::set;
using std::string;
using std::vector;
using tcframe::IOFormat;
using tcframe::IOFormatException;
using tcframe::IOFormatsCollector;
using tcframe::IOMode;
using tcframe::GridIOSegment;
using tcframe::LineIOSegment;
using tcframe::LinesIOSegment;
TEST(LineIOSegmentTest, UnsupportedTypes) {
set<int> s;
LineIOSegment segment("s");
try {
segment, s;
FAIL();
} catch (IOFormatException& e) {
EXPECT_TRUE(string(e.getMessage()).find("is only supported") != string::npos);
}
}
TEST(LineIOSegmentTest, EmptyLinePrinting) {
LineIOSegment segment("");
ostringstream sout;
segment.printTo(sout);
EXPECT_EQ("\n", sout.str());
}
TEST(LineIOSegmentTest, SingleScalarPrinting) {
int X;
LineIOSegment segment("X");
segment, X;
X = 42;
ostringstream sout;
segment.printTo(sout);
EXPECT_EQ("42\n", sout.str());
}
TEST(LineIOSegmentTest, MultipleScalarsPrinting) {
int A, B, C;
LineIOSegment segment("A, B, C");
segment, A, B, C;
A = 42;
B = 7;
C = 123;
ostringstream sout;
segment.printTo(sout);
EXPECT_EQ("42 7 123\n", sout.str());
}
TEST(LineIOSegmentTest, SingleVectorPrinting) {
vector<int> V;
LineIOSegment segment("V");
segment, V;
V = vector<int>{1, 2, 3};
ostringstream sout;
segment.printTo(sout);
EXPECT_EQ("1 2 3\n", sout.str());
}
TEST(LineIOSegmentTest, MultipleVectorsPrinting) {
vector<int> V, W;
LineIOSegment segment("V, W");
segment, V, W;
V = vector<int>{1, 2, 3};
W = vector<int>{4, 5, 6};
ostringstream sout;
segment.printTo(sout);
EXPECT_EQ("1 2 3 4 5 6\n", sout.str());
}
TEST(LineIOSegmentTest, MixedVariablesPrinting) {
vector<int> V, W;
int A, B;
LineIOSegment segment("A, V, B, W");
segment, A, V, B, W;
V = vector<int>{1, 2, 3};
W = vector<int>{4, 5, 6, 7};
A = V.size();
B = W.size();
ostringstream sout;
segment.printTo(sout);
EXPECT_EQ("3 1 2 3 4 4 5 6 7\n", sout.str());
}
TEST(LinesIOSegmentTest, UnsupportedTypes) {
int X;
LinesIOSegment segment("X");
try {
segment, X;
FAIL();
} catch (IOFormatException& e) {
EXPECT_TRUE(string(e.getMessage()).find("is only supported for vector") != string::npos);
}
vector<vector<int>> V;
segment = LinesIOSegment("V");
try {
segment, V;
FAIL();
} catch (IOFormatException& e) {
EXPECT_TRUE(string(e.getMessage()).find("is only supported for vector of basic scalars") != string::npos);
}
}
TEST(LinesIOSegmentTest, IncompatibleVectorSizes) {
vector<int> V, W;
LinesIOSegment segment("V, W");
segment, V, W;
V = vector<int>{1, 2, 3};
W = vector<int>{4, 5, 6, 7};
ostringstream sout;
try {
segment.printTo(sout);
FAIL();
} catch (IOFormatException& e) {
EXPECT_TRUE(string(e.getMessage()).find("must have equal sizes") != string::npos);
}
}
TEST(LinesIOSegmentTest, NoVariables) {
LinesIOSegment segment("");
ostringstream sout;
try {
segment.printTo(sout);
FAIL();
} catch (IOFormatException& e) {
EXPECT_TRUE(string(e.getMessage()).find("must have at least one variable"));
}
}
TEST(LinesIOSegmentTest, SingleVectorPrinting) {
vector<int> V;
LinesIOSegment segment("V");
segment, V;
V = vector<int>{1, 2, 3};
ostringstream sout;
segment.printTo(sout);
EXPECT_EQ("1\n2\n3\n", sout.str());
}
TEST(LinesIOSegmentTest, MultipleVectorsPrinting) {
vector<int> V;
vector<string> W;
LinesIOSegment segment("V, W");
segment, V, W;
V = vector<int>{1, 2, 3};
W = vector<string>{"a", "bb", "ccc"};
ostringstream sout;
segment.printTo(sout);
EXPECT_EQ("1 a\n2 bb\n3 ccc\n", sout.str());
}
TEST(GridIOSegmentTest, UnsupportedTypes) {
int X;
GridIOSegment segment("X");
try {
segment, X;
FAIL();
} catch (IOFormatException& e) {
EXPECT_TRUE(string(e.getMessage()).find("is only supported for matrix") != string::npos);
}
vector<vector<vector<int>>> V;
segment = GridIOSegment("V");
try {
segment, V;
FAIL();
} catch (IOFormatException& e) {
EXPECT_TRUE(string(e.getMessage()).find("is only supported for matrix of basic scalars") != string::npos);
}
}
TEST(GridIOSegmentTest, IncompatibleDimensionSizes) {
vector<vector<int>> V;
GridIOSegment segment("V");
segment, V;
V = vector<vector<int>>{ {1, 2}, {3, 4, 5} };
ostringstream sout;
try {
segment.printTo(sout);
FAIL();
} catch (IOFormatException& e) {
EXPECT_TRUE(string(e.getMessage()).find("must have equal number of columns") != string::npos);
}
}
TEST(GridIOSegmentTest, NonSingularVariables) {
GridIOSegment segment("");
ostringstream sout;
try {
segment.printTo(sout);
FAIL();
} catch (IOFormatException& e) {
EXPECT_TRUE(string(e.getMessage()).find("must have exactly one variable") != string::npos);
}
vector<vector<int>> V, W;
segment = GridIOSegment("V, W");
try {
segment, V, W;
FAIL();
} catch (IOFormatException& e) {
EXPECT_TRUE(string(e.getMessage()).find("must have exactly one variable") != string::npos);
}
}
TEST(GridIOSegmentTest, CharPrinting) {
vector<vector<char>> C;
GridIOSegment segment("C");
segment, C;
C = vector<vector<char>>{ {'a', 'b'}, {'c', 'd'} };
ostringstream sout;
segment.printTo(sout);
EXPECT_EQ("ab\ncd\n", sout.str());
}
TEST(GridIOSegmentTest, NonCharPrinting) {
vector<vector<int>> C;
GridIOSegment segment("C");
segment, C;
C = vector<vector<int>>{ {1, 2}, {3, 4} };
ostringstream sout;
segment.printTo(sout);
EXPECT_EQ("1 2\n3 4\n", sout.str());
}
TEST(IOFormatTest, MultipleLinesPrinting) {
int A, B;
int K;
IOFormat format;
LineIOSegment segment1("A, B");
segment1, A, B;
LineIOSegment segment2("K");
segment2, K;
format.addSegment(&segment1);
format.addSegment(&segment2);
A = 1;
B = 2;
K = 77;
ostringstream sout;
format.printTo(sout);
EXPECT_EQ("1 2\n77\n", sout.str());
}
TEST(IOFormatsCollectorTest, InputFormatCollection) {
int A, B;
int K;
IOFormatsCollector collector;
collector.addLineSegment("A, B"), A, B;
collector.addLineSegment("K"), K;
A = 1;
B = 2;
K = 77;
IOFormat* format = collector.collectFormat(IOMode::INPUT);
ostringstream sout;
format->printTo(sout);
EXPECT_EQ("1 2\n77\n", sout.str());
}
<|endoftext|>
|
<commit_before>//----------------------------------------------------------------------------
// Copyright(c) 2015-2020, Robert Kimball
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//----------------------------------------------------------------------------
#include <iostream>
#include "PacketIO.hpp"
#include "gtest/gtest.h"
void RxData(uint8_t* data, size_t length)
{
std::cout << "Rx " << length << std::endl;
}
TEST(DISABLED_network, raw_socket)
{
#ifdef _WIN32
NetworkConfig& config = *(NetworkConfig*)param;
char device[256];
PacketIO::GetDevice(config.interfaceNumber, device, sizeof(device));
printf("using device %s\n", device);
// PacketIO::GetMACAddress( device, Config.MACAddress );
PIO = new PacketIO(device);
ProtocolMACEthernet::Initialize(PIO);
StartEvent.Notify();
// This method does not return...ever
PIO->Start(packet_handler);
#elif __linux__
PacketIO* PIO = new PacketIO();
PIO->Start(RxData);
#endif
}
<commit_msg>disable test<commit_after>//----------------------------------------------------------------------------
// Copyright(c) 2015-2020, Robert Kimball
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//----------------------------------------------------------------------------
#include <iostream>
#include "PacketIO.hpp"
#include "gtest/gtest.h"
// void RxData(uint8_t* data, size_t length)
// {
// std::cout << "Rx " << length << std::endl;
// }
// TEST(DISABLED_network, raw_socket)
// {
// #ifdef _WIN32
// NetworkConfig& config = *(NetworkConfig*)param;
// char device[256];
// PacketIO::GetDevice(config.interfaceNumber, device, sizeof(device));
// printf("using device %s\n", device);
// // PacketIO::GetMACAddress( device, Config.MACAddress );
// PIO = new PacketIO(device);
// ProtocolMACEthernet::Initialize(PIO);
// StartEvent.Notify();
// // This method does not return...ever
// PIO->Start(packet_handler);
// #elif __linux__
// PacketIO* PIO = new PacketIO();
// PIO->Start(RxData);
// #endif
// }
<|endoftext|>
|
<commit_before>/* -------------------------------------------------------------------------- *
* OpenSim: buildDeviceModel.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): Chris Dembia, Shrinidhi K. Lakshmikanth, Ajay Seth, *
* Thomas Uchida *
* *
* 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. *
* -------------------------------------------------------------------------- */
/* Build an OpenSim model of a device for assisting our hopping mechanism. The
device consists of two bodies ("cuffA" and "cuffB") connected by a PathActuator
("cableAtoB") that can wrap around the hopper's patella (similar to the vastus
muscle in the hopper). The actuator receives its control signal from a
PropMyoController. Each cuff is attached to the "child" frame of a WeldJoint;
the "parent" frames of these joints will be connected to PhysicalFrames on the
hopper or testbed.
Several lines of code need to be added to this file; see exampleHopperDevice.cpp
and the "TODO" comments below for instructions. */
#include <OpenSim/OpenSim.h>
#include "defineDeviceAndController.h"
#include "helperMethods.h"
static const double OPTIMAL_FORCE{ 4000. };
static const double GAIN{ 1.0 };
namespace OpenSim {
// [Step 2, Task C]
Device* buildDevice() {
using SimTK::Vec3;
using SimTK::Inertia;
// Create the device.
auto device = new Device();
device->setName("device");
// The device's mass is distributed between two identical cuffs that attach
// to the hopper via WeldJoints (to be added below).
double deviceMass = 2.0;
auto cuffA = new Body("cuffA", deviceMass/2., Vec3(0), Inertia(0.5));
//TODO: Repeat for cuffB.
//TODO: Add the cuff Components to the device.
// Attach a sphere to each cuff for visualization.
auto sphere = new Sphere(0.01);
sphere->setName("sphere");
sphere->setColor(SimTK::Red);
cuffA->attachGeometry(sphere);
//cuffB->attachGeometry(sphere->clone());
// Create a WeldJoint to anchor cuffA to the hopper.
auto anchorA = new WeldJoint();
anchorA->setName("anchorA");
//TODO: Connect the "child_frame" (a PhysicalFrame) Socket of anchorA to
// cuffA. Note that only the child frame is connected now; the parent
// frame will be connected in exampleHopperDevice.cpp.
//TODO: Add anchorA to the device.
//TODO: Create a WeldJoint to anchor cuffB to the hopper. Connect the
// "child_frame" Socket of anchorB to cuffB and add anchorB to the
// device.
// Attach a PathActuator between the two cuffs.
auto pathActuator = new PathActuator();
pathActuator->setName("cableAtoB");
pathActuator->set_optimal_force(OPTIMAL_FORCE);
pathActuator->addNewPathPoint("pointA", *cuffA, Vec3(0));
//pathActuator->addNewPathPoint("pointB", *cuffB, Vec3(0));
device->addComponent(pathActuator);
// Create a PropMyoController.
auto controller = new PropMyoController();
controller->setName("controller");
controller->set_gain(GAIN);
//TODO: Connect the controller's "actuator" Socket to pathActuator.
//TODO: Add the controller to the device.
return device;
}
} // end of namespace OpenSim
<commit_msg>removed #include "helperMethods.h"<commit_after>/* -------------------------------------------------------------------------- *
* OpenSim: buildDeviceModel.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): Chris Dembia, Shrinidhi K. Lakshmikanth, Ajay Seth, *
* Thomas Uchida *
* *
* 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. *
* -------------------------------------------------------------------------- */
/* Build an OpenSim model of a device for assisting our hopping mechanism. The
device consists of two bodies ("cuffA" and "cuffB") connected by a PathActuator
("cableAtoB") that can wrap around the hopper's patella (similar to the vastus
muscle in the hopper). The actuator receives its control signal from a
PropMyoController. Each cuff is attached to the "child" frame of a WeldJoint;
the "parent" frames of these joints will be connected to PhysicalFrames on the
hopper or testbed.
Several lines of code need to be added to this file; see exampleHopperDevice.cpp
and the "TODO" comments below for instructions. */
#include <OpenSim/OpenSim.h>
#include "defineDeviceAndController.h"
static const double OPTIMAL_FORCE{ 4000. };
static const double GAIN{ 1.0 };
namespace OpenSim {
// [Step 2, Task C]
Device* buildDevice() {
using SimTK::Vec3;
using SimTK::Inertia;
// Create the device.
auto device = new Device();
device->setName("device");
// The device's mass is distributed between two identical cuffs that attach
// to the hopper via WeldJoints (to be added below).
double deviceMass = 2.0;
auto cuffA = new Body("cuffA", deviceMass/2., Vec3(0), Inertia(0.5));
//TODO: Repeat for cuffB.
//TODO: Add the cuff Components to the device.
// Attach a sphere to each cuff for visualization.
auto sphere = new Sphere(0.01);
sphere->setName("sphere");
sphere->setColor(SimTK::Red);
cuffA->attachGeometry(sphere);
//cuffB->attachGeometry(sphere->clone());
// Create a WeldJoint to anchor cuffA to the hopper.
auto anchorA = new WeldJoint();
anchorA->setName("anchorA");
//TODO: Connect the "child_frame" (a PhysicalFrame) Socket of anchorA to
// cuffA. Note that only the child frame is connected now; the parent
// frame will be connected in exampleHopperDevice.cpp.
//TODO: Add anchorA to the device.
//TODO: Create a WeldJoint to anchor cuffB to the hopper. Connect the
// "child_frame" Socket of anchorB to cuffB and add anchorB to the
// device.
// Attach a PathActuator between the two cuffs.
auto pathActuator = new PathActuator();
pathActuator->setName("cableAtoB");
pathActuator->set_optimal_force(OPTIMAL_FORCE);
pathActuator->addNewPathPoint("pointA", *cuffA, Vec3(0));
//pathActuator->addNewPathPoint("pointB", *cuffB, Vec3(0));
device->addComponent(pathActuator);
// Create a PropMyoController.
auto controller = new PropMyoController();
controller->setName("controller");
controller->set_gain(GAIN);
//TODO: Connect the controller's "actuator" Socket to pathActuator.
//TODO: Add the controller to the device.
return device;
}
} // end of namespace OpenSim
<|endoftext|>
|
<commit_before>/*******************************************************************************
Copyright (c) 2012-2016 Alex Zhondin <[email protected]>
Copyright (c) 2015-2020 Alexandra Cherdantseva <[email protected]>
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 "PropertyDelegateSliderBox.h"
#include "QtnProperty/PropertyView.h"
#include "QtnProperty/Auxiliary/PropertyMacro.h"
#include "QtnProperty/PropertyDelegateAttrs.h"
#include "QtnProperty/MultiProperty.h"
#include <QMouseEvent>
#include <QVariantAnimation>
QByteArray qtnFillColorAttr()
{
return QByteArrayLiteral("fillColor");
}
QByteArray qtnLiveUpdateAttr()
{
return QByteArrayLiteral("liveUpdate");
}
QByteArray qtnDrawBorderAttr()
{
return QByteArrayLiteral("drawBorder");
}
QByteArray qtnUpdateByScrollAttr()
{
return QByteArrayLiteral("updateByScroll");
}
QByteArray qtnAnimateAttr()
{
return QByteArrayLiteral("animate");
}
QByteArray qtnToolTipAttr()
{
return QByteArrayLiteral("toolTip");
}
QtnPropertyDelegateSlideBox::QtnPropertyDelegateSlideBox(QtnPropertyBase &owner)
: QtnPropertyDelegateWithValue(owner)
, m_liveUpdate(false)
, m_drawBorder(true)
, m_updateByScroll(true)
, m_animate(false)
, m_boxFillColor(QColor::fromRgb(200, 200, 255))
, m_itemToolTip(QtnPropertyView::tr("Drag/Scroll mouse to change value"))
, m_dragValuePart(0.0)
, m_oldValuePart(0.0)
, m_animateWidget(nullptr)
{
}
QtnPropertyDelegateSlideBox::~QtnPropertyDelegateSlideBox()
{
m_animation.reset();
}
void QtnPropertyDelegateSlideBox::applyAttributesImpl(
const QtnPropertyDelegateInfo &info)
{
info.loadAttribute(qtnFillColorAttr(), m_boxFillColor);
info.loadAttribute(qtnLiveUpdateAttr(), m_liveUpdate);
info.loadAttribute(qtnDrawBorderAttr(), m_drawBorder);
info.loadAttribute(qtnUpdateByScrollAttr(), m_updateByScroll);
info.loadAttribute(qtnAnimateAttr(), m_animate);
info.loadAttribute(qtnToolTipAttr(), m_itemToolTip);
info.loadAttribute(qtnSuffixAttr(), m_suffix);
info.loadAttribute(qtnPrecisionAttr(), m_precision);
info.loadAttribute(qtnMultiplierAttr(), m_multiplier);
m_min = info.attributes.value(qtnMinAttr());
m_max = info.attributes.value(qtnMaxAttr());
m_precision = qBound(0, m_precision, std::numeric_limits<double>::digits10);
if (!qIsFinite(m_multiplier) || qFuzzyCompare(m_multiplier, 0.0))
{
m_multiplier = 1.0;
}
}
bool QtnPropertyDelegateSlideBox::createSubItemValueImpl(
QtnDrawContext &context, QtnSubItem &subItemValue)
{
subItemValue.trackState();
subItemValue.setTextAsTooltip(m_itemToolTip);
subItemValue.drawHandler =
qtnMemFn(this, &QtnPropertyDelegateSlideBox::draw);
subItemValue.eventHandler =
qtnMemFn(this, &QtnPropertyDelegateSlideBox::event);
if (m_animate)
{
m_dragValuePart = propertyValuePart();
m_animation.reset(new QVariantAnimation());
m_animateWidget = context.widget->viewport();
}
return true;
}
void QtnPropertyDelegateSlideBox::draw(
QtnDrawContext &context, const QtnSubItem &item)
{
if (stateProperty()->isMultiValue())
{
qtnDrawValueText(QtnMultiProperty::getMultiValuePlaceholder(),
*context.painter, item.rect, context.style());
return;
}
double valuePart = m_dragValuePart =
(item.state() == QtnSubItemStatePushed ||
(m_animate && m_animation->state() == QVariantAnimation::Running))
? dragValuePart()
: propertyValuePart();
if (valuePart < 0.0)
return;
auto boxRect = item.rect;
boxRect.adjust(2, 2, -2, -2);
auto valueRect = boxRect;
valueRect.setWidth(int(valuePart * valueRect.width()));
auto &painter = *context.painter;
painter.save();
auto palette = painter.style()->standardPalette();
auto colorGroup = stateProperty()->isEditableByUser() ? QPalette::Active
: QPalette::Disabled;
painter.fillRect(boxRect, palette.color(colorGroup, QPalette::Background));
painter.fillRect(valueRect, m_boxFillColor);
painter.setPen(context.textColorFor(stateProperty()->isEditableByUser()));
painter.drawRect(valueRect);
if (m_drawBorder)
painter.drawRect(boxRect);
painter.restore();
qtnDrawValueText(
valuePartToStr(valuePart), painter, boxRect, context.style());
}
bool QtnPropertyDelegateSlideBox::event(
QtnEventContext &context, const QtnSubItem &item, QtnPropertyToEdit *toEdit)
{
switch (context.eventType())
{
case QEvent::KeyPress:
{
int key = context.eventAs<QKeyEvent>()->key();
int increment = 0;
if ((key == Qt::Key_Plus) || (key == Qt::Key_Equal))
increment = 1;
else if ((key == Qt::Key_Minus) || (key == Qt::Key_Underscore))
increment = -1;
else
return false;
toEdit->setup(property(), [this, increment]() -> QWidget * {
incrementPropertyValueInternal(increment);
return nullptr;
});
return true;
}
case QEvent::Wheel:
{
if (m_updateByScroll)
{
int steps =
context.eventAs<QWheelEvent>()->angleDelta().y() / 120;
toEdit->setup(property(), [this, steps]() -> QWidget * {
incrementPropertyValueInternal(steps);
return nullptr;
});
return true;
}
return false;
}
case QtnSubItemEvent::Activated:
{
m_oldCursor = context.widget->cursor();
return true;
}
case QtnSubItemEvent::PressMouse:
{
if (!m_animate)
{
m_dragValuePart = toDragValuePart(
context.eventAs<QtnSubItemEvent>()->x(), item.rect);
context.updateWidget();
}
return true;
}
case QEvent::MouseMove:
{
if (item.state() == QtnSubItemStatePushed)
{
auto dragValuePart = toDragValuePart(
context.eventAs<QMouseEvent>()->x(), item.rect);
if (m_liveUpdate)
{
if (m_animate)
m_animation->stop();
m_dragValuePart = dragValuePart;
toEdit->setup(
property(), [this, dragValuePart]() -> QWidget * {
setPropertyValuePart(dragValuePart);
return nullptr;
});
} else if (!m_animate)
{
m_dragValuePart = dragValuePart;
context.updateWidget();
}
}
return true;
}
case QtnSubItemEvent::ReleaseMouse:
{
context.widget->setCursor(m_oldCursor);
auto dragValuePart = toDragValuePart(
context.eventAs<QtnSubItemEvent>()->x(), item.rect);
toEdit->setup(property(), [this, dragValuePart]() -> QWidget * {
dragTo(dragValuePart);
return nullptr;
});
return true;
}
default:
return false;
}
}
void QtnPropertyDelegateSlideBox::incrementPropertyValueInternal(int steps)
{
if (m_animate)
m_animation->stop();
incrementPropertyValue(steps);
m_dragValuePart = propertyValuePart();
}
double QtnPropertyDelegateSlideBox::toDragValuePart(int x, const QRect &rect)
{
double result = double(x - rect.left()) / rect.width();
if (result < 0.0)
result = 0.0;
else if (result > 1.0)
result = 1.0;
return result;
}
void QtnPropertyDelegateSlideBox::dragTo(double value)
{
if (m_animate)
prepareAnimate();
setPropertyValuePart(value);
if (m_animate)
startAnimate();
else
m_dragValuePart = value;
}
void QtnPropertyDelegateSlideBox::prepareAnimate()
{
if (m_animation->state() == QVariantAnimation::Running)
{
m_oldValuePart = m_dragValuePart;
m_animation->stop();
} else
{
m_oldValuePart = m_dragValuePart = propertyValuePart();
}
}
void QtnPropertyDelegateSlideBox::startAnimate()
{
double startValue = m_oldValuePart;
double endValue = propertyValuePart();
if (endValue == startValue)
return;
m_animation->setStartValue(startValue);
m_animation->setEndValue(endValue);
m_animation->setDuration(300);
m_animation->setEasingCurve(QEasingCurve::OutCirc);
QObject::connect(m_animation.data(), &QVariantAnimation::valueChanged,
qtnMemFn(this, &QtnPropertyDelegateSlideBox::onAnimationChanged));
m_animation->start();
}
void QtnPropertyDelegateSlideBox::onAnimationChanged(const QVariant &value)
{
m_dragValuePart = value.toDouble();
if (m_animateWidget)
m_animateWidget->update();
}
<commit_msg>fix slider box<commit_after>/*******************************************************************************
Copyright (c) 2012-2016 Alex Zhondin <[email protected]>
Copyright (c) 2015-2020 Alexandra Cherdantseva <[email protected]>
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 "PropertyDelegateSliderBox.h"
#include "QtnProperty/PropertyView.h"
#include "QtnProperty/Auxiliary/PropertyMacro.h"
#include "QtnProperty/PropertyDelegateAttrs.h"
#include "QtnProperty/MultiProperty.h"
#include <QMouseEvent>
#include <QVariantAnimation>
QByteArray qtnFillColorAttr()
{
return QByteArrayLiteral("fillColor");
}
QByteArray qtnLiveUpdateAttr()
{
return QByteArrayLiteral("liveUpdate");
}
QByteArray qtnDrawBorderAttr()
{
return QByteArrayLiteral("drawBorder");
}
QByteArray qtnUpdateByScrollAttr()
{
return QByteArrayLiteral("updateByScroll");
}
QByteArray qtnAnimateAttr()
{
return QByteArrayLiteral("animate");
}
QByteArray qtnToolTipAttr()
{
return QByteArrayLiteral("toolTip");
}
QtnPropertyDelegateSlideBox::QtnPropertyDelegateSlideBox(QtnPropertyBase &owner)
: QtnPropertyDelegateWithValue(owner)
, m_liveUpdate(false)
, m_drawBorder(true)
, m_updateByScroll(true)
, m_animate(false)
, m_precision(std::numeric_limits<double>::digits10)
, m_multiplier(1.0)
, m_boxFillColor(QColor::fromRgb(200, 200, 255))
, m_itemToolTip(QtnPropertyView::tr("Drag/Scroll mouse to change value"))
, m_dragValuePart(0.0)
, m_oldValuePart(0.0)
, m_animateWidget(nullptr)
{
}
QtnPropertyDelegateSlideBox::~QtnPropertyDelegateSlideBox()
{
m_animation.reset();
}
void QtnPropertyDelegateSlideBox::applyAttributesImpl(
const QtnPropertyDelegateInfo &info)
{
info.loadAttribute(qtnFillColorAttr(), m_boxFillColor);
info.loadAttribute(qtnLiveUpdateAttr(), m_liveUpdate);
info.loadAttribute(qtnDrawBorderAttr(), m_drawBorder);
info.loadAttribute(qtnUpdateByScrollAttr(), m_updateByScroll);
info.loadAttribute(qtnAnimateAttr(), m_animate);
info.loadAttribute(qtnToolTipAttr(), m_itemToolTip);
info.loadAttribute(qtnSuffixAttr(), m_suffix);
info.loadAttribute(qtnPrecisionAttr(), m_precision);
info.loadAttribute(qtnMultiplierAttr(), m_multiplier);
m_min = info.attributes.value(qtnMinAttr());
m_max = info.attributes.value(qtnMaxAttr());
m_precision = qBound(0, m_precision, std::numeric_limits<double>::digits10);
if (!qIsFinite(m_multiplier) || qFuzzyCompare(m_multiplier, 0.0))
{
m_multiplier = 1.0;
}
}
bool QtnPropertyDelegateSlideBox::createSubItemValueImpl(
QtnDrawContext &context, QtnSubItem &subItemValue)
{
subItemValue.trackState();
subItemValue.setTextAsTooltip(m_itemToolTip);
subItemValue.drawHandler =
qtnMemFn(this, &QtnPropertyDelegateSlideBox::draw);
subItemValue.eventHandler =
qtnMemFn(this, &QtnPropertyDelegateSlideBox::event);
if (m_animate)
{
m_dragValuePart = propertyValuePart();
m_animation.reset(new QVariantAnimation());
m_animateWidget = context.widget->viewport();
}
return true;
}
void QtnPropertyDelegateSlideBox::draw(
QtnDrawContext &context, const QtnSubItem &item)
{
if (stateProperty()->isMultiValue())
{
qtnDrawValueText(QtnMultiProperty::getMultiValuePlaceholder(),
*context.painter, item.rect, context.style());
return;
}
double valuePart = m_dragValuePart =
(item.state() == QtnSubItemStatePushed ||
(m_animate && m_animation->state() == QVariantAnimation::Running))
? dragValuePart()
: propertyValuePart();
if (valuePart < 0.0)
return;
auto boxRect = item.rect;
boxRect.adjust(2, 2, -2, -2);
auto valueRect = boxRect;
valueRect.setWidth(int(valuePart * valueRect.width()));
auto &painter = *context.painter;
painter.save();
auto palette = painter.style()->standardPalette();
auto colorGroup = stateProperty()->isEditableByUser() ? QPalette::Active
: QPalette::Disabled;
painter.fillRect(boxRect, palette.color(colorGroup, QPalette::Background));
painter.fillRect(valueRect, m_boxFillColor);
painter.setPen(context.textColorFor(stateProperty()->isEditableByUser()));
painter.drawRect(valueRect);
if (m_drawBorder)
painter.drawRect(boxRect);
painter.restore();
qtnDrawValueText(
valuePartToStr(valuePart), painter, boxRect, context.style());
}
bool QtnPropertyDelegateSlideBox::event(
QtnEventContext &context, const QtnSubItem &item, QtnPropertyToEdit *toEdit)
{
switch (context.eventType())
{
case QEvent::KeyPress:
{
int key = context.eventAs<QKeyEvent>()->key();
int increment = 0;
if ((key == Qt::Key_Plus) || (key == Qt::Key_Equal))
increment = 1;
else if ((key == Qt::Key_Minus) || (key == Qt::Key_Underscore))
increment = -1;
else
return false;
toEdit->setup(property(), [this, increment]() -> QWidget * {
incrementPropertyValueInternal(increment);
return nullptr;
});
return true;
}
case QEvent::Wheel:
{
if (m_updateByScroll)
{
int steps =
context.eventAs<QWheelEvent>()->angleDelta().y() / 120;
toEdit->setup(property(), [this, steps]() -> QWidget * {
incrementPropertyValueInternal(steps);
return nullptr;
});
return true;
}
return false;
}
case QtnSubItemEvent::Activated:
{
m_oldCursor = context.widget->cursor();
return true;
}
case QtnSubItemEvent::PressMouse:
{
if (!m_animate)
{
m_dragValuePart = toDragValuePart(
context.eventAs<QtnSubItemEvent>()->x(), item.rect);
context.updateWidget();
}
return true;
}
case QEvent::MouseMove:
{
if (item.state() == QtnSubItemStatePushed)
{
auto dragValuePart = toDragValuePart(
context.eventAs<QMouseEvent>()->x(), item.rect);
if (m_liveUpdate)
{
if (m_animate)
m_animation->stop();
m_dragValuePart = dragValuePart;
toEdit->setup(
property(), [this, dragValuePart]() -> QWidget * {
setPropertyValuePart(dragValuePart);
return nullptr;
});
} else if (!m_animate)
{
m_dragValuePart = dragValuePart;
context.updateWidget();
}
return true;
}
break;
}
case QtnSubItemEvent::ReleaseMouse:
{
context.widget->setCursor(m_oldCursor);
auto dragValuePart = toDragValuePart(
context.eventAs<QtnSubItemEvent>()->x(), item.rect);
toEdit->setup(property(), [this, dragValuePart]() -> QWidget * {
dragTo(dragValuePart);
return nullptr;
});
return true;
}
default:
break;
}
return false;
}
void QtnPropertyDelegateSlideBox::incrementPropertyValueInternal(int steps)
{
if (m_animate)
m_animation->stop();
incrementPropertyValue(steps);
m_dragValuePart = propertyValuePart();
}
double QtnPropertyDelegateSlideBox::toDragValuePart(int x, const QRect &rect)
{
double result = double(x - rect.left()) / rect.width();
if (result < 0.0)
result = 0.0;
else if (result > 1.0)
result = 1.0;
return result;
}
void QtnPropertyDelegateSlideBox::dragTo(double value)
{
if (m_animate)
prepareAnimate();
setPropertyValuePart(value);
if (m_animate)
startAnimate();
else
m_dragValuePart = value;
}
void QtnPropertyDelegateSlideBox::prepareAnimate()
{
if (m_animation->state() == QVariantAnimation::Running)
{
m_oldValuePart = m_dragValuePart;
m_animation->stop();
} else
{
m_oldValuePart = m_dragValuePart = propertyValuePart();
}
}
void QtnPropertyDelegateSlideBox::startAnimate()
{
double startValue = m_oldValuePart;
double endValue = propertyValuePart();
if (endValue == startValue)
return;
m_animation->setStartValue(startValue);
m_animation->setEndValue(endValue);
m_animation->setDuration(300);
m_animation->setEasingCurve(QEasingCurve::OutCirc);
QObject::connect(m_animation.data(), &QVariantAnimation::valueChanged,
qtnMemFn(this, &QtnPropertyDelegateSlideBox::onAnimationChanged));
m_animation->start();
}
void QtnPropertyDelegateSlideBox::onAnimationChanged(const QVariant &value)
{
m_dragValuePart = value.toDouble();
if (m_animateWidget)
m_animateWidget->update();
}
<|endoftext|>
|
<commit_before>// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
#include "TextAssetEditorPrivatePCH.h"
#include "Factories.h"
#include "SDockTab.h"
#define LOCTEXT_NAMESPACE "FTextAssetEditorToolkit"
DEFINE_LOG_CATEGORY_STATIC(LogTextAssetEditor, Log, All);
/* Local constants
*****************************************************************************/
static const FName TextAssetEditorAppIdentifier("TextAssetEditorApp");
static const FName TextEditorTabId("TextEditor");
/* FTextAssetEditorToolkit structors
*****************************************************************************/
FTextAssetEditorToolkit::FTextAssetEditorToolkit(const TSharedRef<ISlateStyle>& InStyle)
: TextAsset(nullptr)
, Style(InStyle)
{ }
FTextAssetEditorToolkit::~FTextAssetEditorToolkit()
{
FReimportManager::Instance()->OnPreReimport().RemoveAll(this);
FReimportManager::Instance()->OnPostReimport().RemoveAll(this);
GEditor->UnregisterForUndo(this);
}
/* FTextAssetEditorToolkit interface
*****************************************************************************/
void FTextAssetEditorToolkit::Initialize(UTextAsset* InTextAsset, const EToolkitMode::Type InMode, const TSharedPtr<class IToolkitHost>& InToolkitHost)
{
TextAsset = InTextAsset;
// Support undo/redo
TextAsset->SetFlags(RF_Transactional);
GEditor->RegisterForUndo(this);
// create tab layout
const TSharedRef<FTabManager::FLayout> Layout = FTabManager::NewLayout("Standalone_TextAssetEditor")
->AddArea
(
FTabManager::NewPrimaryArea()
->SetOrientation(Orient_Horizontal)
->Split
(
FTabManager::NewSplitter()
->SetOrientation(Orient_Vertical)
->SetSizeCoefficient(0.66f)
->Split
(
FTabManager::NewStack()
->AddTab(GetToolbarTabId(), ETabState::OpenedTab)
->SetHideTabWell(true)
->SetSizeCoefficient(0.1f)
)
->Split
(
FTabManager::NewStack()
->AddTab(TextEditorTabId, ETabState::OpenedTab)
->SetHideTabWell(true)
->SetSizeCoefficient(0.9f)
)
)
);
FAssetEditorToolkit::InitAssetEditor(
InMode,
InToolkitHost,
TextAssetEditorAppIdentifier,
Layout,
true /*bCreateDefaultStandaloneMenu*/,
true /*bCreateDefaultToolbar*/,
InTextAsset);
RegenerateMenusAndToolbars();
}
/* FAssetEditorToolkit interface
*****************************************************************************/
FString FTextAssetEditorToolkit::GetDocumentationLink() const
{
return FString(TEXT("https://github.com/ue4plugins/TextAsset"));
}
void FTextAssetEditorToolkit::RegisterTabSpawners(const TSharedRef<class FTabManager>& TabManager)
{
WorkspaceMenuCategory = TabManager->AddLocalWorkspaceMenuCategory(LOCTEXT("WorkspaceMenu_TextAssetEditor", "Text Asset Editor"));
auto WorkspaceMenuCategoryRef = WorkspaceMenuCategory.ToSharedRef();
FAssetEditorToolkit::RegisterTabSpawners(TabManager);
TabManager->RegisterTabSpawner(TextEditorTabId, FOnSpawnTab::CreateSP(this, &FTextAssetEditorToolkit::HandleTabManagerSpawnTab, TextEditorTabId))
.SetDisplayName(LOCTEXT("TextEditorTabName", "Text Editor"))
.SetGroup(WorkspaceMenuCategoryRef)
.SetIcon(FSlateIcon(FEditorStyle::GetStyleSetName(), "LevelEditor.Tabs.Viewports"));
}
void FTextAssetEditorToolkit::UnregisterTabSpawners(const TSharedRef<class FTabManager>& TabManager)
{
FAssetEditorToolkit::UnregisterTabSpawners(TabManager);
TabManager->UnregisterTabSpawner(TextEditorTabId);
}
/* IToolkit interface
*****************************************************************************/
FText FTextAssetEditorToolkit::GetBaseToolkitName() const
{
return LOCTEXT("AppLabel", "Text Asset Editor");
}
FName FTextAssetEditorToolkit::GetToolkitFName() const
{
return FName("TextAssetEditor");
}
FLinearColor FTextAssetEditorToolkit::GetWorldCentricTabColorScale() const
{
return FLinearColor(0.3f, 0.2f, 0.5f, 0.5f);
}
FString FTextAssetEditorToolkit::GetWorldCentricTabPrefix() const
{
return LOCTEXT("WorldCentricTabPrefix", "TextAsset ").ToString();
}
/* FGCObject interface
*****************************************************************************/
void FTextAssetEditorToolkit::AddReferencedObjects(FReferenceCollector& Collector)
{
Collector.AddReferencedObject(TextAsset);
}
/* FEditorUndoClient interface
*****************************************************************************/
void FTextAssetEditorToolkit::PostUndo(bool bSuccess)
{ }
void FTextAssetEditorToolkit::PostRedo(bool bSuccess)
{
PostUndo(bSuccess);
}
/* FTextAssetEditorToolkit callbacks
*****************************************************************************/
TSharedRef<SDockTab> FTextAssetEditorToolkit::HandleTabManagerSpawnTab(const FSpawnTabArgs& Args, FName TabIdentifier)
{
TSharedPtr<SWidget> TabWidget = SNullWidget::NullWidget;
if (TabIdentifier == TextEditorTabId)
{
TabWidget = SNew(STextAssetEditor, TextAsset, Style);
}
return SNew(SDockTab)
.TabRole(ETabRole::PanelTab)
[
TabWidget.ToSharedRef()
];
}
#undef LOCTEXT_NAMESPACE
<commit_msg>Fixed shadowed variable.<commit_after>// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
#include "TextAssetEditorPrivatePCH.h"
#include "Factories.h"
#include "SDockTab.h"
#define LOCTEXT_NAMESPACE "FTextAssetEditorToolkit"
DEFINE_LOG_CATEGORY_STATIC(LogTextAssetEditor, Log, All);
/* Local constants
*****************************************************************************/
static const FName TextAssetEditorAppIdentifier("TextAssetEditorApp");
static const FName TextEditorTabId("TextEditor");
/* FTextAssetEditorToolkit structors
*****************************************************************************/
FTextAssetEditorToolkit::FTextAssetEditorToolkit(const TSharedRef<ISlateStyle>& InStyle)
: TextAsset(nullptr)
, Style(InStyle)
{ }
FTextAssetEditorToolkit::~FTextAssetEditorToolkit()
{
FReimportManager::Instance()->OnPreReimport().RemoveAll(this);
FReimportManager::Instance()->OnPostReimport().RemoveAll(this);
GEditor->UnregisterForUndo(this);
}
/* FTextAssetEditorToolkit interface
*****************************************************************************/
void FTextAssetEditorToolkit::Initialize(UTextAsset* InTextAsset, const EToolkitMode::Type InMode, const TSharedPtr<class IToolkitHost>& InToolkitHost)
{
TextAsset = InTextAsset;
// Support undo/redo
TextAsset->SetFlags(RF_Transactional);
GEditor->RegisterForUndo(this);
// create tab layout
const TSharedRef<FTabManager::FLayout> Layout = FTabManager::NewLayout("Standalone_TextAssetEditor")
->AddArea
(
FTabManager::NewPrimaryArea()
->SetOrientation(Orient_Horizontal)
->Split
(
FTabManager::NewSplitter()
->SetOrientation(Orient_Vertical)
->SetSizeCoefficient(0.66f)
->Split
(
FTabManager::NewStack()
->AddTab(GetToolbarTabId(), ETabState::OpenedTab)
->SetHideTabWell(true)
->SetSizeCoefficient(0.1f)
)
->Split
(
FTabManager::NewStack()
->AddTab(TextEditorTabId, ETabState::OpenedTab)
->SetHideTabWell(true)
->SetSizeCoefficient(0.9f)
)
)
);
FAssetEditorToolkit::InitAssetEditor(
InMode,
InToolkitHost,
TextAssetEditorAppIdentifier,
Layout,
true /*bCreateDefaultStandaloneMenu*/,
true /*bCreateDefaultToolbar*/,
InTextAsset
);
RegenerateMenusAndToolbars();
}
/* FAssetEditorToolkit interface
*****************************************************************************/
FString FTextAssetEditorToolkit::GetDocumentationLink() const
{
return FString(TEXT("https://github.com/ue4plugins/TextAsset"));
}
void FTextAssetEditorToolkit::RegisterTabSpawners(const TSharedRef<class FTabManager>& InTabManager)
{
WorkspaceMenuCategory = InTabManager->AddLocalWorkspaceMenuCategory(LOCTEXT("WorkspaceMenu_TextAssetEditor", "Text Asset Editor"));
auto WorkspaceMenuCategoryRef = WorkspaceMenuCategory.ToSharedRef();
FAssetEditorToolkit::RegisterTabSpawners(InTabManager);
InTabManager->RegisterTabSpawner(TextEditorTabId, FOnSpawnTab::CreateSP(this, &FTextAssetEditorToolkit::HandleTabManagerSpawnTab, TextEditorTabId))
.SetDisplayName(LOCTEXT("TextEditorTabName", "Text Editor"))
.SetGroup(WorkspaceMenuCategoryRef)
.SetIcon(FSlateIcon(FEditorStyle::GetStyleSetName(), "LevelEditor.Tabs.Viewports"));
}
void FTextAssetEditorToolkit::UnregisterTabSpawners(const TSharedRef<class FTabManager>& InTabManager)
{
FAssetEditorToolkit::UnregisterTabSpawners(InTabManager);
InTabManager->UnregisterTabSpawner(TextEditorTabId);
}
/* IToolkit interface
*****************************************************************************/
FText FTextAssetEditorToolkit::GetBaseToolkitName() const
{
return LOCTEXT("AppLabel", "Text Asset Editor");
}
FName FTextAssetEditorToolkit::GetToolkitFName() const
{
return FName("TextAssetEditor");
}
FLinearColor FTextAssetEditorToolkit::GetWorldCentricTabColorScale() const
{
return FLinearColor(0.3f, 0.2f, 0.5f, 0.5f);
}
FString FTextAssetEditorToolkit::GetWorldCentricTabPrefix() const
{
return LOCTEXT("WorldCentricTabPrefix", "TextAsset ").ToString();
}
/* FGCObject interface
*****************************************************************************/
void FTextAssetEditorToolkit::AddReferencedObjects(FReferenceCollector& Collector)
{
Collector.AddReferencedObject(TextAsset);
}
/* FEditorUndoClient interface
*****************************************************************************/
void FTextAssetEditorToolkit::PostUndo(bool bSuccess)
{ }
void FTextAssetEditorToolkit::PostRedo(bool bSuccess)
{
PostUndo(bSuccess);
}
/* FTextAssetEditorToolkit callbacks
*****************************************************************************/
TSharedRef<SDockTab> FTextAssetEditorToolkit::HandleTabManagerSpawnTab(const FSpawnTabArgs& Args, FName TabIdentifier)
{
TSharedPtr<SWidget> TabWidget = SNullWidget::NullWidget;
if (TabIdentifier == TextEditorTabId)
{
TabWidget = SNew(STextAssetEditor, TextAsset, Style);
}
return SNew(SDockTab)
.TabRole(ETabRole::PanelTab)
[
TabWidget.ToSharedRef()
];
}
#undef LOCTEXT_NAMESPACE
<|endoftext|>
|
<commit_before>
#include <cstdio>
#include <cstdlib>
#include <cstddef>
#include <cstring>
#include <ctime>
#include <memory>
#include "tagha.h"
struct Player {
float speed;
uint32_t health, ammo;
};
/* lldiv_t lldiv(long long int numer, long long int denom); */
void Native_lldiv(class CTagha *sys, union TaghaVal *retval, const size_t args, union TaghaVal params[])
{
(void)sys; (void)args; (void)retval; // makes the compiler stop bitching.
lldiv_t *val = (lldiv_t *)params[0].Ptr;
*val = lldiv(params[1].Int64, params[2].Int64);
}
/* int puts(const char *str); */
void Native_puts(class CTagha *sys, union TaghaVal *retval, const size_t args, union TaghaVal params[])
{
(void)sys; (void)args;
const char *p = (const char *)params[0].Ptr;
if( !p ) {
puts("Native_puts :: ERROR **** p is nullptr ****");
retval->Int32 = -1;
return;
}
retval->Int32 = puts(p);
}
/* char *fgets(char *buffer, int num, FILE *stream); */
void Native_fgets(class CTagha *sys, union TaghaVal *retval, const size_t args, union TaghaVal params[])
{
(void)sys; (void)args;
char *buf = (char *)params[0].Ptr;
if( !buf ) {
puts("buf is nullptr");
return;
}
FILE *stream = (FILE *)params[2].Ptr;
if( !stream ) {
puts("stream is nullptr");
return;
}
retval->Ptr = (void *)fgets(buf, params[1].Int32, stream);
}
/* size_t strlen(const char *s); */
void Native_strlen(class CTagha *sys, union TaghaVal *retval, const size_t args, union TaghaVal params[])
{
(void)sys; (void)args;
retval->UInt64 = strlen((const char *)params[0].Ptr);
}
void Native_AddOne(class CTagha *sys, union TaghaVal *retval, const size_t args, union TaghaVal params[])
{
(void)sys; (void)args;
retval->Int32 = params[0].Int32 + 1;
}
static size_t GetFileSize(FILE *const restrict file)
{
int64_t size = 0L;
if( !file )
return size;
if( !fseek(file, 0, SEEK_END) ) {
size = ftell(file);
if( size == -1 )
return 0L;
rewind(file);
}
return (size_t)size;
}
int main(int argc, char *argv[])
{
(void)argc;
if( !argv[1] ) {
printf("[TaghaVM Usage]: '%s' '.tbc filepath' \n", argv[0]);
return 1;
}
FILE *script = fopen(argv[1], "rb");
if( !script )
return 1;
const size_t filesize = GetFileSize(script);
std::unique_ptr<uint8_t> process(new uint8_t[filesize]);
const size_t val = fread(process.get(), sizeof(uint8_t), filesize, script);
(void)val;
fclose(script), script=nullptr;
const CNativeInfo host_natives[] = {
{"puts", Native_puts},
{"fgets", Native_fgets},
{"strlen", Native_strlen},
{"AddOne", Native_AddOne},
{nullptr, nullptr}
};
std::unique_ptr<CTagha> vm = std::make_unique<CTagha>(process.get(), host_natives);
//CTagha *vm = new CTagha(process, host_natives);
Player player; player.speed = 0.f, player.health = 0, player.ammo = 0;
Player **pp = (struct Player **)vm->GetGlobalVarByName("g_pPlayer");
if( pp )
*pp = &player;
char i[] = "hello from main argv!";
char *arguments[] = {i, nullptr};
int32_t result = vm->RunScript(1, arguments);
//union TaghaVal values[1]; values[0].UInt64 = 5;
//int32_t result = vm->CallFunc("factorial", 1, values);
if( pp )
printf("player.speed: '%f' | player.health: '%u' | player.ammo: '%u'\n", player.speed, player.health, player.ammo);
printf("result?: '%i'\n", result);
//delete vm;
//delete[] process;
}
<commit_msg>Delete test_hostapp.cpp<commit_after><|endoftext|>
|
<commit_before>#include "musicabstractmoveresizewidget.h"
#include <QPainter>
#include <QMouseEvent>
#include <QApplication>
#define DISTANCE 5
MusicAbstractMoveResizeWidget::MusicAbstractMoveResizeWidget(QWidget *parent)
: QWidget(parent)
{
m_struct.m_mouseLeftPress = false;
m_direction = Direction_No;
setWindowFlags(Qt::FramelessWindowHint);
setAttribute(Qt::WA_TranslucentBackground);
setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
setMouseTracking(true);
}
QString MusicAbstractMoveResizeWidget::getClassName()
{
return staticMetaObject.className();
}
bool MusicAbstractMoveResizeWidget::eventFilter(QObject *object, QEvent *event)
{
QWidget::eventFilter(object, event);
if(QEvent::MouseMove == event->type())
{
QMouseEvent *mouseEvent = MStatic_cast(QMouseEvent*, event);
QApplication::sendEvent(this, mouseEvent);
}
return false;
}
void MusicAbstractMoveResizeWidget::mouseDoubleClickEvent(QMouseEvent *event)
{
QWidget::mouseDoubleClickEvent(event);
// if( event->buttons() == Qt::LeftButton)
// {
// if(isMaximized())
// {
// showNormal();
// }
// else
// {
// showMaximized();
// }
// }
}
void MusicAbstractMoveResizeWidget::mousePressEvent(QMouseEvent *event)
{
QWidget::mousePressEvent(event);
m_struct.m_pressedSize = size();
m_struct.m_isPressBorder = false;
setFocus();
if(event->button() == Qt::LeftButton)
{
m_struct.m_windowPos = pos();
if(QRect(DISTANCE + 1, DISTANCE + 1, width() - (DISTANCE + 1)*2,
height() - (DISTANCE + 1)*2).contains(event->pos()))
{
m_struct.m_mousePos = event->globalPos();
m_struct.m_mouseLeftPress = true;
}
else
{
m_struct.m_isPressBorder = true;
}
}
}
void MusicAbstractMoveResizeWidget::mouseMoveEvent(QMouseEvent *event)
{
QWidget::mouseMoveEvent(event);
!m_struct.m_isPressBorder ? sizeDirection() : moveDirection();
if(m_struct.m_mouseLeftPress)
{
move(m_struct.m_windowPos + (event->globalPos() - m_struct.m_mousePos));
}
}
void MusicAbstractMoveResizeWidget::mouseReleaseEvent(QMouseEvent *event)
{
QWidget::mouseReleaseEvent(event);
m_struct.m_isPressBorder = false;
m_struct.m_mouseLeftPress = false;
setCursor(QCursor(Qt::ArrowCursor));
}
void MusicAbstractMoveResizeWidget::sizeDirection()
{
QPoint point = mapFromGlobal(QCursor::pos());
if( point.x() > width() - DISTANCE && point.y() < height() - DISTANCE &&
point.y() > DISTANCE )//right side
{
setCursor(Qt::SizeHorCursor);
m_direction = Direction_Right;
}
else if( point.x() < DISTANCE && point.y() < height() - DISTANCE &&
point.y() > DISTANCE )
{
setCursor(Qt::SizeHorCursor);
m_direction = Direction_Left;
}
else if( point.y() > height() - DISTANCE && point.x() > DISTANCE &&
point.x() < width() - DISTANCE )
{
setCursor(Qt::SizeVerCursor);
m_direction = Direction_Bottom;
}
else if( point.y() < DISTANCE && point.x() > DISTANCE &&
point.x() < width() - DISTANCE )
{
setCursor(Qt::SizeVerCursor);
m_direction = Direction_Top;
}
else if( point.y() < DISTANCE && point.x() > width() - DISTANCE )
{
setCursor(Qt::SizeBDiagCursor);
m_direction = Direction_RightTop;
}
else if( point.y() < DISTANCE && point.x() < DISTANCE)
{
setCursor(Qt::SizeFDiagCursor);
m_direction = Direction_LeftTop;
}
else if( point.x() > DISTANCE && point.y() > height() - DISTANCE )
{
setCursor(Qt::SizeFDiagCursor);
m_direction = Direction_RightBottom;
}
else if( point.x() < DISTANCE && point.y() > height() - DISTANCE )
{
setCursor(Qt::SizeBDiagCursor);
m_direction = Direction_LeftBottom;
}
else
{
setCursor(Qt::ArrowCursor);
m_direction = Direction_No;
}
}
void MusicAbstractMoveResizeWidget::moveDirection()
{
switch(m_direction)
{
case Direction_Right:
{
int wValue = QCursor::pos().x() - x();
if(minimumWidth() <= wValue && wValue <= maximumWidth())
{
setGeometry(x(), y(), wValue, height());
}
break;
}
case Direction_Left:
{
int wValue = x() + width() - QCursor::pos().x();
if(minimumWidth() <= wValue && wValue <= maximumWidth())
{
setGeometry(QCursor::pos().x(), y(), wValue, height());
}
break;
}
case Direction_Bottom:
{
int hValue = QCursor::pos().y() - y();
if(minimumHeight() <= hValue && hValue <= maximumHeight())
{
setGeometry(x(), y(), width(), hValue);
}
break;
}
case Direction_Top:
{
int hValue = y() - QCursor::pos().y() + height();
if(minimumHeight() <= hValue && hValue <= maximumHeight())
{
setGeometry(x(), QCursor::pos().y(), width(), hValue);
}
break;
}
case Direction_RightTop:
{
int hValue = y() + height() - QCursor::pos().y();
int wValue = QCursor::pos().x() - x();
int yValue = QCursor::pos().y();
if(hValue >= maximumHeight())
{
yValue = m_struct.m_windowPos.y() + m_struct.m_pressedSize.height() - height();
hValue = maximumHeight();
}
if(hValue <= minimumHeight())
{
yValue = m_struct.m_windowPos.y() + m_struct.m_pressedSize.height() - height();
hValue = minimumHeight();
}
setGeometry(m_struct.m_windowPos.x(), yValue, wValue, hValue);
break;
}
case Direction_LeftTop:
{
int yValue = QCursor::pos().y();
int xValue = QCursor::pos().x();
int wValue = pos().x() + width( )- xValue;
int hValue = pos().y() + height() - yValue;
int twValue = m_struct.m_windowPos.x() + m_struct.m_pressedSize.width();
int thValue = m_struct.m_windowPos.y() + m_struct.m_pressedSize.height();
if(twValue - xValue >= maximumWidth())
{
xValue = twValue - maximumWidth();
wValue = maximumWidth();
}
if(twValue - xValue <= minimumWidth())
{
xValue = twValue - minimumWidth();
wValue = minimumWidth();
}
if(thValue - yValue >= maximumHeight())
{
yValue = thValue - maximumHeight();
hValue = maximumHeight();
}
if(thValue - yValue <= minimumHeight())
{
yValue = thValue - minimumHeight();
hValue = minimumHeight();
}
setGeometry(xValue, yValue, wValue, hValue);
break;
}
case Direction_RightBottom:
{
int wValue = QCursor::pos().x() - x();
int hValue = QCursor::pos().y() - y();
setGeometry(m_struct.m_windowPos.x(), m_struct.m_windowPos.y(), wValue, hValue);
break;
}
case Direction_LeftBottom:
{
int wValue = x() + width() - QCursor::pos().x();
int hValue = QCursor::pos().y() - m_struct.m_windowPos.y();
int xValue = QCursor::pos().x();
int twValue = m_struct.m_windowPos.x() + m_struct.m_pressedSize.width();
if(twValue - xValue >= maximumWidth())
{
xValue = twValue - maximumWidth();
wValue = maximumWidth();
}
if(twValue - xValue <= minimumWidth())
{
xValue = twValue - minimumWidth();
wValue = minimumWidth();
}
setGeometry(xValue, m_struct.m_windowPos.y(), wValue, hValue);
break;
}
default: break;
}
}
QObjectList MusicAbstractMoveResizeWidget::foreachWidget(QObject *object)
{
QObjectList result;
foreach(QObject *obj, object->children())
{
if("QWidget" == QString(obj->metaObject()->className()))
{
result.append(obj);
}
result += foreachWidget(obj);
}
return result;
}
<commit_msg>support window mouse double click[841039]<commit_after>#include "musicabstractmoveresizewidget.h"
#include <QPainter>
#include <QMouseEvent>
#include <QApplication>
#define DISTANCE 5
MusicAbstractMoveResizeWidget::MusicAbstractMoveResizeWidget(QWidget *parent)
: QWidget(parent)
{
m_struct.m_mouseLeftPress = false;
m_direction = Direction_No;
setWindowFlags(Qt::FramelessWindowHint);
setAttribute(Qt::WA_TranslucentBackground);
setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
setMouseTracking(true);
}
QString MusicAbstractMoveResizeWidget::getClassName()
{
return staticMetaObject.className();
}
bool MusicAbstractMoveResizeWidget::eventFilter(QObject *object, QEvent *event)
{
QWidget::eventFilter(object, event);
if(QEvent::MouseMove == event->type())
{
QMouseEvent *mouseEvent = MStatic_cast(QMouseEvent*, event);
QApplication::sendEvent(this, mouseEvent);
}
return false;
}
void MusicAbstractMoveResizeWidget::mouseDoubleClickEvent(QMouseEvent *event)
{
QWidget::mouseDoubleClickEvent(event);
if( event->buttons() == Qt::LeftButton)
{
if(isMaximized())
{
showNormal();
}
else
{
showMaximized();
}
}
}
void MusicAbstractMoveResizeWidget::mousePressEvent(QMouseEvent *event)
{
QWidget::mousePressEvent(event);
m_struct.m_pressedSize = size();
m_struct.m_isPressBorder = false;
setFocus();
if(event->button() == Qt::LeftButton)
{
m_struct.m_windowPos = pos();
if(QRect(DISTANCE + 1, DISTANCE + 1, width() - (DISTANCE + 1)*2,
height() - (DISTANCE + 1)*2).contains(event->pos()))
{
m_struct.m_mousePos = event->globalPos();
m_struct.m_mouseLeftPress = true;
}
else
{
m_struct.m_isPressBorder = true;
}
}
}
void MusicAbstractMoveResizeWidget::mouseMoveEvent(QMouseEvent *event)
{
QWidget::mouseMoveEvent(event);
!m_struct.m_isPressBorder ? sizeDirection() : moveDirection();
if(m_struct.m_mouseLeftPress)
{
move(m_struct.m_windowPos + (event->globalPos() - m_struct.m_mousePos));
}
}
void MusicAbstractMoveResizeWidget::mouseReleaseEvent(QMouseEvent *event)
{
QWidget::mouseReleaseEvent(event);
m_struct.m_isPressBorder = false;
m_struct.m_mouseLeftPress = false;
setCursor(QCursor(Qt::ArrowCursor));
}
void MusicAbstractMoveResizeWidget::sizeDirection()
{
QPoint point = mapFromGlobal(QCursor::pos());
if( point.x() > width() - DISTANCE && point.y() < height() - DISTANCE &&
point.y() > DISTANCE )//right side
{
setCursor(Qt::SizeHorCursor);
m_direction = Direction_Right;
}
else if( point.x() < DISTANCE && point.y() < height() - DISTANCE &&
point.y() > DISTANCE )
{
setCursor(Qt::SizeHorCursor);
m_direction = Direction_Left;
}
else if( point.y() > height() - DISTANCE && point.x() > DISTANCE &&
point.x() < width() - DISTANCE )
{
setCursor(Qt::SizeVerCursor);
m_direction = Direction_Bottom;
}
else if( point.y() < DISTANCE && point.x() > DISTANCE &&
point.x() < width() - DISTANCE )
{
setCursor(Qt::SizeVerCursor);
m_direction = Direction_Top;
}
else if( point.y() < DISTANCE && point.x() > width() - DISTANCE )
{
setCursor(Qt::SizeBDiagCursor);
m_direction = Direction_RightTop;
}
else if( point.y() < DISTANCE && point.x() < DISTANCE)
{
setCursor(Qt::SizeFDiagCursor);
m_direction = Direction_LeftTop;
}
else if( point.x() > DISTANCE && point.y() > height() - DISTANCE )
{
setCursor(Qt::SizeFDiagCursor);
m_direction = Direction_RightBottom;
}
else if( point.x() < DISTANCE && point.y() > height() - DISTANCE )
{
setCursor(Qt::SizeBDiagCursor);
m_direction = Direction_LeftBottom;
}
else
{
setCursor(Qt::ArrowCursor);
m_direction = Direction_No;
}
}
void MusicAbstractMoveResizeWidget::moveDirection()
{
switch(m_direction)
{
case Direction_Right:
{
int wValue = QCursor::pos().x() - x();
if(minimumWidth() <= wValue && wValue <= maximumWidth())
{
setGeometry(x(), y(), wValue, height());
}
break;
}
case Direction_Left:
{
int wValue = x() + width() - QCursor::pos().x();
if(minimumWidth() <= wValue && wValue <= maximumWidth())
{
setGeometry(QCursor::pos().x(), y(), wValue, height());
}
break;
}
case Direction_Bottom:
{
int hValue = QCursor::pos().y() - y();
if(minimumHeight() <= hValue && hValue <= maximumHeight())
{
setGeometry(x(), y(), width(), hValue);
}
break;
}
case Direction_Top:
{
int hValue = y() - QCursor::pos().y() + height();
if(minimumHeight() <= hValue && hValue <= maximumHeight())
{
setGeometry(x(), QCursor::pos().y(), width(), hValue);
}
break;
}
case Direction_RightTop:
{
int hValue = y() + height() - QCursor::pos().y();
int wValue = QCursor::pos().x() - x();
int yValue = QCursor::pos().y();
if(hValue >= maximumHeight())
{
yValue = m_struct.m_windowPos.y() + m_struct.m_pressedSize.height() - height();
hValue = maximumHeight();
}
if(hValue <= minimumHeight())
{
yValue = m_struct.m_windowPos.y() + m_struct.m_pressedSize.height() - height();
hValue = minimumHeight();
}
setGeometry(m_struct.m_windowPos.x(), yValue, wValue, hValue);
break;
}
case Direction_LeftTop:
{
int yValue = QCursor::pos().y();
int xValue = QCursor::pos().x();
int wValue = pos().x() + width( )- xValue;
int hValue = pos().y() + height() - yValue;
int twValue = m_struct.m_windowPos.x() + m_struct.m_pressedSize.width();
int thValue = m_struct.m_windowPos.y() + m_struct.m_pressedSize.height();
if(twValue - xValue >= maximumWidth())
{
xValue = twValue - maximumWidth();
wValue = maximumWidth();
}
if(twValue - xValue <= minimumWidth())
{
xValue = twValue - minimumWidth();
wValue = minimumWidth();
}
if(thValue - yValue >= maximumHeight())
{
yValue = thValue - maximumHeight();
hValue = maximumHeight();
}
if(thValue - yValue <= minimumHeight())
{
yValue = thValue - minimumHeight();
hValue = minimumHeight();
}
setGeometry(xValue, yValue, wValue, hValue);
break;
}
case Direction_RightBottom:
{
int wValue = QCursor::pos().x() - x();
int hValue = QCursor::pos().y() - y();
setGeometry(m_struct.m_windowPos.x(), m_struct.m_windowPos.y(), wValue, hValue);
break;
}
case Direction_LeftBottom:
{
int wValue = x() + width() - QCursor::pos().x();
int hValue = QCursor::pos().y() - m_struct.m_windowPos.y();
int xValue = QCursor::pos().x();
int twValue = m_struct.m_windowPos.x() + m_struct.m_pressedSize.width();
if(twValue - xValue >= maximumWidth())
{
xValue = twValue - maximumWidth();
wValue = maximumWidth();
}
if(twValue - xValue <= minimumWidth())
{
xValue = twValue - minimumWidth();
wValue = minimumWidth();
}
setGeometry(xValue, m_struct.m_windowPos.y(), wValue, hValue);
break;
}
default: break;
}
}
QObjectList MusicAbstractMoveResizeWidget::foreachWidget(QObject *object)
{
QObjectList result;
foreach(QObject *obj, object->children())
{
if("QWidget" == QString(obj->metaObject()->className()))
{
result.append(obj);
}
result += foreachWidget(obj);
}
return result;
}
<|endoftext|>
|
<commit_before>#include "amftest.hpp"
#include "amf.hpp"
#include "types/amfdouble.hpp"
static void isEqual(const std::vector<u8>& expected, double value) {
ASSERT_EQ(expected, AmfDouble(value).serialize());
}
TEST(DoubleSerializationTest, SimpleValues) {
isEqual(v8 { 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, 0);
isEqual(v8 { 0x05, 0x3F, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, 0.5);
isEqual(v8 { 0x05, 0xBF, 0xF3, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33 }, -1.2);
isEqual(v8 { 0x05, 0x3F, 0xD5, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55 }, 0.3333333333333333);
isEqual(v8 { 0x05, 0xBF, 0xD5, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55 }, -0.3333333333333333);
isEqual(v8 { 0x05, 0x4A, 0x9A, 0xBA, 0x47, 0x14, 0x95, 0x7D, 0x30 }, 2.5e+51);
isEqual(v8 { 0x05, 0xCA, 0x9A, 0xBA, 0x47, 0x14, 0x95, 0x7D, 0x30 }, -2.5e+51);
isEqual(v8 { 0x05, 0x47, 0x37, 0xC6, 0xE3, 0xC0, 0x32, 0xF7, 0x20 }, 1.2345678912345e+35);
isEqual(v8 { 0x05, 0xC7, 0x37, 0xC6, 0xE3, 0xC0, 0x32, 0xF7, 0x20 }, -1.2345678912345e+35);
isEqual(v8 { 0x05, 0x42, 0x06, 0xFE, 0xE0, 0xE1, 0xA0, 0x00, 0x00 }, 12345678900);
isEqual(v8 { 0x05, 0x3D, 0xE0, 0xF7, 0xBF, 0xE5, 0xDB, 0x09, 0xEB }, 1.23456789e-10);
isEqual(v8 { 0x05, 0xC2, 0x06, 0xFE, 0xE0, 0xE1, 0xA0, 0x00, 0x00 }, -12345678900);
isEqual(v8 { 0x05, 0xBD, 0xE0, 0xF7, 0xBF, 0xE5, 0xDB, 0x09, 0xEB }, -1.23456789e-10);
isEqual(v8 { 0x05, 0x3F, 0xEA, 0x2E, 0x8B, 0xA2, 0xE8, 0xBA, 0x2F }, 0.8181818181818182);
isEqual(v8 { 0x05, 0x3F, 0xF3, 0x8E, 0x38, 0xE3, 0x8E, 0x38, 0xE4 }, 1.2222222222222223);
isEqual(v8 { 0x05, 0x40, 0x09, 0x21, 0xF9, 0xF0, 0x1B, 0x86, 0x6E }, 3.14159);
isEqual(v8 { 0x05, 0xBF, 0xEA, 0x2E, 0x8B, 0xA2, 0xE8, 0xBA, 0x2F }, -0.8181818181818182);
isEqual(v8 { 0x05, 0xBF, 0xF3, 0x8E, 0x38, 0xE3, 0x8E, 0x38, 0xE4 }, -1.2222222222222223);
isEqual(v8 { 0x05, 0xC0, 0x09, 0x21, 0xF9, 0xF0, 0x1B, 0x86, 0x6E }, -3.14159);
}
<commit_msg>Add another double test.<commit_after>#include "amftest.hpp"
#include "amf.hpp"
#include "types/amfdouble.hpp"
static void isEqual(const std::vector<u8>& expected, double value) {
ASSERT_EQ(expected, AmfDouble(value).serialize());
}
TEST(DoubleSerializationTest, SimpleValues) {
isEqual(v8 { 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, 0);
isEqual(v8 { 0x05, 0x3F, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, 0.5);
isEqual(v8 { 0x05, 0xBF, 0xF3, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33 }, -1.2);
isEqual(v8 { 0x05, 0x3F, 0xD5, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55 }, 0.3333333333333333);
isEqual(v8 { 0x05, 0xBF, 0xD5, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55 }, -0.3333333333333333);
isEqual(v8 { 0x05, 0x4A, 0x9A, 0xBA, 0x47, 0x14, 0x95, 0x7D, 0x30 }, 2.5e+51);
isEqual(v8 { 0x05, 0xCA, 0x9A, 0xBA, 0x47, 0x14, 0x95, 0x7D, 0x30 }, -2.5e+51);
isEqual(v8 { 0x05, 0x47, 0x37, 0xC6, 0xE3, 0xC0, 0x32, 0xF7, 0x20 }, 1.2345678912345e+35);
isEqual(v8 { 0x05, 0xC7, 0x37, 0xC6, 0xE3, 0xC0, 0x32, 0xF7, 0x20 }, -1.2345678912345e+35);
isEqual(v8 { 0x05, 0x42, 0x06, 0xFE, 0xE0, 0xE1, 0xA0, 0x00, 0x00 }, 12345678900);
isEqual(v8 { 0x05, 0x3D, 0xE0, 0xF7, 0xBF, 0xE5, 0xDB, 0x09, 0xEB }, 1.23456789e-10);
isEqual(v8 { 0x05, 0xC2, 0x06, 0xFE, 0xE0, 0xE1, 0xA0, 0x00, 0x00 }, -12345678900);
isEqual(v8 { 0x05, 0xBD, 0xE0, 0xF7, 0xBF, 0xE5, 0xDB, 0x09, 0xEB }, -1.23456789e-10);
isEqual(v8 { 0x05, 0x3F, 0xEA, 0x2E, 0x8B, 0xA2, 0xE8, 0xBA, 0x2F }, 0.8181818181818182);
isEqual(v8 { 0x05, 0x3F, 0xF3, 0x8E, 0x38, 0xE3, 0x8E, 0x38, 0xE4 }, 1.2222222222222223);
isEqual(v8 { 0x05, 0x40, 0x09, 0x21, 0xF9, 0xF0, 0x1B, 0x86, 0x6E }, 3.14159);
isEqual(v8 { 0x05, 0xBF, 0xEA, 0x2E, 0x8B, 0xA2, 0xE8, 0xBA, 0x2F }, -0.8181818181818182);
isEqual(v8 { 0x05, 0xBF, 0xF3, 0x8E, 0x38, 0xE3, 0x8E, 0x38, 0xE4 }, -1.2222222222222223);
isEqual(v8 { 0x05, 0xC0, 0x09, 0x21, 0xF9, 0xF0, 0x1B, 0x86, 0x6E }, -3.14159);
isEqual(v8 { 0x05, 0x40, 0x31, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, 17.0);
}
<|endoftext|>
|
<commit_before>// Copyright 2010-2013 The CefSharp Project. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
#include "Stdafx.h"
#include "Cef.h"
#include "Settings.h"
#include "Internals\ClientApp.h"
using namespace System::Runtime::InteropServices;
using namespace System::Reflection;
namespace CefSharp
{
void Cef::Initialize(Settings^ settings)
{
// TODO: Remove if we conclude that we won't need it. The problem with it that we don't always have an EntryAssembly,
// e.g. when running unit tests.
//auto module = Assembly::GetEntryAssembly()->GetModules()[0];
//auto hInstance = (HINSTANCE) Marshal::GetHINSTANCE(module).ToPointer();
CefMainArgs main_args; //(hInstance);
CefRefPtr<ClientApp> app(new ClientApp);
int exitCode = CefExecuteProcess(main_args, app.get());
if (exitCode >= 0)
{
throw gcnew Exception(
"Failed to execute CEF process. Possible causes could be version mismatches (replacing libcef.dll etc. without " +
"recompiling CefSharp). Error code was: " + exitCode);
}
CefInitialize(main_args, *(settings->_cefSettings), app.get());
}
void Cef::NavigateTo(Uri^ uri)
{
}
}<commit_msg>We don't need this one any more; all of the implementation is in the .h(eader) file anyway.<commit_after><|endoftext|>
|
<commit_before>
//ADDED FOR COMPATIBILITY WITH WIRING
extern "C" {
#include <stdlib.h>
}
#include "CmdMessenger.h"
#include <Streaming.h>
//////////////////// Cmd Messenger imp ////////////////
CmdMessenger::CmdMessenger(Stream &ccomms)
{
comms = &ccomms;
init(' ',';');
}
CmdMessenger::CmdMessenger(Stream &ccomms, char field_separator)
{
comms = &ccomms;
init(field_separator,';');
}
CmdMessenger::CmdMessenger(Stream &ccomms, char field_separator, char cmd_separator)
{
comms = &ccomms;
init(field_separator,cmd_separator);
}
void CmdMessenger::attach(byte msgId, messengerCallbackFunction newFunction) {
if (msgId > 0 && msgId <= MAXCALLBACKS) // <= ? I think its ok ?
callbackList[msgId-1] = newFunction;
}
void CmdMessenger::discard_LF_CR()
{
discard_newlines = true;
}
void CmdMessenger::print_LF_CR()
{
print_newlines = true;
}
void CmdMessenger::init(char field_separator, char cmd_separator)
{
discard_newlines = false;
print_newlines = false;
callback = NULL;
token[0] = field_separator;
token[1] = '\0';
command_separator = cmd_separator;
bufferLength = MESSENGERBUFFERSIZE;
bufferLastIndex = MESSENGERBUFFERSIZE -1;
reset();
for (int i = 0; i < MAXCALLBACKS; i++)
callbackList[i] = NULL;
pauseProcessing = false;
}
void CmdMessenger::init()
{
for (int i = 0; i < MAXCALLBACKS; i++)
callbackList[i] = NULL;
pauseProcessing = false;
}
uint8_t CmdMessenger::process(int serialByte) {
messageState = 0;
if (serialByte > 0) {
if((char)serialByte == command_separator)
{
buffer[bufferIndex]=0;
if(bufferIndex > 0)
{
messageState = 1;
current = buffer;
}
reset();
}
else
{
buffer[bufferIndex]=serialByte;
bufferIndex++;
if (bufferIndex >= bufferLastIndex) reset();
if(discard_newlines)
if(((char)serialByte == '\n') || ((char)serialByte == '\r'))
reset();
}
}
if ( messageState == 1 ) {
handleMessage();
}
return messageState;
}
void CmdMessenger::handleMessage()
{
int id = readInt();
//Serial << "ID+" << id << endl;
// Because readInt() can fail and return a 0 we can't
// start our array index at that number
if (id > 0 && id <= MAXCALLBACKS && callbackList[id-1] != NULL)
(*callbackList[id-1])();
else // Cmd not registered default callback
(*callback)();
}
void CmdMessenger::feedinSerialData()
{
while ( !pauseProcessing && comms->available( ) )
process(comms->read( ) );
}
// Taken from RougueMP3 library
int8_t CmdMessenger::_read_blocked(void)
{
// int8_t r;
while(!comms->available());
// while((r = this->_readf()) < 0); // this would be faster if we could guarantee that the _readf() function
// would return -1 if there was no byte read
return comms->read();
}
boolean CmdMessenger::blockedTillReply(int timeout)
{
unsigned long start = millis();
unsigned long time = start;
while(!comms->available() || (start - time) > timeout )
time = millis();
}
// Not sure if it will work for signed.. check it out
/*unsigned char *CmdMessenger::writeRealInt(int val, unsigned char buff[2])
{
buff[1] = (unsigned char)val;
buff[0] = (unsigned char)(val >> 8);
buff[2] = 0;
return buff;
}
char* CmdMessenger::writeRealLong(long val, char buff[4])
{
//buff[1] = (unsigned char)val;
//buff[0] = (unsigned char)(val >> 8);
return buff;
}
char* CmdMessenger::writeRealFloat(float val, char buff[4])
{
//buff[1] = (unsigned char)val;
//buff[0] = (unsigned char)(val >> 8);
return buff;
}
*/
// if the arguments in the future could be passed in as int/long/float etc
// then it might make sense to use the above writeReal????() methods
// I've removed them for now.
char* CmdMessenger::sendCmd(int cmdId, char *msg, boolean reqAc,
char *replyBuff, int butSize, int timeout,
int retryCount)
{
int tryCount = 0;
pauseProcessing = true;
//*comms << cmdId << token[0] << msg << endl;
comms->print(cmdId);
comms->print(token[0]);
comms->print(msg);
if(print_newlines)
comms->println();
if (reqAc) {
do {
blockedTillReply(timeout);
//strcpy(replyBuff, buf;
} while( tryCount < retryCount);
}
pauseProcessing = false;
return NULL;
}<commit_msg>Comment about the command encoding. atoi() - its an arbitrary sized ASCII integer<commit_after>
//ADDED FOR COMPATIBILITY WITH WIRING
extern "C" {
#include <stdlib.h>
}
#include "CmdMessenger.h"
#include <Streaming.h>
//////////////////// Cmd Messenger imp ////////////////
CmdMessenger::CmdMessenger(Stream &ccomms)
{
comms = &ccomms;
init(' ',';');
}
CmdMessenger::CmdMessenger(Stream &ccomms, char field_separator)
{
comms = &ccomms;
init(field_separator,';');
}
CmdMessenger::CmdMessenger(Stream &ccomms, char field_separator, char cmd_separator)
{
comms = &ccomms;
init(field_separator,cmd_separator);
}
void CmdMessenger::attach(byte msgId, messengerCallbackFunction newFunction) {
if (msgId > 0 && msgId <= MAXCALLBACKS) // <= ? I think its ok ?
callbackList[msgId-1] = newFunction;
}
void CmdMessenger::discard_LF_CR()
{
discard_newlines = true;
}
void CmdMessenger::print_LF_CR()
{
print_newlines = true;
}
void CmdMessenger::init(char field_separator, char cmd_separator)
{
discard_newlines = false;
print_newlines = false;
callback = NULL;
token[0] = field_separator;
token[1] = '\0';
command_separator = cmd_separator;
bufferLength = MESSENGERBUFFERSIZE;
bufferLastIndex = MESSENGERBUFFERSIZE -1;
reset();
for (int i = 0; i < MAXCALLBACKS; i++)
callbackList[i] = NULL;
pauseProcessing = false;
}
void CmdMessenger::init()
{
for (int i = 0; i < MAXCALLBACKS; i++)
callbackList[i] = NULL;
pauseProcessing = false;
}
uint8_t CmdMessenger::process(int serialByte) {
messageState = 0;
if (serialByte > 0) {
if((char)serialByte == command_separator)
{
buffer[bufferIndex]=0;
if(bufferIndex > 0)
{
messageState = 1;
current = buffer;
}
reset();
}
else
{
buffer[bufferIndex]=serialByte;
bufferIndex++;
if (bufferIndex >= bufferLastIndex) reset();
if(discard_newlines)
if(((char)serialByte == '\n') || ((char)serialByte == '\r'))
reset();
}
}
if ( messageState == 1 ) {
handleMessage();
}
return messageState;
}
void CmdMessenger::handleMessage()
{
// If we didnt want to use ASCII integer...
// we would change the line below vv
int id = readInt();
//Serial << "ID+" << id << endl;
// Because readInt() can fail and return a 0 we can't
// start our array index at that number
if (id > 0 && id <= MAXCALLBACKS && callbackList[id-1] != NULL)
(*callbackList[id-1])();
else // Cmd not registered default callback
(*callback)();
}
void CmdMessenger::feedinSerialData()
{
while ( !pauseProcessing && comms->available( ) )
process(comms->read( ) );
}
// Taken from RougueMP3 library
int8_t CmdMessenger::_read_blocked(void)
{
// int8_t r;
while(!comms->available());
// while((r = this->_readf()) < 0); // this would be faster if we could guarantee that the _readf() function
// would return -1 if there was no byte read
return comms->read();
}
boolean CmdMessenger::blockedTillReply(int timeout)
{
unsigned long start = millis();
unsigned long time = start;
while(!comms->available() || (start - time) > timeout )
time = millis();
}
// Not sure if it will work for signed.. check it out
/*unsigned char *CmdMessenger::writeRealInt(int val, unsigned char buff[2])
{
buff[1] = (unsigned char)val;
buff[0] = (unsigned char)(val >> 8);
buff[2] = 0;
return buff;
}
char* CmdMessenger::writeRealLong(long val, char buff[4])
{
//buff[1] = (unsigned char)val;
//buff[0] = (unsigned char)(val >> 8);
return buff;
}
char* CmdMessenger::writeRealFloat(float val, char buff[4])
{
//buff[1] = (unsigned char)val;
//buff[0] = (unsigned char)(val >> 8);
return buff;
}
*/
// if the arguments in the future could be passed in as int/long/float etc
// then it might make sense to use the above writeReal????() methods
// I've removed them for now.
char* CmdMessenger::sendCmd(int cmdId, char *msg, boolean reqAc,
char *replyBuff, int butSize, int timeout,
int retryCount)
{
int tryCount = 0;
pauseProcessing = true;
//*comms << cmdId << token[0] << msg << endl;
comms->print(cmdId);
comms->print(token[0]);
comms->print(msg);
if(print_newlines)
comms->println();
if (reqAc) {
do {
blockedTillReply(timeout);
//strcpy(replyBuff, buf;
} while( tryCount < retryCount);
}
pauseProcessing = false;
return NULL;
}<|endoftext|>
|
<commit_before>// Natron
//
/* 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/. */
/*
*Created by Alexandre GAUTHIER-FOICHAT on 6/1/2012.
*contact: immarespond at gmail dot com
*
*/
#include "Image.h"
#include "Engine/Lut.h"
RectI Natron::Bitmap::minimalNonMarkedBbox(const RectI& roi) const
{
/*if we rendered everything we just append
a NULL box to indicate we rendered it all.*/
// if(!memchr(_map.get(),0,_rod.area())){
// ret.push_back(RectI());
// return ret;
// }
RectI bbox = roi;
//find bottom
for (int i = bbox.bottom(); i < bbox.top();++i) {
char* buf = &_map[(i-_rod.bottom())*_rod.width()];
if(!memchr(buf, 0, _rod.width())){
bbox.set_bottom(bbox.bottom()+1);
} else {
break;
}
}
//find top (will do zero iteration if the bbox is already empty)
for (int i = bbox.top()-1; i >= bbox.bottom();--i) {
char* buf = &_map[(i-_rod.bottom())*_rod.width()];
if (!memchr(buf, 0, _rod.width())) {
bbox.set_top(bbox.top()-1);
} else {
break;
}
}
// avoid making bbox.width() iterations for nothing
if (bbox.isNull()) {
return bbox;
}
//find left
for (int j = bbox.left(); j < bbox.right(); ++j) {
bool shouldStop = false;
for (int i = bbox.bottom(); i < bbox.top(); ++i) {
if (!_map[(i-_rod.bottom())*_rod.width() + (j-_rod.left())]) {
shouldStop = true;
break;
}
}
if (!shouldStop) {
bbox.set_left(bbox.left()+1);
} else {
break;
}
}
//find right
for (int j = bbox.right()-1; j >= bbox.left(); --j) {
bool shouldStop = false;
for (int i = bbox.bottom(); i < bbox.top(); ++i) {
if (!_map[(i-_rod.bottom())*_rod.width() + (j-_rod.left())]) {
shouldStop = true;
break;
}
}
if (!shouldStop) {
bbox.set_right(bbox.right()-1);
} else {
break;
}
}
return bbox;
}
std::list<RectI> Natron::Bitmap::minimalNonMarkedRects(const RectI& roi) const
{
/*for now a simple version that computes the bbox*/
std::list<RectI> ret;
RectI bbox = minimalNonMarkedBbox(roi);
if (bbox.isNull()) {
return ret; // return an empty rectangle list
}
// optimization by Fred, Jan 31, 2014
//
// Now that we have the smallest enclosing bounding box,
// let's try to find rectangles for the bottom, the top,
// the left and the right part.
// This happens quite often, for example when zooming out,
// the rectangles may be just A, B, C and D from the following
// drawing, where A, B, C, D are just zeroes, and X contains
// zeroes and ones.
//
// BBBBBBBBBBBBBB
// BBBBBBBBBBBBBB
// CXXXXXXXXXXDDD
// CXXXXXXXXXXDDD
// CXXXXXXXXXXDDD
// CXXXXXXXXXXDDD
// AAAAAAAAAAAAAA
// First, find if there's an "A" rectangle, and push it to the result
//find bottom
RectI bbox_sub = bbox;
bbox_sub.set_top(bbox.bottom());
for (int i = bbox.bottom(); i < bbox.top();++i) {
char* buf = &_map[(i-_rod.bottom())*_rod.width()];
if (!memchr(buf, 1, _rod.width())) {
bbox.set_bottom(bbox.bottom()+1);
bbox_sub.set_top(bbox.bottom());
} else {
break;
}
}
if (!bbox_sub.isNull()) { // empty boxes should not be pushed
ret.push_back(bbox_sub);
}
// Now, find the "B" rectangle
//find top
bbox_sub = bbox;
bbox_sub.set_bottom(bbox.bottom());
for (int i = bbox.top()-1; i >= bbox.bottom();--i) {
char* buf = &_map[(i-_rod.bottom())*_rod.width()];
if (!memchr(buf, 1, _rod.width())) {
bbox.set_top(bbox.top()-1);
bbox_sub.set_bottom(bbox.top());
} else {
break;
}
}
if (!bbox_sub.isNull()) { // empty boxes should not be pushed
ret.push_back(bbox_sub);
}
//find left
bbox_sub = bbox;
bbox_sub.set_right(bbox.left());
for (int j = bbox.left(); j < bbox.right(); ++j) {
bool shouldStop = false;
for (int i = bbox.bottom(); i < bbox.top(); ++i) {
if (_map[(i-_rod.bottom())*_rod.width()+(j-_rod.left())]) {
shouldStop = true;
break;
}
}
if (!shouldStop) {
bbox.set_left(bbox.left()+1);
bbox_sub.set_right(bbox.left());
} else {
break;
}
}
if (!bbox_sub.isNull()) { // empty boxes should not be pushed
ret.push_back(bbox_sub);
}
//find right
bbox_sub = bbox;
bbox_sub.set_left(bbox.right());
for (int j = bbox.right()-1; j >= bbox.left(); --j) {
bool shouldStop = false;
for (int i = bbox.bottom(); i < bbox.top(); ++i) {
if (_map[(i-_rod.bottom())*_rod.width()+(j-_rod.left())]) {
shouldStop = true;
break;
}
}
if (!shouldStop) {
bbox.set_right(bbox.right()-1);
bbox_sub.set_left(bbox.right());
} else {
break;
}
}
// get the bounding box of what's left (the X rectangle in the drawing above)
bbox = minimalNonMarkedBbox(bbox);
if (!bbox.isNull()) { // empty boxes should not be pushed
ret.push_back(bbox);
}
return ret;
}
void Natron::Bitmap::markForRendered(const RectI& roi){
for (int i = roi.bottom(); i < roi.top();++i) {
char* buf = &_map[(i-_rod.bottom())*_rod.width()];
memset(buf, 1, roi.width());
}
}
void Natron::Image::copy(const Natron::Image& other){
RectI intersection;
this->_params._rod.intersect(other._params._rod, &intersection);
if (intersection.isNull()) {
return;
}
const float* src = other.pixelAt(0, 0);
float* dst = pixelAt(0, 0);
memcpy(dst, src, intersection.area());
}
namespace Natron{
void debugImage(Natron::Image* img,const QString& filename){
const RectI& rod = img->getRoD();
QImage output(rod.width(),rod.height(),QImage::Format_ARGB32);
const Natron::Color::Lut* lut = Natron::Color::LutManager::sRGBLut();
lut->to_byte_packed(output.bits(), img->pixelAt(0, 0), rod, rod, rod,
Natron::Color::PACKING_RGBA,Natron::Color::PACKING_BGRA, true,false);
U64 hashKey = img->getHashKey();
QString hashKeyStr = QString::number(hashKey);
QString realFileName = filename.isEmpty() ? QString(hashKeyStr+".png") : filename;
output.save(realFileName);
}
}
<commit_msg>Natron::Bitmap::minimalNonMarkedRects: more comments<commit_after>// Natron
//
/* 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/. */
/*
*Created by Alexandre GAUTHIER-FOICHAT on 6/1/2012.
*contact: immarespond at gmail dot com
*
*/
#include "Image.h"
#include "Engine/Lut.h"
RectI Natron::Bitmap::minimalNonMarkedBbox(const RectI& roi) const
{
/*if we rendered everything we just append
a NULL box to indicate we rendered it all.*/
// if(!memchr(_map.get(),0,_rod.area())){
// ret.push_back(RectI());
// return ret;
// }
RectI bbox = roi;
//find bottom
for (int i = bbox.bottom(); i < bbox.top();++i) {
char* buf = &_map[(i-_rod.bottom())*_rod.width()];
if(!memchr(buf, 0, _rod.width())){
bbox.set_bottom(bbox.bottom()+1);
} else {
break;
}
}
//find top (will do zero iteration if the bbox is already empty)
for (int i = bbox.top()-1; i >= bbox.bottom();--i) {
char* buf = &_map[(i-_rod.bottom())*_rod.width()];
if (!memchr(buf, 0, _rod.width())) {
bbox.set_top(bbox.top()-1);
} else {
break;
}
}
// avoid making bbox.width() iterations for nothing
if (bbox.isNull()) {
return bbox;
}
//find left
for (int j = bbox.left(); j < bbox.right(); ++j) {
bool shouldStop = false;
for (int i = bbox.bottom(); i < bbox.top(); ++i) {
if (!_map[(i-_rod.bottom())*_rod.width() + (j-_rod.left())]) {
shouldStop = true;
break;
}
}
if (!shouldStop) {
bbox.set_left(bbox.left()+1);
} else {
break;
}
}
//find right
for (int j = bbox.right()-1; j >= bbox.left(); --j) {
bool shouldStop = false;
for (int i = bbox.bottom(); i < bbox.top(); ++i) {
if (!_map[(i-_rod.bottom())*_rod.width() + (j-_rod.left())]) {
shouldStop = true;
break;
}
}
if (!shouldStop) {
bbox.set_right(bbox.right()-1);
} else {
break;
}
}
return bbox;
}
std::list<RectI> Natron::Bitmap::minimalNonMarkedRects(const RectI& roi) const
{
/*for now a simple version that computes the bbox*/
std::list<RectI> ret;
RectI bbox = minimalNonMarkedBbox(roi);
if (bbox.isNull()) {
return ret; // return an empty rectangle list
}
// optimization by Fred, Jan 31, 2014
//
// Now that we have the smallest enclosing bounding box,
// let's try to find rectangles for the bottom, the top,
// the left and the right part.
// This happens quite often, for example when zooming out
// (in this case the area to compute is formed of A, B, C and D,
// and X is already rendered), or when panning (in this case the area
// is just two rectangles, e.g. A and C, and the rectangles B, D and
// X are already rendered).
// The rectangles A, B, C and D from the following drawing are just
// zeroes, and X contains zeroes and ones.
//
// BBBBBBBBBBBBBB
// BBBBBBBBBBBBBB
// CXXXXXXXXXXDDD
// CXXXXXXXXXXDDD
// CXXXXXXXXXXDDD
// CXXXXXXXXXXDDD
// AAAAAAAAAAAAAA
// First, find if there's an "A" rectangle, and push it to the result
//find bottom
RectI bbox_sub = bbox;
bbox_sub.set_top(bbox.bottom());
for (int i = bbox.bottom(); i < bbox.top();++i) {
char* buf = &_map[(i-_rod.bottom())*_rod.width()];
if (!memchr(buf, 1, _rod.width())) {
bbox.set_bottom(bbox.bottom()+1);
bbox_sub.set_top(bbox.bottom());
} else {
break;
}
}
if (!bbox_sub.isNull()) { // empty boxes should not be pushed
ret.push_back(bbox_sub);
}
// Now, find the "B" rectangle
//find top
bbox_sub = bbox;
bbox_sub.set_bottom(bbox.bottom());
for (int i = bbox.top()-1; i >= bbox.bottom();--i) {
char* buf = &_map[(i-_rod.bottom())*_rod.width()];
if (!memchr(buf, 1, _rod.width())) {
bbox.set_top(bbox.top()-1);
bbox_sub.set_bottom(bbox.top());
} else {
break;
}
}
if (!bbox_sub.isNull()) { // empty boxes should not be pushed
ret.push_back(bbox_sub);
}
//find left
bbox_sub = bbox;
bbox_sub.set_right(bbox.left());
for (int j = bbox.left(); j < bbox.right(); ++j) {
bool shouldStop = false;
for (int i = bbox.bottom(); i < bbox.top(); ++i) {
if (_map[(i-_rod.bottom())*_rod.width()+(j-_rod.left())]) {
shouldStop = true;
break;
}
}
if (!shouldStop) {
bbox.set_left(bbox.left()+1);
bbox_sub.set_right(bbox.left());
} else {
break;
}
}
if (!bbox_sub.isNull()) { // empty boxes should not be pushed
ret.push_back(bbox_sub);
}
//find right
bbox_sub = bbox;
bbox_sub.set_left(bbox.right());
for (int j = bbox.right()-1; j >= bbox.left(); --j) {
bool shouldStop = false;
for (int i = bbox.bottom(); i < bbox.top(); ++i) {
if (_map[(i-_rod.bottom())*_rod.width()+(j-_rod.left())]) {
shouldStop = true;
break;
}
}
if (!shouldStop) {
bbox.set_right(bbox.right()-1);
bbox_sub.set_left(bbox.right());
} else {
break;
}
}
// get the bounding box of what's left (the X rectangle in the drawing above)
bbox = minimalNonMarkedBbox(bbox);
if (!bbox.isNull()) { // empty boxes should not be pushed
ret.push_back(bbox);
}
return ret;
}
void Natron::Bitmap::markForRendered(const RectI& roi){
for (int i = roi.bottom(); i < roi.top();++i) {
char* buf = &_map[(i-_rod.bottom())*_rod.width()];
memset(buf, 1, roi.width());
}
}
void Natron::Image::copy(const Natron::Image& other){
RectI intersection;
this->_params._rod.intersect(other._params._rod, &intersection);
if (intersection.isNull()) {
return;
}
const float* src = other.pixelAt(0, 0);
float* dst = pixelAt(0, 0);
memcpy(dst, src, intersection.area());
}
namespace Natron{
void debugImage(Natron::Image* img,const QString& filename){
const RectI& rod = img->getRoD();
QImage output(rod.width(),rod.height(),QImage::Format_ARGB32);
const Natron::Color::Lut* lut = Natron::Color::LutManager::sRGBLut();
lut->to_byte_packed(output.bits(), img->pixelAt(0, 0), rod, rod, rod,
Natron::Color::PACKING_RGBA,Natron::Color::PACKING_BGRA, true,false);
U64 hashKey = img->getHashKey();
QString hashKeyStr = QString::number(hashKey);
QString realFileName = filename.isEmpty() ? QString(hashKeyStr+".png") : filename;
output.save(realFileName);
}
}
<|endoftext|>
|
<commit_before>#include "Cube.h"
#include <GL/glew.h>
#include <MathGeoLib/include/Math/float3.h>
#include <MathGeoLib/include/Math/MathFunc.h>
Cube::Cube() :
Primitive() {}
Cube::Cube(const float3& position, const Quat& rotation) :
Primitive(position, rotation) {}
Cube::Cube(const float3& position, const Quat& rotation, int textureId) : Primitive(position, rotation), _textureId(textureId)
{
}
Cube::Cube(const float3& position, const Quat& rotation, const float3& color) :
Primitive(position, rotation, color) {}
Cube::~Cube() {}
void Cube::Draw()
{
glPushMatrix();
glBindTexture(GL_TEXTURE_2D, _textureId);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);
glTranslatef(Position.x, Position.y, Position.z);
float3 axis = Rotation.Axis();
glRotatef(RadToDeg(Rotation.Angle()), axis.x, axis.y, axis.z);
glColor3f(Color.x, Color.y, Color.z);
glBegin(GL_TRIANGLES);
// a, b, c
glTexCoord2f(1.f, 1.f);
glVertex3f(1.f, 1.f, 0);
glTexCoord2f(0.f, 1.f);
glVertex3f(0.f, 1.f, 0.f);
glTexCoord2f(0.f, 0.f);
glVertex3f(0.f, 0.f, 0.f);
// c, d, a
glTexCoord2f(0.f, 0.f);
glVertex3f(0.f, 0.f, 0);
glTexCoord2f(1.f, 0.f);
glVertex3f(1.f, 0.f, 0.f);
glTexCoord2f(1.f, 1.f);
glVertex3f(1.f, 1.f, 0.f);
// a, d, e
glTexCoord2f(0.f, 1.f);
glVertex3f(1.f, 1.f, 0.f);
glTexCoord2f(0.f, 0.f);
glVertex3f(1.f, 0.f, 0.f);
glTexCoord2f(1.f, 0.f);
glVertex3f(1.f, 0.f, -1.f);
// e, f, a
glTexCoord2f(1.f, 0.f);
glVertex3f(1.f, 0.f, -1.f);
glTexCoord2f(1.f, 1.f);
glVertex3f(1.f, 1.f, -1.f);
glTexCoord2f(0.f, 1.f);
glVertex3f(1.f, 1.f, 0.f);
// a, f, g
glTexCoord2f(1.f, 0.f);
glVertex3f(1.f, 1.f, 0.f);
glTexCoord2f(1.f, 1.f);
glVertex3f(1.f, 1.f, -1.f);
glTexCoord2f(0.f, 1.f);
glVertex3f(0.f, 1.f, -1.f);
// g, b, a
glTexCoord2f(0.f, 1.f);
glVertex3f(0.f, 1.f, -1.f);
glTexCoord2f(0.f, 0.f);
glVertex3f(0.f, 1.f, 0.f);
glTexCoord2f(1.f, 0.f);
glVertex3f(1.f, 1.f, 0.f);
// g, f, e
glTexCoord2f(1.f, 1.f);
glVertex3f(0.f, 1.f, -1.f);
glTexCoord2f(0.f, 1.f);
glVertex3f(1.f, 1.f, -1.f);
glTexCoord2f(0.f, 0.f);
glVertex3f(1.f, 0.f, -1.f);
// e, h, g
glTexCoord2f(0.f, 0.f);
glVertex3f(1.f, 0.f, -1.f);
glTexCoord2f(1.f, 0.f);
glVertex3f(0.f, 0.f, -1.f);
glTexCoord2f(1.f, 1.f);
glVertex3f(0.f, 1.f, -1.f);
// g, h, c
glTexCoord2f(1.f, 1.f);
glVertex3f(0.f, 1.f, -1.f);
glTexCoord2f(1.f, 0.f);
glVertex3f(0.f, 0.f, -1.f);
glTexCoord2f(0.f, 0.f);
glVertex3f(0.f, 0.f, 0.f);
// c, b, g
glTexCoord2f(0.f, 0.f);
glVertex3f(0.f, 0.f, 0.f);
glTexCoord2f(0.f, 1.f);
glVertex3f(0.f, 1.f, 0.f);
glTexCoord2f(1.f, 1.f);
glVertex3f(0.f, 1.f, -1.f);
// h, e, d
glTexCoord2f(1.f, 1.f);
glVertex3f(0.f, 0.f, -1.f);
glTexCoord2f(0.f, 1.f);
glVertex3f(1.f, 0.f, -1.f);
glTexCoord2f(0.f, 0.f);
glVertex3f(1.f, 0.f, 0.f);
// d, c, h
glTexCoord2f(0.f, 0.f);
glVertex3f(1.f, 0.f, 0.f);
glTexCoord2f(1.f, 0.f);
glVertex3f(0.f, 0.f, 0.f);
glTexCoord2f(1.f, 1.f);
glVertex3f(0.f, 0.f, -1.f);
glEnd();
glBindTexture(GL_TEXTURE_2D, 0);
glPopMatrix();
}
<commit_msg>Fix model transparency<commit_after>#include "Cube.h"
#include <GL/glew.h>
#include <MathGeoLib/include/Math/float3.h>
#include <MathGeoLib/include/Math/MathFunc.h>
Cube::Cube() :
Primitive() {}
Cube::Cube(const float3& position, const Quat& rotation) :
Primitive(position, rotation) {}
Cube::Cube(const float3& position, const Quat& rotation, int textureId) : Primitive(position, rotation), _textureId(textureId)
{
}
Cube::Cube(const float3& position, const Quat& rotation, const float3& color) :
Primitive(position, rotation, color) {}
Cube::~Cube() {}
void Cube::Draw()
{
glPushMatrix();
glBindTexture(GL_TEXTURE_2D, _textureId);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);
glTranslatef(Position.x, Position.y, Position.z);
float3 axis = Rotation.Axis();
glRotatef(RadToDeg(Rotation.Angle()), axis.x, axis.y, axis.z);
glColor3f(Color.x, Color.y, Color.z);
glBegin(GL_TRIANGLES);
// a, b, c
glTexCoord2f(1.f, 1.f);
glVertex3f(1.f, 1.f, 0);
glTexCoord2f(0.f, 1.f);
glVertex3f(0.f, 1.f, 0.f);
glTexCoord2f(0.f, 0.f);
glVertex3f(0.f, 0.f, 0.f);
// c, d, a
glTexCoord2f(0.f, 0.f);
glVertex3f(0.f, 0.f, 0);
glTexCoord2f(1.f, 0.f);
glVertex3f(1.f, 0.f, 0.f);
glTexCoord2f(1.f, 1.f);
glVertex3f(1.f, 1.f, 0.f);
// a, d, e
glTexCoord2f(0.f, 1.f);
glVertex3f(1.f, 1.f, 0.f);
glTexCoord2f(0.f, 0.f);
glVertex3f(1.f, 0.f, 0.f);
glTexCoord2f(1.f, 0.f);
glVertex3f(1.f, 0.f, -1.f);
// e, f, a
glTexCoord2f(1.f, 0.f);
glVertex3f(1.f, 0.f, -1.f);
glTexCoord2f(1.f, 1.f);
glVertex3f(1.f, 1.f, -1.f);
glTexCoord2f(0.f, 1.f);
glVertex3f(1.f, 1.f, 0.f);
// a, f, g
glTexCoord2f(1.f, 0.f);
glVertex3f(1.f, 1.f, 0.f);
glTexCoord2f(1.f, 1.f);
glVertex3f(1.f, 1.f, -1.f);
glTexCoord2f(0.f, 1.f);
glVertex3f(0.f, 1.f, -1.f);
// g, b, a
glTexCoord2f(0.f, 1.f);
glVertex3f(0.f, 1.f, -1.f);
glTexCoord2f(0.f, 0.f);
glVertex3f(0.f, 1.f, 0.f);
glTexCoord2f(1.f, 0.f);
glVertex3f(1.f, 1.f, 0.f);
// g, f, e
glTexCoord2f(1.f, 1.f);
glVertex3f(0.f, 1.f, -1.f);
glTexCoord2f(0.f, 1.f);
glVertex3f(1.f, 1.f, -1.f);
glTexCoord2f(0.f, 0.f);
glVertex3f(1.f, 0.f, -1.f);
// e, h, g
glTexCoord2f(0.f, 0.f);
glVertex3f(1.f, 0.f, -1.f);
glTexCoord2f(1.f, 0.f);
glVertex3f(0.f, 0.f, -1.f);
glTexCoord2f(1.f, 1.f);
glVertex3f(0.f, 1.f, -1.f);
// g, h, c
glTexCoord2f(1.f, 1.f);
glVertex3f(0.f, 1.f, -1.f);
glTexCoord2f(1.f, 0.f);
glVertex3f(0.f, 0.f, -1.f);
glTexCoord2f(0.f, 0.f);
glVertex3f(0.f, 0.f, 0.f);
// c, b, g
glTexCoord2f(0.f, 0.f);
glVertex3f(0.f, 0.f, 0.f);
glTexCoord2f(0.f, 1.f);
glVertex3f(0.f, 1.f, 0.f);
glTexCoord2f(1.f, 1.f);
glVertex3f(0.f, 1.f, -1.f);
// h, e, d
glTexCoord2f(1.f, 1.f);
glVertex3f(0.f, 0.f, -1.f);
glTexCoord2f(0.f, 1.f);
glVertex3f(1.f, 0.f, -1.f);
glTexCoord2f(0.f, 0.f);
glVertex3f(1.f, 0.f, 0.f);
// d, c, h
glTexCoord2f(0.f, 0.f);
glVertex3f(1.f, 0.f, 0.f);
glTexCoord2f(1.f, 0.f);
glVertex3f(0.f, 0.f, 0.f);
glTexCoord2f(1.f, 1.f);
glVertex3f(0.f, 0.f, -1.f);
glEnd();
glBindTexture(GL_TEXTURE_2D, 0);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); // Always restore Texture Environment to GL_MODULATE
glPopMatrix();
}
<|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 "base/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/extension_webrequest_api.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/login/login_prompt.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/browser/renderer_host/render_view_host.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/public/browser/notification_registrar.h"
#include "content/public/browser/notification_service.h"
#include "net/base/mock_host_resolver.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebInputEvent.h"
namespace {
class CancelLoginDialog : public content::NotificationObserver {
public:
CancelLoginDialog() {
registrar_.Add(this,
chrome::NOTIFICATION_AUTH_NEEDED,
content::NotificationService::AllSources());
}
virtual ~CancelLoginDialog() {}
virtual void Observe(int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) {
LoginHandler* handler =
content::Details<LoginNotificationDetails>(details).ptr()->handler();
handler->CancelAuth();
}
private:
content::NotificationRegistrar registrar_;
DISALLOW_COPY_AND_ASSIGN(CancelLoginDialog);
};
} // namespace
class ExtensionWebRequestApiTest : public ExtensionApiTest {
public:
virtual void SetUpInProcessBrowserTestFixture() {
ExtensionApiTest::SetUpInProcessBrowserTestFixture();
host_resolver()->AddRule("*", "127.0.0.1");
ASSERT_TRUE(StartTestServer());
}
};
IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, WebRequestApi) {
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableExperimentalExtensionApis);
ASSERT_TRUE(RunExtensionSubtest("webrequest", "test_api.html")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, WebRequestSimple) {
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableExperimentalExtensionApis);
ASSERT_TRUE(RunExtensionSubtest("webrequest", "test_simple.html")) <<
message_;
}
// Broken, http://crbug.com/101651
IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, DISABLED_WebRequestComplex) {
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableExperimentalExtensionApis);
ASSERT_TRUE(RunExtensionSubtest("webrequest", "test_complex.html")) <<
message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, WebRequestAuthRequired) {
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableExperimentalExtensionApis);
CancelLoginDialog login_dialog_helper;
ASSERT_TRUE(RunExtensionSubtest("webrequest", "test_auth_required.html")) <<
message_;
}
// Hangs flakily: http://crbug.com/91715
IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest,
DISABLED_WebRequestBlocking) {
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableExperimentalExtensionApis);
ASSERT_TRUE(RunExtensionSubtest("webrequest", "test_blocking.html")) <<
message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, WebRequestNewTab) {
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableExperimentalExtensionApis);
// Wait for the extension to set itself up and return control to us.
ASSERT_TRUE(RunExtensionSubtest("webrequest", "test_newTab.html"))
<< message_;
TabContents* tab = browser()->GetSelectedTabContents();
ui_test_utils::WaitForLoadStop(tab);
ResultCatcher catcher;
ExtensionService* service = browser()->profile()->GetExtensionService();
const Extension* extension =
service->GetExtensionById(last_loaded_extension_id_, false);
GURL url = extension->GetResourceURL("newTab/a.html");
ui_test_utils::NavigateToURL(browser(), url);
// There's a link on a.html with target=_blank. Click on it to open it in a
// new tab.
WebKit::WebMouseEvent mouse_event;
mouse_event.type = WebKit::WebInputEvent::MouseDown;
mouse_event.button = WebKit::WebMouseEvent::ButtonLeft;
mouse_event.x = 7;
mouse_event.y = 7;
mouse_event.clickCount = 1;
tab->render_view_host()->ForwardMouseEvent(mouse_event);
mouse_event.type = WebKit::WebInputEvent::MouseUp;
tab->render_view_host()->ForwardMouseEvent(mouse_event);
ASSERT_TRUE(catcher.GetNextResult()) << catcher.message();
}
<commit_msg>Reenable ExtensionWebRequestApiTest.WebRequestComplex after bug 101651 is fixed<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 "base/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/extension_webrequest_api.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/login/login_prompt.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/browser/renderer_host/render_view_host.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/public/browser/notification_registrar.h"
#include "content/public/browser/notification_service.h"
#include "net/base/mock_host_resolver.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebInputEvent.h"
namespace {
class CancelLoginDialog : public content::NotificationObserver {
public:
CancelLoginDialog() {
registrar_.Add(this,
chrome::NOTIFICATION_AUTH_NEEDED,
content::NotificationService::AllSources());
}
virtual ~CancelLoginDialog() {}
virtual void Observe(int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) {
LoginHandler* handler =
content::Details<LoginNotificationDetails>(details).ptr()->handler();
handler->CancelAuth();
}
private:
content::NotificationRegistrar registrar_;
DISALLOW_COPY_AND_ASSIGN(CancelLoginDialog);
};
} // namespace
class ExtensionWebRequestApiTest : public ExtensionApiTest {
public:
virtual void SetUpInProcessBrowserTestFixture() {
ExtensionApiTest::SetUpInProcessBrowserTestFixture();
host_resolver()->AddRule("*", "127.0.0.1");
ASSERT_TRUE(StartTestServer());
}
};
IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, WebRequestApi) {
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableExperimentalExtensionApis);
ASSERT_TRUE(RunExtensionSubtest("webrequest", "test_api.html")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, WebRequestSimple) {
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableExperimentalExtensionApis);
ASSERT_TRUE(RunExtensionSubtest("webrequest", "test_simple.html")) <<
message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, WebRequestComplex) {
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableExperimentalExtensionApis);
ASSERT_TRUE(RunExtensionSubtest("webrequest", "test_complex.html")) <<
message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, WebRequestAuthRequired) {
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableExperimentalExtensionApis);
CancelLoginDialog login_dialog_helper;
ASSERT_TRUE(RunExtensionSubtest("webrequest", "test_auth_required.html")) <<
message_;
}
// Hangs flakily: http://crbug.com/91715
IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest,
DISABLED_WebRequestBlocking) {
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableExperimentalExtensionApis);
ASSERT_TRUE(RunExtensionSubtest("webrequest", "test_blocking.html")) <<
message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, WebRequestNewTab) {
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableExperimentalExtensionApis);
// Wait for the extension to set itself up and return control to us.
ASSERT_TRUE(RunExtensionSubtest("webrequest", "test_newTab.html"))
<< message_;
TabContents* tab = browser()->GetSelectedTabContents();
ui_test_utils::WaitForLoadStop(tab);
ResultCatcher catcher;
ExtensionService* service = browser()->profile()->GetExtensionService();
const Extension* extension =
service->GetExtensionById(last_loaded_extension_id_, false);
GURL url = extension->GetResourceURL("newTab/a.html");
ui_test_utils::NavigateToURL(browser(), url);
// There's a link on a.html with target=_blank. Click on it to open it in a
// new tab.
WebKit::WebMouseEvent mouse_event;
mouse_event.type = WebKit::WebInputEvent::MouseDown;
mouse_event.button = WebKit::WebMouseEvent::ButtonLeft;
mouse_event.x = 7;
mouse_event.y = 7;
mouse_event.clickCount = 1;
tab->render_view_host()->ForwardMouseEvent(mouse_event);
mouse_event.type = WebKit::WebInputEvent::MouseUp;
tab->render_view_host()->ForwardMouseEvent(mouse_event);
ASSERT_TRUE(catcher.GetNextResult()) << catcher.message();
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2009 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/extensions/sandboxed_extension_unpacker.h"
#include <set>
#include "base/crypto/signature_verifier.h"
#include "base/file_util.h"
#include "base/gfx/png_encoder.h"
#include "base/message_loop.h"
#include "base/scoped_handle.h"
#include "base/task.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/renderer_host/resource_dispatcher_host.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/extensions/extension_constants.h"
#include "chrome/common/extensions/extension_unpacker.h"
#include "chrome/common/json_value_serializer.h"
#include "net/base/base64.h"
#include "third_party/skia/include/core/SkBitmap.h"
const char SandboxedExtensionUnpacker::kExtensionHeaderMagic[] = "Cr24";
SandboxedExtensionUnpacker::SandboxedExtensionUnpacker(
const FilePath& crx_path, ResourceDispatcherHost* rdh,
SandboxedExtensionUnpackerClient* client)
: crx_path_(crx_path), file_loop_(NULL), rdh_(rdh), client_(client),
got_response_(false) {
}
void SandboxedExtensionUnpacker::Start() {
// We assume that we are started on the thread that the client wants us to do
// file IO on.
file_loop_ = MessageLoop::current();
// Create a temporary directory to work in.
if (!temp_dir_.CreateUniqueTempDir()) {
ReportFailure("Could not create temporary directory.");
return;
}
// Initialize the path that will eventually contain the unpacked extension.
extension_root_ = temp_dir_.path().AppendASCII("TEMP_INSTALL");
// Extract the public key and validate the package.
if (!ValidateSignature())
return; // ValidateSignature() already reported the error.
// Copy the crx file into our working directory.
FilePath temp_crx_path = temp_dir_.path().Append(crx_path_.BaseName());
if (!file_util::CopyFile(crx_path_, temp_crx_path)) {
ReportFailure("Failed to copy extension file to temporary directory.");
return;
}
// If we are supposed to use a subprocess, copy the crx to the temp directory
// and kick off the subprocess.
if (rdh_) {
ChromeThread::GetMessageLoop(ChromeThread::IO)->PostTask(FROM_HERE,
NewRunnableMethod(this,
&SandboxedExtensionUnpacker::StartProcessOnIOThread,
temp_crx_path));
} else {
// Otherwise, unpack the extension in this process.
ExtensionUnpacker unpacker(temp_crx_path);
if (unpacker.Run() && unpacker.DumpImagesToFile())
OnUnpackExtensionSucceeded(*unpacker.parsed_manifest());
else
OnUnpackExtensionFailed(unpacker.error_message());
}
}
void SandboxedExtensionUnpacker::StartProcessOnIOThread(
const FilePath& temp_crx_path) {
UtilityProcessHost* host = new UtilityProcessHost(rdh_, this, file_loop_);
host->StartExtensionUnpacker(temp_crx_path);
}
void SandboxedExtensionUnpacker::OnUnpackExtensionSucceeded(
const DictionaryValue& manifest) {
DCHECK(file_loop_ == MessageLoop::current());
got_response_ = true;
ExtensionUnpacker::DecodedImages images;
if (!ExtensionUnpacker::ReadImagesFromFile(temp_dir_.path(), &images)) {
ReportFailure("Couldn't read image data from disk.");
return;
}
// Add the public key extracted earlier to the parsed manifest and overwrite
// the original manifest. We do this to ensure the manifest doesn't contain an
// exploitable bug that could be used to compromise the browser.
scoped_ptr<DictionaryValue> final_manifest(
static_cast<DictionaryValue*>(manifest.DeepCopy()));
final_manifest->SetString(extension_manifest_keys::kPublicKey, public_key_);
std::string manifest_json;
JSONStringValueSerializer serializer(&manifest_json);
serializer.set_pretty_print(true);
if (!serializer.Serialize(*final_manifest)) {
ReportFailure("Error serializing manifest.json.");
return;
}
FilePath manifest_path =
extension_root_.AppendASCII(Extension::kManifestFilename);
if (!file_util::WriteFile(manifest_path,
manifest_json.data(), manifest_json.size())) {
ReportFailure("Error saving manifest.json.");
return;
}
// Delete any images that may be used by the browser. We're going to write
// out our own versions of the parsed images, and we want to make sure the
// originals are gone for good.
extension_.reset(new Extension);
std::string manifest_error;
// Update the path to refer to the temporary location. We do this because
// clients may want to use resources inside the extension before it is
// installed and they need the correct path. For example, the install UI shows
// one of the icons from the extension.
extension_->set_path(extension_root_);
if (!extension_->InitFromValue(*final_manifest, true, // require id
&manifest_error)) {
ReportFailure(std::string("Manifest is invalid: ") +
manifest_error);
return;
}
std::set<FilePath> image_paths = extension_->GetBrowserImages();
if (image_paths.size() != images.size()) {
ReportFailure("Decoded images don't match what's in the manifest.");
return;
}
for (std::set<FilePath>::iterator it = image_paths.begin();
it != image_paths.end(); ++it) {
if (!file_util::Delete(extension_root_.Append(*it), false)) {
ReportFailure("Error removing old image file.");
return;
}
}
// Write our parsed images back to disk as well.
for (size_t i = 0; i < images.size(); ++i) {
const SkBitmap& image = images[i].a;
FilePath path = extension_root_.Append(images[i].b);
std::vector<unsigned char> image_data;
// TODO(mpcomplete): It's lame that we're encoding all images as PNG, even
// though they may originally be .jpg, etc. Figure something out.
// http://code.google.com/p/chromium/issues/detail?id=12459
if (!PNGEncoder::EncodeBGRASkBitmap(image, false, &image_data)) {
ReportFailure("Error re-encoding theme image.");
return;
}
// Note: we're overwriting existing files that the utility process wrote,
// so we can be sure the directory exists.
const char* image_data_ptr = reinterpret_cast<const char*>(&image_data[0]);
if (!file_util::WriteFile(path, image_data_ptr, image_data.size())) {
ReportFailure("Error saving theme image.");
return;
}
}
ReportSuccess();
}
void SandboxedExtensionUnpacker::OnUnpackExtensionFailed(
const std::string& error) {
DCHECK(file_loop_ == MessageLoop::current());
got_response_ = true;
ReportFailure(error);
}
void SandboxedExtensionUnpacker::OnProcessCrashed() {
// Don't report crashes if they happen after we got a response.
if (got_response_)
return;
ReportFailure("Utility process crashed while trying to install.");
}
bool SandboxedExtensionUnpacker::ValidateSignature() {
ScopedStdioHandle file(file_util::OpenFile(crx_path_, "rb"));
if (!file.get()) {
ReportFailure("Could not open crx file for reading");
return false;
}
// Read and verify the header.
ExtensionHeader header;
size_t len;
// TODO(erikkay): Yuck. I'm not a big fan of this kind of code, but it
// appears that we don't have any endian/alignment aware serialization
// code in the code base. So for now, this assumes that we're running
// on a little endian machine with 4 byte alignment.
len = fread(&header, 1, sizeof(ExtensionHeader),
file.get());
if (len < sizeof(ExtensionHeader)) {
ReportFailure("Invalid crx header");
return false;
}
if (strncmp(kExtensionHeaderMagic, header.magic,
sizeof(header.magic))) {
ReportFailure("Bad magic number");
return false;
}
if (header.version != kCurrentVersion) {
ReportFailure("Bad version number");
return false;
}
if (header.key_size > kMaxPublicKeySize ||
header.signature_size > kMaxSignatureSize) {
ReportFailure("Excessively large key or signature");
return false;
}
std::vector<uint8> key;
key.resize(header.key_size);
len = fread(&key.front(), sizeof(uint8), header.key_size, file.get());
if (len < header.key_size) {
ReportFailure("Invalid public key");
return false;
}
std::vector<uint8> signature;
signature.resize(header.signature_size);
len = fread(&signature.front(), sizeof(uint8), header.signature_size,
file.get());
if (len < header.signature_size) {
ReportFailure("Invalid signature");
return false;
}
// Note: this structure is an ASN.1 which encodes the algorithm used
// with its parameters. This is defined in PKCS #1 v2.1 (RFC 3447).
// It is encoding: { OID sha1WithRSAEncryption PARAMETERS NULL }
// TODO(aa): This needs to be factored away someplace common.
const uint8 signature_algorithm[15] = {
0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86,
0xf7, 0x0d, 0x01, 0x01, 0x05, 0x05, 0x00
};
base::SignatureVerifier verifier;
if (!verifier.VerifyInit(signature_algorithm,
sizeof(signature_algorithm),
&signature.front(),
signature.size(),
&key.front(),
key.size())) {
ReportFailure("Signature verification initialization failed. "
"This is most likely caused by a public key in "
"the wrong format (should encode algorithm).");
return false;
}
unsigned char buf[1 << 12];
while ((len = fread(buf, 1, sizeof(buf), file.get())) > 0)
verifier.VerifyUpdate(buf, len);
if (!verifier.VerifyFinal()) {
ReportFailure("Signature verification failed");
return false;
}
net::Base64Encode(std::string(reinterpret_cast<char*>(&key.front()),
key.size()), &public_key_);
return true;
}
void SandboxedExtensionUnpacker::ReportFailure(const std::string& error) {
client_->OnUnpackFailure(error);
}
void SandboxedExtensionUnpacker::ReportSuccess() {
// Client takes ownership of temporary directory and extension.
client_->OnUnpackSuccess(temp_dir_.Take(), extension_root_,
extension_.release());
}
<commit_msg>Unpack extensions in-process in --single-process mode.<commit_after>// Copyright (c) 2009 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/extensions/sandboxed_extension_unpacker.h"
#include <set>
#include "base/crypto/signature_verifier.h"
#include "base/file_util.h"
#include "base/gfx/png_encoder.h"
#include "base/message_loop.h"
#include "base/scoped_handle.h"
#include "base/task.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/renderer_host/resource_dispatcher_host.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/extensions/extension_constants.h"
#include "chrome/common/extensions/extension_unpacker.h"
#include "chrome/common/json_value_serializer.h"
#include "net/base/base64.h"
#include "third_party/skia/include/core/SkBitmap.h"
const char SandboxedExtensionUnpacker::kExtensionHeaderMagic[] = "Cr24";
SandboxedExtensionUnpacker::SandboxedExtensionUnpacker(
const FilePath& crx_path, ResourceDispatcherHost* rdh,
SandboxedExtensionUnpackerClient* client)
: crx_path_(crx_path), file_loop_(NULL), rdh_(rdh), client_(client),
got_response_(false) {
}
void SandboxedExtensionUnpacker::Start() {
// We assume that we are started on the thread that the client wants us to do
// file IO on.
file_loop_ = MessageLoop::current();
// Create a temporary directory to work in.
if (!temp_dir_.CreateUniqueTempDir()) {
ReportFailure("Could not create temporary directory.");
return;
}
// Initialize the path that will eventually contain the unpacked extension.
extension_root_ = temp_dir_.path().AppendASCII("TEMP_INSTALL");
// Extract the public key and validate the package.
if (!ValidateSignature())
return; // ValidateSignature() already reported the error.
// Copy the crx file into our working directory.
FilePath temp_crx_path = temp_dir_.path().Append(crx_path_.BaseName());
if (!file_util::CopyFile(crx_path_, temp_crx_path)) {
ReportFailure("Failed to copy extension file to temporary directory.");
return;
}
// If we are supposed to use a subprocess, copy the crx to the temp directory
// and kick off the subprocess.
if (rdh_ &&
!CommandLine::ForCurrentProcess()->HasSwitch(switches::kSingleProcess)) {
ChromeThread::GetMessageLoop(ChromeThread::IO)->PostTask(FROM_HERE,
NewRunnableMethod(this,
&SandboxedExtensionUnpacker::StartProcessOnIOThread,
temp_crx_path));
} else {
// Otherwise, unpack the extension in this process.
ExtensionUnpacker unpacker(temp_crx_path);
if (unpacker.Run() && unpacker.DumpImagesToFile())
OnUnpackExtensionSucceeded(*unpacker.parsed_manifest());
else
OnUnpackExtensionFailed(unpacker.error_message());
}
}
void SandboxedExtensionUnpacker::StartProcessOnIOThread(
const FilePath& temp_crx_path) {
UtilityProcessHost* host = new UtilityProcessHost(rdh_, this, file_loop_);
host->StartExtensionUnpacker(temp_crx_path);
}
void SandboxedExtensionUnpacker::OnUnpackExtensionSucceeded(
const DictionaryValue& manifest) {
DCHECK(file_loop_ == MessageLoop::current());
got_response_ = true;
ExtensionUnpacker::DecodedImages images;
if (!ExtensionUnpacker::ReadImagesFromFile(temp_dir_.path(), &images)) {
ReportFailure("Couldn't read image data from disk.");
return;
}
// Add the public key extracted earlier to the parsed manifest and overwrite
// the original manifest. We do this to ensure the manifest doesn't contain an
// exploitable bug that could be used to compromise the browser.
scoped_ptr<DictionaryValue> final_manifest(
static_cast<DictionaryValue*>(manifest.DeepCopy()));
final_manifest->SetString(extension_manifest_keys::kPublicKey, public_key_);
std::string manifest_json;
JSONStringValueSerializer serializer(&manifest_json);
serializer.set_pretty_print(true);
if (!serializer.Serialize(*final_manifest)) {
ReportFailure("Error serializing manifest.json.");
return;
}
FilePath manifest_path =
extension_root_.AppendASCII(Extension::kManifestFilename);
if (!file_util::WriteFile(manifest_path,
manifest_json.data(), manifest_json.size())) {
ReportFailure("Error saving manifest.json.");
return;
}
// Delete any images that may be used by the browser. We're going to write
// out our own versions of the parsed images, and we want to make sure the
// originals are gone for good.
extension_.reset(new Extension);
std::string manifest_error;
// Update the path to refer to the temporary location. We do this because
// clients may want to use resources inside the extension before it is
// installed and they need the correct path. For example, the install UI shows
// one of the icons from the extension.
extension_->set_path(extension_root_);
if (!extension_->InitFromValue(*final_manifest, true, // require id
&manifest_error)) {
ReportFailure(std::string("Manifest is invalid: ") +
manifest_error);
return;
}
std::set<FilePath> image_paths = extension_->GetBrowserImages();
if (image_paths.size() != images.size()) {
ReportFailure("Decoded images don't match what's in the manifest.");
return;
}
for (std::set<FilePath>::iterator it = image_paths.begin();
it != image_paths.end(); ++it) {
if (!file_util::Delete(extension_root_.Append(*it), false)) {
ReportFailure("Error removing old image file.");
return;
}
}
// Write our parsed images back to disk as well.
for (size_t i = 0; i < images.size(); ++i) {
const SkBitmap& image = images[i].a;
FilePath path = extension_root_.Append(images[i].b);
std::vector<unsigned char> image_data;
// TODO(mpcomplete): It's lame that we're encoding all images as PNG, even
// though they may originally be .jpg, etc. Figure something out.
// http://code.google.com/p/chromium/issues/detail?id=12459
if (!PNGEncoder::EncodeBGRASkBitmap(image, false, &image_data)) {
ReportFailure("Error re-encoding theme image.");
return;
}
// Note: we're overwriting existing files that the utility process wrote,
// so we can be sure the directory exists.
const char* image_data_ptr = reinterpret_cast<const char*>(&image_data[0]);
if (!file_util::WriteFile(path, image_data_ptr, image_data.size())) {
ReportFailure("Error saving theme image.");
return;
}
}
ReportSuccess();
}
void SandboxedExtensionUnpacker::OnUnpackExtensionFailed(
const std::string& error) {
DCHECK(file_loop_ == MessageLoop::current());
got_response_ = true;
ReportFailure(error);
}
void SandboxedExtensionUnpacker::OnProcessCrashed() {
// Don't report crashes if they happen after we got a response.
if (got_response_)
return;
ReportFailure("Utility process crashed while trying to install.");
}
bool SandboxedExtensionUnpacker::ValidateSignature() {
ScopedStdioHandle file(file_util::OpenFile(crx_path_, "rb"));
if (!file.get()) {
ReportFailure("Could not open crx file for reading");
return false;
}
// Read and verify the header.
ExtensionHeader header;
size_t len;
// TODO(erikkay): Yuck. I'm not a big fan of this kind of code, but it
// appears that we don't have any endian/alignment aware serialization
// code in the code base. So for now, this assumes that we're running
// on a little endian machine with 4 byte alignment.
len = fread(&header, 1, sizeof(ExtensionHeader),
file.get());
if (len < sizeof(ExtensionHeader)) {
ReportFailure("Invalid crx header");
return false;
}
if (strncmp(kExtensionHeaderMagic, header.magic,
sizeof(header.magic))) {
ReportFailure("Bad magic number");
return false;
}
if (header.version != kCurrentVersion) {
ReportFailure("Bad version number");
return false;
}
if (header.key_size > kMaxPublicKeySize ||
header.signature_size > kMaxSignatureSize) {
ReportFailure("Excessively large key or signature");
return false;
}
std::vector<uint8> key;
key.resize(header.key_size);
len = fread(&key.front(), sizeof(uint8), header.key_size, file.get());
if (len < header.key_size) {
ReportFailure("Invalid public key");
return false;
}
std::vector<uint8> signature;
signature.resize(header.signature_size);
len = fread(&signature.front(), sizeof(uint8), header.signature_size,
file.get());
if (len < header.signature_size) {
ReportFailure("Invalid signature");
return false;
}
// Note: this structure is an ASN.1 which encodes the algorithm used
// with its parameters. This is defined in PKCS #1 v2.1 (RFC 3447).
// It is encoding: { OID sha1WithRSAEncryption PARAMETERS NULL }
// TODO(aa): This needs to be factored away someplace common.
const uint8 signature_algorithm[15] = {
0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86,
0xf7, 0x0d, 0x01, 0x01, 0x05, 0x05, 0x00
};
base::SignatureVerifier verifier;
if (!verifier.VerifyInit(signature_algorithm,
sizeof(signature_algorithm),
&signature.front(),
signature.size(),
&key.front(),
key.size())) {
ReportFailure("Signature verification initialization failed. "
"This is most likely caused by a public key in "
"the wrong format (should encode algorithm).");
return false;
}
unsigned char buf[1 << 12];
while ((len = fread(buf, 1, sizeof(buf), file.get())) > 0)
verifier.VerifyUpdate(buf, len);
if (!verifier.VerifyFinal()) {
ReportFailure("Signature verification failed");
return false;
}
net::Base64Encode(std::string(reinterpret_cast<char*>(&key.front()),
key.size()), &public_key_);
return true;
}
void SandboxedExtensionUnpacker::ReportFailure(const std::string& error) {
client_->OnUnpackFailure(error);
}
void SandboxedExtensionUnpacker::ReportSuccess() {
// Client takes ownership of temporary directory and extension.
client_->OnUnpackSuccess(temp_dir_.Take(), extension_root_,
extension_.release());
}
<|endoftext|>
|
<commit_before> /*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: NPreparedStatement.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-08 05:51:42 $
*
* 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 <stdio.h>
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _CONNECTIVITY_EVOAB_PREPAREDSTATEMENT_HXX_
#include "NPreparedStatement.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_DATATYPE_HPP_
#include <com/sun/star/sdbc/DataType.hpp>
#endif
#ifndef _CPPUHELPER_TYPEPROVIDER_HXX_
#include <cppuhelper/typeprovider.hxx>
#endif
#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif
#ifndef _CONNECTIVITY_PROPERTYIDS_HXX_
#include "propertyids.hxx"
#endif
using namespace connectivity::evoab;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::beans;
using namespace com::sun::star::sdbc;
using namespace com::sun::star::container;
using namespace com::sun::star::io;
using namespace com::sun::star::util;
IMPLEMENT_SERVICE_INFO(OEvoabPreparedStatement,"com.sun.star.sdbcx.evoab.PreparedStatement","com.sun.star.sdbc.PreparedStatement");
OEvoabPreparedStatement::OEvoabPreparedStatement( OEvoabConnection* _pConnection, const ::rtl::OUString& sql)
:OStatement_BASE2(_pConnection)
,m_bPrepared(sal_False)
,m_sSqlStatement(sql)
,m_nNumParams(0)
{
}
// -----------------------------------------------------------------------------
OEvoabPreparedStatement::~OEvoabPreparedStatement()
{
}
// -----------------------------------------------------------------------------
void SAL_CALL OEvoabPreparedStatement::acquire() throw()
{
OStatement_BASE2::acquire();
}
// -----------------------------------------------------------------------------
void SAL_CALL OEvoabPreparedStatement::release() throw()
{
OStatement_BASE2::release();
}
// -----------------------------------------------------------------------------
Any SAL_CALL OEvoabPreparedStatement::queryInterface( const Type & rType ) throw(RuntimeException)
{
Any aRet = OStatement_BASE2::queryInterface(rType);
if(!aRet.hasValue())
aRet = OPreparedStatement_BASE::queryInterface(rType);
return aRet;
}
// -------------------------------------------------------------------------
::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL OEvoabPreparedStatement::getTypes( ) throw(::com::sun::star::uno::RuntimeException)
{
return ::comphelper::concatSequences(OPreparedStatement_BASE::getTypes(),OStatement_BASE2::getTypes());
}
// -------------------------------------------------------------------------
Reference< XResultSetMetaData > SAL_CALL OEvoabPreparedStatement::getMetaData( ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OStatement_BASE::rBHelper.bDisposed);
if(!m_xMetaData.is())
m_xMetaData = new OEvoabResultSetMetaData(m_pConnection->getCurrentTableName());
return m_xMetaData;
}
// -------------------------------------------------------------------------
void SAL_CALL OEvoabPreparedStatement::close( ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OStatement_BASE::rBHelper.bDisposed);
// Reset last warning message
try {
clearWarnings ();
OStatement_BASE2::close();
}
catch (SQLException &) {
// If we get an error, ignore
}
// Remove this Statement object from the Connection object's
// list
}
// -------------------------------------------------------------------------
sal_Bool SAL_CALL OEvoabPreparedStatement::execute( ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OStatement_BASE::rBHelper.bDisposed);
Reference< XResultSet> xRS = OStatement_Base::executeQuery( m_sSqlStatement );
// same as in statement with the difference that this statement also can contain parameter
return xRS.is();
}
// -------------------------------------------------------------------------
sal_Int32 SAL_CALL OEvoabPreparedStatement::executeUpdate( ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OStatement_BASE::rBHelper.bDisposed);
// same as in statement with the difference that this statement also can contain parameter
return 0;
}
// -------------------------------------------------------------------------
void SAL_CALL OEvoabPreparedStatement::setString( sal_Int32 parameterIndex, const ::rtl::OUString& x ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OStatement_BASE::rBHelper.bDisposed);
}
// -------------------------------------------------------------------------
Reference< XConnection > SAL_CALL OEvoabPreparedStatement::getConnection( ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OStatement_BASE::rBHelper.bDisposed);
return (Reference< XConnection >)m_pConnection;
}
// -------------------------------------------------------------------------
Reference< XResultSet > SAL_CALL OEvoabPreparedStatement::executeQuery( ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OStatement_BASE::rBHelper.bDisposed);
Reference< XResultSet > rs = OStatement_Base::executeQuery( m_sSqlStatement );
return rs;
}
// -------------------------------------------------------------------------
void SAL_CALL OEvoabPreparedStatement::setBoolean( sal_Int32 parameterIndex, sal_Bool x ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OStatement_BASE::rBHelper.bDisposed);
}
// -------------------------------------------------------------------------
void SAL_CALL OEvoabPreparedStatement::setByte( sal_Int32 parameterIndex, sal_Int8 x ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OStatement_BASE::rBHelper.bDisposed);
}
// -------------------------------------------------------------------------
void SAL_CALL OEvoabPreparedStatement::setDate( sal_Int32 parameterIndex, const Date& aData ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OStatement_BASE::rBHelper.bDisposed);
}
// -------------------------------------------------------------------------
void SAL_CALL OEvoabPreparedStatement::setTime( sal_Int32 parameterIndex, const Time& aVal ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OStatement_BASE::rBHelper.bDisposed);
}
// -------------------------------------------------------------------------
void SAL_CALL OEvoabPreparedStatement::setTimestamp( sal_Int32 parameterIndex, const DateTime& aVal ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OStatement_BASE::rBHelper.bDisposed);
}
// -------------------------------------------------------------------------
void SAL_CALL OEvoabPreparedStatement::setDouble( sal_Int32 parameterIndex, double x ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OStatement_BASE::rBHelper.bDisposed);
}
// -------------------------------------------------------------------------
void SAL_CALL OEvoabPreparedStatement::setFloat( sal_Int32 parameterIndex, float x ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OStatement_BASE::rBHelper.bDisposed);
}
// -------------------------------------------------------------------------
void SAL_CALL OEvoabPreparedStatement::setInt( sal_Int32 parameterIndex, sal_Int32 x ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OStatement_BASE::rBHelper.bDisposed);
}
// -------------------------------------------------------------------------
void SAL_CALL OEvoabPreparedStatement::setLong( sal_Int32 parameterIndex, sal_Int64 aVal ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OStatement_BASE::rBHelper.bDisposed);
}
// -------------------------------------------------------------------------
void SAL_CALL OEvoabPreparedStatement::setNull( sal_Int32 parameterIndex, sal_Int32 sqlType ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OStatement_BASE::rBHelper.bDisposed);
}
// -------------------------------------------------------------------------
void SAL_CALL OEvoabPreparedStatement::setClob( sal_Int32 parameterIndex, const Reference< XClob >& x ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OStatement_BASE::rBHelper.bDisposed);
}
// -------------------------------------------------------------------------
void SAL_CALL OEvoabPreparedStatement::setBlob( sal_Int32 parameterIndex, const Reference< XBlob >& x ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OStatement_BASE::rBHelper.bDisposed);
}
// -------------------------------------------------------------------------
void SAL_CALL OEvoabPreparedStatement::setArray( sal_Int32 parameterIndex, const Reference< XArray >& x ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OStatement_BASE::rBHelper.bDisposed);
}
// -------------------------------------------------------------------------
void SAL_CALL OEvoabPreparedStatement::setRef( sal_Int32 parameterIndex, const Reference< XRef >& x ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OStatement_BASE::rBHelper.bDisposed);
}
// -------------------------------------------------------------------------
void SAL_CALL OEvoabPreparedStatement::setObjectWithInfo( sal_Int32 parameterIndex, const Any& x, sal_Int32 sqlType, sal_Int32 scale ) throw(SQLException, RuntimeException)
{
checkDisposed(OStatement_BASE::rBHelper.bDisposed);
::osl::MutexGuard aGuard( m_aMutex );
}
// -------------------------------------------------------------------------
void SAL_CALL OEvoabPreparedStatement::setObjectNull( sal_Int32 parameterIndex, sal_Int32 sqlType, const ::rtl::OUString& typeName ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OStatement_BASE::rBHelper.bDisposed);
}
// -------------------------------------------------------------------------
void SAL_CALL OEvoabPreparedStatement::setObject( sal_Int32 parameterIndex, const Any& x ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OStatement_BASE::rBHelper.bDisposed);
}
// -------------------------------------------------------------------------
void SAL_CALL OEvoabPreparedStatement::setShort( sal_Int32 parameterIndex, sal_Int16 x ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OStatement_BASE::rBHelper.bDisposed);
}
// -------------------------------------------------------------------------
void SAL_CALL OEvoabPreparedStatement::setBytes( sal_Int32 parameterIndex, const Sequence< sal_Int8 >& x ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OStatement_BASE::rBHelper.bDisposed);
}
// -------------------------------------------------------------------------
void SAL_CALL OEvoabPreparedStatement::setCharacterStream( sal_Int32 parameterIndex, const Reference< ::com::sun::star::io::XInputStream >& x, sal_Int32 length ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OStatement_BASE::rBHelper.bDisposed);
}
// -------------------------------------------------------------------------
void SAL_CALL OEvoabPreparedStatement::setBinaryStream( sal_Int32 parameterIndex, const Reference< ::com::sun::star::io::XInputStream >& x, sal_Int32 length ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OStatement_BASE::rBHelper.bDisposed);
}
// -------------------------------------------------------------------------
void SAL_CALL OEvoabPreparedStatement::clearParameters( ) throw(SQLException, RuntimeException)
{
}
// -------------------------------------------------------------------------
void OEvoabPreparedStatement::setFastPropertyValue_NoBroadcast(sal_Int32 nHandle,const Any& rValue) throw (Exception)
{
switch(nHandle)
{
case PROPERTY_ID_RESULTSETCONCURRENCY:
break;
case PROPERTY_ID_RESULTSETTYPE:
break;
case PROPERTY_ID_FETCHDIRECTION:
break;
case PROPERTY_ID_USEBOOKMARKS:
break;
default:
OStatement_Base::setFastPropertyValue_NoBroadcast(nHandle,rValue);
}
}
// -----------------------------------------------------------------------------
void OEvoabPreparedStatement::checkParameterIndex(sal_Int32 _parameterIndex)
{
if( !_parameterIndex || _parameterIndex > m_nNumParams)
throw SQLException();
}
// -----------------------------------------------------------------------------
::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > SAL_CALL OEvoabPreparedStatement::getResultSet( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)
{
return NULL;
}
// -----------------------------------------------------------------------------
sal_Int32 SAL_CALL OEvoabPreparedStatement::getUpdateCount( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)
{
return 0;
}
// -----------------------------------------------------------------------------
sal_Bool SAL_CALL OEvoabPreparedStatement::getMoreResults( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)
{
return sal_False;
}
// -----------------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS evo2fixes (1.3.74); FILE MERGED 2006/02/15 12:15:31 mmeeks 1.3.74.1: Issue numbers: i#50913#, i#62042#, i#55893#, i#62043# Submitted by: misc, Tor, Jayant, me Reviewed by: mmeeks<commit_after> /*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: NPreparedStatement.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: kz $ $Date: 2006-02-28 10:33:45 $
*
* 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 <stdio.h>
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _CONNECTIVITY_EVOAB_PREPAREDSTATEMENT_HXX_
#include "NPreparedStatement.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_DATATYPE_HPP_
#include <com/sun/star/sdbc/DataType.hpp>
#endif
#ifndef _CPPUHELPER_TYPEPROVIDER_HXX_
#include <cppuhelper/typeprovider.hxx>
#endif
#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif
#ifndef _CONNECTIVITY_PROPERTYIDS_HXX_
#include "propertyids.hxx"
#endif
using namespace connectivity::evoab;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::beans;
using namespace com::sun::star::sdbc;
using namespace com::sun::star::container;
using namespace com::sun::star::io;
using namespace com::sun::star::util;
IMPLEMENT_SERVICE_INFO(OEvoabPreparedStatement,"com.sun.star.sdbcx.evoab.PreparedStatement","com.sun.star.sdbc.PreparedStatement");
OEvoabPreparedStatement::OEvoabPreparedStatement( OEvoabConnection* _pConnection, const ::rtl::OUString& sql)
:OStatement_BASE2(_pConnection)
,m_bPrepared(sal_False)
,m_sSqlStatement(sql)
,m_nNumParams(0)
{
}
// -----------------------------------------------------------------------------
OEvoabPreparedStatement::~OEvoabPreparedStatement()
{
}
// -----------------------------------------------------------------------------
void SAL_CALL OEvoabPreparedStatement::acquire() throw()
{
OStatement_BASE2::acquire();
}
// -----------------------------------------------------------------------------
void SAL_CALL OEvoabPreparedStatement::release() throw()
{
OStatement_BASE2::release();
}
// -----------------------------------------------------------------------------
Any SAL_CALL OEvoabPreparedStatement::queryInterface( const Type & rType ) throw(RuntimeException)
{
Any aRet = OStatement_BASE2::queryInterface(rType);
if(!aRet.hasValue())
aRet = OPreparedStatement_BASE::queryInterface(rType);
return aRet;
}
// -------------------------------------------------------------------------
::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL OEvoabPreparedStatement::getTypes( ) throw(::com::sun::star::uno::RuntimeException)
{
return ::comphelper::concatSequences(OPreparedStatement_BASE::getTypes(),OStatement_BASE2::getTypes());
}
// -------------------------------------------------------------------------
Reference< XResultSetMetaData > SAL_CALL OEvoabPreparedStatement::getMetaData( ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OStatement_BASE::rBHelper.bDisposed);
if(!m_xMetaData.is())
m_xMetaData = new OEvoabResultSetMetaData(m_pConnection->getCurrentTableName());
return m_xMetaData;
}
// -------------------------------------------------------------------------
void SAL_CALL OEvoabPreparedStatement::close( ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OStatement_BASE::rBHelper.bDisposed);
free_column_resources();
// Reset last warning message
try {
clearWarnings ();
OStatement_BASE2::close();
}
catch (SQLException &) {
// If we get an error, ignore
}
}
// -------------------------------------------------------------------------
sal_Bool SAL_CALL OEvoabPreparedStatement::execute( ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OStatement_BASE::rBHelper.bDisposed);
Reference< XResultSet> xRS = OStatement_Base::executeQuery( m_sSqlStatement );
// same as in statement with the difference that this statement also can contain parameter
return xRS.is();
}
// -------------------------------------------------------------------------
sal_Int32 SAL_CALL OEvoabPreparedStatement::executeUpdate( ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OStatement_BASE::rBHelper.bDisposed);
// same as in statement with the difference that this statement also can contain parameter
return 0;
}
// -------------------------------------------------------------------------
void SAL_CALL OEvoabPreparedStatement::setString( sal_Int32 parameterIndex, const ::rtl::OUString& x ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OStatement_BASE::rBHelper.bDisposed);
}
// -------------------------------------------------------------------------
Reference< XConnection > SAL_CALL OEvoabPreparedStatement::getConnection( ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OStatement_BASE::rBHelper.bDisposed);
return (Reference< XConnection >)m_pConnection;
}
// -------------------------------------------------------------------------
Reference< XResultSet > SAL_CALL OEvoabPreparedStatement::executeQuery( ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OStatement_BASE::rBHelper.bDisposed);
Reference< XResultSet > rs = OStatement_Base::executeQuery( m_sSqlStatement );
return rs;
}
// -------------------------------------------------------------------------
void SAL_CALL OEvoabPreparedStatement::setBoolean( sal_Int32 parameterIndex, sal_Bool x ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OStatement_BASE::rBHelper.bDisposed);
}
// -------------------------------------------------------------------------
void SAL_CALL OEvoabPreparedStatement::setByte( sal_Int32 parameterIndex, sal_Int8 x ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OStatement_BASE::rBHelper.bDisposed);
}
// -------------------------------------------------------------------------
void SAL_CALL OEvoabPreparedStatement::setDate( sal_Int32 parameterIndex, const Date& aData ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OStatement_BASE::rBHelper.bDisposed);
}
// -------------------------------------------------------------------------
void SAL_CALL OEvoabPreparedStatement::setTime( sal_Int32 parameterIndex, const Time& aVal ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OStatement_BASE::rBHelper.bDisposed);
}
// -------------------------------------------------------------------------
void SAL_CALL OEvoabPreparedStatement::setTimestamp( sal_Int32 parameterIndex, const DateTime& aVal ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OStatement_BASE::rBHelper.bDisposed);
}
// -------------------------------------------------------------------------
void SAL_CALL OEvoabPreparedStatement::setDouble( sal_Int32 parameterIndex, double x ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OStatement_BASE::rBHelper.bDisposed);
}
// -------------------------------------------------------------------------
void SAL_CALL OEvoabPreparedStatement::setFloat( sal_Int32 parameterIndex, float x ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OStatement_BASE::rBHelper.bDisposed);
}
// -------------------------------------------------------------------------
void SAL_CALL OEvoabPreparedStatement::setInt( sal_Int32 parameterIndex, sal_Int32 x ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OStatement_BASE::rBHelper.bDisposed);
}
// -------------------------------------------------------------------------
void SAL_CALL OEvoabPreparedStatement::setLong( sal_Int32 parameterIndex, sal_Int64 aVal ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OStatement_BASE::rBHelper.bDisposed);
}
// -------------------------------------------------------------------------
void SAL_CALL OEvoabPreparedStatement::setNull( sal_Int32 parameterIndex, sal_Int32 sqlType ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OStatement_BASE::rBHelper.bDisposed);
}
// -------------------------------------------------------------------------
void SAL_CALL OEvoabPreparedStatement::setClob( sal_Int32 parameterIndex, const Reference< XClob >& x ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OStatement_BASE::rBHelper.bDisposed);
}
// -------------------------------------------------------------------------
void SAL_CALL OEvoabPreparedStatement::setBlob( sal_Int32 parameterIndex, const Reference< XBlob >& x ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OStatement_BASE::rBHelper.bDisposed);
}
// -------------------------------------------------------------------------
void SAL_CALL OEvoabPreparedStatement::setArray( sal_Int32 parameterIndex, const Reference< XArray >& x ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OStatement_BASE::rBHelper.bDisposed);
}
// -------------------------------------------------------------------------
void SAL_CALL OEvoabPreparedStatement::setRef( sal_Int32 parameterIndex, const Reference< XRef >& x ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OStatement_BASE::rBHelper.bDisposed);
}
// -------------------------------------------------------------------------
void SAL_CALL OEvoabPreparedStatement::setObjectWithInfo( sal_Int32 parameterIndex, const Any& x, sal_Int32 sqlType, sal_Int32 scale ) throw(SQLException, RuntimeException)
{
checkDisposed(OStatement_BASE::rBHelper.bDisposed);
::osl::MutexGuard aGuard( m_aMutex );
}
// -------------------------------------------------------------------------
void SAL_CALL OEvoabPreparedStatement::setObjectNull( sal_Int32 parameterIndex, sal_Int32 sqlType, const ::rtl::OUString& typeName ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OStatement_BASE::rBHelper.bDisposed);
}
// -------------------------------------------------------------------------
void SAL_CALL OEvoabPreparedStatement::setObject( sal_Int32 parameterIndex, const Any& x ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OStatement_BASE::rBHelper.bDisposed);
}
// -------------------------------------------------------------------------
void SAL_CALL OEvoabPreparedStatement::setShort( sal_Int32 parameterIndex, sal_Int16 x ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OStatement_BASE::rBHelper.bDisposed);
}
// -------------------------------------------------------------------------
void SAL_CALL OEvoabPreparedStatement::setBytes( sal_Int32 parameterIndex, const Sequence< sal_Int8 >& x ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OStatement_BASE::rBHelper.bDisposed);
}
// -------------------------------------------------------------------------
void SAL_CALL OEvoabPreparedStatement::setCharacterStream( sal_Int32 parameterIndex, const Reference< ::com::sun::star::io::XInputStream >& x, sal_Int32 length ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OStatement_BASE::rBHelper.bDisposed);
}
// -------------------------------------------------------------------------
void SAL_CALL OEvoabPreparedStatement::setBinaryStream( sal_Int32 parameterIndex, const Reference< ::com::sun::star::io::XInputStream >& x, sal_Int32 length ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OStatement_BASE::rBHelper.bDisposed);
}
// -------------------------------------------------------------------------
void SAL_CALL OEvoabPreparedStatement::clearParameters( ) throw(SQLException, RuntimeException)
{
}
// -------------------------------------------------------------------------
void OEvoabPreparedStatement::setFastPropertyValue_NoBroadcast(sal_Int32 nHandle,const Any& rValue) throw (Exception)
{
switch(nHandle)
{
case PROPERTY_ID_RESULTSETCONCURRENCY:
break;
case PROPERTY_ID_RESULTSETTYPE:
break;
case PROPERTY_ID_FETCHDIRECTION:
break;
case PROPERTY_ID_USEBOOKMARKS:
break;
default:
OStatement_Base::setFastPropertyValue_NoBroadcast(nHandle,rValue);
}
}
// -----------------------------------------------------------------------------
void OEvoabPreparedStatement::checkParameterIndex(sal_Int32 _parameterIndex)
{
if( !_parameterIndex || _parameterIndex > m_nNumParams)
throw SQLException();
}
// -----------------------------------------------------------------------------
::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > SAL_CALL OEvoabPreparedStatement::getResultSet( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)
{
return NULL;
}
// -----------------------------------------------------------------------------
sal_Int32 SAL_CALL OEvoabPreparedStatement::getUpdateCount( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)
{
return 0;
}
// -----------------------------------------------------------------------------
sal_Bool SAL_CALL OEvoabPreparedStatement::getMoreResults( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)
{
return sal_False;
}
// -----------------------------------------------------------------------------
<|endoftext|>
|
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/dom_storage/dom_storage_message_filter.h"
#include "base/auto_reset.h"
#include "base/bind.h"
#include "base/nullable_string16.h"
#include "base/threading/sequenced_worker_pool.h"
#include "base/utf_string_conversions.h"
#include "content/public/browser/user_metrics.h"
#include "content/browser/dom_storage/dom_storage_context_impl.h"
#include "content/common/dom_storage_messages.h"
#include "googleurl/src/gurl.h"
#include "webkit/dom_storage/dom_storage_area.h"
#include "webkit/dom_storage/dom_storage_host.h"
#include "webkit/dom_storage/dom_storage_task_runner.h"
using content::BrowserThread;
using content::UserMetricsAction;
using dom_storage::DomStorageTaskRunner;
using WebKit::WebStorageArea;
DOMStorageMessageFilter::DOMStorageMessageFilter(
int unused,
DOMStorageContextImpl* context)
: context_(context->context()),
connection_dispatching_message_for_(0) {
}
DOMStorageMessageFilter::~DOMStorageMessageFilter() {
DCHECK(!host_.get());
}
void DOMStorageMessageFilter::InitializeInSequence() {
DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::IO));
host_.reset(new dom_storage::DomStorageHost(context_));
context_->AddEventObserver(this);
}
void DOMStorageMessageFilter::UninitializeInSequence() {
DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::IO));
context_->RemoveEventObserver(this);
host_.reset();
}
void DOMStorageMessageFilter::OnFilterAdded(IPC::Channel* channel) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
BrowserMessageFilter::OnFilterAdded(channel);
context_->task_runner()->PostShutdownBlockingTask(
FROM_HERE,
DomStorageTaskRunner::PRIMARY_SEQUENCE,
base::Bind(&DOMStorageMessageFilter::InitializeInSequence, this));
}
void DOMStorageMessageFilter::OnFilterRemoved() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
BrowserMessageFilter::OnFilterRemoved();
context_->task_runner()->PostShutdownBlockingTask(
FROM_HERE,
DomStorageTaskRunner::PRIMARY_SEQUENCE,
base::Bind(&DOMStorageMessageFilter::UninitializeInSequence, this));
}
base::TaskRunner* DOMStorageMessageFilter::OverrideTaskRunnerForMessage(
const IPC::Message& message) {
if (IPC_MESSAGE_CLASS(message) == DOMStorageMsgStart)
return context_->task_runner();
return NULL;
}
bool DOMStorageMessageFilter::OnMessageReceived(const IPC::Message& message,
bool* message_was_ok) {
if (IPC_MESSAGE_CLASS(message) != DOMStorageMsgStart)
return false;
DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::IO));
DCHECK(host_.get());
DCHECK_EQ(0, connection_dispatching_message_for_);
// The connection_id is always the first param.
int connection_id = IPC::MessageIterator(message).NextInt();
AutoReset<int> auto_reset(&connection_dispatching_message_for_,
connection_id);
bool handled = true;
IPC_BEGIN_MESSAGE_MAP_EX(DOMStorageMessageFilter, message, *message_was_ok)
IPC_MESSAGE_HANDLER(DOMStorageHostMsg_OpenStorageArea, OnOpenStorageArea)
IPC_MESSAGE_HANDLER(DOMStorageHostMsg_CloseStorageArea, OnCloseStorageArea)
IPC_MESSAGE_HANDLER(DOMStorageHostMsg_LoadStorageArea, OnLoadStorageArea)
IPC_MESSAGE_HANDLER(DOMStorageHostMsg_Length, OnLength)
IPC_MESSAGE_HANDLER(DOMStorageHostMsg_Key, OnKey)
IPC_MESSAGE_HANDLER(DOMStorageHostMsg_GetItem, OnGetItem)
IPC_MESSAGE_HANDLER(DOMStorageHostMsg_SetItem, OnSetItem)
IPC_MESSAGE_HANDLER(DOMStorageHostMsg_SetItemAsync, OnSetItemAsync)
IPC_MESSAGE_HANDLER(DOMStorageHostMsg_RemoveItem, OnRemoveItem)
IPC_MESSAGE_HANDLER(DOMStorageHostMsg_RemoveItemAsync, OnRemoveItemAsync)
IPC_MESSAGE_HANDLER(DOMStorageHostMsg_Clear, OnClear)
IPC_MESSAGE_HANDLER(DOMStorageHostMsg_ClearAsync, OnClearAsync)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
void DOMStorageMessageFilter::OnOpenStorageArea(int connection_id,
int64 namespace_id,
const GURL& origin) {
DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::IO));
if (!host_->OpenStorageArea(connection_id, namespace_id, origin)) {
content::RecordAction(UserMetricsAction("BadMessageTerminate_DSMF_1"));
BadMessageReceived();
}
}
void DOMStorageMessageFilter::OnCloseStorageArea(int connection_id) {
DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::IO));
host_->CloseStorageArea(connection_id);
}
void DOMStorageMessageFilter::OnLoadStorageArea(int connection_id,
dom_storage::ValuesMap* map) {
DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::IO));
if (!host_->ExtractAreaValues(connection_id, map)) {
content::RecordAction(UserMetricsAction("BadMessageTerminate_DSMF_2"));
BadMessageReceived();
}
}
void DOMStorageMessageFilter::OnLength(int connection_id,
unsigned* length) {
DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::IO));
*length = host_->GetAreaLength(connection_id);
}
void DOMStorageMessageFilter::OnKey(int connection_id, unsigned index,
NullableString16* key) {
DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::IO));
*key = host_->GetAreaKey(connection_id, index);
}
void DOMStorageMessageFilter::OnGetItem(int connection_id,
const string16& key,
NullableString16* value) {
DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::IO));
*value = host_->GetAreaItem(connection_id, key);
}
void DOMStorageMessageFilter::OnSetItem(
int connection_id, const string16& key,
const string16& value, const GURL& page_url,
WebKit::WebStorageArea::Result* result, NullableString16* old_value) {
DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::IO));
*old_value = NullableString16(true);
if (host_->SetAreaItem(connection_id, key, value, page_url, old_value))
*result = WebKit::WebStorageArea::ResultOK;
else
*result = WebKit::WebStorageArea::ResultBlockedByQuota;
}
void DOMStorageMessageFilter::OnSetItemAsync(
int connection_id, int operation_id, const string16& key,
const string16& value, const GURL& page_url) {
DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::IO));
NullableString16 not_used;
bool success = host_->SetAreaItem(connection_id, key, value,
page_url, ¬_used);
Send(new DOMStorageMsg_AsyncOperationComplete(operation_id, success));
}
void DOMStorageMessageFilter::OnRemoveItem(
int connection_id, const string16& key, const GURL& page_url,
NullableString16* old_value) {
DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::IO));
string16 old_string_value;
if (host_->RemoveAreaItem(connection_id, key, page_url, &old_string_value))
*old_value = NullableString16(old_string_value, false);
else
*old_value = NullableString16(true);
}
void DOMStorageMessageFilter::OnRemoveItemAsync(
int connection_id, int operation_id, const string16& key,
const GURL& page_url) {
DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::IO));
string16 not_used;
host_->RemoveAreaItem(connection_id, key, page_url, ¬_used);
Send(new DOMStorageMsg_AsyncOperationComplete(operation_id, true));
}
void DOMStorageMessageFilter::OnClear(int connection_id, const GURL& page_url,
bool* something_cleared) {
DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::IO));
*something_cleared = host_->ClearArea(connection_id, page_url);
}
void DOMStorageMessageFilter::OnClearAsync(
int connection_id, int operation_id, const GURL& page_url) {
DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::IO));
host_->ClearArea(connection_id, page_url);
Send(new DOMStorageMsg_AsyncOperationComplete(operation_id, true));
}
void DOMStorageMessageFilter::OnDomStorageItemSet(
const dom_storage::DomStorageArea* area,
const string16& key,
const string16& new_value,
const NullableString16& old_value,
const GURL& page_url) {
SendDomStorageEvent(area, page_url,
NullableString16(key, false),
NullableString16(new_value, false),
old_value);
}
void DOMStorageMessageFilter::OnDomStorageItemRemoved(
const dom_storage::DomStorageArea* area,
const string16& key,
const string16& old_value,
const GURL& page_url) {
SendDomStorageEvent(area, page_url,
NullableString16(key, false),
NullableString16(true),
NullableString16(old_value, false));
}
void DOMStorageMessageFilter::OnDomStorageAreaCleared(
const dom_storage::DomStorageArea* area,
const GURL& page_url) {
SendDomStorageEvent(area, page_url,
NullableString16(true),
NullableString16(true),
NullableString16(true));
}
void DOMStorageMessageFilter::SendDomStorageEvent(
const dom_storage::DomStorageArea* area,
const GURL& page_url,
const NullableString16& key,
const NullableString16& new_value,
const NullableString16& old_value) {
DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::IO));
DOMStorageMsg_Event_Params params;
params.origin = area->origin();
params.page_url = page_url;
params.connection_id = connection_dispatching_message_for_;
params.key = key;
params.new_value = new_value;
params.old_value = old_value;
params.namespace_id = area->namespace_id();
Send(new DOMStorageMsg_Event(params));
}
<commit_msg>Fix a DomStorageEvent bug with reporting the wrong connection_id to renderers and avoid sending session storage events across process boundaries.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/dom_storage/dom_storage_message_filter.h"
#include "base/auto_reset.h"
#include "base/bind.h"
#include "base/nullable_string16.h"
#include "base/threading/sequenced_worker_pool.h"
#include "base/utf_string_conversions.h"
#include "content/public/browser/user_metrics.h"
#include "content/browser/dom_storage/dom_storage_context_impl.h"
#include "content/common/dom_storage_messages.h"
#include "googleurl/src/gurl.h"
#include "webkit/dom_storage/dom_storage_area.h"
#include "webkit/dom_storage/dom_storage_host.h"
#include "webkit/dom_storage/dom_storage_task_runner.h"
using content::BrowserThread;
using content::UserMetricsAction;
using dom_storage::DomStorageTaskRunner;
using WebKit::WebStorageArea;
DOMStorageMessageFilter::DOMStorageMessageFilter(
int unused,
DOMStorageContextImpl* context)
: context_(context->context()),
connection_dispatching_message_for_(0) {
}
DOMStorageMessageFilter::~DOMStorageMessageFilter() {
DCHECK(!host_.get());
}
void DOMStorageMessageFilter::InitializeInSequence() {
DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::IO));
host_.reset(new dom_storage::DomStorageHost(context_));
context_->AddEventObserver(this);
}
void DOMStorageMessageFilter::UninitializeInSequence() {
DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::IO));
context_->RemoveEventObserver(this);
host_.reset();
}
void DOMStorageMessageFilter::OnFilterAdded(IPC::Channel* channel) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
BrowserMessageFilter::OnFilterAdded(channel);
context_->task_runner()->PostShutdownBlockingTask(
FROM_HERE,
DomStorageTaskRunner::PRIMARY_SEQUENCE,
base::Bind(&DOMStorageMessageFilter::InitializeInSequence, this));
}
void DOMStorageMessageFilter::OnFilterRemoved() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
BrowserMessageFilter::OnFilterRemoved();
context_->task_runner()->PostShutdownBlockingTask(
FROM_HERE,
DomStorageTaskRunner::PRIMARY_SEQUENCE,
base::Bind(&DOMStorageMessageFilter::UninitializeInSequence, this));
}
base::TaskRunner* DOMStorageMessageFilter::OverrideTaskRunnerForMessage(
const IPC::Message& message) {
if (IPC_MESSAGE_CLASS(message) == DOMStorageMsgStart)
return context_->task_runner();
return NULL;
}
bool DOMStorageMessageFilter::OnMessageReceived(const IPC::Message& message,
bool* message_was_ok) {
if (IPC_MESSAGE_CLASS(message) != DOMStorageMsgStart)
return false;
DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::IO));
DCHECK(host_.get());
bool handled = true;
IPC_BEGIN_MESSAGE_MAP_EX(DOMStorageMessageFilter, message, *message_was_ok)
IPC_MESSAGE_HANDLER(DOMStorageHostMsg_OpenStorageArea, OnOpenStorageArea)
IPC_MESSAGE_HANDLER(DOMStorageHostMsg_CloseStorageArea, OnCloseStorageArea)
IPC_MESSAGE_HANDLER(DOMStorageHostMsg_LoadStorageArea, OnLoadStorageArea)
IPC_MESSAGE_HANDLER(DOMStorageHostMsg_Length, OnLength)
IPC_MESSAGE_HANDLER(DOMStorageHostMsg_Key, OnKey)
IPC_MESSAGE_HANDLER(DOMStorageHostMsg_GetItem, OnGetItem)
IPC_MESSAGE_HANDLER(DOMStorageHostMsg_SetItem, OnSetItem)
IPC_MESSAGE_HANDLER(DOMStorageHostMsg_SetItemAsync, OnSetItemAsync)
IPC_MESSAGE_HANDLER(DOMStorageHostMsg_RemoveItem, OnRemoveItem)
IPC_MESSAGE_HANDLER(DOMStorageHostMsg_RemoveItemAsync, OnRemoveItemAsync)
IPC_MESSAGE_HANDLER(DOMStorageHostMsg_Clear, OnClear)
IPC_MESSAGE_HANDLER(DOMStorageHostMsg_ClearAsync, OnClearAsync)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
void DOMStorageMessageFilter::OnOpenStorageArea(int connection_id,
int64 namespace_id,
const GURL& origin) {
DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::IO));
if (!host_->OpenStorageArea(connection_id, namespace_id, origin)) {
content::RecordAction(UserMetricsAction("BadMessageTerminate_DSMF_1"));
BadMessageReceived();
}
}
void DOMStorageMessageFilter::OnCloseStorageArea(int connection_id) {
DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::IO));
host_->CloseStorageArea(connection_id);
}
void DOMStorageMessageFilter::OnLoadStorageArea(int connection_id,
dom_storage::ValuesMap* map) {
DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::IO));
if (!host_->ExtractAreaValues(connection_id, map)) {
content::RecordAction(UserMetricsAction("BadMessageTerminate_DSMF_2"));
BadMessageReceived();
}
}
void DOMStorageMessageFilter::OnLength(int connection_id,
unsigned* length) {
DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::IO));
*length = host_->GetAreaLength(connection_id);
}
void DOMStorageMessageFilter::OnKey(int connection_id, unsigned index,
NullableString16* key) {
DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::IO));
*key = host_->GetAreaKey(connection_id, index);
}
void DOMStorageMessageFilter::OnGetItem(int connection_id,
const string16& key,
NullableString16* value) {
DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::IO));
*value = host_->GetAreaItem(connection_id, key);
}
void DOMStorageMessageFilter::OnSetItem(
int connection_id, const string16& key,
const string16& value, const GURL& page_url,
WebKit::WebStorageArea::Result* result, NullableString16* old_value) {
DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::IO));
DCHECK_EQ(0, connection_dispatching_message_for_);
AutoReset<int> auto_reset(&connection_dispatching_message_for_,
connection_id);
*old_value = NullableString16(true);
if (host_->SetAreaItem(connection_id, key, value, page_url, old_value))
*result = WebKit::WebStorageArea::ResultOK;
else
*result = WebKit::WebStorageArea::ResultBlockedByQuota;
}
void DOMStorageMessageFilter::OnSetItemAsync(
int connection_id, int operation_id, const string16& key,
const string16& value, const GURL& page_url) {
DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::IO));
DCHECK_EQ(0, connection_dispatching_message_for_);
AutoReset<int> auto_reset(&connection_dispatching_message_for_,
connection_id);
NullableString16 not_used;
bool success = host_->SetAreaItem(connection_id, key, value,
page_url, ¬_used);
Send(new DOMStorageMsg_AsyncOperationComplete(operation_id, success));
}
void DOMStorageMessageFilter::OnRemoveItem(
int connection_id, const string16& key, const GURL& page_url,
NullableString16* old_value) {
DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::IO));
DCHECK_EQ(0, connection_dispatching_message_for_);
AutoReset<int> auto_reset(&connection_dispatching_message_for_,
connection_id);
string16 old_string_value;
if (host_->RemoveAreaItem(connection_id, key, page_url, &old_string_value))
*old_value = NullableString16(old_string_value, false);
else
*old_value = NullableString16(true);
}
void DOMStorageMessageFilter::OnRemoveItemAsync(
int connection_id, int operation_id, const string16& key,
const GURL& page_url) {
DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::IO));
DCHECK_EQ(0, connection_dispatching_message_for_);
AutoReset<int> auto_reset(&connection_dispatching_message_for_,
connection_id);
string16 not_used;
host_->RemoveAreaItem(connection_id, key, page_url, ¬_used);
Send(new DOMStorageMsg_AsyncOperationComplete(operation_id, true));
}
void DOMStorageMessageFilter::OnClear(int connection_id, const GURL& page_url,
bool* something_cleared) {
DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::IO));
DCHECK_EQ(0, connection_dispatching_message_for_);
AutoReset<int> auto_reset(&connection_dispatching_message_for_,
connection_id);
*something_cleared = host_->ClearArea(connection_id, page_url);
}
void DOMStorageMessageFilter::OnClearAsync(
int connection_id, int operation_id, const GURL& page_url) {
DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::IO));
DCHECK_EQ(0, connection_dispatching_message_for_);
AutoReset<int> auto_reset(&connection_dispatching_message_for_,
connection_id);
host_->ClearArea(connection_id, page_url);
Send(new DOMStorageMsg_AsyncOperationComplete(operation_id, true));
}
void DOMStorageMessageFilter::OnDomStorageItemSet(
const dom_storage::DomStorageArea* area,
const string16& key,
const string16& new_value,
const NullableString16& old_value,
const GURL& page_url) {
SendDomStorageEvent(area, page_url,
NullableString16(key, false),
NullableString16(new_value, false),
old_value);
}
void DOMStorageMessageFilter::OnDomStorageItemRemoved(
const dom_storage::DomStorageArea* area,
const string16& key,
const string16& old_value,
const GURL& page_url) {
SendDomStorageEvent(area, page_url,
NullableString16(key, false),
NullableString16(true),
NullableString16(old_value, false));
}
void DOMStorageMessageFilter::OnDomStorageAreaCleared(
const dom_storage::DomStorageArea* area,
const GURL& page_url) {
SendDomStorageEvent(area, page_url,
NullableString16(true),
NullableString16(true),
NullableString16(true));
}
void DOMStorageMessageFilter::SendDomStorageEvent(
const dom_storage::DomStorageArea* area,
const GURL& page_url,
const NullableString16& key,
const NullableString16& new_value,
const NullableString16& old_value) {
DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::IO));
if (area->namespace_id() != dom_storage::kLocalStorageNamespaceId &&
!connection_dispatching_message_for_) {
return; // No need to broadcast session storage events across processes.
}
DOMStorageMsg_Event_Params params;
params.origin = area->origin();
params.page_url = page_url;
params.connection_id = connection_dispatching_message_for_;
params.key = key;
params.new_value = new_value;
params.old_value = old_value;
params.namespace_id = area->namespace_id();
Send(new DOMStorageMsg_Event(params));
}
<|endoftext|>
|
<commit_before>/**
* Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* This file is licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License. A copy of
* the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* This file 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.
*/
// snippet-sourcedescription:[GameLift-Unreal-game-server.cs demonstrates a basic integration of Amazon GameLift into a game server built with Unreal Engine.]
// snippet-service:[gamelift]
// snippet-keyword:[Amazon GameLift]
//snippet-keyword:[C++]
//snippet-keyword:[Code Sample]
//snippet-keyword:[InitSDK]
//snippet-keyword:[ActivateGameSession]
//snippet-keyword:[ProcessReady]
//snippet-keyword:[ProcessEnding]
//snippet-keyword:[]
// snippet-sourcetype:[full-example]
// snippet-sourcedate:[2018-12-12]
// snippet-sourceauthor:[AWS]
// snippet-start:[gamelift.cpp.game-server.unreal]
//This is an example of a simple integration with GameLift server SDK that makes game server
//processes go active on Amazon GameLift
// Include game project files. "GameLiftFPS" is a sample game name, replace with file names from your own game project
#include "GameLiftFPS.h"
#include "Engine.h"
#include "EngineGlobals.h"
#include "GameLiftFPSGameMode.h"
#include "GameLiftFPSHUD.h"
#include "GameLiftFPSCharacter.h"
#include "GameLiftServerSDK.h"
AGameLiftFPSGameMode::AGameLiftFPSGameMode()
: Super()
{
//Let's run this code only if GAMELIFT is enabled. Only with Server targets!
#if WITH_GAMELIFT
//Getting the module first.
FGameLiftServerSDKModule* gameLiftSdkModule = &FModuleManager::LoadModuleChecked<FGameLiftServerSDKModule>(FName("GameLiftServerSDK"));
//InitSDK establishes a local connection with GameLift's agent to enable communication.
gameLiftSdkModule->InitSDK();
//Respond to new game session activation request. GameLift sends activation request
//to the game server along with a game session object containing game properties
//and other settings. Once the game server is ready to receive player connections,
//invoke GameLiftServerAPI.ActivateGameSession()
auto onGameSession = [=](Aws::GameLift::Server::Model::GameSession gameSession)
{
gameLiftSdkModule->ActivateGameSession();
};
FProcessParameters* params = new FProcessParameters();
params->OnStartGameSession.BindLambda(onGameSession);
//OnProcessTerminate callback. GameLift invokes this before shutting down the instance
//that is hosting this game server to give it time to gracefully shut down on its own.
//In this example, we simply tell GameLift we are indeed going to shut down.
params->OnTerminate.BindLambda([=](){gameLiftSdkModule->ProcessEnding();});
//HealthCheck callback. GameLift invokes this callback about every 60 seconds. By default,
//GameLift API automatically responds 'true'. A game can optionally perform checks on
//dependencies and such and report status based on this info. If no response is received
//within 60 seconds, health status is recorded as 'false'.
//In this example, we're always healthy!
params->OnHealthCheck.BindLambda([](){return true; });
//Here, the game server tells GameLift what port it is listening on for incoming player
//connections. In this example, the port is hardcoded for simplicity. Since active game
//that are on the same instance must have unique ports, you may want to assign port values
//from a range, such as:
//const int32 port = FURL::UrlConfig.DefaultPort;
//params->port;
params->port = 7777;
//Here, the game server tells GameLift what set of files to upload when the game session
//ends. GameLift uploads everything specified here for the developers to fetch later.
TArray<FString> logfiles;
logfiles.Add(TEXT("aLogFile.txt"));
params->logParameters = logfiles;
//Call ProcessReady to tell GameLift this game server is ready to receive game sessions!
gameLiftSdkModule->ProcessReady(*params);
#endif
}
// snippet-end:[gamelift.cpp.game-server.unreal]<commit_msg>Update GameLift-Unreal-game-server.cpp<commit_after>/**
* Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* This file is licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License. A copy of
* the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* This file 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.
*/
// snippet-sourcedescription:[GameLift-Unreal-game-server.cs demonstrates a basic integration of Amazon GameLift into a game server built with Unreal Engine.]
// snippet-service:[gamelift]
// snippet-keyword:[Amazon GameLift]
//snippet-keyword:[C++]
//snippet-keyword:[Code Sample]
//snippet-keyword:[InitSDK]
//snippet-keyword:[ActivateGameSession]
//snippet-keyword:[ProcessReady]
//snippet-keyword:[ProcessEnding]
//snippet-keyword:[]
// snippet-sourcetype:[full-example]
// snippet-sourcedate:[2018-12-12]
// snippet-sourceauthor:[AWS]
// snippet-start:[gamelift.cpp.game-server.unreal]
//This is an example of a simple integration with GameLift server SDK that makes game server
//processes go active on Amazon GameLift
// Include game project files. "GameLiftFPS" is a sample game name, replace with file names from your own game project
#include "GameLiftFPSGameMode.h"
#include "GameLiftFPS.h"
#include "Engine.h"
#include "EngineGlobals.h"
#include "GameLiftFPSHUD.h"
#include "GameLiftFPSCharacter.h"
#include "GameLiftServerSDK.h"
AGameLiftFPSGameMode::AGameLiftFPSGameMode()
: Super()
{
//Let's run this code only if GAMELIFT is enabled. Only with Server targets!
#if WITH_GAMELIFT
//Getting the module first.
FGameLiftServerSDKModule* gameLiftSdkModule = &FModuleManager::LoadModuleChecked<FGameLiftServerSDKModule>(FName("GameLiftServerSDK"));
//InitSDK establishes a local connection with GameLift's agent to enable communication.
gameLiftSdkModule->InitSDK();
//Respond to new game session activation request. GameLift sends activation request
//to the game server along with a game session object containing game properties
//and other settings. Once the game server is ready to receive player connections,
//invoke GameLiftServerAPI.ActivateGameSession()
auto onGameSession = [=](Aws::GameLift::Server::Model::GameSession gameSession)
{
gameLiftSdkModule->ActivateGameSession();
};
FProcessParameters* params = new FProcessParameters();
params->OnStartGameSession.BindLambda(onGameSession);
//OnProcessTerminate callback. GameLift invokes this before shutting down the instance
//that is hosting this game server to give it time to gracefully shut down on its own.
//In this example, we simply tell GameLift we are indeed going to shut down.
params->OnTerminate.BindLambda([=](){gameLiftSdkModule->ProcessEnding();});
//HealthCheck callback. GameLift invokes this callback about every 60 seconds. By default,
//GameLift API automatically responds 'true'. A game can optionally perform checks on
//dependencies and such and report status based on this info. If no response is received
//within 60 seconds, health status is recorded as 'false'.
//In this example, we're always healthy!
params->OnHealthCheck.BindLambda([](){return true; });
//Here, the game server tells GameLift what port it is listening on for incoming player
//connections. In this example, the port is hardcoded for simplicity. Since active game
//that are on the same instance must have unique ports, you may want to assign port values
//from a range, such as:
//const int32 port = FURL::UrlConfig.DefaultPort;
//params->port;
params->port = 7777;
//Here, the game server tells GameLift what set of files to upload when the game session
//ends. GameLift uploads everything specified here for the developers to fetch later.
TArray<FString> logfiles;
logfiles.Add(TEXT("aLogFile.txt"));
params->logParameters = logfiles;
//Call ProcessReady to tell GameLift this game server is ready to receive game sessions!
gameLiftSdkModule->ProcessReady(*params);
#endif
}
// snippet-end:[gamelift.cpp.game-server.unreal]<|endoftext|>
|
<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// 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.
#pragma once
#ifndef TAR_HPP
#define TAR_HPP
#include <posix/tar.h> // Our posix header has the Tar_header struct, which the newlib tar.h does not
#include <tinf.h> // From uzlib (mod)
#include <util/crc32.hpp>
#include <info>
#include <string>
#include <vector>
#include <stdexcept>
#include <memory>
extern uint8_t _binary_input_bin_start;
extern uintptr_t _binary_input_bin_size;
namespace tar {
static const int SECTOR_SIZE = 512;
static const int DECOMPRESSION_SIZE = 256;
static bool has_uzlib_init = false;
// --------------------------- Tar_exception ---------------------------
class Tar_exception : public std::runtime_error {
using runtime_error::runtime_error;
};
// ------------------------------ Element ------------------------------
// Element/file/folder in tarball
class Element {
public:
Element(Tar_header& header)
: header_{header} {}
Element(Tar_header& header, const uint8_t* content_start)
: header_{header}, content_start_{content_start} {}
const Tar_header& header() const noexcept { return header_; }
void set_header(const Tar_header& header) { header_ = header; }
const uint8_t* content() const { return content_start_; }
void set_content_start(const uint8_t* content_start) { content_start_ = content_start; }
std::string name() const { return std::string{header_.name}; }
std::string mode() const { return std::string{header_.mode}; }
std::string uid() const { return std::string{header_.uid}; }
std::string gid() const { return std::string{header_.gid}; }
long int size() const noexcept;
std::string mod_time() const { return std::string{header_.mod_time, LENGTH_MTIME}; }
std::string checksum() const { return std::string{header_.checksum}; }
char typeflag() const noexcept { return header_.typeflag; }
std::string linkname() const { return std::string{header_.linkname}; }
std::string magic() const { return std::string{header_.magic}; }
std::string version() const { return std::string{header_.version, LENGTH_VERSION}; }
std::string uname() const { return std::string{header_.uname}; }
std::string gname() const { return std::string{header_.gname}; }
std::string devmajor() const { return std::string{header_.devmajor}; }
std::string devminor() const { return std::string{header_.devminor}; }
std::string prefix() const { return std::string{header_.prefix}; }
std::string pad() const { return std::string{header_.pad}; }
bool is_ustar() const noexcept { return header_.magic == TMAGIC; }
bool is_dir() const noexcept { return header_.typeflag == DIRTYPE; }
bool typeflag_is_set() const noexcept { return header_.typeflag not_eq ' '; }
bool is_empty() const noexcept { return size() == 0; }
bool is_tar_gz() const noexcept;
int num_content_blocks() const noexcept {
int num_blocks = 0;
const long int sz = size();
if (sz % SECTOR_SIZE not_eq 0)
num_blocks = (sz / SECTOR_SIZE) + 1;
else
num_blocks = (sz / SECTOR_SIZE);
return num_blocks;
}
private:
Tar_header& header_;
const uint8_t* content_start_ = nullptr;
};
// --------------------------------- Tar ---------------------------------
class Tar {
public:
Tar() = default;
int num_elements() const noexcept { return elements_.size(); }
void add_element(const Element& element) { elements_.push_back(element); }
const Element& element(const std::string& path) const;
const std::vector<Element>& elements() const noexcept { return elements_; }
std::vector<std::string> element_names() const;
private:
std::vector<Element> elements_;
}; // class Tar
// ------------------------------ Reader ------------------------------
class Reader {
public:
uint32_t checksum(Element& element) const { return crc32(element.content(), element.size()); }
unsigned int decompressed_length(const uint8_t* data, size_t size) const;
Tar read_binary_tar() {
const uint8_t* bin_content = &_binary_input_bin_start;
const int bin_size = (intptr_t) &_binary_input_bin_size;
return read_uncompressed(bin_content, bin_size);
}
Tar read_binary_tar_gz() {
const uint8_t* bin_content = &_binary_input_bin_start;
const int bin_size = (intptr_t) &_binary_input_bin_size;
return decompress(bin_content, bin_size);
}
/**
dlen is only given if the data is from an Element - see decompress(Element&)
*/
Tar decompress(const uint8_t* data, size_t size, unsigned int dlen = 0) {
if (!has_uzlib_init) {
uzlib_init();
has_uzlib_init = true;
}
// If not decompressing an Element:
if (dlen == 0)
dlen = decompressed_length(data, size);
TINF_DATA d;
d.source = data;
int res = uzlib_gzip_parse_header(&d);
if (res != TINF_OK)
throw Tar_exception(std::string{"Error parsing header: " + std::to_string(res)});
uzlib_uncompress_init(&d, NULL, 0);
auto dest = std::make_unique<unsigned char[]>(dlen);
d.dest = dest.get();
// decompress byte by byte or any other length
d.destSize = DECOMPRESSION_SIZE;
// INFO("tar::Reader", "Decompression started - waiting...");
do {
res = uzlib_uncompress_chksum(&d);
} while (res == TINF_OK);
if (res not_eq TINF_DONE)
throw Tar_exception(std::string{"Error during decompression. Res: " + std::to_string(res)});
// INFO("tar::Reader", "Decompressed %d bytes", d.dest - dest.get());
return read_uncompressed(dest.get(), dlen);
}
/* When have a tar.gz file inside a tar file f.ex. */
Tar decompress(const Element& element) {
return decompress(element.content(), element.size(), decompressed_length(element.content(), element.size()));
}
Tar read_uncompressed(const uint8_t* data, size_t size);
}; // < class Reader
}; // namespace tar
#endif
<commit_msg>tar: improve is_ustar()<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// 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.
#pragma once
#ifndef TAR_HPP
#define TAR_HPP
#include <posix/tar.h> // Our posix header has the Tar_header struct, which the newlib tar.h does not
#include <tinf.h> // From uzlib (mod)
#include <util/crc32.hpp>
#include <info>
#include <string>
#include <vector>
#include <stdexcept>
#include <memory>
extern uint8_t _binary_input_bin_start;
extern uintptr_t _binary_input_bin_size;
namespace tar {
static const int SECTOR_SIZE = 512;
static const int DECOMPRESSION_SIZE = 256;
static bool has_uzlib_init = false;
// --------------------------- Tar_exception ---------------------------
class Tar_exception : public std::runtime_error {
using runtime_error::runtime_error;
};
// ------------------------------ Element ------------------------------
// Element/file/folder in tarball
class Element {
public:
Element(Tar_header& header)
: header_{header} {}
Element(Tar_header& header, const uint8_t* content_start)
: header_{header}, content_start_{content_start} {}
const Tar_header& header() const noexcept { return header_; }
void set_header(const Tar_header& header) { header_ = header; }
const uint8_t* content() const { return content_start_; }
void set_content_start(const uint8_t* content_start) { content_start_ = content_start; }
std::string name() const { return std::string{header_.name}; }
std::string mode() const { return std::string{header_.mode}; }
std::string uid() const { return std::string{header_.uid}; }
std::string gid() const { return std::string{header_.gid}; }
long int size() const noexcept;
std::string mod_time() const { return std::string{header_.mod_time, LENGTH_MTIME}; }
std::string checksum() const { return std::string{header_.checksum}; }
char typeflag() const noexcept { return header_.typeflag; }
std::string linkname() const { return std::string{header_.linkname}; }
std::string magic() const { return std::string{header_.magic}; }
std::string version() const { return std::string{header_.version, LENGTH_VERSION}; }
std::string uname() const { return std::string{header_.uname}; }
std::string gname() const { return std::string{header_.gname}; }
std::string devmajor() const { return std::string{header_.devmajor}; }
std::string devminor() const { return std::string{header_.devminor}; }
std::string prefix() const { return std::string{header_.prefix}; }
std::string pad() const { return std::string{header_.pad}; }
bool is_ustar() const noexcept { return (strncmp(header_.magic, TMAGIC, TMAGLEN) == 0); }
bool is_dir() const noexcept { return header_.typeflag == DIRTYPE; }
bool typeflag_is_set() const noexcept { return header_.typeflag not_eq ' '; }
bool is_empty() const noexcept { return size() == 0; }
bool is_tar_gz() const noexcept;
int num_content_blocks() const noexcept {
int num_blocks = 0;
const long int sz = size();
if (sz % SECTOR_SIZE not_eq 0)
num_blocks = (sz / SECTOR_SIZE) + 1;
else
num_blocks = (sz / SECTOR_SIZE);
return num_blocks;
}
private:
Tar_header& header_;
const uint8_t* content_start_ = nullptr;
};
// --------------------------------- Tar ---------------------------------
class Tar {
public:
Tar() = default;
int num_elements() const noexcept { return elements_.size(); }
void add_element(const Element& element) { elements_.push_back(element); }
const Element& element(const std::string& path) const;
const std::vector<Element>& elements() const noexcept { return elements_; }
std::vector<std::string> element_names() const;
private:
std::vector<Element> elements_;
}; // class Tar
// ------------------------------ Reader ------------------------------
class Reader {
public:
uint32_t checksum(Element& element) const { return crc32(element.content(), element.size()); }
unsigned int decompressed_length(const uint8_t* data, size_t size) const;
Tar read_binary_tar() {
const uint8_t* bin_content = &_binary_input_bin_start;
const int bin_size = (intptr_t) &_binary_input_bin_size;
return read_uncompressed(bin_content, bin_size);
}
Tar read_binary_tar_gz() {
const uint8_t* bin_content = &_binary_input_bin_start;
const int bin_size = (intptr_t) &_binary_input_bin_size;
return decompress(bin_content, bin_size);
}
/**
dlen is only given if the data is from an Element - see decompress(Element&)
*/
Tar decompress(const uint8_t* data, size_t size, unsigned int dlen = 0) {
if (!has_uzlib_init) {
uzlib_init();
has_uzlib_init = true;
}
// If not decompressing an Element:
if (dlen == 0)
dlen = decompressed_length(data, size);
TINF_DATA d;
d.source = data;
int res = uzlib_gzip_parse_header(&d);
if (res != TINF_OK)
throw Tar_exception(std::string{"Error parsing header: " + std::to_string(res)});
uzlib_uncompress_init(&d, NULL, 0);
auto dest = std::make_unique<unsigned char[]>(dlen);
d.dest = dest.get();
// decompress byte by byte or any other length
d.destSize = DECOMPRESSION_SIZE;
// INFO("tar::Reader", "Decompression started - waiting...");
do {
res = uzlib_uncompress_chksum(&d);
} while (res == TINF_OK);
if (res not_eq TINF_DONE)
throw Tar_exception(std::string{"Error during decompression. Res: " + std::to_string(res)});
// INFO("tar::Reader", "Decompressed %d bytes", d.dest - dest.get());
return read_uncompressed(dest.get(), dlen);
}
/* When have a tar.gz file inside a tar file f.ex. */
Tar decompress(const Element& element) {
return decompress(element.content(), element.size(), decompressed_length(element.content(), element.size()));
}
Tar read_uncompressed(const uint8_t* data, size_t size);
}; // < class Reader
}; // namespace tar
#endif
<|endoftext|>
|
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/common/chrome_paths_internal.h"
#include "base/environment.h"
#include "base/file_util.h"
#include "base/memory/scoped_ptr.h"
#include "base/nix/xdg_util.h"
#include "base/path_service.h"
namespace {
const char kDownloadsDir[] = "Downloads";
const char kPicturesDir[] = "Pictures";
} // namespace
namespace chrome {
using base::nix::GetXDGDirectory;
using base::nix::GetXDGUserDirectory;
using base::nix::kDotConfigDir;
using base::nix::kXdgConfigHomeEnvVar;
// See http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
// for a spec on where config files go. The net effect for most
// systems is we use ~/.config/chromium/ for Chromium and
// ~/.config/google-chrome/ for official builds.
// (This also helps us sidestep issues with other apps grabbing ~/.chromium .)
bool GetDefaultUserDataDirectory(FilePath* result) {
scoped_ptr<base::Environment> env(base::Environment::Create());
FilePath config_dir(GetXDGDirectory(env.get(),
kXdgConfigHomeEnvVar,
kDotConfigDir));
#if defined(GOOGLE_CHROME_BUILD)
*result = config_dir.Append("google-chrome");
#else
*result = config_dir.Append("chromium");
#endif
return true;
}
void GetUserCacheDirectory(const FilePath& profile_dir, FilePath* result) {
// See http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
// for a spec on where cache files go. Our rule is:
// - if the user-data-dir in the standard place,
// use same subdirectory of the cache directory.
// (this maps ~/.config/google-chrome to ~/.cache/google-chrome as well
// as the same thing for ~/.config/chromium)
// - otherwise, use the profile dir directly.
// Default value in cases where any of the following fails.
*result = profile_dir;
scoped_ptr<base::Environment> env(base::Environment::Create());
FilePath cache_dir;
if (!PathService::Get(base::DIR_CACHE, &cache_dir))
return;
FilePath config_dir(GetXDGDirectory(env.get(),
kXdgConfigHomeEnvVar,
kDotConfigDir));
if (!config_dir.AppendRelativePath(profile_dir, &cache_dir))
return;
*result = cache_dir;
}
bool GetChromeFrameUserDataDirectory(FilePath* result) {
scoped_ptr<base::Environment> env(base::Environment::Create());
FilePath config_dir(GetXDGDirectory(env.get(),
kXdgConfigHomeEnvVar,
kDotConfigDir));
#if defined(GOOGLE_CHROME_BUILD)
*result = config_dir.Append("google-chrome-frame");
#else
*result = config_dir.Append("chrome-frame");
#endif
return true;
}
bool GetUserDocumentsDirectory(FilePath* result) {
*result = GetXDGUserDirectory("DOCUMENTS", "Documents");
return true;
}
bool GetUserDownloadsDirectorySafe(FilePath* result) {
FilePath home = file_util::GetHomeDir();
*result = home.Append(kDownloadsDir);
return true;
}
bool GetUserDownloadsDirectory(FilePath* result) {
*result = base::nix::GetXDGUserDirectory("DOWNLOAD", kDownloadsDir);
return true;
}
// We respect the user's preferred pictures location, unless it is
// ~ or their desktop directory, in which case we default to ~/Pictures.
bool GetUserPicturesDirectory(FilePath* result) {
*result = GetXDGUserDirectory("PICTURES", kPicturesDir);
FilePath home = file_util::GetHomeDir();
if (*result != home) {
FilePath desktop;
GetUserDesktop(&desktop);
if (*result != desktop) {
return true;
}
}
*result = home.Append(kPicturesDir);
return true;
}
bool GetUserDesktop(FilePath* result) {
*result = GetXDGUserDirectory("DESKTOP", "Desktop");
return true;
}
bool ProcessNeedsProfileDir(const std::string& process_type) {
// For now we have no reason to forbid this on Linux as we don't
// have the roaming profile troubles there. Moreover the Linux breakpad needs
// profile dir access in all process if enabled on Linux.
return true;
}
} // namespace chrome
<commit_msg>ChromeOS: Don't report the presence of a user pictures directory.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/common/chrome_paths_internal.h"
#include "base/environment.h"
#include "base/file_util.h"
#include "base/memory/scoped_ptr.h"
#include "base/nix/xdg_util.h"
#include "base/path_service.h"
namespace {
const char kDownloadsDir[] = "Downloads";
const char kPicturesDir[] = "Pictures";
} // namespace
namespace chrome {
using base::nix::GetXDGDirectory;
using base::nix::GetXDGUserDirectory;
using base::nix::kDotConfigDir;
using base::nix::kXdgConfigHomeEnvVar;
// See http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
// for a spec on where config files go. The net effect for most
// systems is we use ~/.config/chromium/ for Chromium and
// ~/.config/google-chrome/ for official builds.
// (This also helps us sidestep issues with other apps grabbing ~/.chromium .)
bool GetDefaultUserDataDirectory(FilePath* result) {
scoped_ptr<base::Environment> env(base::Environment::Create());
FilePath config_dir(GetXDGDirectory(env.get(),
kXdgConfigHomeEnvVar,
kDotConfigDir));
#if defined(GOOGLE_CHROME_BUILD)
*result = config_dir.Append("google-chrome");
#else
*result = config_dir.Append("chromium");
#endif
return true;
}
void GetUserCacheDirectory(const FilePath& profile_dir, FilePath* result) {
// See http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
// for a spec on where cache files go. Our rule is:
// - if the user-data-dir in the standard place,
// use same subdirectory of the cache directory.
// (this maps ~/.config/google-chrome to ~/.cache/google-chrome as well
// as the same thing for ~/.config/chromium)
// - otherwise, use the profile dir directly.
// Default value in cases where any of the following fails.
*result = profile_dir;
scoped_ptr<base::Environment> env(base::Environment::Create());
FilePath cache_dir;
if (!PathService::Get(base::DIR_CACHE, &cache_dir))
return;
FilePath config_dir(GetXDGDirectory(env.get(),
kXdgConfigHomeEnvVar,
kDotConfigDir));
if (!config_dir.AppendRelativePath(profile_dir, &cache_dir))
return;
*result = cache_dir;
}
bool GetChromeFrameUserDataDirectory(FilePath* result) {
scoped_ptr<base::Environment> env(base::Environment::Create());
FilePath config_dir(GetXDGDirectory(env.get(),
kXdgConfigHomeEnvVar,
kDotConfigDir));
#if defined(GOOGLE_CHROME_BUILD)
*result = config_dir.Append("google-chrome-frame");
#else
*result = config_dir.Append("chrome-frame");
#endif
return true;
}
bool GetUserDocumentsDirectory(FilePath* result) {
*result = GetXDGUserDirectory("DOCUMENTS", "Documents");
return true;
}
bool GetUserDownloadsDirectorySafe(FilePath* result) {
FilePath home = file_util::GetHomeDir();
*result = home.Append(kDownloadsDir);
return true;
}
bool GetUserDownloadsDirectory(FilePath* result) {
*result = base::nix::GetXDGUserDirectory("DOWNLOAD", kDownloadsDir);
return true;
}
// We respect the user's preferred pictures location, unless it is
// ~ or their desktop directory, in which case we default to ~/Pictures.
bool GetUserPicturesDirectory(FilePath* result) {
#if defined(OS_CHROMEOS)
// No local Pictures directory on CrOS.
return false;
#else
*result = GetXDGUserDirectory("PICTURES", kPicturesDir);
FilePath home = file_util::GetHomeDir();
if (*result != home) {
FilePath desktop;
GetUserDesktop(&desktop);
if (*result != desktop) {
return true;
}
}
*result = home.Append(kPicturesDir);
return true;
#endif
}
bool GetUserDesktop(FilePath* result) {
*result = GetXDGUserDirectory("DESKTOP", "Desktop");
return true;
}
bool ProcessNeedsProfileDir(const std::string& process_type) {
// For now we have no reason to forbid this on Linux as we don't
// have the roaming profile troubles there. Moreover the Linux breakpad needs
// profile dir access in all process if enabled on Linux.
return true;
}
} // namespace chrome
<|endoftext|>
|
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/platform_thread.h"
#include "base/string_util.h"
#include "base/test_file_util.h"
#include "base/time.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"
using base::TimeDelta;
using base::TimeTicks;
namespace {
class StartupTest : public UITest {
public:
StartupTest() {
show_window_ = true;
pages_ = "about:blank";
}
void SetUp() {}
void TearDown() {}
// Load a file on startup rather than about:blank. This tests a longer
// startup path, including resource loading and the loading of gears.dll.
void SetUpWithFileURL() {
FilePath file_url;
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &file_url));
file_url = file_url.AppendASCII("empty.html");
ASSERT_TRUE(file_util::PathExists(file_url));
launch_arguments_.AppendLooseValue(file_url.ToWStringHack());
pages_ = WideToUTF8(file_url.ToWStringHack());
}
// Use the given profile in the test data extensions/profiles dir. This tests
// startup with extensions installed.
void SetUpWithExtensionsProfile(const char* profile) {
FilePath data_dir;
PathService::Get(chrome::DIR_TEST_DATA, &data_dir);
data_dir = data_dir.AppendASCII("extensions").AppendASCII("profiles").
AppendASCII(profile);
set_template_user_data(data_dir.ToWStringHack());
}
void RunStartupTest(const char* graph, const char* trace,
bool test_cold, bool important, int profile_type) {
profile_type_ = profile_type;
// Sets the profile data for the run. For now, this is only used for
// the non-default themes test.
if (profile_type != UITest::DEFAULT_THEME) {
set_template_user_data(UITest::ComputeTypicalUserDataSource(
profile_type).ToWStringHack());
}
const int kNumCyclesMax = 20;
int numCycles = kNumCyclesMax;
// It's ok for unit test code to use getenv(), isn't it?
#if defined(OS_WIN)
#pragma warning( disable : 4996 )
#endif
const char* numCyclesEnv = getenv("STARTUP_TESTS_NUMCYCLES");
if (numCyclesEnv && StringToInt(numCyclesEnv, &numCycles))
LOG(INFO) << "STARTUP_TESTS_NUMCYCLES set in environment, "
<< "so setting numCycles to " << numCycles;
TimeDelta timings[kNumCyclesMax];
for (int i = 0; i < numCycles; ++i) {
if (test_cold) {
FilePath dir_app;
ASSERT_TRUE(PathService::Get(chrome::DIR_APP, &dir_app));
FilePath chrome_exe(dir_app.Append(
FilePath::FromWStringHack(chrome::kBrowserProcessExecutablePath)));
ASSERT_TRUE(EvictFileFromSystemCacheWrapper(chrome_exe));
#if defined(OS_WIN)
// chrome.dll is windows specific.
FilePath chrome_dll(dir_app.Append(FILE_PATH_LITERAL("chrome.dll")));
ASSERT_TRUE(EvictFileFromSystemCacheWrapper(chrome_dll));
#endif
#if defined(OS_WIN)
// TODO(port): Re-enable once gears is working on mac/linux.
FilePath gears_dll;
ASSERT_TRUE(PathService::Get(chrome::FILE_GEARS_PLUGIN, &gears_dll));
ASSERT_TRUE(EvictFileFromSystemCacheWrapper(gears_dll));
#else
NOTIMPLEMENTED() << "gears not enabled yet";
#endif
}
UITest::SetUp();
TimeTicks end_time = TimeTicks::Now();
timings[i] = end_time - browser_launch_time_;
// TODO(beng): Can't shut down so quickly. Figure out why, and fix. If we
// do, we crash.
PlatformThread::Sleep(50);
UITest::TearDown();
if (i == 0) {
// Re-use the profile data after first run so that the noise from
// creating databases doesn't impact all the runs.
clear_profile_ = false;
// Clear template_user_data_ so we don't try to copy it over each time
// through.
set_template_user_data(L"");
}
}
std::string times;
for (int i = 0; i < numCycles; ++i)
StringAppendF(×, "%.2f,", timings[i].InMillisecondsF());
PrintResultList(graph, "", trace, times, "ms", important);
}
protected:
std::string pages_;
};
class StartupReferenceTest : public StartupTest {
public:
// override the browser directory that is used by UITest::SetUp to cause it
// to use the reference build instead.
void SetUp() {
FilePath dir;
PathService::Get(chrome::DIR_TEST_TOOLS, &dir);
dir = dir.AppendASCII("reference_build");
#if defined(OS_WIN)
dir = dir.AppendASCII("chrome");
#elif defined(OS_LINUX)
dir = dir.AppendASCII("chrome_linux");
#elif defined(OS_MACOSX)
dir = dir.AppendASCII("chrome_mac");
#endif
browser_directory_ = dir;
}
};
TEST_F(StartupTest, Perf) {
RunStartupTest("warm", "t", false /* not cold */, true /* important */,
UITest::DEFAULT_THEME);
}
// TODO(port): We need a mac reference build checked in for this.
TEST_F(StartupReferenceTest, Perf) {
RunStartupTest("warm", "t_ref", false /* not cold */,
true /* important */, UITest::DEFAULT_THEME);
}
// TODO(mpcomplete): Should we have reference timings for all these?
TEST_F(StartupTest, PerfCold) {
RunStartupTest("cold", "t", true /* cold */, false /* not important */,
UITest::DEFAULT_THEME);
}
TEST_F(StartupTest, PerfExtensionEmpty) {
SetUpWithFileURL();
SetUpWithExtensionsProfile("empty");
RunStartupTest("warm", "t", false /* cold */, false /* not important */,
UITest::DEFAULT_THEME);
}
TEST_F(StartupTest, PerfExtensionToolstrips1) {
SetUpWithFileURL();
SetUpWithExtensionsProfile("toolstrips1");
RunStartupTest("warm", "extension_toolstrip1",
false /* cold */, false /* not important */,
UITest::DEFAULT_THEME);
}
TEST_F(StartupTest, PerfExtensionToolstrips50) {
SetUpWithFileURL();
SetUpWithExtensionsProfile("toolstrips50");
RunStartupTest("warm", "extension_toolstrip50",
false /* cold */, false /* not important */,
UITest::DEFAULT_THEME);
}
TEST_F(StartupTest, PerfExtensionContentScript1) {
SetUpWithFileURL();
SetUpWithExtensionsProfile("content_scripts1");
RunStartupTest("warm", "extension_content_scripts1",
false /* cold */, false /* not important */,
UITest::DEFAULT_THEME);
}
TEST_F(StartupTest, PerfExtensionContentScript50) {
SetUpWithFileURL();
SetUpWithExtensionsProfile("content_scripts50");
RunStartupTest("warm", "extension_content_scripts50",
false /* cold */, false /* not important */,
UITest::DEFAULT_THEME);
}
#if defined(OS_WIN)
// TODO(port): Enable gears tests on linux/mac once gears is working.
TEST_F(StartupTest, PerfGears) {
SetUpWithFileURL();
RunStartupTest("warm", "gears", false /* not cold */,
false /* not important */, UITest::DEFAULT_THEME);
}
TEST_F(StartupTest, PerfColdGears) {
SetUpWithFileURL();
RunStartupTest("cold", "gears", true /* cold */,
false /* not important */, UITest::DEFAULT_THEME);
}
#endif
TEST_F(StartupTest, PerfColdComplexTheme) {
RunStartupTest("warm", "t-theme", false /* warm */,
false /* not important */, UITest::COMPLEX_THEME);
}
#if defined(OS_LINUX)
TEST_F(StartupTest, PerfColdGtkTheme) {
RunStartupTest("warm", "gtk-theme", false /* warm */,
false /* not important */, UITest::NATIVE_THEME);
}
TEST_F(StartupTest, PrefColdNativeFrame) {
RunStartupTest("warm", "custom-frame", false /* warm */,
false /* not important */, UITest::CUSTOM_FRAME);
}
TEST_F(StartupTest, PerfColdNativeFrameGtkTheme) {
RunStartupTest("warm", "custom-frame-gtk-theme", false /* warm */,
false /* not important */, UITest::CUSTOM_FRAME_NATIVE_THEME);
}
#endif
} // namespace
<commit_msg>Disable extension startup tests on Mac, since they're causing it to hang.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/platform_thread.h"
#include "base/string_util.h"
#include "base/test_file_util.h"
#include "base/time.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"
using base::TimeDelta;
using base::TimeTicks;
namespace {
class StartupTest : public UITest {
public:
StartupTest() {
show_window_ = true;
pages_ = "about:blank";
}
void SetUp() {}
void TearDown() {}
// Load a file on startup rather than about:blank. This tests a longer
// startup path, including resource loading and the loading of gears.dll.
void SetUpWithFileURL() {
FilePath file_url;
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &file_url));
file_url = file_url.AppendASCII("empty.html");
ASSERT_TRUE(file_util::PathExists(file_url));
launch_arguments_.AppendLooseValue(file_url.ToWStringHack());
pages_ = WideToUTF8(file_url.ToWStringHack());
}
// Use the given profile in the test data extensions/profiles dir. This tests
// startup with extensions installed.
void SetUpWithExtensionsProfile(const char* profile) {
FilePath data_dir;
PathService::Get(chrome::DIR_TEST_DATA, &data_dir);
data_dir = data_dir.AppendASCII("extensions").AppendASCII("profiles").
AppendASCII(profile);
set_template_user_data(data_dir.ToWStringHack());
}
void RunStartupTest(const char* graph, const char* trace,
bool test_cold, bool important, int profile_type) {
profile_type_ = profile_type;
// Sets the profile data for the run. For now, this is only used for
// the non-default themes test.
if (profile_type != UITest::DEFAULT_THEME) {
set_template_user_data(UITest::ComputeTypicalUserDataSource(
profile_type).ToWStringHack());
}
const int kNumCyclesMax = 20;
int numCycles = kNumCyclesMax;
// It's ok for unit test code to use getenv(), isn't it?
#if defined(OS_WIN)
#pragma warning( disable : 4996 )
#endif
const char* numCyclesEnv = getenv("STARTUP_TESTS_NUMCYCLES");
if (numCyclesEnv && StringToInt(numCyclesEnv, &numCycles))
LOG(INFO) << "STARTUP_TESTS_NUMCYCLES set in environment, "
<< "so setting numCycles to " << numCycles;
TimeDelta timings[kNumCyclesMax];
for (int i = 0; i < numCycles; ++i) {
if (test_cold) {
FilePath dir_app;
ASSERT_TRUE(PathService::Get(chrome::DIR_APP, &dir_app));
FilePath chrome_exe(dir_app.Append(
FilePath::FromWStringHack(chrome::kBrowserProcessExecutablePath)));
ASSERT_TRUE(EvictFileFromSystemCacheWrapper(chrome_exe));
#if defined(OS_WIN)
// chrome.dll is windows specific.
FilePath chrome_dll(dir_app.Append(FILE_PATH_LITERAL("chrome.dll")));
ASSERT_TRUE(EvictFileFromSystemCacheWrapper(chrome_dll));
#endif
#if defined(OS_WIN)
// TODO(port): Re-enable once gears is working on mac/linux.
FilePath gears_dll;
ASSERT_TRUE(PathService::Get(chrome::FILE_GEARS_PLUGIN, &gears_dll));
ASSERT_TRUE(EvictFileFromSystemCacheWrapper(gears_dll));
#else
NOTIMPLEMENTED() << "gears not enabled yet";
#endif
}
UITest::SetUp();
TimeTicks end_time = TimeTicks::Now();
timings[i] = end_time - browser_launch_time_;
// TODO(beng): Can't shut down so quickly. Figure out why, and fix. If we
// do, we crash.
PlatformThread::Sleep(50);
UITest::TearDown();
if (i == 0) {
// Re-use the profile data after first run so that the noise from
// creating databases doesn't impact all the runs.
clear_profile_ = false;
// Clear template_user_data_ so we don't try to copy it over each time
// through.
set_template_user_data(L"");
}
}
std::string times;
for (int i = 0; i < numCycles; ++i)
StringAppendF(×, "%.2f,", timings[i].InMillisecondsF());
PrintResultList(graph, "", trace, times, "ms", important);
}
protected:
std::string pages_;
};
class StartupReferenceTest : public StartupTest {
public:
// override the browser directory that is used by UITest::SetUp to cause it
// to use the reference build instead.
void SetUp() {
FilePath dir;
PathService::Get(chrome::DIR_TEST_TOOLS, &dir);
dir = dir.AppendASCII("reference_build");
#if defined(OS_WIN)
dir = dir.AppendASCII("chrome");
#elif defined(OS_LINUX)
dir = dir.AppendASCII("chrome_linux");
#elif defined(OS_MACOSX)
dir = dir.AppendASCII("chrome_mac");
#endif
browser_directory_ = dir;
}
};
TEST_F(StartupTest, Perf) {
RunStartupTest("warm", "t", false /* not cold */, true /* important */,
UITest::DEFAULT_THEME);
}
// TODO(port): We need a mac reference build checked in for this.
TEST_F(StartupReferenceTest, Perf) {
RunStartupTest("warm", "t_ref", false /* not cold */,
true /* important */, UITest::DEFAULT_THEME);
}
// TODO(mpcomplete): Should we have reference timings for all these?
TEST_F(StartupTest, PerfCold) {
RunStartupTest("cold", "t", true /* cold */, false /* not important */,
UITest::DEFAULT_THEME);
}
#if defined(OS_MACOSX)
// TODO(mpcomplete): running these tests on a mac builder results in leaked
// chrome processes, causing the build slave to hang.
// http://code.google.com/p/chromium/issues/detail?id=22287
#else
TEST_F(StartupTest, PerfExtensionEmpty) {
SetUpWithFileURL();
SetUpWithExtensionsProfile("empty");
RunStartupTest("warm", "t", false /* cold */, false /* not important */,
UITest::DEFAULT_THEME);
}
x
TEST_F(StartupTest, PerfExtensionToolstrips1) {
SetUpWithFileURL();
SetUpWithExtensionsProfile("toolstrips1");
RunStartupTest("warm", "extension_toolstrip1",
false /* cold */, false /* not important */,
UITest::DEFAULT_THEME);
}
TEST_F(StartupTest, PerfExtensionToolstrips50) {
SetUpWithFileURL();
SetUpWithExtensionsProfile("toolstrips50");
RunStartupTest("warm", "extension_toolstrip50",
false /* cold */, false /* not important */,
UITest::DEFAULT_THEME);
}
TEST_F(StartupTest, PerfExtensionContentScript1) {
SetUpWithFileURL();
SetUpWithExtensionsProfile("content_scripts1");
RunStartupTest("warm", "extension_content_scripts1",
false /* cold */, false /* not important */,
UITest::DEFAULT_THEME);
}
TEST_F(StartupTest, PerfExtensionContentScript50) {
SetUpWithFileURL();
SetUpWithExtensionsProfile("content_scripts50");
RunStartupTest("warm", "extension_content_scripts50",
false /* cold */, false /* not important */,
UITest::DEFAULT_THEME);
}
#endif
#if defined(OS_WIN)
// TODO(port): Enable gears tests on linux/mac once gears is working.
TEST_F(StartupTest, PerfGears) {
SetUpWithFileURL();
RunStartupTest("warm", "gears", false /* not cold */,
false /* not important */, UITest::DEFAULT_THEME);
}
TEST_F(StartupTest, PerfColdGears) {
SetUpWithFileURL();
RunStartupTest("cold", "gears", true /* cold */,
false /* not important */, UITest::DEFAULT_THEME);
}
#endif
TEST_F(StartupTest, PerfColdComplexTheme) {
RunStartupTest("warm", "t-theme", false /* warm */,
false /* not important */, UITest::COMPLEX_THEME);
}
#if defined(OS_LINUX)
TEST_F(StartupTest, PerfColdGtkTheme) {
RunStartupTest("warm", "gtk-theme", false /* warm */,
false /* not important */, UITest::NATIVE_THEME);
}
TEST_F(StartupTest, PrefColdNativeFrame) {
RunStartupTest("warm", "custom-frame", false /* warm */,
false /* not important */, UITest::CUSTOM_FRAME);
}
TEST_F(StartupTest, PerfColdNativeFrameGtkTheme) {
RunStartupTest("warm", "custom-frame-gtk-theme", false /* warm */,
false /* not important */, UITest::CUSTOM_FRAME_NATIVE_THEME);
}
#endif
} // namespace
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: rscdbl.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: obo $ $Date: 2006-09-17 15:57:57 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_rsc.hxx"
#include <stdio.h>
#ifndef _RSCDB_HXX
#include <rscdb.hxx>
#endif
#ifndef _RSCALL_H
#include <rscall.h>
#endif
#ifndef _RSCHASH_HXX
#include <rschash.hxx>
#endif
#ifndef _RSCTREE_HXX
#include <rsctree.hxx>
#endif
#ifndef _RSCTOP_HXX
#include <rsctop.hxx>
#endif
#ifndef _RSCLST_HXX
#include "rsclst.hxx"
#endif
/*************************************************************************
|*
|* RscTypCont::FillNameIdList()
|*
|* Beschreibung
|* Ersterstellung MM 07.05.91
|* Letzte Aenderung MM 30.05.91
|*
*************************************************************************/
REResourceList * InsertList( Atom nClassName, const RscId& rId,
REResourceList * pList ){
REResourceList * pSubList;
const char * pStrClass;
ByteString aStrClass;
pStrClass = pHS->getString( nClassName ).getStr();
if( pStrClass )
aStrClass = pStrClass;
else
aStrClass = ByteString::CreateFromInt32( (long)nClassName );
pSubList = new REResourceList( pList, aStrClass, rId );
pList->Insert( pSubList, 0xFFFFFFFF );
return( pSubList );
}
void FillSubList( RSCINST & rInst, REResourceList * pList )
{
sal_uInt32 nCount, i;
SUBINFO_STRUCT aInfo;
REResourceList* pSubList;
RSCINST aTmpI;
nCount = rInst.pClass->GetCount( rInst );
for( i = 0; i < nCount; i++ ){
aInfo = rInst.pClass->GetInfoEle( rInst, i );
aTmpI = rInst.pClass->GetPosEle( rInst, i );
pSubList = InsertList( aInfo.pClass->GetId(),
aInfo.aId, pList );
FillSubList( aTmpI, pSubList );
};
}
void FillListObj( ObjNode * pObjNode, RscTop * pRscTop,
REResourceList * pList, ULONG lFileKey )
{
if( pObjNode ){
if( pObjNode->GetFileKey() == lFileKey ){
RSCINST aTmpI;
REResourceList* pSubList;
FillListObj( (ObjNode*)pObjNode->Left(), pRscTop,
pList, lFileKey );
pSubList = InsertList( pRscTop->GetId(),
pObjNode->GetRscId(), pList );
aTmpI.pClass = pRscTop;
aTmpI.pData = pObjNode->GetRscObj();
FillSubList( aTmpI, pSubList );
FillListObj( (ObjNode*)pObjNode->Right(), pRscTop,
pList, lFileKey );
}
};
}
void FillList( RscTop * pRscTop, REResourceList * pList, ULONG lFileKey ){
if( pRscTop ){
FillList( (RscTop*)pRscTop->Left(), pList, lFileKey );
FillListObj( pRscTop->GetObjNode(), pRscTop, pList, lFileKey );
FillList( (RscTop*)pRscTop->Right(), pList, lFileKey );
};
}
void RscTypCont::FillNameIdList( REResourceList * pList, ULONG lFileKey ){
FillList( pRoot, pList, lFileKey );
}
<commit_msg>INTEGRATION: CWS changefileheader (1.4.54); FILE MERGED 2008/04/01 12:33:28 thb 1.4.54.2: #i85898# Stripping all external header guards 2008/03/31 13:15:58 rt 1.4.54.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: rscdbl.cxx,v $
* $Revision: 1.5 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_rsc.hxx"
#include <stdio.h>
#include <rscdb.hxx>
#include <rscall.h>
#include <rschash.hxx>
#include <rsctree.hxx>
#include <rsctop.hxx>
#include "rsclst.hxx"
/*************************************************************************
|*
|* RscTypCont::FillNameIdList()
|*
|* Beschreibung
|* Ersterstellung MM 07.05.91
|* Letzte Aenderung MM 30.05.91
|*
*************************************************************************/
REResourceList * InsertList( Atom nClassName, const RscId& rId,
REResourceList * pList ){
REResourceList * pSubList;
const char * pStrClass;
ByteString aStrClass;
pStrClass = pHS->getString( nClassName ).getStr();
if( pStrClass )
aStrClass = pStrClass;
else
aStrClass = ByteString::CreateFromInt32( (long)nClassName );
pSubList = new REResourceList( pList, aStrClass, rId );
pList->Insert( pSubList, 0xFFFFFFFF );
return( pSubList );
}
void FillSubList( RSCINST & rInst, REResourceList * pList )
{
sal_uInt32 nCount, i;
SUBINFO_STRUCT aInfo;
REResourceList* pSubList;
RSCINST aTmpI;
nCount = rInst.pClass->GetCount( rInst );
for( i = 0; i < nCount; i++ ){
aInfo = rInst.pClass->GetInfoEle( rInst, i );
aTmpI = rInst.pClass->GetPosEle( rInst, i );
pSubList = InsertList( aInfo.pClass->GetId(),
aInfo.aId, pList );
FillSubList( aTmpI, pSubList );
};
}
void FillListObj( ObjNode * pObjNode, RscTop * pRscTop,
REResourceList * pList, ULONG lFileKey )
{
if( pObjNode ){
if( pObjNode->GetFileKey() == lFileKey ){
RSCINST aTmpI;
REResourceList* pSubList;
FillListObj( (ObjNode*)pObjNode->Left(), pRscTop,
pList, lFileKey );
pSubList = InsertList( pRscTop->GetId(),
pObjNode->GetRscId(), pList );
aTmpI.pClass = pRscTop;
aTmpI.pData = pObjNode->GetRscObj();
FillSubList( aTmpI, pSubList );
FillListObj( (ObjNode*)pObjNode->Right(), pRscTop,
pList, lFileKey );
}
};
}
void FillList( RscTop * pRscTop, REResourceList * pList, ULONG lFileKey ){
if( pRscTop ){
FillList( (RscTop*)pRscTop->Left(), pList, lFileKey );
FillListObj( pRscTop->GetObjNode(), pRscTop, pList, lFileKey );
FillList( (RscTop*)pRscTop->Right(), pList, lFileKey );
};
}
void RscTypCont::FillNameIdList( REResourceList * pList, ULONG lFileKey ){
FillList( pRoot, pList, lFileKey );
}
<|endoftext|>
|
<commit_before>/* -*- mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
// vim:sts=4:sw=4:ts=4:noet:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s
/*
* Copyright (C) 2014 FFLAS-FFACK group
*
* Written by Clement Pernet <[email protected]>
* Brice Boyer (briceboyer) <[email protected]>
*
*
* ========LICENCE========
* This file is part of the library FFLAS-FFPACK.
*
* FFLAS-FFPACK 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
* ========LICENCE========
*.
*/
#ifndef __FFLASFFPACK_ffpack_ftrtr_INL
#define __FFLASFFPACK_ffpack_ftrtr_INL
namespace FFPACK {
template<class Field>
void
ftrtri (const Field& F, const FFLAS::FFLAS_UPLO Uplo, const FFLAS::FFLAS_DIAG Diag,
const size_t N, typename Field::Element_ptr A, const size_t lda)
{
if (!N) return;
if (N == 1){
if (Diag == FFLAS::FflasNonUnit)
F.invin (*A);
}
else {
size_t N1 = N/2;
size_t N2 = N - N1;
ftrtri (F, Uplo, Diag, N1, A, lda);
ftrtri (F, Uplo, Diag, N2, A + N1*(lda+1), lda);
if (Uplo == FFLAS::FflasUpper){
ftrmm (F, FFLAS::FflasLeft, Uplo, FFLAS::FflasNoTrans, Diag, N1, N2,
F.one, A, lda, A + N1, lda);
ftrmm (F, FFLAS::FflasRight, Uplo, FFLAS::FflasNoTrans, Diag, N1, N2,
F.mOne, A + N1*(lda+1), lda, A + N1, lda);
}
else {
ftrmm (F, FFLAS::FflasLeft, Uplo, FFLAS::FflasNoTrans, Diag, N2, N1,
F.one, A + N1*(lda+1), lda, A + N1*lda, lda);
ftrmm (F, FFLAS::FflasRight, Uplo, FFLAS::FflasNoTrans, Diag, N2, N1,
F.mOne, A, lda, A + N1*lda, lda);
}
}
}
template<class Field>
void
ftrtrm (const Field& F, const FFLAS::FFLAS_SIDE side, const FFLAS::FFLAS_DIAG diag,
const size_t N, typename Field::Element_ptr A, const size_t lda)
{
if (N <= 1)
return;
size_t N1 = N/2;
size_t N2 = N-N1;
if (side == FFLAS::FflasLeft){
ftrtrm (F, side, diag, N1, A, lda);
FFLAS::fgemm (F, FFLAS::FflasNoTrans, FFLAS::FflasNoTrans, N1, N1, N2, F.one,
A+N1, lda, A+N1*lda, lda, F.one, A, lda);
FFLAS::ftrmm (F, FFLAS::FflasRight, FFLAS::FflasLower, FFLAS::FflasNoTrans,
(diag == FFLAS::FflasUnit) ? FFLAS::FflasNonUnit : FFLAS::FflasUnit,
N1, N2, F.one, A + N1*(lda+1), lda, A + N1, lda);
FFLAS::ftrmm (F, FFLAS::FflasLeft, FFLAS::FflasUpper, FFLAS::FflasNoTrans, diag, N2, N1,
F.one, A + N1*(lda+1), lda, A + N1*lda, lda);
ftrtrm (F, side, diag, N2, A + N1*(lda+1), lda);
} else { // side = FflasRight
ftrtrm (F, side, diag, N2, A + N1*(lda+1), lda);
FFLAS::fgemm (F, FFLAS::FflasNoTrans, FFLAS::FflasNoTrans, N2, N2, N1, F.one,
A+N1*lda, lda, A+N1, lda, F.one, A + N1*(lda+1), lda);
FFLAS::ftrmm (F, FFLAS::FflasLeft, FFLAS::FflasLower, FFLAS::FflasNoTrans,
(diag == FFLAS::FflasUnit) ? FFLAS::FflasNonUnit : FFLAS::FflasUnit,
N1, N2, F.one, A, lda, A + N1, lda);
FFLAS::ftrmm (F, FFLAS::FflasRight, FFLAS::FflasUpper, FFLAS::FflasNoTrans, diag, N2, N1,
F.one, A, lda, A + N1*lda, lda);
ftrtrm (F, side, diag, N1, A, lda);
}
}
template<class Field>
void trinv_left( const Field& F, const size_t N, typename Field::ConstElement_ptr L, const size_t ldl,
typename Field::Element_ptr X, const size_t ldx )
{
FFLAS::fassign(F,N,N,L,ldl,X,ldx);
ftrtri (F, FFLAS::FflasLower, FFLAS::FflasUnit, N, X, ldx);
//invL(F,N,L,ldl,X,ldx);
}
} // FFPACK
#endif // __FFLASFFPACK_ffpack_ftrtr_INL
<commit_msg>Modified base case in ftrtri to use an iterative algorithm. The current threshold is N == 5. TODO : find optimal threshold.<commit_after>/* -*- mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
// vim:sts=4:sw=4:ts=4:noet:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s
/*
* Copyright (C) 2014 FFLAS-FFACK group
*
* Written by Clement Pernet <[email protected]>
* Brice Boyer (briceboyer) <[email protected]>
*
*
* ========LICENCE========
* This file is part of the library FFLAS-FFPACK.
*
* FFLAS-FFPACK 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
* ========LICENCE========
*.
*/
#ifndef __FFLASFFPACK_ffpack_ftrtr_INL
#define __FFLASFFPACK_ffpack_ftrtr_INL
namespace FFPACK {
template<class Field>
void
ftrtri (const Field& F, const FFLAS::FFLAS_UPLO Uplo, const FFLAS::FFLAS_DIAG Diag,
const size_t N, typename Field::Element_ptr A, const size_t lda)
{
std::cout << "rec call" << std::endl;
if (!N) return;
if (N <= 5){ // base case
if (Uplo == FFLAS::FflasUpper){
for(size_t li = N-1; li < N; li--){ // since li is size_t when it goes below 0 it will overflow above size
if(Diag == FFLAS::FflasNonUnit)
F.invin(A[(lda+1)*li]); //invert element on diagonal
for(size_t co = N-1; co > li; co--){
fgemv(F,FFLAS::FflasNoTrans,1,co-li,
A[li*(lda+1)], // diagonal element of the current line
(A+li*(lda+1)+1),1, // horizontal vector starting after the diagonal left of the current element
(A+co+lda*(li+1)),lda, // vertical vector starting below the current element
F.zero,(A+co+lda*li),lda); // The currrent element
F.negin(A[co+lda*li]);
}
}
}
else{ // Uplo == FflasLower
for(size_t li = 0; li < N; li++){
F.invin(A[(lda+1)*li]); //invert element on diagonal
for(size_t co = 0; co < li; co++){
fgemv(F,FFLAS::FflasNoTrans,1,li-co,
*(A+li*(lda+1)), // diagonal element of the current line
(A+co+li*lda),1, // horizontal vector starting at the current element
(A+co*(lda+1)),lda, // vertical vector starting at the diagonal element above the current element
F.zero,
(A+co+lda*li),lda); // The currrent element
F.negin(A[co+lda*li]);
}
}
}
}
else { // recursive case
size_t N1 = N/2;
size_t N2 = N - N1;
ftrtri (F, Uplo, Diag, N1, A, lda);
ftrtri (F, Uplo, Diag, N2, A + N1*(lda+1), lda);
if (Uplo == FFLAS::FflasUpper){
ftrmm (F, FFLAS::FflasLeft, Uplo, FFLAS::FflasNoTrans, Diag, N1, N2,
F.one, A, lda, A + N1, lda);
ftrmm (F, FFLAS::FflasRight, Uplo, FFLAS::FflasNoTrans, Diag, N1, N2,
F.mOne, A + N1*(lda+1), lda, A + N1, lda);
}
else {
ftrmm (F, FFLAS::FflasLeft, Uplo, FFLAS::FflasNoTrans, Diag, N2, N1,
F.one, A + N1*(lda+1), lda, A + N1*lda, lda);
ftrmm (F, FFLAS::FflasRight, Uplo, FFLAS::FflasNoTrans, Diag, N2, N1,
F.mOne, A, lda, A + N1*lda, lda);
}
}
}
template<class Field>
void
ftrtrm (const Field& F, const FFLAS::FFLAS_SIDE side, const FFLAS::FFLAS_DIAG diag,
const size_t N, typename Field::Element_ptr A, const size_t lda)
{
if (N <= 1)
return;
size_t N1 = N/2;
size_t N2 = N-N1;
if (side == FFLAS::FflasLeft){
ftrtrm (F, side, diag, N1, A, lda);
FFLAS::fgemm (F, FFLAS::FflasNoTrans, FFLAS::FflasNoTrans, N1, N1, N2, F.one,
A+N1, lda, A+N1*lda, lda, F.one, A, lda);
FFLAS::ftrmm (F, FFLAS::FflasRight, FFLAS::FflasLower, FFLAS::FflasNoTrans,
(diag == FFLAS::FflasUnit) ? FFLAS::FflasNonUnit : FFLAS::FflasUnit,
N1, N2, F.one, A + N1*(lda+1), lda, A + N1, lda);
FFLAS::ftrmm (F, FFLAS::FflasLeft, FFLAS::FflasUpper, FFLAS::FflasNoTrans, diag, N2, N1,
F.one, A + N1*(lda+1), lda, A + N1*lda, lda);
ftrtrm (F, side, diag, N2, A + N1*(lda+1), lda);
} else { // side = FflasRight
ftrtrm (F, side, diag, N2, A + N1*(lda+1), lda);
FFLAS::fgemm (F, FFLAS::FflasNoTrans, FFLAS::FflasNoTrans, N2, N2, N1, F.one,
A+N1*lda, lda, A+N1, lda, F.one, A + N1*(lda+1), lda);
FFLAS::ftrmm (F, FFLAS::FflasLeft, FFLAS::FflasLower, FFLAS::FflasNoTrans,
(diag == FFLAS::FflasUnit) ? FFLAS::FflasNonUnit : FFLAS::FflasUnit,
N1, N2, F.one, A, lda, A + N1, lda);
FFLAS::ftrmm (F, FFLAS::FflasRight, FFLAS::FflasUpper, FFLAS::FflasNoTrans, diag, N2, N1,
F.one, A, lda, A + N1*lda, lda);
ftrtrm (F, side, diag, N1, A, lda);
}
}
template<class Field>
void trinv_left( const Field& F, const size_t N, typename Field::ConstElement_ptr L, const size_t ldl,
typename Field::Element_ptr X, const size_t ldx )
{
FFLAS::fassign(F,N,N,L,ldl,X,ldx);
ftrtri (F, FFLAS::FflasLower, FFLAS::FflasUnit, N, X, ldx);
//invL(F,N,L,ldl,X,ldx);
}
} // FFPACK
#endif // __FFLASFFPACK_ffpack_ftrtr_INL
<|endoftext|>
|
<commit_before>//
// Pipeline.cpp
// Vortex2D
//
#include "Pipeline.h"
#include <algorithm>
namespace Vortex2D { namespace Renderer {
GraphicsPipeline::Builder::Builder()
{
mInputAssembly = vk::PipelineInputAssemblyStateCreateInfo()
.setTopology(vk::PrimitiveTopology::eTriangleList);
mRasterizationInfo = vk::PipelineRasterizationStateCreateInfo()
.setLineWidth(1.0f)
.setCullMode(vk::CullModeFlagBits::eBack)
.setFrontFace(vk::FrontFace::eClockwise)
.setPolygonMode(vk::PolygonMode::eFill);
// TODO multisample as parameter
mMultisampleInfo = vk::PipelineMultisampleStateCreateInfo()
.setRasterizationSamples(vk::SampleCountFlagBits::e1)
.setMinSampleShading(1.0f);
}
GraphicsPipeline::Builder& GraphicsPipeline::Builder::Shader(vk::ShaderModule shader,
vk::ShaderStageFlagBits shaderStage)
{
auto shaderStageInfo = vk::PipelineShaderStageCreateInfo()
.setModule(shader)
.setPName("main")
.setStage(shaderStage);
mShaderStages.push_back(shaderStageInfo);
return *this;
}
GraphicsPipeline::Builder& GraphicsPipeline::Builder::VertexAttribute(uint32_t location,
uint32_t binding,
vk::Format format,
uint32_t offset)
{
mVertexAttributeDescriptions.push_back({location, binding, format, offset});
return *this;
}
GraphicsPipeline::Builder& GraphicsPipeline::Builder::VertexBinding(uint32_t binding,
uint32_t stride,
vk::VertexInputRate inputRate)
{
mVertexBindingDescriptions.push_back({binding, stride, inputRate});
return *this;
}
GraphicsPipeline::Builder& GraphicsPipeline::Builder::Topology(vk::PrimitiveTopology topology)
{
mInputAssembly.setTopology(topology);
return *this;
}
GraphicsPipeline::Builder& GraphicsPipeline::Builder::Layout(vk::PipelineLayout pipelineLayout)
{
mPipelineLayout = pipelineLayout;
return *this;
}
vk::UniquePipeline GraphicsPipeline::Builder::Create(vk::Device device, const RenderState& renderState)
{
auto vertexInputInfo = vk::PipelineVertexInputStateCreateInfo()
.setVertexBindingDescriptionCount((uint32_t)mVertexBindingDescriptions.size())
.setPVertexBindingDescriptions(mVertexBindingDescriptions.data())
.setVertexAttributeDescriptionCount((uint32_t)mVertexAttributeDescriptions.size())
.setPVertexAttributeDescriptions(mVertexAttributeDescriptions.data());
auto viewPort = vk::Viewport(0, 0, static_cast<float>(renderState.Width), static_cast<float>(renderState.Height), 0.0f, 1.0f);
auto scissor = vk::Rect2D({0, 0}, {renderState.Width, renderState.Height});
auto viewPortState = vk::PipelineViewportStateCreateInfo()
.setScissorCount(1)
.setPScissors(&scissor)
.setViewportCount(1)
.setPViewports(&viewPort);
auto blendInfo = vk::PipelineColorBlendStateCreateInfo()
.setAttachmentCount(1)
.setPAttachments(&renderState.BlendState.ColorBlend)
.setBlendConstants(renderState.BlendState.BlendConstants);
auto pipelineInfo = vk::GraphicsPipelineCreateInfo()
.setStageCount((uint32_t)mShaderStages.size())
.setPStages(mShaderStages.data())
.setPVertexInputState(&vertexInputInfo)
.setPInputAssemblyState(&mInputAssembly)
.setPRasterizationState(&mRasterizationInfo)
.setPMultisampleState(&mMultisampleInfo)
.setPColorBlendState(&blendInfo)
.setLayout(mPipelineLayout)
.setRenderPass(renderState.RenderPass)
.setPViewportState(&viewPortState);
return device.createGraphicsPipelineUnique(nullptr, pipelineInfo);
}
GraphicsPipeline::GraphicsPipeline()
{
}
GraphicsPipeline::GraphicsPipeline(GraphicsPipeline::Builder builder)
: mBuilder(builder)
{
}
void GraphicsPipeline::Create(vk::Device device, const RenderState& renderState)
{
auto it = std::find_if(mPipelines.begin(), mPipelines.end(), [&](const PipelineList::value_type& value)
{
return value.first == renderState;
});
if (it == mPipelines.end())
{
mPipelines.emplace_back(renderState, mBuilder.Create(device, renderState));
}
}
void GraphicsPipeline::Bind(vk::CommandBuffer commandBuffer, const RenderState& renderState)
{
auto it = std::find_if(mPipelines.begin(), mPipelines.end(), [&](const PipelineList::value_type& value)
{
return value.first == renderState;
});
if (it != mPipelines.end())
{
commandBuffer.bindPipeline(vk::PipelineBindPoint::eGraphics, *it->second);
}
else
{
throw std::runtime_error("No pipeline for this renderpass!");
}
}
SpecConstInfo::SpecConstInfo()
{
}
vk::UniquePipeline MakeComputePipeline(vk::Device device,
vk::ShaderModule shader,
vk::PipelineLayout layout,
SpecConstInfo specConstInfo)
{
auto stageInfo = vk::PipelineShaderStageCreateInfo()
.setModule(shader)
.setPName("main")
.setStage(vk::ShaderStageFlagBits::eCompute)
.setPSpecializationInfo(&specConstInfo.info);
auto pipelineInfo = vk::ComputePipelineCreateInfo()
.setStage(stageInfo)
.setLayout(layout);
return device.createComputePipelineUnique(nullptr, pipelineInfo);
}
}}
<commit_msg>no triangle culling. adding dynamic viewport and sciscors<commit_after>//
// Pipeline.cpp
// Vortex2D
//
#include "Pipeline.h"
#include <algorithm>
namespace Vortex2D { namespace Renderer {
GraphicsPipeline::Builder::Builder()
{
mInputAssembly = vk::PipelineInputAssemblyStateCreateInfo()
.setTopology(vk::PrimitiveTopology::eTriangleList);
mRasterizationInfo = vk::PipelineRasterizationStateCreateInfo()
.setLineWidth(1.0f)
.setCullMode(vk::CullModeFlagBits::eNone)
.setFrontFace(vk::FrontFace::eCounterClockwise)
.setPolygonMode(vk::PolygonMode::eFill);
// TODO multisample as parameter
mMultisampleInfo = vk::PipelineMultisampleStateCreateInfo()
.setRasterizationSamples(vk::SampleCountFlagBits::e1)
.setMinSampleShading(1.0f);
}
GraphicsPipeline::Builder& GraphicsPipeline::Builder::Shader(vk::ShaderModule shader,
vk::ShaderStageFlagBits shaderStage)
{
auto shaderStageInfo = vk::PipelineShaderStageCreateInfo()
.setModule(shader)
.setPName("main")
.setStage(shaderStage);
mShaderStages.push_back(shaderStageInfo);
return *this;
}
GraphicsPipeline::Builder& GraphicsPipeline::Builder::VertexAttribute(uint32_t location,
uint32_t binding,
vk::Format format,
uint32_t offset)
{
mVertexAttributeDescriptions.push_back({location, binding, format, offset});
return *this;
}
GraphicsPipeline::Builder& GraphicsPipeline::Builder::VertexBinding(uint32_t binding,
uint32_t stride,
vk::VertexInputRate inputRate)
{
mVertexBindingDescriptions.push_back({binding, stride, inputRate});
return *this;
}
GraphicsPipeline::Builder& GraphicsPipeline::Builder::Topology(vk::PrimitiveTopology topology)
{
mInputAssembly.setTopology(topology);
return *this;
}
GraphicsPipeline::Builder& GraphicsPipeline::Builder::Layout(vk::PipelineLayout pipelineLayout)
{
mPipelineLayout = pipelineLayout;
return *this;
}
vk::UniquePipeline GraphicsPipeline::Builder::Create(vk::Device device, const RenderState& renderState)
{
auto vertexInputInfo = vk::PipelineVertexInputStateCreateInfo()
.setVertexBindingDescriptionCount((uint32_t)mVertexBindingDescriptions.size())
.setPVertexBindingDescriptions(mVertexBindingDescriptions.data())
.setVertexAttributeDescriptionCount((uint32_t)mVertexAttributeDescriptions.size())
.setPVertexAttributeDescriptions(mVertexAttributeDescriptions.data());
auto viewPort = vk::Viewport(0, 0, static_cast<float>(renderState.Width), static_cast<float>(renderState.Height), 0.0f, 1.0f);
auto scissor = vk::Rect2D({0, 0}, {renderState.Width, renderState.Height});
auto viewPortState = vk::PipelineViewportStateCreateInfo()
.setScissorCount(1)
.setPScissors(&scissor)
.setViewportCount(1)
.setPViewports(&viewPort);
auto blendInfo = vk::PipelineColorBlendStateCreateInfo()
.setAttachmentCount(1)
.setPAttachments(&renderState.BlendState.ColorBlend)
.setBlendConstants(renderState.BlendState.BlendConstants);
vk::DynamicState dynamicStates[] = {vk::DynamicState::eScissor, vk::DynamicState::eViewport};
auto dynamicState = vk::PipelineDynamicStateCreateInfo()
.setPDynamicStates(dynamicStates)
.setDynamicStateCount(2);
auto pipelineInfo = vk::GraphicsPipelineCreateInfo()
.setStageCount((uint32_t)mShaderStages.size())
.setPStages(mShaderStages.data())
.setPVertexInputState(&vertexInputInfo)
.setPInputAssemblyState(&mInputAssembly)
.setPRasterizationState(&mRasterizationInfo)
.setPMultisampleState(&mMultisampleInfo)
.setPColorBlendState(&blendInfo)
.setLayout(mPipelineLayout)
.setRenderPass(renderState.RenderPass)
.setPViewportState(&viewPortState)
.setPDynamicState(&dynamicState);
return device.createGraphicsPipelineUnique(nullptr, pipelineInfo);
}
GraphicsPipeline::GraphicsPipeline()
{
}
GraphicsPipeline::GraphicsPipeline(GraphicsPipeline::Builder builder)
: mBuilder(builder)
{
}
void GraphicsPipeline::Create(vk::Device device, const RenderState& renderState)
{
auto it = std::find_if(mPipelines.begin(), mPipelines.end(), [&](const PipelineList::value_type& value)
{
return value.first == renderState;
});
if (it == mPipelines.end())
{
mPipelines.emplace_back(renderState, mBuilder.Create(device, renderState));
}
}
void GraphicsPipeline::Bind(vk::CommandBuffer commandBuffer, const RenderState& renderState)
{
auto it = std::find_if(mPipelines.begin(), mPipelines.end(), [&](const PipelineList::value_type& value)
{
return value.first == renderState;
});
if (it != mPipelines.end())
{
commandBuffer.bindPipeline(vk::PipelineBindPoint::eGraphics, *it->second);
}
else
{
throw std::runtime_error("No pipeline for this renderpass!");
}
}
SpecConstInfo::SpecConstInfo()
{
}
vk::UniquePipeline MakeComputePipeline(vk::Device device,
vk::ShaderModule shader,
vk::PipelineLayout layout,
SpecConstInfo specConstInfo)
{
auto stageInfo = vk::PipelineShaderStageCreateInfo()
.setModule(shader)
.setPName("main")
.setStage(vk::ShaderStageFlagBits::eCompute)
.setPSpecializationInfo(&specConstInfo.info);
auto pipelineInfo = vk::ComputePipelineCreateInfo()
.setStage(stageInfo)
.setLayout(layout);
return device.createComputePipelineUnique(nullptr, pipelineInfo);
}
}}
<|endoftext|>
|
<commit_before>#include "colibri_ca.h"
scan_ca::scan_ca()
{
goal_dir = 60; //goal direction
memset(scan4ca, 0.2, NUM_RAY4CA);
ptrScan4ca = scan4ca;
memset(delta_phi_vec, 0, NUM_RAY4CA);
memset(kp_phi_vec, 0, NUM_RAY4CA);
memset(phi_start_vec, 1, NUM_RAY4CA);
memset(phi_end_vec, 181, NUM_RAY4CA);
memset(krf_vec, 1/D_M, NUM_RAY4CA);
memset(kaf_vec, 0.0, NUM_RAY4CA);
memset(passfcn_vec, 0, NUM_RAY4CA);
max_passfcn_val = 0.0;
fwd_maxpass_cnt = 0;
bwd_maxpass_cnt = 0;
maxfcn_fwdbnd = 0;
maxfcn_bwdbnd = 0;
v = 0.0;
vth = 0.0;
angle_adj = 0.0;
vel_adj = 0.0;
apf_alarm = 0;
wander = 0;
scan_sub4ca = nh_ca.subscribe<sensor_msgs::LaserScan>("/scan", 1, &scan_ca::ScanCallBack, this);
apf_pub4mntr = nh_ca.advertise<colibri_msgs::AngPotnEngy>("/apf", 5);
rf_pub4mntr = nh_ca.advertise<colibri_msgs::AngPotnEngy>("/rf", 5);
}
scan_ca::~scan_ca()
{
}
void scan_ca::ScanCallBack(const sensor_msgs::LaserScan::ConstPtr& scan_ca)
{
int j = 61;
for(int i = 0; i < NUM_RAY4CA; i++)
{
scan4ca[i] = scan_ca->ranges[j];
/* if(scan4ca[i] < 0.1)
{
scan4ca[i] = (scan_ca->ranges[j-2]+scan_ca->ranges[j+2]+scan_ca->ranges[j-5]+scan_ca->ranges[j+5]) / 4 + LASER_EDGE_MIN;
}
*/
if(scan4ca[i] < 0.05)
{
scan4ca[i] = scan4ca[i-1];
}
j = j + 2;
}
}
void scan_ca::CalcKrfTheta(float* ptrKp_phi_vector, int* ptrPhi_range_start, int* ptrPhi_range_end)
{
for(int theta_index = 0; theta_index < NUM_RAY4CA; theta_index++)
{
for(int phi_index = 0; phi_index < NUM_RAY4CA; phi_index++)
{
if((theta_index >= *(ptrPhi_range_start+phi_index)) && (theta_index <= *(ptrPhi_range_end+phi_index)))
{
if(krf_vec[theta_index] <= *(ptrKp_phi_vector + phi_index)) // to obtain the max [Krf(phi,theta)] as Krf(theta)
{
krf_vec[theta_index] = *(ptrKp_phi_vector + phi_index);
}
}
}
}
}
void scan_ca::CalcPhiRange(int i, int range_num, int* ptrPhi_start, int* ptrPhi_end)
{
int index_start = 0;
int index_end = 0;
index_start = i - range_num;
index_end = i + range_num;
if(index_start < 1)
{
*ptrPhi_start = 1;
*ptrPhi_end = index_end;
}else if(index_end > NUM_RAY4CA)
{
*ptrPhi_start = index_start;
*ptrPhi_end = NUM_RAY4CA;
}else
{
*ptrPhi_start = index_start;
*ptrPhi_end = index_end;
}
}
void scan_ca::CalcPassFcnAndFwdBnd(unsigned int flag, float* max_passfcn_val, float* ptrK_pg)
{
float tmp_passfcn_value = 0.0;
int tmp_bound_forward = 0;
for(int j = 0; j < NUM_RAY4CA; j++) //from right to left search the max passfcn val and the max passfcn's bound index should locate at left terminal
{
if(flag == 1)
{
*(ptrK_pg + j) = 1 / (krf_vec[j]);
}
else
{
*(ptrK_pg + j) = kaf_vec[j] / (krf_vec[j]);
}
if(tmp_passfcn_value <= *(ptrK_pg + j))
{
tmp_bound_forward = j;
tmp_passfcn_value = *(ptrK_pg + j);
}
}
maxfcn_fwdbnd = tmp_bound_forward;
*max_passfcn_val = tmp_passfcn_value;
}
void scan_ca::CalcPassFcnAndBwdBnd(unsigned int flag, float* max_passfcn_val, float* ptrK_pg)
{
float tmp_passfcn_value = 0.0;
int tmp_bound_backward = 0;
for(int k = NUM_RAY4CA - 1; k >= 0; k--) //from left to right search the max passfcn val and the max passfcn's bound index should locate at right terminal
{
if(flag == 1)
{
*(ptrK_pg + k) = 1 / (krf_vec[k]);
}
else
{
*(ptrK_pg + k) = kaf_vec[k] / (krf_vec[k]);
}
if(tmp_passfcn_value <= *(ptrK_pg + k))
{
tmp_bound_backward = k;
tmp_passfcn_value = *(ptrK_pg + k);
}
}
maxfcn_bwdbnd = tmp_bound_backward;
*max_passfcn_val = tmp_passfcn_value;
}
void scan_ca::CalcAlarmInAPF(void)
{
if(max_passfcn_val <= PASSFCN_THD_RATIO * D_M)
{
apf_alarm = 1;
}
else
{
apf_alarm = 0;
}
}
float scan_ca::CalcAdjDir(float* ptrPassfcn_vector, float max_passfcn_val, int* fwd_bound, int* bwd_bound)
{
int mid_num = 90;
float adj_dir = 0.0;
float tmp_scope = MAX(PASSVAL_TOLLERENCE * max_passfcn_val, MAX_PASSFCN_SCOPE);
for(int m = 0; m <= mid_num; m++) //backward directrion(CW 180->0) search using forward bound
{
if(abs(*(ptrPassfcn_vector + *(fwd_bound) - m) - max_passfcn_val) < tmp_scope)
{
fwd_maxpass_cnt++;
}else
{
break;
}
}
for(int n = 0; n <= mid_num; n++) // forward direction(CCW 0->180) search using backward bound
{
if(abs(*(ptrPassfcn_vector + *(bwd_bound) + n) - max_passfcn_val) < tmp_scope)
{
bwd_maxpass_cnt++;
}else
{
break;
}
}
if (fwd_maxpass_cnt <= bwd_maxpass_cnt)
{
adj_dir = *bwd_bound + bwd_maxpass_cnt / 2.0 - mid_num;
}else
{
adj_dir = *fwd_bound - fwd_maxpass_cnt / 2.0 - mid_num;
}
return adj_dir;
}
float scan_ca::CalcDsrVc(float vel_center)
{
float d_sr_v = 0.0;
d_sr_v = -0.5 * K_SR * vel_center * vel_center / ACC_DEC;
return d_sr_v;
}
float scan_ca::CalcKpPhi(float vel_center, float d_phi)
{
float tmpDsr = 0.0;
float kp_phi = 0.0;
tmpDsr = CalcDsrVc(vel_center);
if(d_phi <= tmpDsr)
{
kp_phi = KP_PHI_INF;
}
else if((d_phi <= D_M)&&(tmpDsr < d_phi))
{
kp_phi = 1 / (d_phi - tmpDsr);
}
else if(d_phi > D_M)
{
kp_phi = 1 / (D_M - tmpDsr);
}
else
{
cout<<"Calc Kp_phi exception in CalcKpPhi Function ! : " <<endl;
cout<< "tmpDsr : "<< tmpDsr <<endl;
cout<< "d_phi : "<< d_phi <<endl;
}
return kp_phi;
}
void scan_ca::ResetMaxPassValCnt(void)
{
fwd_maxpass_cnt = 0;
bwd_maxpass_cnt = 0;
}
void scan_ca::LimitAngle(float & delta_ang)
{
if(delta_ang >= 90) // for calc attract field , the delta angle should be -90~90 deg to ignore neg val
{
delta_ang = 90;
}
else if (delta_ang <= -90)
{
delta_ang = -90;
}
else
{
}
}
void scan_ca::CalcCorrectedKrf(void)
{
float corrector;
for(int i = 0; i < NUM_RAY4CA; i++)
{
corrector = CalcKrfCorrectFactor(i);
krf_vec[i] = corrector * krf_vec[i];
}
}
float scan_ca::CalcKrfCorrectFactor(int index)
{
//to make the scan front circle krf_vec factor as : y = 1+k * pow(x,2)
float factor = 1.0;
float tmp_puv = (90 - index) / 90.0; // index : 0~180
factor = 1.0 + KRF_CORRECTOR * pow(tmp_puv, 2);
return factor;
}
void scan_ca::CalcPhiParam(float vel_center, float& dir_goal_inlaser)
{
int range_num = 0;
//float tmp_theta_laseray = 0.0; //obstacle 's theta angle
float tmp_delta = 0.0;
for(int i = 0; i < NUM_RAY4CA; i++)
{
delta_phi_vec[i] = asin(D_SF / (*(ptrScan4ca + i))) * RAD2DEG;
range_num = floor(delta_phi_vec[i] / RAY_RESOL4CA);
CalcPhiRange(i, range_num, &phi_start_vec[i], &phi_end_vec[i]);
kp_phi_vec[i] = CalcKpPhi(vel_center, *(ptrScan4ca + i));
krf_vec[i] = kp_phi_vec[i];
tmp_delta = i - dir_goal_inlaser; // unit in degree
LimitAngle(tmp_delta);
kaf_vec[i] = cos(tmp_delta * DEG2RAD); //dir_goal_in_laser is 0~180 degree from right side
}
}
<commit_msg>modify MAX() to MIN() for calc the adj dir<commit_after>#include "colibri_ca.h"
scan_ca::scan_ca()
{
goal_dir = 60; //goal direction
memset(scan4ca, 0.2, NUM_RAY4CA);
ptrScan4ca = scan4ca;
memset(delta_phi_vec, 0, NUM_RAY4CA);
memset(kp_phi_vec, 0, NUM_RAY4CA);
memset(phi_start_vec, 1, NUM_RAY4CA);
memset(phi_end_vec, 181, NUM_RAY4CA);
memset(krf_vec, 1/D_M, NUM_RAY4CA);
memset(kaf_vec, 0.0, NUM_RAY4CA);
memset(passfcn_vec, 0, NUM_RAY4CA);
max_passfcn_val = 0.0;
fwd_maxpass_cnt = 0;
bwd_maxpass_cnt = 0;
maxfcn_fwdbnd = 0;
maxfcn_bwdbnd = 0;
v = 0.0;
vth = 0.0;
angle_adj = 0.0;
vel_adj = 0.0;
apf_alarm = 0;
wander = 0;
scan_sub4ca = nh_ca.subscribe<sensor_msgs::LaserScan>("/scan", 1, &scan_ca::ScanCallBack, this);
apf_pub4mntr = nh_ca.advertise<colibri_msgs::AngPotnEngy>("/apf", 5);
rf_pub4mntr = nh_ca.advertise<colibri_msgs::AngPotnEngy>("/rf", 5);
}
scan_ca::~scan_ca()
{
}
void scan_ca::ScanCallBack(const sensor_msgs::LaserScan::ConstPtr& scan_ca)
{
int j = 61;
for(int i = 0; i < NUM_RAY4CA; i++)
{
scan4ca[i] = scan_ca->ranges[j];
/* if(scan4ca[i] < 0.1)
{
scan4ca[i] = (scan_ca->ranges[j-2]+scan_ca->ranges[j+2]+scan_ca->ranges[j-5]+scan_ca->ranges[j+5]) / 4 + LASER_EDGE_MIN;
}
*/
if(scan4ca[i] < 0.05)
{
scan4ca[i] = scan4ca[i-1];
}
j = j + 2;
}
}
void scan_ca::CalcKrfTheta(float* ptrKp_phi_vector, int* ptrPhi_range_start, int* ptrPhi_range_end)
{
for(int theta_index = 0; theta_index < NUM_RAY4CA; theta_index++)
{
for(int phi_index = 0; phi_index < NUM_RAY4CA; phi_index++)
{
if((theta_index >= *(ptrPhi_range_start+phi_index)) && (theta_index <= *(ptrPhi_range_end+phi_index)))
{
if(krf_vec[theta_index] <= *(ptrKp_phi_vector + phi_index)) // to obtain the max [Krf(phi,theta)] as Krf(theta)
{
krf_vec[theta_index] = *(ptrKp_phi_vector + phi_index);
}
}
}
}
}
void scan_ca::CalcPhiRange(int i, int range_num, int* ptrPhi_start, int* ptrPhi_end)
{
int index_start = 0;
int index_end = 0;
index_start = i - range_num;
index_end = i + range_num;
if(index_start < 1)
{
*ptrPhi_start = 1;
*ptrPhi_end = index_end;
}else if(index_end > NUM_RAY4CA)
{
*ptrPhi_start = index_start;
*ptrPhi_end = NUM_RAY4CA;
}else
{
*ptrPhi_start = index_start;
*ptrPhi_end = index_end;
}
}
void scan_ca::CalcPassFcnAndFwdBnd(unsigned int flag, float* max_passfcn_val, float* ptrK_pg)
{
float tmp_passfcn_value = 0.0;
int tmp_bound_forward = 0;
for(int j = 0; j < NUM_RAY4CA; j++) //from right to left search the max passfcn val and the max passfcn's bound index should locate at left terminal
{
if(flag == 1)
{
*(ptrK_pg + j) = 1 / (krf_vec[j]);
}
else
{
*(ptrK_pg + j) = kaf_vec[j] / (krf_vec[j]);
}
if(tmp_passfcn_value <= *(ptrK_pg + j))
{
tmp_bound_forward = j;
tmp_passfcn_value = *(ptrK_pg + j);
}
}
maxfcn_fwdbnd = tmp_bound_forward;
*max_passfcn_val = tmp_passfcn_value;
}
void scan_ca::CalcPassFcnAndBwdBnd(unsigned int flag, float* max_passfcn_val, float* ptrK_pg)
{
float tmp_passfcn_value = 0.0;
int tmp_bound_backward = 0;
for(int k = NUM_RAY4CA - 1; k >= 0; k--) //from left to right search the max passfcn val and the max passfcn's bound index should locate at right terminal
{
if(flag == 1)
{
*(ptrK_pg + k) = 1 / (krf_vec[k]);
}
else
{
*(ptrK_pg + k) = kaf_vec[k] / (krf_vec[k]);
}
if(tmp_passfcn_value <= *(ptrK_pg + k))
{
tmp_bound_backward = k;
tmp_passfcn_value = *(ptrK_pg + k);
}
}
maxfcn_bwdbnd = tmp_bound_backward;
*max_passfcn_val = tmp_passfcn_value;
}
void scan_ca::CalcAlarmInAPF(void)
{
if(max_passfcn_val <= PASSFCN_THD_RATIO * D_M)
{
apf_alarm = 1;
}
else
{
apf_alarm = 0;
}
}
float scan_ca::CalcAdjDir(float* ptrPassfcn_vector, float max_passfcn_val, int* fwd_bound, int* bwd_bound)
{
int mid_num = 90;
float adj_dir = 0.0;
float tmp_scope = MIN(PASSVAL_TOLLERENCE * max_passfcn_val, MAX_PASSFCN_SCOPE);
for(int m = 0; m <= mid_num; m++) //backward directrion(CW 180->0) search using forward bound
{
if(abs(*(ptrPassfcn_vector + *(fwd_bound) - m) - max_passfcn_val) < tmp_scope)
{
fwd_maxpass_cnt++;
}else
{
break;
}
}
for(int n = 0; n <= mid_num; n++) // forward direction(CCW 0->180) search using backward bound
{
if(abs(*(ptrPassfcn_vector + *(bwd_bound) + n) - max_passfcn_val) < tmp_scope)
{
bwd_maxpass_cnt++;
}else
{
break;
}
}
if (fwd_maxpass_cnt <= bwd_maxpass_cnt)
{
adj_dir = *bwd_bound + bwd_maxpass_cnt / 2.0 - mid_num;
}else
{
adj_dir = *fwd_bound - fwd_maxpass_cnt / 2.0 - mid_num;
}
return adj_dir;
}
float scan_ca::CalcDsrVc(float vel_center)
{
float d_sr_v = 0.0;
d_sr_v = -0.5 * K_SR * vel_center * vel_center / ACC_DEC;
return d_sr_v;
}
float scan_ca::CalcKpPhi(float vel_center, float d_phi)
{
float tmpDsr = 0.0;
float kp_phi = 0.0;
tmpDsr = CalcDsrVc(vel_center);
if(d_phi <= tmpDsr)
{
kp_phi = KP_PHI_INF;
}
else if((d_phi <= D_M)&&(tmpDsr < d_phi))
{
kp_phi = 1 / (d_phi - tmpDsr);
}
else if(d_phi > D_M)
{
kp_phi = 1 / (D_M - tmpDsr);
}
else
{
cout<<"Calc Kp_phi exception in CalcKpPhi Function ! : " <<endl;
cout<< "tmpDsr : "<< tmpDsr <<endl;
cout<< "d_phi : "<< d_phi <<endl;
}
return kp_phi;
}
void scan_ca::ResetMaxPassValCnt(void)
{
fwd_maxpass_cnt = 0;
bwd_maxpass_cnt = 0;
}
void scan_ca::LimitAngle(float & delta_ang)
{
if(delta_ang >= 90) // for calc attract field , the delta angle should be -90~90 deg to ignore neg val
{
delta_ang = 90;
}
else if (delta_ang <= -90)
{
delta_ang = -90;
}
else
{
}
}
void scan_ca::CalcCorrectedKrf(void)
{
float corrector;
for(int i = 0; i < NUM_RAY4CA; i++)
{
corrector = CalcKrfCorrectFactor(i);
krf_vec[i] = corrector * krf_vec[i];
}
}
float scan_ca::CalcKrfCorrectFactor(int index)
{
//to make the scan front circle krf_vec factor as : y = 1+k * pow(x,2)
float factor = 1.0;
float tmp_puv = (90 - index) / 90.0; // index : 0~180
factor = 1.0 + KRF_CORRECTOR * pow(tmp_puv, 2);
return factor;
}
void scan_ca::CalcPhiParam(float vel_center, float& dir_goal_inlaser)
{
int range_num = 0;
//float tmp_theta_laseray = 0.0; //obstacle 's theta angle
float tmp_delta = 0.0;
for(int i = 0; i < NUM_RAY4CA; i++)
{
delta_phi_vec[i] = asin(D_SF / (*(ptrScan4ca + i))) * RAD2DEG;
range_num = floor(delta_phi_vec[i] / RAY_RESOL4CA);
CalcPhiRange(i, range_num, &phi_start_vec[i], &phi_end_vec[i]);
kp_phi_vec[i] = CalcKpPhi(vel_center, *(ptrScan4ca + i));
krf_vec[i] = kp_phi_vec[i];
tmp_delta = i - dir_goal_inlaser; // unit in degree
LimitAngle(tmp_delta);
kaf_vec[i] = cos(tmp_delta * DEG2RAD); //dir_goal_in_laser is 0~180 degree from right side
}
}
<|endoftext|>
|
<commit_before>/*
I heard of the longest palindrome string problem the first time,
and was researching for what it is. Then I found leetcode official tuto.
http://articles.leetcode.com/2011/11/longest-palindromic-substring-part-i.html
Among my google result, it was the best study material I had.
It was short and simple, that I didn't feel any need to do additional work.
I decided to paste it here and re-implement myself months later.
Now I would go to study the O(N) solution:
http://articles.leetcode.com/2011/11/longest-palindromic-substring-part-ii.html
*/
string expandAroundCenter(string s, int c1, int c2) {
int l = c1, r = c2;
int n = s.length();
while (l >= 0 && r <= n-1 && s[l] == s[r]) {
l--;
r++;
}
return s.substr(l+1, r-l-1);
}
string longestPalindromeSimple(string s) {
int n = s.length();
if (n == 0) return "";
string longest = s.substr(0, 1); // a single char itself is a palindrome
for (int i = 0; i < n-1; i++) {
string p1 = expandAroundCenter(s, i, i);
if (p1.length() > longest.length())
longest = p1;
string p2 = expandAroundCenter(s, i, i+1);
if (p2.length() > longest.length())
longest = p2;
}
return longest;
}
class Solution {
public:
string longestPalindrome(string s) {
return longestPalindromeSimple(s);
}
};
<commit_msg>05 O(N)<commit_after>/*
I heard of the longest palindrome string problem the first time,
and was researching for what it is. Then I found leetcode official tuto.
http://articles.leetcode.com/2011/11/longest-palindromic-substring-part-i.html
Among my google result, it was the best study material I had.
It was short and simple, that I didn't feel any need to do additional work.
I decided to paste it here and re-implement myself months later.
*/
/*
string expandAroundCenter(string s, int c1, int c2) {
int l = c1, r = c2;
int n = s.length();
while (l >= 0 && r <= n-1 && s[l] == s[r]) {
l--;
r++;
}
return s.substr(l+1, r-l-1);
}
string longestPalindromeSimple(string s) {
int n = s.length();
if (n == 0) return "";
string longest = s.substr(0, 1); // a single char itself is a palindrome
for (int i = 0; i < n-1; i++) {
string p1 = expandAroundCenter(s, i, i);
if (p1.length() > longest.length())
longest = p1;
string p2 = expandAroundCenter(s, i, i+1);
if (p2.length() > longest.length())
longest = p2;
}
return longest;
}
class Solution {
public:
string longestPalindrome(string s) {
return longestPalindromeSimple(s);
}
};
*/
/* O(N) solution, aka Manacher’s Algorithm.
cited from:
http://articles.leetcode.com/2011/11/longest-palindromic-substring-part-ii.html
*/
// Transform S into T.
// For example, S = "abba", T = "^#a#b#b#a#$".
// ^ and $ signs are sentinels appended to each end to avoid bounds checking
string preProcess(string s) {
int n = s.length();
if (n == 0) return "^$";
string ret = "^";
for (int i = 0; i < n; i++)
ret += "#" + s.substr(i, 1);
ret += "#$";
return ret;
}
string longestPalindrome(string s) {
string T = preProcess(s);
int n = T.length();
int *P = new int[n];
int C = 0, R = 0;
for (int i = 1; i < n-1; i++) {
int i_mirror = 2*C-i; // equals to i' = C - (i-C)
P[i] = (R > i) ? min(R-i, P[i_mirror]) : 0;
// Attempt to expand palindrome centered at i
while (T[i + 1 + P[i]] == T[i - 1 - P[i]])
P[i]++;
// If palindrome centered at i expand past R,
// adjust center based on expanded palindrome.
if (i + P[i] > R) {
C = i;
R = i + P[i];
}
}
// Find the maximum element in P.
int maxLen = 0;
int centerIndex = 0;
for (int i = 1; i < n-1; i++) {
if (P[i] > maxLen) {
maxLen = P[i];
centerIndex = i;
}
}
delete[] P;
return s.substr((centerIndex - 1 - maxLen)/2, maxLen);
}
class Solution {
public:
string longestPalindrome(string s) {
return longestPalindrome(s);
}
};
<|endoftext|>
|
<commit_before>#if defined(_MSC_VER)
#define _CRTDBG_MAP_ALLOC
#define _CRT_SECURE_NO_WARNINGS
#include <crtdbg.h>
#include <sys/stat.h>
#else
#include <sys/stat.h>
#endif
#include <string>
//#include "CoolProp.h"
#include "IncompressibleBackend.h"
#include "../Fluids/FluidLibrary.h"
#include "Solvers.h"
#include "MatrixMath.h"
namespace CoolProp {
IncompressibleBackend::IncompressibleBackend(const std::string &fluid_name) {
throw CoolProp::NotImplementedError("Mixture-style constructor is not implemented yet for incompressible fluids");
}
IncompressibleBackend::IncompressibleBackend(const std::vector<std::string> &component_names) {
throw CoolProp::NotImplementedError("Mixture-style constructor is not implemented yet for incompressible fluids");
}
bool IncompressibleBackend::using_mole_fractions(){return false;}
void IncompressibleBackend::update(long input_pair, double value1, double value2) {
switch (input_pair) {
case PT_INPUTS: {
break;
}
// case DmassP_INPUTS: {
//
// }
// break;
// }
// case HmassP_INPUTS: {
// // Call again, but this time with molar units
// // H: [J/kg] * [kg/mol] -> [J/mol]
// update(HmolarP_INPUTS, value1 * (double) _molar_mass, value2);
// return;
// }
// case PUmass_INPUTS: {
// // Call again, but this time with molar units
// // U: [J/kg] * [kg/mol] -> [J/mol]
// update(PUmolar_INPUTS, value1, value2 * (double) _molar_mass);
// return;
// }
// case PSmass_INPUTS: {
// // Call again, but this time with molar units
// // U: [J/kg] * [kg/mol] -> [J/mol]
// update(PUmolar_INPUTS, value1, value2 * (double) _molar_mass);
// return;
// }
default: {
throw ValueError(
format("This pair of inputs [%s] is not yet supported",
get_input_pair_short_desc(input_pair).c_str()));
}
}
}
/// Set the mole fractions
/**
@param mole_fractions The vector of mole fractions of the components
*/
void IncompressibleBackend::set_mole_fractions(const std::vector<long double> &mole_fractions) {
throw CoolProp::NotImplementedError("Cannot set mole fractions for incompressible fluid");
}
/// Set the mass fractions
/**
@param mass_fractions The vector of mass fractions of the components
*/
void IncompressibleBackend::set_mass_fractions(const std::vector<long double> &mass_fractions) {
this->mass_fractions = mass_fractions;
}
/// Check if the mole fractions have been set, etc.
void IncompressibleBackend::check_status() {
throw CoolProp::NotImplementedError("Cannot check status for incompressible fluid");
}
/// Get the viscosity [Pa-s]
long double IncompressibleBackend::calc_viscosity(void){
throw NotImplementedError();
}
/// Get the thermal conductivity [W/m/K] (based on the temperature and density in the state class)
long double IncompressibleBackend::calc_conductivity(void){
throw NotImplementedError();
}
}
<commit_msg>Fixed incompressible include path<commit_after>#if defined(_MSC_VER)
#define _CRTDBG_MAP_ALLOC
#define _CRT_SECURE_NO_WARNINGS
#include <crtdbg.h>
#include <sys/stat.h>
#else
#include <sys/stat.h>
#endif
#include <string>
//#include "CoolProp.h"
#include "IncompressibleBackend.h"
#include "../Helmholtz/Fluids/FluidLibrary.h"
#include "Solvers.h"
#include "MatrixMath.h"
namespace CoolProp {
IncompressibleBackend::IncompressibleBackend(const std::string &fluid_name) {
throw CoolProp::NotImplementedError("Mixture-style constructor is not implemented yet for incompressible fluids");
}
IncompressibleBackend::IncompressibleBackend(const std::vector<std::string> &component_names) {
throw CoolProp::NotImplementedError("Mixture-style constructor is not implemented yet for incompressible fluids");
}
bool IncompressibleBackend::using_mole_fractions(){return false;}
void IncompressibleBackend::update(long input_pair, double value1, double value2) {
switch (input_pair) {
case PT_INPUTS: {
break;
}
// case DmassP_INPUTS: {
//
// }
// break;
// }
// case HmassP_INPUTS: {
// // Call again, but this time with molar units
// // H: [J/kg] * [kg/mol] -> [J/mol]
// update(HmolarP_INPUTS, value1 * (double) _molar_mass, value2);
// return;
// }
// case PUmass_INPUTS: {
// // Call again, but this time with molar units
// // U: [J/kg] * [kg/mol] -> [J/mol]
// update(PUmolar_INPUTS, value1, value2 * (double) _molar_mass);
// return;
// }
// case PSmass_INPUTS: {
// // Call again, but this time with molar units
// // U: [J/kg] * [kg/mol] -> [J/mol]
// update(PUmolar_INPUTS, value1, value2 * (double) _molar_mass);
// return;
// }
default: {
throw ValueError(
format("This pair of inputs [%s] is not yet supported",
get_input_pair_short_desc(input_pair).c_str()));
}
}
}
/// Set the mole fractions
/**
@param mole_fractions The vector of mole fractions of the components
*/
void IncompressibleBackend::set_mole_fractions(const std::vector<long double> &mole_fractions) {
throw CoolProp::NotImplementedError("Cannot set mole fractions for incompressible fluid");
}
/// Set the mass fractions
/**
@param mass_fractions The vector of mass fractions of the components
*/
void IncompressibleBackend::set_mass_fractions(const std::vector<long double> &mass_fractions) {
this->mass_fractions = mass_fractions;
}
/// Check if the mole fractions have been set, etc.
void IncompressibleBackend::check_status() {
throw CoolProp::NotImplementedError("Cannot check status for incompressible fluid");
}
/// Get the viscosity [Pa-s]
long double IncompressibleBackend::calc_viscosity(void){
throw NotImplementedError();
}
/// Get the thermal conductivity [W/m/K] (based on the temperature and density in the state class)
long double IncompressibleBackend::calc_conductivity(void){
throw NotImplementedError();
}
}
<|endoftext|>
|
<commit_before>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 1773
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<commit_msg>P4 to Git Change 1138374 by johtaylo@johtaylo-JTBUILDER03-increment on 2015/04/08 03:01:12<commit_after>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 1774
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<|endoftext|>
|
<commit_before>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 2425
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<commit_msg>P4 to Git Change 1412538 by johtaylo@johtaylo-jtincrementor-increment on 2017/05/23 03:00:04<commit_after>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 2426
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<|endoftext|>
|
<commit_before>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 2819
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<commit_msg>P4 to Git Change 1734433 by chui@ocl-promo-incrementor on 2019/01/23 03:00:12<commit_after>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 2820
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<|endoftext|>
|
<commit_before>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 2933
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<commit_msg>P4 to Git Change 1907374 by chui@ocl-promo-incrementor on 2019/06/27 03:00:43<commit_after>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 2934
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<|endoftext|>
|
<commit_before>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 1590
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<commit_msg>P4 to Git Change 1056619 by johtaylo@johtaylo-JTBUILDER03-increment on 2014/07/18 03:00:12<commit_after>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 1591
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<|endoftext|>
|
<commit_before>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3058
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<commit_msg>P4 to Git Change 2043044 by chui@ocl-promo-incrementor on 2019/12/10 03:00:17<commit_after>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3059
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.