text
stringlengths 54
60.6k
|
---|
<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 "build/build_config.h"
#if defined(OS_WIN)
#include <windows.h>
#include <shellapi.h>
#include <shlobj.h>
#endif
#include "chrome/common/chrome_paths.h"
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/sys_info.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_switches.h"
namespace chrome {
// Gets the default user data directory, regardless of whether
// DIR_USER_DATA has been overridden by a command-line option.
bool GetDefaultUserDataDirectory(std::wstring* result) {
#if defined(OS_WIN)
if (!PathService::Get(base::DIR_LOCAL_APP_DATA, result))
return false;
#if defined(GOOGLE_CHROME_BUILD)
file_util::AppendToPath(result, L"Google");
#endif
file_util::AppendToPath(result, chrome::kBrowserAppName);
file_util::AppendToPath(result, chrome::kUserDataDirname);
return true;
#else // defined(OS_WIN)
// TODO(port): Decide what to do on other platforms.
NOTIMPLEMENTED();
return false;
#endif // defined(OS_WIN)
}
bool GetGearsPluginPathFromCommandLine(std::wstring *path) {
#ifndef NDEBUG
// for debugging, support a cmd line based override
CommandLine command_line;
*path = command_line.GetSwitchValue(switches::kGearsPluginPathOverride);
return !path->empty();
#else
return false;
#endif
}
bool PathProvider(int key, FilePath* result) {
// Some keys are just aliases...
switch (key) {
case chrome::DIR_APP:
return PathService::Get(base::DIR_MODULE, result);
case chrome::DIR_LOGS:
#ifndef NDEBUG
return PathService::Get(chrome::DIR_USER_DATA, result);
#else
return PathService::Get(base::DIR_EXE, result);
#endif
case chrome::FILE_RESOURCE_MODULE:
return PathService::Get(base::FILE_MODULE, result);
}
// Assume that we will need to create the directory if it does not already
// exist. This flag can be set to true to prevent checking.
bool exists = false;
std::wstring cur;
switch (key) {
case chrome::DIR_USER_DATA:
if (!GetDefaultUserDataDirectory(&cur))
return false;
break;
case chrome::DIR_USER_DOCUMENTS:
#if defined(OS_WIN)
{
wchar_t path_buf[MAX_PATH];
if (FAILED(SHGetFolderPath(NULL, CSIDL_MYDOCUMENTS, NULL,
SHGFP_TYPE_CURRENT, path_buf)))
return false;
cur.assign(path_buf);
}
#else
// TODO(port): Get the path (possibly using xdg-user-dirs)
// or decide we don't need it on other platforms.
NOTIMPLEMENTED();
return false;
#endif
break;
case chrome::DIR_DEFAULT_DOWNLOADS:
// On Vista, we can get the download path using a Win API
// (http://msdn.microsoft.com/en-us/library/bb762584(VS.85).aspx),
// but it can be set to Desktop, which is dangerous. Instead,
// we just use 'Downloads' under DIR_USER_DOCUMENTS. Localizing
// 'downloads' is not a good idea because Chrome's UI language
// can be changed.
if (!PathService::Get(chrome::DIR_USER_DOCUMENTS, &cur))
return false;
file_util::AppendToPath(&cur, L"Downloads");
// TODO(port): This will fail on other platforms unless we
// implement DIR_USER_DOCUMENTS or use xdg-user-dirs to
// get the download directory independently of DIR_USER_DOCUMENTS.
break;
case chrome::DIR_CRASH_DUMPS:
// The crash reports are always stored relative to the default user data
// directory. This avoids the problem of having to re-initialize the
// exception handler after parsing command line options, which may
// override the location of the app's profile directory.
if (!GetDefaultUserDataDirectory(&cur))
return false;
file_util::AppendToPath(&cur, L"Crash Reports");
break;
case chrome::DIR_USER_DESKTOP:
#if defined(OS_WIN)
{
// We need to go compute the value. It would be nice to support paths
// with names longer than MAX_PATH, but the system functions don't seem
// to be designed for it either, with the exception of GetTempPath
// (but other things will surely break if the temp path is too long,
// so we don't bother handling it.
wchar_t system_buffer[MAX_PATH];
system_buffer[0] = 0;
if (FAILED(SHGetFolderPath(NULL, CSIDL_DESKTOPDIRECTORY, NULL,
SHGFP_TYPE_CURRENT, system_buffer)))
return false;
cur.assign(system_buffer);
}
#else
// TODO(port): Get the path (possibly using xdg-user-dirs)
// or decide we don't need it on other platforms.
NOTIMPLEMENTED();
return false;
#endif
exists = true;
break;
case chrome::DIR_RESOURCES:
if (!PathService::Get(chrome::DIR_APP, &cur))
return false;
file_util::AppendToPath(&cur, L"resources");
break;
case chrome::DIR_INSPECTOR:
if (!PathService::Get(chrome::DIR_APP, &cur))
return false;
file_util::AppendToPath(&cur, L"Resources");
file_util::AppendToPath(&cur, L"Inspector");
exists = true;
break;
case chrome::DIR_THEMES:
if (!PathService::Get(chrome::DIR_APP, &cur))
return false;
file_util::AppendToPath(&cur, L"themes");
break;
case chrome::DIR_LOCALES:
if (!PathService::Get(chrome::DIR_APP, &cur))
return false;
file_util::AppendToPath(&cur, L"locales");
break;
case chrome::DIR_APP_DICTIONARIES:
if (!PathService::Get(base::DIR_EXE, &cur))
return false;
file_util::AppendToPath(&cur, L"Dictionaries");
break;
case chrome::DIR_USER_SCRIPTS:
// TODO(aa): Figure out where the script directory should live.
#if defined(OS_WIN)
cur = L"C:\\SCRIPTS\\";
#else
NOTIMPLEMENTED();
return false;
#endif
exists = true; // don't trigger directory creation code
break;
case chrome::FILE_LOCAL_STATE:
if (!PathService::Get(chrome::DIR_USER_DATA, &cur))
return false;
file_util::AppendToPath(&cur, chrome::kLocalStateFilename);
exists = true; // don't trigger directory creation code
break;
case chrome::FILE_RECORDED_SCRIPT:
if (!PathService::Get(chrome::DIR_USER_DATA, &cur))
return false;
file_util::AppendToPath(&cur, L"script.log");
exists = true;
break;
case chrome::FILE_GEARS_PLUGIN:
if (!GetGearsPluginPathFromCommandLine(&cur)) {
// Search for gears.dll alongside chrome.dll first. This new model
// allows us to package gears.dll with the Chrome installer and update
// it while Chrome is running.
if (!PathService::Get(base::DIR_MODULE, &cur))
return false;
file_util::AppendToPath(&cur, L"gears.dll");
if (!file_util::PathExists(cur)) {
if (!PathService::Get(base::DIR_EXE, &cur))
return false;
file_util::AppendToPath(&cur, L"plugins");
file_util::AppendToPath(&cur, L"gears");
file_util::AppendToPath(&cur, L"gears.dll");
}
}
exists = true;
break;
// The following are only valid in the development environment, and
// will fail if executed from an installed executable (because the
// generated path won't exist).
case chrome::DIR_TEST_DATA:
if (!PathService::Get(chrome::DIR_APP, &cur))
return false;
file_util::UpOneDirectory(&cur);
file_util::AppendToPath(&cur, L"test");
file_util::AppendToPath(&cur, L"data");
if (!file_util::PathExists(cur)) // we don't want to create this
return false;
exists = true;
break;
case chrome::DIR_TEST_TOOLS:
if (!PathService::Get(chrome::DIR_APP, &cur))
return false;
file_util::UpOneDirectory(&cur);
file_util::AppendToPath(&cur, L"tools");
file_util::AppendToPath(&cur, L"test");
if (!file_util::PathExists(cur)) // we don't want to create this
return false;
exists = true;
break;
case chrome::FILE_PYTHON_RUNTIME:
if (!PathService::Get(chrome::DIR_APP, &cur))
return false;
file_util::UpOneDirectory(&cur); // chrome
file_util::UpOneDirectory(&cur);
file_util::AppendToPath(&cur, L"third_party");
file_util::AppendToPath(&cur, L"python_24");
file_util::AppendToPath(&cur, L"python.exe");
if (!file_util::PathExists(cur)) // we don't want to create this
return false;
exists = true;
break;
case chrome::FILE_TEST_SERVER:
if (!PathService::Get(chrome::DIR_APP, &cur))
return false;
file_util::UpOneDirectory(&cur);
file_util::AppendToPath(&cur, L"tools");
file_util::AppendToPath(&cur, L"test");
file_util::AppendToPath(&cur, L"testserver");
file_util::AppendToPath(&cur, L"testserver.py");
if (!file_util::PathExists(cur)) // we don't want to create this
return false;
exists = true;
break;
default:
return false;
}
if (!exists && !file_util::PathExists(cur) && !file_util::CreateDirectory(cur))
return false;
*result = FilePath::FromWStringHack(cur);
return true;
}
// This cannot be done as a static initializer sadly since Visual Studio will
// eliminate this object file if there is no direct entry point into it.
void RegisterPathProvider() {
PathService::RegisterProvider(PathProvider, PATH_START, PATH_END);
}
} // namespace chrome
<commit_msg>Don't create the default download directory just because we ask for its location. This is a first step toward not creating _any_ directories when we merely ask for their locations. Patch by Marc-André Decoste, r=cpu. See http://codereview.chromium.org/11586 .<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 "build/build_config.h"
#if defined(OS_WIN)
#include <windows.h>
#include <shellapi.h>
#include <shlobj.h>
#endif
#include "chrome/common/chrome_paths.h"
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/sys_info.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_switches.h"
namespace chrome {
// Gets the default user data directory, regardless of whether
// DIR_USER_DATA has been overridden by a command-line option.
bool GetDefaultUserDataDirectory(std::wstring* result) {
#if defined(OS_WIN)
if (!PathService::Get(base::DIR_LOCAL_APP_DATA, result))
return false;
#if defined(GOOGLE_CHROME_BUILD)
file_util::AppendToPath(result, L"Google");
#endif
file_util::AppendToPath(result, chrome::kBrowserAppName);
file_util::AppendToPath(result, chrome::kUserDataDirname);
return true;
#else // defined(OS_WIN)
// TODO(port): Decide what to do on other platforms.
NOTIMPLEMENTED();
return false;
#endif // defined(OS_WIN)
}
bool GetGearsPluginPathFromCommandLine(std::wstring *path) {
#ifndef NDEBUG
// for debugging, support a cmd line based override
CommandLine command_line;
*path = command_line.GetSwitchValue(switches::kGearsPluginPathOverride);
return !path->empty();
#else
return false;
#endif
}
bool PathProvider(int key, FilePath* result) {
// Some keys are just aliases...
switch (key) {
case chrome::DIR_APP:
return PathService::Get(base::DIR_MODULE, result);
case chrome::DIR_LOGS:
#ifndef NDEBUG
return PathService::Get(chrome::DIR_USER_DATA, result);
#else
return PathService::Get(base::DIR_EXE, result);
#endif
case chrome::FILE_RESOURCE_MODULE:
return PathService::Get(base::FILE_MODULE, result);
}
// Assume that we will not need to create the directory if it does not exist.
// This flag can be set to true for the cases where we want to create it.
bool create_dir = false;
std::wstring cur;
switch (key) {
case chrome::DIR_USER_DATA:
if (!GetDefaultUserDataDirectory(&cur))
return false;
create_dir = true;
break;
case chrome::DIR_USER_DOCUMENTS:
#if defined(OS_WIN)
{
wchar_t path_buf[MAX_PATH];
if (FAILED(SHGetFolderPath(NULL, CSIDL_MYDOCUMENTS, NULL,
SHGFP_TYPE_CURRENT, path_buf)))
return false;
cur.assign(path_buf);
}
#else
// TODO(port): Get the path (possibly using xdg-user-dirs)
// or decide we don't need it on other platforms.
NOTIMPLEMENTED();
return false;
#endif
create_dir = true;
break;
case chrome::DIR_DEFAULT_DOWNLOADS:
// On Vista, we can get the download path using a Win API
// (http://msdn.microsoft.com/en-us/library/bb762584(VS.85).aspx),
// but it can be set to Desktop, which is dangerous. Instead,
// we just use 'Downloads' under DIR_USER_DOCUMENTS. Localizing
// 'downloads' is not a good idea because Chrome's UI language
// can be changed.
if (!PathService::Get(chrome::DIR_USER_DOCUMENTS, &cur))
return false;
file_util::AppendToPath(&cur, L"Downloads");
// TODO(port): This will fail on other platforms unless we
// implement DIR_USER_DOCUMENTS or use xdg-user-dirs to
// get the download directory independently of DIR_USER_DOCUMENTS.
break;
case chrome::DIR_CRASH_DUMPS:
// The crash reports are always stored relative to the default user data
// directory. This avoids the problem of having to re-initialize the
// exception handler after parsing command line options, which may
// override the location of the app's profile directory.
if (!GetDefaultUserDataDirectory(&cur))
return false;
file_util::AppendToPath(&cur, L"Crash Reports");
create_dir = true;
break;
case chrome::DIR_USER_DESKTOP:
#if defined(OS_WIN)
{
// We need to go compute the value. It would be nice to support paths
// with names longer than MAX_PATH, but the system functions don't seem
// to be designed for it either, with the exception of GetTempPath
// (but other things will surely break if the temp path is too long,
// so we don't bother handling it.
wchar_t system_buffer[MAX_PATH];
system_buffer[0] = 0;
if (FAILED(SHGetFolderPath(NULL, CSIDL_DESKTOPDIRECTORY, NULL,
SHGFP_TYPE_CURRENT, system_buffer)))
return false;
cur.assign(system_buffer);
}
#else
// TODO(port): Get the path (possibly using xdg-user-dirs)
// or decide we don't need it on other platforms.
NOTIMPLEMENTED();
return false;
#endif
break;
case chrome::DIR_RESOURCES:
if (!PathService::Get(chrome::DIR_APP, &cur))
return false;
file_util::AppendToPath(&cur, L"resources");
create_dir = true;
break;
case chrome::DIR_INSPECTOR:
if (!PathService::Get(chrome::DIR_APP, &cur))
return false;
file_util::AppendToPath(&cur, L"Resources");
file_util::AppendToPath(&cur, L"Inspector");
break;
case chrome::DIR_THEMES:
if (!PathService::Get(chrome::DIR_APP, &cur))
return false;
file_util::AppendToPath(&cur, L"themes");
create_dir = true;
break;
case chrome::DIR_LOCALES:
if (!PathService::Get(chrome::DIR_APP, &cur))
return false;
file_util::AppendToPath(&cur, L"locales");
create_dir = true;
break;
case chrome::DIR_APP_DICTIONARIES:
if (!PathService::Get(base::DIR_EXE, &cur))
return false;
file_util::AppendToPath(&cur, L"Dictionaries");
create_dir = true;
break;
case chrome::DIR_USER_SCRIPTS:
// TODO(aa): Figure out where the script directory should live.
#if defined(OS_WIN)
cur = L"C:\\SCRIPTS\\";
#else
NOTIMPLEMENTED();
return false;
#endif
break;
case chrome::FILE_LOCAL_STATE:
if (!PathService::Get(chrome::DIR_USER_DATA, &cur))
return false;
file_util::AppendToPath(&cur, chrome::kLocalStateFilename);
break;
case chrome::FILE_RECORDED_SCRIPT:
if (!PathService::Get(chrome::DIR_USER_DATA, &cur))
return false;
file_util::AppendToPath(&cur, L"script.log");
break;
case chrome::FILE_GEARS_PLUGIN:
if (!GetGearsPluginPathFromCommandLine(&cur)) {
// Search for gears.dll alongside chrome.dll first. This new model
// allows us to package gears.dll with the Chrome installer and update
// it while Chrome is running.
if (!PathService::Get(base::DIR_MODULE, &cur))
return false;
file_util::AppendToPath(&cur, L"gears.dll");
if (!file_util::PathExists(cur)) {
if (!PathService::Get(base::DIR_EXE, &cur))
return false;
file_util::AppendToPath(&cur, L"plugins");
file_util::AppendToPath(&cur, L"gears");
file_util::AppendToPath(&cur, L"gears.dll");
}
}
break;
// The following are only valid in the development environment, and
// will fail if executed from an installed executable (because the
// generated path won't exist).
case chrome::DIR_TEST_DATA:
if (!PathService::Get(chrome::DIR_APP, &cur))
return false;
file_util::UpOneDirectory(&cur);
file_util::AppendToPath(&cur, L"test");
file_util::AppendToPath(&cur, L"data");
if (!file_util::PathExists(cur)) // we don't want to create this
return false;
break;
case chrome::DIR_TEST_TOOLS:
if (!PathService::Get(chrome::DIR_APP, &cur))
return false;
file_util::UpOneDirectory(&cur);
file_util::AppendToPath(&cur, L"tools");
file_util::AppendToPath(&cur, L"test");
if (!file_util::PathExists(cur)) // we don't want to create this
return false;
break;
case chrome::FILE_PYTHON_RUNTIME:
if (!PathService::Get(chrome::DIR_APP, &cur))
return false;
file_util::UpOneDirectory(&cur); // chrome
file_util::UpOneDirectory(&cur);
file_util::AppendToPath(&cur, L"third_party");
file_util::AppendToPath(&cur, L"python_24");
file_util::AppendToPath(&cur, L"python.exe");
if (!file_util::PathExists(cur)) // we don't want to create this
return false;
break;
case chrome::FILE_TEST_SERVER:
if (!PathService::Get(chrome::DIR_APP, &cur))
return false;
file_util::UpOneDirectory(&cur);
file_util::AppendToPath(&cur, L"tools");
file_util::AppendToPath(&cur, L"test");
file_util::AppendToPath(&cur, L"testserver");
file_util::AppendToPath(&cur, L"testserver.py");
if (!file_util::PathExists(cur)) // we don't want to create this
return false;
break;
default:
return false;
}
if (create_dir && !file_util::PathExists(cur) && !file_util::CreateDirectory(cur))
return false;
*result = FilePath::FromWStringHack(cur);
return true;
}
// This cannot be done as a static initializer sadly since Visual Studio will
// eliminate this object file if there is no direct entry point into it.
void RegisterPathProvider() {
PathService::RegisterProvider(PathProvider, PATH_START, PATH_END);
}
} // namespace chrome
<|endoftext|> |
<commit_before>#include "EventDelegate.h"
#include "EventDialog.cpp"
#include <QItemEditorFactory>
#include <QDebug>
EventDelegate::EventDelegate(QObject *parent) :
QItemDelegate(parent)
{
}
QWidget* EventDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &, const QModelIndex &) const {
EventDialog *dialog = new EventDialog(parent);
dialog->setWindowModality(Qt::WindowModal);
return dialog;
}
void EventDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const {
EventDialog *dialog = qobject_cast<EventDialog*>(editor);
Q_ASSERT(dialog);
if (!dialog)
return;
QSqlRelationalTableModel *model = qobject_cast<QSqlRelationalTableModel*>(m_model);
Q_ASSERT(model);
if (!model)
return;
dialog->setModelRow(m_model, index.row());
}
void EventDelegate::setModelData(QWidget *editor, QAbstractItemModel*, const QModelIndex &) const {
EventDialog *dialog = qobject_cast<EventDialog*>(editor);
Q_ASSERT(dialog);
if (dialog && dialog->result() == QDialog::Accepted)
dialog->writeToModel();
}
void EventDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem&, const QModelIndex&) const {
Q_ASSERT(qobject_cast<EventDialog*>(editor));
// Don't do anything, we're modal and sharing the same widget.
}
bool EventDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index) {
QSqlRelationalTableModel *sqlModel = qobject_cast<QSqlRelationalTableModel*>(model);
Q_ASSERT(sqlModel);
if (sqlModel)
m_model = sqlModel;
return QItemDelegate::editorEvent(event, model, option, index);
}
<commit_msg>Fix compilation error from including .cpp file.<commit_after>#include "EventDelegate.h"
#include "EventDialog.h"
#include <QItemEditorFactory>
#include <QDebug>
#include <QSqlRelationalTableModel>
EventDelegate::EventDelegate(QObject *parent) :
QItemDelegate(parent)
{
}
QWidget* EventDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &, const QModelIndex &) const {
EventDialog *dialog = new EventDialog(parent);
dialog->setWindowModality(Qt::WindowModal);
return dialog;
}
void EventDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const {
EventDialog *dialog = qobject_cast<EventDialog*>(editor);
Q_ASSERT(dialog);
if (!dialog)
return;
QSqlRelationalTableModel *model = qobject_cast<QSqlRelationalTableModel*>(m_model);
Q_ASSERT(model);
if (!model)
return;
dialog->setModelRow(m_model, index.row());
}
void EventDelegate::setModelData(QWidget *editor, QAbstractItemModel*, const QModelIndex &) const {
EventDialog *dialog = qobject_cast<EventDialog*>(editor);
Q_ASSERT(dialog);
if (dialog && dialog->result() == QDialog::Accepted)
dialog->writeToModel();
}
void EventDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem&, const QModelIndex&) const {
Q_UNUSED(editor);
Q_ASSERT(qobject_cast<EventDialog*>(editor));
// Don't do anything, we're modal and sharing the same widget.
}
bool EventDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index) {
QSqlRelationalTableModel *sqlModel = qobject_cast<QSqlRelationalTableModel*>(model);
Q_ASSERT(sqlModel);
if (sqlModel)
m_model = sqlModel;
return QItemDelegate::editorEvent(event, model, option, index);
}
<|endoftext|> |
<commit_before>/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Module: FGCoefficient.cpp
Author: Jon S. Berndt
Date started: 12/28/98
Purpose: Encapsulates the stability derivative class FGCoefficient;
Called by: FGAircraft
------------- Copyright (C) 1999 Jon S. Berndt ([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-1307, USA.
Further information about the GNU General Public License can also be found on
the world wide web at http://www.gnu.org.
FUNCTIONAL DESCRIPTION
--------------------------------------------------------------------------------
This class models the stability derivative coefficient lookup tables or
equations. Note that the coefficients need not be calculated each delta-t.
Note that the values in a row which index into the table must be the same value
for each column of data, so the first column of numbers for each altitude are
seen to be equal, and there are the same number of values for each altitude.
See the header file FGCoefficient.h for the values of the identifiers.
HISTORY
--------------------------------------------------------------------------------
12/28/98 JSB Created
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
INCLUDES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
#include "FGCoefficient.h"
#include "FGState.h"
#include "FGFDMExec.h"
#include "FGPropertyManager.h"
#ifndef FGFS
# if defined(sgi) && !defined(__GNUC__)
# include <iomanip.h>
# else
# include <iomanip>
# endif
#else
# include STL_IOMANIP
#endif
static const char *IdSrc = "$Id: FGCoefficient.cpp,v 1.56 2002/07/10 22:17:00 apeden Exp $";
static const char *IdHdr = ID_COEFFICIENT;
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
CLASS IMPLEMENTATION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
FGCoefficient::FGCoefficient( FGFDMExec* fdex )
{
FDMExec = fdex;
State = FDMExec->GetState();
Table = 0;
PropertyManager = FDMExec->GetPropertyManager();
Table = (FGTable*)0L;
LookupR = LookupC = 0;
numInstances = 0;
rows = columns = 0;
StaticValue = 0.0;
totalValue = 0.0;
bias = 0.0;
gain = 1.0;
SD = 0.0;
filename.erase();
description.erase();
name.erase();
method.erase();
multparms.erase();
multparmsRow.erase();
multparmsCol.erase();
Debug(0);
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
FGCoefficient::~FGCoefficient()
{
if (Table) delete Table;
Debug(1);
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
bool FGCoefficient::Load(FGConfigFile *AC_cfg)
{
int start, end, n;
string mult,prop;
if (AC_cfg) {
name = AC_cfg->GetValue("NAME");
method = AC_cfg->GetValue("TYPE");
AC_cfg->GetNextConfigLine();
*AC_cfg >> description;
if (method == "EQUATION") type = EQUATION;
else if (method == "TABLE") type = TABLE;
else if (method == "VECTOR") type = VECTOR;
else if (method == "VALUE") type = VALUE;
else type = UNKNOWN;
if (type == VECTOR || type == TABLE) {
*AC_cfg >> rows;
if (type == TABLE) {
*AC_cfg >> columns;
Table = new FGTable(rows, columns);
} else {
Table = new FGTable(rows);
}
*AC_cfg >> multparmsRow;
prop = State->GetPropertyName( multparmsRow );
LookupR = PropertyManager->GetNode( prop );
}
if (type == TABLE) {
*AC_cfg >> multparmsCol;
prop = State->GetPropertyName( multparmsCol );
LookupC = PropertyManager->GetNode( prop );
}
// Here, read in the line of the form (e.g.) FG_MACH|FG_QBAR|FG_ALPHA
// where each non-dimensionalizing parameter for this coefficient is
// separated by a | character
*AC_cfg >> multparms;
end = multparms.length();
n = multparms.find("|");
start = 0;
if (multparms != string("FG_NONE")) {
while (n < end && n >= 0) {
n -= start;
mult = multparms.substr(start,n);
prop= State->GetPropertyName( mult );
multipliers.push_back( PropertyManager->GetNode(prop) );
start += n+1;
n = multparms.find("|",start);
}
prop=State->GetPropertyName( multparms.substr(start,n) );
mult = multparms.substr(start,n);
multipliers.push_back( PropertyManager->GetNode(prop) );
// End of non-dimensionalizing parameter read-in
}
if (type == VALUE) {
*AC_cfg >> StaticValue;
} else if (type == VECTOR || type == TABLE) {
*Table << *AC_cfg;
} else {
cerr << "Unimplemented coefficient type: " << type << endl;
}
AC_cfg->GetNextConfigLine();
FGCoefficient::Debug(2);
return true;
} else {
return false;
}
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
double FGCoefficient::Value(double rVal, double cVal)
{
double Value;
unsigned int midx;
SD = Value = gain*Table->GetValue(rVal, cVal) + bias;
for (midx=0; midx < multipliers.size(); midx++) {
Value *= multipliers[midx]->getDoubleValue();
}
return Value;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
double FGCoefficient::Value(double Val)
{
double Value;
SD = Value = gain*Table->GetValue(Val) + bias;
for (unsigned int midx=0; midx < multipliers.size(); midx++)
Value *= multipliers[midx]->getDoubleValue();
return Value;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
double FGCoefficient::Value(void)
{
double Value;
SD = Value = gain*StaticValue + bias;
for (unsigned int midx=0; midx < multipliers.size(); midx++)
Value *= multipliers[midx]->getDoubleValue();
return Value;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
double FGCoefficient::TotalValue(void)
{
switch(type) {
case UNKNOWN:
totalValue = -1;
break;
case VALUE:
totalValue = Value();
break;
case VECTOR:
totalValue = Value( LookupR->getDoubleValue() );
break;
case TABLE:
totalValue = Value( LookupR->getDoubleValue(),
LookupC->getDoubleValue() );
break;
case EQUATION:
totalValue = 0.0;
break;
}
return totalValue;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
void FGCoefficient::DisplayCoeffFactors(void)
{
unsigned int i;
cout << " Non-Dimensionalized by: ";
if (multipliers.size() == 0) {
cout << "none" << endl;
} else {
for (i=0; i<multipliers.size(); i++)
cout << multipliers[i]->getName() << " ";
}
cout << endl;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
string FGCoefficient::GetSDstring(void)
{
char buffer[10];
string value;
sprintf(buffer,"%9.6f",SD);
value = string(buffer);
return value;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
void FGCoefficient::bind(FGPropertyManager *parent)
{
string mult;
unsigned i;
node=parent->GetNode(name,true);
node->SetString("description",description);
if (LookupR) node->SetString("row-parm",LookupR->getName() );
if (LookupC) node->SetString("column-parm",LookupC->getName() );
mult="";
if (multipliers.size() == 0)
mult="none";
for (i=0; i<multipliers.size(); i++) {
mult += multipliers[i]->getName();
if ( i < multipliers.size()-1 ) mult += " ";
}
node->SetString("multipliers",mult);
node->Tie("SD-norm",this,&FGCoefficient::GetSD );
node->Tie("value-lbs",this,&FGCoefficient::GetValue );
node->Tie("bias", this, &FGCoefficient::getBias,
&FGCoefficient::setBias );
node->Tie("gain", this, &FGCoefficient::getGain,
&FGCoefficient::setGain );
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
void FGCoefficient::unbind(void)
{
node->Untie("SD-norm");
node->Untie("value-lbs");
node->Untie("bias");
node->Untie("gain");
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// The bitmasked value choices are as follows:
// unset: In this case (the default) JSBSim would only print
// out the normally expected messages, essentially echoing
// the config files as they are read. If the environment
// variable is not set, debug_lvl is set to 1 internally
// 0: This requests JSBSim not to output any messages
// whatsoever.
// 1: This value explicity requests the normal JSBSim
// startup messages
// 2: This value asks for a message to be printed out when
// a class is instantiated
// 4: When this value is set, a message is displayed when a
// FGModel object executes its Run() method
// 8: When this value is set, various runtime state variables
// are printed out periodically
// 16: When set various parameters are sanity checked and
// a message is printed out when they go out of bounds
void FGCoefficient::Debug(int from)
{
if (debug_lvl <= 0) return;
if (debug_lvl & 1) { // Standard console startup message output
if (from == 2) { // Loading
cout << "\n " << highint << underon << name << underoff << normint << endl;
cout << " " << description << endl;
cout << " " << method << endl;
if (type == VECTOR || type == TABLE) {
cout << " Rows: " << rows << " ";
if (type == TABLE) {
cout << "Cols: " << columns;
}
cout << endl << " Row indexing parameter: " << LookupR->getName() << endl;
}
if (type == TABLE) {
cout << " Column indexing parameter: " << LookupC->getName() << endl;
}
if (type == VALUE) {
cout << " Value = " << StaticValue << endl;
} else if (type == VECTOR || type == TABLE) {
Table->Print();
}
DisplayCoeffFactors();
}
}
if (debug_lvl & 2 ) { // Instantiation/Destruction notification
if (from == 0) cout << "Instantiated: FGCoefficient" << endl;
if (from == 1) cout << "Destroyed: FGCoefficient" << endl;
}
if (debug_lvl & 4 ) { // Run() method entry print for FGModel-derived objects
}
if (debug_lvl & 8 ) { // Runtime state variables
}
if (debug_lvl & 16) { // Sanity checking
}
if (debug_lvl & 64) {
if (from == 0) { // Constructor
cout << IdSrc << endl;
cout << IdHdr << endl;
}
}
}
<commit_msg>Warning fixes, fixed missing include.<commit_after>/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Module: FGCoefficient.cpp
Author: Jon S. Berndt
Date started: 12/28/98
Purpose: Encapsulates the stability derivative class FGCoefficient;
Called by: FGAircraft
------------- Copyright (C) 1999 Jon S. Berndt ([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-1307, USA.
Further information about the GNU General Public License can also be found on
the world wide web at http://www.gnu.org.
FUNCTIONAL DESCRIPTION
--------------------------------------------------------------------------------
This class models the stability derivative coefficient lookup tables or
equations. Note that the coefficients need not be calculated each delta-t.
Note that the values in a row which index into the table must be the same value
for each column of data, so the first column of numbers for each altitude are
seen to be equal, and there are the same number of values for each altitude.
See the header file FGCoefficient.h for the values of the identifiers.
HISTORY
--------------------------------------------------------------------------------
12/28/98 JSB Created
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
INCLUDES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
#include <stdio.h>
#include "FGCoefficient.h"
#include "FGState.h"
#include "FGFDMExec.h"
#include "FGPropertyManager.h"
#ifndef FGFS
# if defined(sgi) && !defined(__GNUC__)
# include <iomanip.h>
# else
# include <iomanip>
# endif
#else
# include STL_IOMANIP
#endif
static const char *IdSrc = "$Id: FGCoefficient.cpp,v 1.57 2002/09/07 21:34:02 apeden Exp $";
static const char *IdHdr = ID_COEFFICIENT;
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
CLASS IMPLEMENTATION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
FGCoefficient::FGCoefficient( FGFDMExec* fdex )
{
FDMExec = fdex;
State = FDMExec->GetState();
Table = 0;
PropertyManager = FDMExec->GetPropertyManager();
Table = (FGTable*)0L;
LookupR = LookupC = 0;
numInstances = 0;
rows = columns = 0;
StaticValue = 0.0;
totalValue = 0.0;
bias = 0.0;
gain = 1.0;
SD = 0.0;
filename.erase();
description.erase();
name.erase();
method.erase();
multparms.erase();
multparmsRow.erase();
multparmsCol.erase();
Debug(0);
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
FGCoefficient::~FGCoefficient()
{
if (Table) delete Table;
Debug(1);
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
bool FGCoefficient::Load(FGConfigFile *AC_cfg)
{
int start, end, n;
string mult,prop;
if (AC_cfg) {
name = AC_cfg->GetValue("NAME");
method = AC_cfg->GetValue("TYPE");
AC_cfg->GetNextConfigLine();
*AC_cfg >> description;
if (method == "EQUATION") type = EQUATION;
else if (method == "TABLE") type = TABLE;
else if (method == "VECTOR") type = VECTOR;
else if (method == "VALUE") type = VALUE;
else type = UNKNOWN;
if (type == VECTOR || type == TABLE) {
*AC_cfg >> rows;
if (type == TABLE) {
*AC_cfg >> columns;
Table = new FGTable(rows, columns);
} else {
Table = new FGTable(rows);
}
*AC_cfg >> multparmsRow;
prop = State->GetPropertyName( multparmsRow );
LookupR = PropertyManager->GetNode( prop );
}
if (type == TABLE) {
*AC_cfg >> multparmsCol;
prop = State->GetPropertyName( multparmsCol );
LookupC = PropertyManager->GetNode( prop );
}
// Here, read in the line of the form (e.g.) FG_MACH|FG_QBAR|FG_ALPHA
// where each non-dimensionalizing parameter for this coefficient is
// separated by a | character
*AC_cfg >> multparms;
end = multparms.length();
n = multparms.find("|");
start = 0;
if (multparms != string("FG_NONE")) {
while (n < end && n >= 0) {
n -= start;
mult = multparms.substr(start,n);
prop= State->GetPropertyName( mult );
multipliers.push_back( PropertyManager->GetNode(prop) );
start += n+1;
n = multparms.find("|",start);
}
prop=State->GetPropertyName( multparms.substr(start,n) );
mult = multparms.substr(start,n);
multipliers.push_back( PropertyManager->GetNode(prop) );
// End of non-dimensionalizing parameter read-in
}
if (type == VALUE) {
*AC_cfg >> StaticValue;
} else if (type == VECTOR || type == TABLE) {
*Table << *AC_cfg;
} else {
cerr << "Unimplemented coefficient type: " << type << endl;
}
AC_cfg->GetNextConfigLine();
FGCoefficient::Debug(2);
return true;
} else {
return false;
}
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
double FGCoefficient::Value(double rVal, double cVal)
{
double Value;
unsigned int midx;
SD = Value = gain*Table->GetValue(rVal, cVal) + bias;
for (midx=0; midx < multipliers.size(); midx++) {
Value *= multipliers[midx]->getDoubleValue();
}
return Value;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
double FGCoefficient::Value(double Val)
{
double Value;
SD = Value = gain*Table->GetValue(Val) + bias;
for (unsigned int midx=0; midx < multipliers.size(); midx++)
Value *= multipliers[midx]->getDoubleValue();
return Value;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
double FGCoefficient::Value(void)
{
double Value;
SD = Value = gain*StaticValue + bias;
for (unsigned int midx=0; midx < multipliers.size(); midx++)
Value *= multipliers[midx]->getDoubleValue();
return Value;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
double FGCoefficient::TotalValue(void)
{
switch(type) {
case UNKNOWN:
totalValue = -1;
break;
case VALUE:
totalValue = Value();
break;
case VECTOR:
totalValue = Value( LookupR->getDoubleValue() );
break;
case TABLE:
totalValue = Value( LookupR->getDoubleValue(),
LookupC->getDoubleValue() );
break;
case EQUATION:
totalValue = 0.0;
break;
}
return totalValue;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
void FGCoefficient::DisplayCoeffFactors(void)
{
unsigned int i;
cout << " Non-Dimensionalized by: ";
if (multipliers.size() == 0) {
cout << "none" << endl;
} else {
for (i=0; i<multipliers.size(); i++)
cout << multipliers[i]->getName() << " ";
}
cout << endl;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
string FGCoefficient::GetSDstring(void)
{
char buffer[10];
string value;
sprintf(buffer,"%9.6f",SD);
value = string(buffer);
return value;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
void FGCoefficient::bind(FGPropertyManager *parent)
{
string mult;
unsigned i;
node=parent->GetNode(name,true);
node->SetString("description",description);
if (LookupR) node->SetString("row-parm",LookupR->getName() );
if (LookupC) node->SetString("column-parm",LookupC->getName() );
mult="";
if (multipliers.size() == 0)
mult="none";
for (i=0; i<multipliers.size(); i++) {
mult += multipliers[i]->getName();
if ( i < multipliers.size()-1 ) mult += " ";
}
node->SetString("multipliers",mult);
node->Tie("SD-norm",this,&FGCoefficient::GetSD );
node->Tie("value-lbs",this,&FGCoefficient::GetValue );
node->Tie("bias", this, &FGCoefficient::getBias,
&FGCoefficient::setBias );
node->Tie("gain", this, &FGCoefficient::getGain,
&FGCoefficient::setGain );
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
void FGCoefficient::unbind(void)
{
node->Untie("SD-norm");
node->Untie("value-lbs");
node->Untie("bias");
node->Untie("gain");
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// The bitmasked value choices are as follows:
// unset: In this case (the default) JSBSim would only print
// out the normally expected messages, essentially echoing
// the config files as they are read. If the environment
// variable is not set, debug_lvl is set to 1 internally
// 0: This requests JSBSim not to output any messages
// whatsoever.
// 1: This value explicity requests the normal JSBSim
// startup messages
// 2: This value asks for a message to be printed out when
// a class is instantiated
// 4: When this value is set, a message is displayed when a
// FGModel object executes its Run() method
// 8: When this value is set, various runtime state variables
// are printed out periodically
// 16: When set various parameters are sanity checked and
// a message is printed out when they go out of bounds
void FGCoefficient::Debug(int from)
{
if (debug_lvl <= 0) return;
if (debug_lvl & 1) { // Standard console startup message output
if (from == 2) { // Loading
cout << "\n " << highint << underon << name << underoff << normint << endl;
cout << " " << description << endl;
cout << " " << method << endl;
if (type == VECTOR || type == TABLE) {
cout << " Rows: " << rows << " ";
if (type == TABLE) {
cout << "Cols: " << columns;
}
cout << endl << " Row indexing parameter: " << LookupR->getName() << endl;
}
if (type == TABLE) {
cout << " Column indexing parameter: " << LookupC->getName() << endl;
}
if (type == VALUE) {
cout << " Value = " << StaticValue << endl;
} else if (type == VECTOR || type == TABLE) {
Table->Print();
}
DisplayCoeffFactors();
}
}
if (debug_lvl & 2 ) { // Instantiation/Destruction notification
if (from == 0) cout << "Instantiated: FGCoefficient" << endl;
if (from == 1) cout << "Destroyed: FGCoefficient" << endl;
}
if (debug_lvl & 4 ) { // Run() method entry print for FGModel-derived objects
}
if (debug_lvl & 8 ) { // Runtime state variables
}
if (debug_lvl & 16) { // Sanity checking
}
if (debug_lvl & 64) {
if (from == 0) { // Constructor
cout << IdSrc << endl;
cout << IdHdr << endl;
}
}
}
<|endoftext|> |
<commit_before>// Time: O(p), p is number of positions
// Space: O(p)
class Solution {
public:
vector<int> numIslands2(int m, int n, vector<pair<int, int>>& positions) {
vector<int> numbers;
int number = 0;
const vector<pair<int, int>> directions{{0, -1}, {0, 1},
{-1, 0}, {1, 0}};
unordered_map<int, int> set;
for (const auto& position : positions) {
const auto& node = make_pair(position.first, position.second);
set[node_id(node, n)] = node_id(node, n);
++number;
for (const auto& d : directions) {
const auto& neighbor = make_pair(position.first + d.first,
position.second + d.second);
if (neighbor.first >= 0 && neighbor.first < m &&
neighbor.second >= 0 && neighbor.second < n &&
set.find(node_id(neighbor, n)) != set.end()) {
if (find_set(node_id(node, n), &set) !=
find_set(node_id(neighbor, n), &set)) {
// Merge different islands.
union_set(&set, node_id(node, n), node_id(neighbor, n));
--number;
}
}
}
numbers.emplace_back(number);
}
return numbers;
}
int node_id(const pair<int, int>& node, const int n) {
return node.first * n + node.second;
}
int find_set(int x, unordered_map<int, int> *set) {
if ((*set)[x] != x) {
(*set)[x] = find_set((*set)[x], set); // path compression.
}
return (*set)[x];
}
void union_set(unordered_map<int, int> *set, const int x, const int y) {
int x_root = find_set(x, set), y_root = find_set(y, set);
(*set)[min(x_root, y_root)] = max(x_root, y_root);
}
};
<commit_msg>Update number-of-islands-ii.cpp<commit_after>// Time: O(p), p is number of positions
// Space: O(p)
// Using unordered_map.
class Solution {
public:
vector<int> numIslands2(int m, int n, vector<pair<int, int>>& positions) {
vector<int> numbers;
int number = 0;
const vector<pair<int, int>> directions{{0, -1}, {0, 1},
{-1, 0}, {1, 0}};
unordered_map<int, int> set;
for (const auto& position : positions) {
const auto& node = make_pair(position.first, position.second);
set[node_id(node, n)] = node_id(node, n);
++number;
for (const auto& d : directions) {
const auto& neighbor = make_pair(position.first + d.first,
position.second + d.second);
if (neighbor.first >= 0 && neighbor.first < m &&
neighbor.second >= 0 && neighbor.second < n &&
set.find(node_id(neighbor, n)) != set.end()) {
if (find_set(node_id(node, n), &set) !=
find_set(node_id(neighbor, n), &set)) {
// Merge different islands.
union_set(&set, node_id(node, n), node_id(neighbor, n));
--number;
}
}
}
numbers.emplace_back(number);
}
return numbers;
}
int node_id(const pair<int, int>& node, const int n) {
return node.first * n + node.second;
}
int find_set(int x, unordered_map<int, int> *set) {
if ((*set)[x] != x) {
(*set)[x] = find_set((*set)[x], set); // path compression.
}
return (*set)[x];
}
void union_set(unordered_map<int, int> *set, const int x, const int y) {
int x_root = find_set(x, set), y_root = find_set(y, set);
(*set)[min(x_root, y_root)] = max(x_root, y_root);
}
};
// Time: O(p), p is number of positions
// Space: O(m * n)
// Using vector.
class Solution2 {
public:
/**
* @param n an integer
* @param m an integer
* @param operators an array of point
* @return an integer array
*/
vector<int> numIslands2(int m, int n, vector<pair<int, int>>& positions) {
vector<int> numbers;
int number = 0;
const vector<pair<int, int>> directions{{0, -1}, {0, 1},
{-1, 0}, {1, 0}};
vector<int> set(m * n, -1);
for (const auto& position : positions) {
const auto& node = make_pair(position.first, position.second);
set[node_id(node, n)] = node_id(node, n);
++number;
for (const auto& d : directions) {
const auto& neighbor = make_pair(position.first + d.first,
position.second + d.second);
if (neighbor.first >= 0 && neighbor.first < m &&
neighbor.second >= 0 && neighbor.second < n &&
set[node_id(neighbor, n)] != -1) {
if (find_set(node_id(node, n), &set) !=
find_set(node_id(neighbor, n), &set)) {
// Merge different islands.
union_set(&set, node_id(node, n), node_id(neighbor, n));
--number;
}
}
}
numbers.emplace_back(number);
}
return numbers;
}
int node_id(const pair<int, int>& node, const int m) {
return node.first * m + node.second;
}
int find_set(int x, vector<int> *set) {
int parent = x;
while ((*set)[parent] != parent) {
parent = (*set)[parent];
}
while ((*set)[x] != x) {
int tmp = (*set)[x];
(*set)[x] = parent;
x = tmp;
}
return parent;
}
void union_set(vector<int> *set, const int x, const int y) {
int x_root = find_set(x, set), y_root = find_set(y, set);
(*set)[min(x_root, y_root)] = max(x_root, y_root);
}
};
<|endoftext|> |
<commit_before>class Solution {
public:
vector<int> numIslands2(int m, int n, vector<pair<int, int>>& positions) {
vector<int> numbers;
int number = 0;
const vector<pair<int, int>> directions{{0, -1}, {0, 1},
{-1, 0}, {1, 0}};
unordered_map<int, int> set;
for (const auto& position : positions) {
const auto& node = make_pair(position.first, position.second);
set[node_id(node, n)] = node_id(node, n);
// For each direction, count distinct islands.
unordered_set<int> neighbors;
for (const auto& d : directions) {
const auto& neighbor = make_pair(position.first + d.first,
position.second + d.second);
if (neighbor.first >= 0 && neighbor.first < m &&
neighbor.second >= 0 && neighbor.second < n &&
set.find(node_id(neighbor, n)) != set.end()) {
neighbors.emplace(find_set(node_id(neighbor, n), &set));
}
}
number += 1 - neighbors.size(); // Merge neighbors into one island.
numbers.emplace_back(number);
// For each direction, find and union.
for (const auto& d : directions) {
const auto& neighbor = make_pair(position.first + d.first,
position.second + d.second);
if (neighbor.first >= 0 && neighbor.first < m &&
neighbor.second >= 0 && neighbor.second < n &&
set.find(node_id(neighbor, n)) != set.end()) {
union_set(&set, node_id(node, n), node_id(neighbor, n));
}
}
}
return numbers;
}
int node_id(const pair<int, int>& node, const int n) {
return node.first * n + node.second;
}
int find_set(int x, unordered_map<int, int> *set) {
if ((*set)[x] != x) {
(*set)[x] = find_set((*set)[x], set); // path compression.
}
return (*set)[x];
}
void union_set(unordered_map<int, int> *set, const int x, const int y) {
int x_root = find_set(x, set), y_root = find_set(y, set);
(*set)[min(x_root, y_root)] = max(x_root, y_root);
}
};
<commit_msg>Update number-of-islands-ii.cpp<commit_after>class Solution {
public:
vector<int> numIslands2(int m, int n, vector<pair<int, int>>& positions) {
vector<int> numbers;
int number = 0;
const vector<pair<int, int>> directions{{0, -1}, {0, 1},
{-1, 0}, {1, 0}};
unordered_map<int, int> set;
for (const auto& position : positions) {
const auto& node = make_pair(position.first, position.second);
set[node_id(node, n)] = node_id(node, n);
++number;
for (const auto& d : directions) {
const auto& neighbor = make_pair(position.first + d.first,
position.second + d.second);
if (neighbor.first >= 0 && neighbor.first < m &&
neighbor.second >= 0 && neighbor.second < n &&
set.find(node_id(neighbor, n)) != set.end()) {
if (find_set(node_id(node, n), &set) !=
find_set(node_id(neighbor, n), &set)) {
// Merge different islands.
union_set(&set, node_id(node, n), node_id(neighbor, n));
--number;
}
}
}
numbers.emplace_back(number);
}
return numbers;
}
int node_id(const pair<int, int>& node, const int n) {
return node.first * n + node.second;
}
int find_set(int x, unordered_map<int, int> *set) {
if ((*set)[x] != x) {
(*set)[x] = find_set((*set)[x], set); // path compression.
}
return (*set)[x];
}
void union_set(unordered_map<int, int> *set, const int x, const int y) {
int x_root = find_set(x, set), y_root = find_set(y, set);
(*set)[min(x_root, y_root)] = max(x_root, y_root);
}
};
<|endoftext|> |
<commit_before>// Time: O(nlogn)
// Space: O(n)
class Solution {
public:
/**
* @param nums: A list of integers
* @return: A list of integers includes the index of the first number
* and the index of the last number
*/
vector<int> subarraySumClosest(vector<int> nums) {
const int n = nums.size();
if (n == 1) {
return {0, 0};
}
// sum_from_start[i] denotes sum for 0 ~ i - 1.
vector<pair<int,int>> sum_from_start(n + 1, {0, 0});
sum_from_start[0].second = -1; // For case closest sum is from 0.
for (int i = 0; i < n; ++i) {
sum_from_start[i+1].first = sum_from_start[i].first + nums[i];
sum_from_start[i+1].second = i;
}
// Sort each sum from start.
sort(sum_from_start.begin(), sum_from_start.end());
int min_diff = INT_MAX;
int start = -1;
int end = -1;
// Find min difference of adjacent sum.
for (int i = 1; i <= n; ++i) {
int diff = abs(sum_from_start[i].first - sum_from_start[i-1].first);
if (diff < min_diff) {
min_diff = diff;
start = min(sum_from_start[i].second, sum_from_start[i - 1].second) + 1;
end = max(sum_from_start[i].second, sum_from_start[i - 1].second);
}
}
return {start, end};
}
};
<commit_msg>Update subarray-sum-closest.cpp<commit_after>// Time: O(nlogn)
// Space: O(n)
class Solution {
public:
/**
* @param nums: A list of integers
* @return: A list of integers includes the index of the first number
* and the index of the last number
*/
vector<int> subarraySumClosest(vector<int> nums) {
const int n = nums.size();
if (n == 1) {
return {0, 0};
}
// sum_from_start[i] denotes sum for 0 ~ i - 1.
vector<pair<int,int>> sum_from_start(n + 1, {0, 0});
sum_from_start[0].second = -1; // For case closest sum is from 0.
for (int i = 0; i < n; ++i) {
sum_from_start[i + 1].first = sum_from_start[i].first + nums[i];
sum_from_start[i + 1].second = i;
}
// Sort each sum from start.
sort(sum_from_start.begin(), sum_from_start.end());
int min_diff = INT_MAX;
int start = -1;
int end = -1;
// Find min difference of adjacent sum.
for (int i = 1; i <= n; ++i) {
int diff = abs(sum_from_start[i].first - sum_from_start[i - 1].first);
if (diff < min_diff) {
min_diff = diff;
start = min(sum_from_start[i].second, sum_from_start[i - 1].second) + 1;
end = max(sum_from_start[i].second, sum_from_start[i - 1].second);
}
}
return {start, end};
}
};
<|endoftext|> |
<commit_before>#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <dirent.h>
#include "GRTestProjectCLP.h"
#include <sstream>
#include "GroupwiseRegistration.h"
const char * VTKSUFFIX = ".vtk";
const char * TXTSUFFIX = ".txt";
const char * COEFFSUFFIX = ".coef";
std::vector<std::string> openDirectory (std::string path)
{
DIR* dir;
dirent* pdir;
std::vector<std::string> files;
dir = opendir(path.c_str());
while(pdir = readdir(dir)) {
files.push_back(std::string(pdir->d_name));
}
return files;
}
std::string removePathAndSuffix(std::string fileName){
std::string fileWithoutPath = fileName.substr(fileName.find_last_of("/")+1, fileName.size());
fileWithoutPath = fileWithoutPath.substr(0, fileWithoutPath.find("."));
return fileWithoutPath;
}
bool checkPropList(std::string propDirPath, std::string fileName){
std::vector<std::string> propDirList;
propDirList = openDirectory(propDirPath);
bool hasProp = false;
for(int i = 0; i < propDirList.size(); i++){
if(propDirList[i].find(fileName) != std::string::npos)
hasProp = true;
}
return hasProp;
}
std::vector<std::string> sortSurfFiles (std::string surfPath, std::string propPath, std::string ID){
std::vector<std::string> directoryFileList;
directoryFileList = openDirectory(surfPath);
std::vector<std::string> sortedFileList;
std::string absPathFileName;
int substring;
// std::vector<std::string>::iterator it;
if (directoryFileList.size() > 0) {
bool doesHaveProp = false;
for (int listIndex = 0; listIndex < directoryFileList.size(); listIndex++) {
std::string currentString = directoryFileList[listIndex];
// it = directoryFileList.begin() + listIndex;
absPathFileName = surfPath;
substring = currentString.find(ID);
if (substring != std::string::npos) {
absPathFileName = absPathFileName + "/" + currentString;
sortedFileList.push_back(absPathFileName);
doesHaveProp = checkPropList(propPath, currentString);
if(!doesHaveProp){
std::cout << "\nWARNING: PROPERTIES FOR " <<currentString<< " DO NOT EXIST. IT HAS BEEN REMOVED\n" << std::endl ;
sortedFileList.erase(sortedFileList.begin() + listIndex);
}
}
}
}
return sortedFileList;
}
std::vector<std::string> sortFiles (std::string path, std::string ID){
std::vector<std::string> directoryFileList;
directoryFileList = openDirectory(path);
std::vector<std::string> sortedFileList;
std::string absPathFileName;
int substring;
// std::vector<std::string>::iterator it;
if (directoryFileList.size() > 0) {
bool doesHaveProp = false;
for (int listIndex = 0; listIndex < directoryFileList.size(); listIndex++) {
std::string currentString = directoryFileList[listIndex];
// it = directoryFileList.begin() + listIndex;
absPathFileName = path;
substring = currentString.find(ID);
if (substring != std::string::npos) {
absPathFileName = absPathFileName + "/" + currentString;
sortedFileList.push_back(absPathFileName);
}
}
}
return sortedFileList;
}
std::vector<std::string> setOutputFiles (std::vector<std::string> surfFiles, std::string outPath, std::string ext, std::string coeff){
std::vector<std::string> outFiles;
std::string surfFileName;
std::string outFileName;
for(int i = 0; i < surfFiles.size(); i++){
surfFileName = removePathAndSuffix(surfFiles[i]);
outFileName = outPath + "/" + surfFileName + ext + "." + coeff;
outFiles.push_back(outFileName);
}
return outFiles;
}
std::vector<std::string> sortFiles (std::vector<std::string> list, std::string ID){
std::vector<std::string> sortedFileList;
if (list.size() > 0) {
for (int listIndex = 0; listIndex < list.size(); listIndex++) {
std::string currentString = list[listIndex];
int substring = currentString.find(ID);
if (substring != std::string::npos) {
sortedFileList.push_back(currentString);
}
}
}
return sortedFileList;
}
char **putFilesInCharList (std::vector<std::string> files, int size){
char **fileList = NULL;
fileList = (char **) malloc(sizeof(char *) * size);
for (int i = 0; i < size; i++)
fileList[i] = (char *)malloc(sizeof(char) * 1024);
for (int i = 0; i < size; i++)
strcpy(fileList[i], files[i].c_str());
return fileList;
}
int main(int argc , char* argv[])
{
PARSE_ARGS;
std::vector<std::string> tempPropFiles;
std::vector<std::string> extList;
std::vector<std::string> extSpecifiedTempPropList ;
std::vector<std::string> extSpecifiedTempPropFiles ;
std::string ext;
int tempSize = tempPropFiles.size();
extList = extensions;
int extSize = extList.size();
std::ostringstream ss0 ;
ss0 << tempDir ;
std::string tempDirString = ss0.str() ;
char **tempProp;
if(!tempDirString.empty()){
for(int i = 0; i < extSize; i++){ //filters based on desired ext
extSpecifiedTempPropList = sortFiles(tempDir, extList[i]);
for(int j = 0; j < extSpecifiedTempPropList.size(); j++){
extSpecifiedTempPropFiles.push_back(extSpecifiedTempPropList[j]);
}
}
int extTempPropSize = extSpecifiedTempPropFiles.size();
tempProp = putFilesInCharList(extSpecifiedTempPropFiles, extTempPropSize);
std::cout<<"Template model properties: "<< tempDir << std::endl ;
for(int i = 0; i < extTempPropSize; i++){
std::cout<< " " << tempProp[i] << ' ' << std::endl ;
}
}
else{
std::cout << "Warning: No input for '-t'." << std::endl ;
tempProp = NULL;
}
char *sph = (char *) sphere.c_str();
char *log = (char *) logfile.c_str();
std::cout<<"Sphere: " << sph << std::endl ;
std::cout<<"Degree: " << degree << std::endl ;
std::cout<<"Logfile: " << logfile << std::endl ;
std::cout<<"Max Iterations: " << maxIter << std::endl ;
std::cout<<"addLoc: " << addLoc << std::endl ;
std::cout<<"Temp Surf: " << tempSurface << std::endl ;
std::vector<std::string> surfaceFiles, coefficientFiles, allPropertyFiles, extSpecifiedPropFiles, outputFiles;
//Handling of Surface directory**********************************************************
std::ostringstream ss ;
ss << surfDir ;
std::string surfDirString = ss.str() ;
std::ostringstream ss1 ;
ss1 << propDir ;
std::string propDirString = ss1.str() ;
char **surfFileList;
int surfSize;
if(!surfDirString.empty()){
if(!propDirString.empty()){
surfaceFiles = sortSurfFiles(surfDir, propDir, VTKSUFFIX);
surfSize = surfaceFiles.size();
surfFileList = putFilesInCharList(surfaceFiles, surfSize);
std::cout<<"Surface Directory: "<< surfDir << std::endl ;
for(int i = 0; i < surfSize; i++)
std::cout<< " " << surfFileList[i] << ' ' << std::endl ;
}
else
std::cout << "Warning: No input for '-p'." << std::endl ;
}
else
surfFileList = NULL;
//Handling of Property directory**********************************************************
std::string surfFileWithoutPath;
std::vector<std::string> foundPropFiles ;
char **propFileList;
if(!propDirString.empty()){
for(int i = 0; i < surfSize; i++){ //puts all props w/corresponding surf in surfFileList
surfFileWithoutPath = removePathAndSuffix(surfFileList[i]);
foundPropFiles = sortFiles(propDir, surfFileWithoutPath);
for(int j = 0; j < foundPropFiles.size(); j++)
allPropertyFiles.push_back(foundPropFiles[j]);
}
std::vector<std::string> extSpecifiedPropList ;
for(int i = 0; i < extSize; i++){ //filters props based on desired ext
extSpecifiedPropList = sortFiles(allPropertyFiles, extList[i]);
for(int j = 0; j < extSpecifiedPropList.size(); j++){
extSpecifiedPropFiles.push_back(extSpecifiedPropList[j]);
}
}
int extPropSize = extSpecifiedPropFiles.size();
int newExtPropSize = extSpecifiedPropFiles.size();
propFileList = putFilesInCharList(extSpecifiedPropFiles, newExtPropSize);
std::cout<<"Property Directory: "<< propDir << std::endl ;
for(int i = 0; i < newExtPropSize; i++){
std::cout<< " " << propFileList[i] << ' ' << std::endl ;
}
}
else
propFileList = NULL;
//Handling of Coefficient directory********************************************************
std::ostringstream ss2 ;
ss2 << spharmDir ;
std::string spharmDirString = ss2.str() ;
char **coeffFileList;
if(!spharmDirString.empty()){
coefficientFiles = sortFiles(spharmDir, COEFFSUFFIX);
int coeffSize = coefficientFiles.size();
coeffFileList = putFilesInCharList(coefficientFiles, coeffSize);
std::cout<<"Coefficient Directory: "<< spharmDir << std::endl ;
for(int i = 0; i < coeffSize; i++)
std::cout<< " " << coeffFileList[i] << ' ' << std::endl ;
}
else
coeffFileList = NULL;
//Output Directory*************************************************************************
outputFiles = setOutputFiles(surfaceFiles, outputDir, TXTSUFFIX, "coeff");
int outSize = outputFiles.size();
char **outFileList = putFilesInCharList(outputFiles, outSize);
std::cout << "Output Directory: " << outputDir << std::endl ;
for(int i = 0; i < outSize; i++){
std::cout << " " << outFileList[i] << ' ' << std::endl ;
}
char *tempSurf = new char[tempSurface.length() + 1];
std::strcpy(tempSurf, tempSurface.c_str());
// Call main procedure
// char *sphere, char **tmpDepth, char **subjDepth, int nSubj, int deg, int nProperties, char *coeffLog, char **coeff
GroupwiseRegistration *r = new GroupwiseRegistration(sph, tempProp, propFileList, surfSize, degree, extSize, addLoc, tempSurf, surfFileList, log, coeffFileList, maxIter);
return 0 ;
}//end of main
<commit_msg>Switched order of ext and coeff suffixes in output file names<commit_after>#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <dirent.h>
#include "GRTestProjectCLP.h"
#include <sstream>
#include "GroupwiseRegistration.h"
const char * VTKSUFFIX = ".vtk";
const char * TXTSUFFIX = ".txt";
const char * COEFFSUFFIX = ".coef";
std::vector<std::string> openDirectory (std::string path)
{
DIR* dir;
dirent* pdir;
std::vector<std::string> files;
dir = opendir(path.c_str());
while(pdir = readdir(dir)) {
files.push_back(std::string(pdir->d_name));
}
return files;
}
std::string removePathAndSuffix(std::string fileName){
std::string fileWithoutPath = fileName.substr(fileName.find_last_of("/")+1, fileName.size());
fileWithoutPath = fileWithoutPath.substr(0, fileWithoutPath.find("."));
return fileWithoutPath;
}
bool checkPropList(std::string propDirPath, std::string fileName){
std::vector<std::string> propDirList;
propDirList = openDirectory(propDirPath);
bool hasProp = false;
for(int i = 0; i < propDirList.size(); i++){
if(propDirList[i].find(fileName) != std::string::npos)
hasProp = true;
}
return hasProp;
}
std::vector<std::string> sortSurfFiles (std::string surfPath, std::string propPath, std::string ID){
std::vector<std::string> directoryFileList;
directoryFileList = openDirectory(surfPath);
std::vector<std::string> sortedFileList;
std::string absPathFileName;
int substring;
// std::vector<std::string>::iterator it;
if (directoryFileList.size() > 0) {
bool doesHaveProp = false;
for (int listIndex = 0; listIndex < directoryFileList.size(); listIndex++) {
std::string currentString = directoryFileList[listIndex];
// it = directoryFileList.begin() + listIndex;
absPathFileName = surfPath;
substring = currentString.find(ID);
if (substring != std::string::npos) {
absPathFileName = absPathFileName + "/" + currentString;
sortedFileList.push_back(absPathFileName);
doesHaveProp = checkPropList(propPath, currentString);
if(!doesHaveProp){
std::cout << "\nWARNING: PROPERTIES FOR " <<currentString<< " DO NOT EXIST. IT HAS BEEN REMOVED\n" << std::endl ;
sortedFileList.erase(sortedFileList.begin() + listIndex);
}
}
}
}
return sortedFileList;
}
std::vector<std::string> sortFiles (std::string path, std::string ID){
std::vector<std::string> directoryFileList;
directoryFileList = openDirectory(path);
std::vector<std::string> sortedFileList;
std::string absPathFileName;
int substring;
// std::vector<std::string>::iterator it;
if (directoryFileList.size() > 0) {
bool doesHaveProp = false;
for (int listIndex = 0; listIndex < directoryFileList.size(); listIndex++) {
std::string currentString = directoryFileList[listIndex];
// it = directoryFileList.begin() + listIndex;
absPathFileName = path;
substring = currentString.find(ID);
if (substring != std::string::npos) {
absPathFileName = absPathFileName + "/" + currentString;
sortedFileList.push_back(absPathFileName);
}
}
}
return sortedFileList;
}
std::vector<std::string> setOutputFiles (std::vector<std::string> surfFiles, std::string outPath, std::string ext, std::string coeff){
std::vector<std::string> outFiles;
std::string surfFileName;
std::string outFileName;
for(int i = 0; i < surfFiles.size(); i++){
surfFileName = removePathAndSuffix(surfFiles[i]);
outFileName = outPath + "/" + surfFileName + coeff + "." + ext;
outFiles.push_back(outFileName);
}
return outFiles;
}
std::vector<std::string> sortFiles (std::vector<std::string> list, std::string ID){
std::vector<std::string> sortedFileList;
if (list.size() > 0) {
for (int listIndex = 0; listIndex < list.size(); listIndex++) {
std::string currentString = list[listIndex];
int substring = currentString.find(ID);
if (substring != std::string::npos) {
sortedFileList.push_back(currentString);
}
}
}
return sortedFileList;
}
char **putFilesInCharList (std::vector<std::string> files, int size){
char **fileList = NULL;
fileList = (char **) malloc(sizeof(char *) * size);
for (int i = 0; i < size; i++)
fileList[i] = (char *)malloc(sizeof(char) * 1024);
for (int i = 0; i < size; i++)
strcpy(fileList[i], files[i].c_str());
return fileList;
}
int main(int argc , char* argv[])
{
PARSE_ARGS;
std::vector<std::string> tempPropFiles;
std::vector<std::string> extList;
std::vector<std::string> extSpecifiedTempPropList ;
std::vector<std::string> extSpecifiedTempPropFiles ;
std::string ext;
int tempSize = tempPropFiles.size();
extList = extensions;
int extSize = extList.size();
std::ostringstream ss0 ;
ss0 << tempDir ;
std::string tempDirString = ss0.str() ;
char **tempProp;
if(!tempDirString.empty()){
for(int i = 0; i < extSize; i++){ //filters based on desired ext
extSpecifiedTempPropList = sortFiles(tempDir, extList[i]);
for(int j = 0; j < extSpecifiedTempPropList.size(); j++){
extSpecifiedTempPropFiles.push_back(extSpecifiedTempPropList[j]);
}
}
int extTempPropSize = extSpecifiedTempPropFiles.size();
tempProp = putFilesInCharList(extSpecifiedTempPropFiles, extTempPropSize);
std::cout<<"Template model properties: "<< tempDir << std::endl ;
for(int i = 0; i < extTempPropSize; i++){
std::cout<< " " << tempProp[i] << ' ' << std::endl ;
}
}
else{
std::cout << "Warning: No input for '-t'." << std::endl ;
tempProp = NULL;
}
char *sph = (char *) sphere.c_str();
char *log = (char *) logfile.c_str();
std::cout<<"Sphere: " << sph << std::endl ;
std::cout<<"Degree: " << degree << std::endl ;
std::cout<<"Logfile: " << logfile << std::endl ;
std::cout<<"Max Iterations: " << maxIter << std::endl ;
std::cout<<"addLoc: " << addLoc << std::endl ;
std::cout<<"Temp Surf: " << tempSurface << std::endl ;
std::vector<std::string> surfaceFiles, coefficientFiles, allPropertyFiles, extSpecifiedPropFiles, outputFiles;
//Handling of Surface directory**********************************************************
std::ostringstream ss ;
ss << surfDir ;
std::string surfDirString = ss.str() ;
std::ostringstream ss1 ;
ss1 << propDir ;
std::string propDirString = ss1.str() ;
char **surfFileList;
int surfSize;
if(!surfDirString.empty()){
if(!propDirString.empty()){
surfaceFiles = sortSurfFiles(surfDir, propDir, VTKSUFFIX);
surfSize = surfaceFiles.size();
surfFileList = putFilesInCharList(surfaceFiles, surfSize);
std::cout<<"Surface Directory: "<< surfDir << std::endl ;
for(int i = 0; i < surfSize; i++)
std::cout<< " " << surfFileList[i] << ' ' << std::endl ;
}
else
std::cout << "Warning: No input for '-p'." << std::endl ;
}
else
surfFileList = NULL;
//Handling of Property directory**********************************************************
std::string surfFileWithoutPath;
std::vector<std::string> foundPropFiles ;
char **propFileList;
if(!propDirString.empty()){
for(int i = 0; i < surfSize; i++){ //puts all props w/corresponding surf in surfFileList
surfFileWithoutPath = removePathAndSuffix(surfFileList[i]);
foundPropFiles = sortFiles(propDir, surfFileWithoutPath);
for(int j = 0; j < foundPropFiles.size(); j++)
allPropertyFiles.push_back(foundPropFiles[j]);
}
std::vector<std::string> extSpecifiedPropList ;
for(int i = 0; i < extSize; i++){ //filters props based on desired ext
extSpecifiedPropList = sortFiles(allPropertyFiles, extList[i]);
for(int j = 0; j < extSpecifiedPropList.size(); j++){
extSpecifiedPropFiles.push_back(extSpecifiedPropList[j]);
}
}
int extPropSize = extSpecifiedPropFiles.size();
int newExtPropSize = extSpecifiedPropFiles.size();
propFileList = putFilesInCharList(extSpecifiedPropFiles, newExtPropSize);
std::cout<<"Property Directory: "<< propDir << std::endl ;
for(int i = 0; i < newExtPropSize; i++){
std::cout<< " " << propFileList[i] << ' ' << std::endl ;
}
}
else
propFileList = NULL;
//Handling of Coefficient directory********************************************************
std::ostringstream ss2 ;
ss2 << spharmDir ;
std::string spharmDirString = ss2.str() ;
char **coeffFileList;
if(!spharmDirString.empty()){
coefficientFiles = sortFiles(spharmDir, COEFFSUFFIX);
int coeffSize = coefficientFiles.size();
coeffFileList = putFilesInCharList(coefficientFiles, coeffSize);
std::cout<<"Coefficient Directory: "<< spharmDir << std::endl ;
for(int i = 0; i < coeffSize; i++)
std::cout<< " " << coeffFileList[i] << ' ' << std::endl ;
}
else
coeffFileList = NULL;
//Output Directory*************************************************************************
outputFiles = setOutputFiles(surfaceFiles, outputDir, TXTSUFFIX, "coeff");
int outSize = outputFiles.size();
char **outFileList = putFilesInCharList(outputFiles, outSize);
std::cout << "Output Directory: " << outputDir << std::endl ;
for(int i = 0; i < outSize; i++){
std::cout << " " << outFileList[i] << ' ' << std::endl ;
}
char *tempSurf = new char[tempSurface.length() + 1];
std::strcpy(tempSurf, tempSurface.c_str());
// Call main procedure
// char *sphere, char **tmpDepth, char **subjDepth, int nSubj, int deg, int nProperties, char *coeffLog, char **coeff
GroupwiseRegistration *r = new GroupwiseRegistration(sph, tempProp, propFileList, surfSize, degree, extSize, addLoc, tempSurf, surfFileList, log, coeffFileList, maxIter);
return 0 ;
}//end of main
<|endoftext|> |
<commit_before>#include <cmath>
#include <iostream>
#include <HFO.hpp>
#include <glog/logging.h>
#include <gflags/gflags.h>
#include "dqn.hpp"
#include <boost/filesystem.hpp>
#include <thread>
#include <mutex>
#include <algorithm>
#include <chrono>
#include <limits>
using namespace boost::filesystem;
// DQN Parameters
DEFINE_bool(gpu, true, "Use GPU to brew Caffe");
DEFINE_bool(gui, false, "Open a GUI window");
DEFINE_string(save, "", "Prefix for saving snapshots");
DEFINE_int32(memory, 400000, "Capacity of replay memory");
DEFINE_int32(explore, 1000000, "Iterations for epsilon to reach given value.");
DEFINE_double(epsilon, .1, "Value of epsilon after explore iterations.");
DEFINE_double(gamma, .99, "Discount factor of future rewards (0,1]");
DEFINE_int32(clone_freq, 10000, "Frequency (steps) of cloning the target network.");
DEFINE_int32(memory_threshold, 50000, "Number of transitions to start learning");
DEFINE_int32(skip_frame, 3, "Number of frames skipped");
DEFINE_string(actor_weights, "", "The actor pretrained weights load (*.caffemodel).");
DEFINE_string(critic_weights, "", "The critic pretrained weights load (*.caffemodel).");
DEFINE_string(actor_snapshot, "", "The actor solver state to load (*.solverstate).");
DEFINE_string(critic_snapshot, "", "The critic solver state to load (*.solverstate).");
DEFINE_string(memory_snapshot, "", "The replay memory to load (*.replaymemory).");
DEFINE_bool(resume, true, "Automatically resume training from latest snapshot.");
DEFINE_bool(evaluate, false, "Evaluation mode: only playing a game, no updates");
DEFINE_bool(delay_reward, true, "If false will skip the timesteps between shooting EOT. ");
DEFINE_double(evaluate_with_epsilon, 0, "Epsilon value to be used in evaluation mode");
DEFINE_int32(evaluate_freq, 250000, "Frequency (steps) between evaluations");
DEFINE_int32(repeat_games, 32, "Number of games played in evaluation mode");
DEFINE_int32(actor_update_factor, 4, "Number of actor updates per critic update");
DEFINE_string(actor_solver, "dqn_actor_solver.prototxt", "Actor solver parameter file (*.prototxt)");
DEFINE_string(critic_solver, "dqn_critic_solver.prototxt", "Critic solver parameter file (*.prototxt)");
double CalculateEpsilon(const int iter) {
if (iter < FLAGS_explore) {
return 1.0 - (1.0 - FLAGS_epsilon) * (static_cast<double>(iter) / FLAGS_explore);
} else {
return FLAGS_epsilon;
}
}
/**
* Converts a discrete action into a continuous HFO-action
x*/
Action GetAction(float kickangle) {
// CHECK_LT(kickangle, 90);
// CHECK_GT(kickangle, -90);
Action a;
a = {KICK, 100., kickangle};
return a;
}
/**
* Play one episode and return the total score
*/
double PlayOneEpisode(HFOEnvironment& hfo, dqn::DQN& dqn, const double epsilon,
const bool update) {
std::deque<dqn::ActorStateDataSp> past_states;
double total_score;
hfo_status_t status = IN_GAME;
while (status == IN_GAME) {
const std::vector<float>& current_state = hfo.getState();
CHECK_EQ(current_state.size(),dqn::kStateDataSize);
dqn::ActorStateDataSp current_state_sp = std::make_shared<dqn::ActorStateData>();
std::copy(current_state.begin(), current_state.end(), current_state_sp->begin());
past_states.push_back(current_state_sp);
if (past_states.size() < dqn::kStateInputCount) {
// If there are not past states enough for DQN input, just select DASH
Action a;
a = {DASH, 0., 0.};
status = hfo.act(a);
} else {
while (past_states.size() > dqn::kStateInputCount) {
past_states.pop_front();
}
dqn::ActorInputStates input_states;
std::copy(past_states.begin(), past_states.end(), input_states.begin());
const float kickangle = dqn.SelectAction(input_states, epsilon);
Action action = GetAction(kickangle);
status = hfo.act(action);
if (!FLAGS_delay_reward) { // Skip to EOT if not delayed reward
while (status == IN_GAME) {
status = hfo.act(action);
}
}
// Rewards for DQN are normalized as follows:
// 1 for scoring a goal, -1 for captured by defense, out of bounds, out of time
// 0 for other middle states
float reward = 0;
if (status == GOAL) {
reward = 1;
} else if (status == CAPTURED_BY_DEFENSE || status == OUT_OF_BOUNDS ||
status == OUT_OF_TIME) {
reward = -1;
}
total_score = reward;
if (update) {
// Add the current transition to replay memory
const std::vector<float>& next_state = hfo.getState();
CHECK_EQ(next_state.size(),dqn::kStateDataSize);
dqn::ActorStateDataSp next_state_sp = std::make_shared<dqn::ActorStateData>();
std::copy(next_state.begin(), next_state.end(), next_state_sp->begin());
const auto transition = (status == IN_GAME) ?
dqn::Transition(input_states, kickangle, reward, next_state_sp):
dqn::Transition(input_states, kickangle, reward, boost::none);
dqn.AddTransition(transition);
// If the size of replay memory is large enough, update DQN
if (dqn.memory_size() > FLAGS_memory_threshold) {
dqn.UpdateCritic();
for (int u = 0; u < FLAGS_actor_update_factor; ++u) {
dqn.UpdateActor();
}
}
}
}
}
return total_score;
}
/**
* Evaluate the current player
*/
double Evaluate(HFOEnvironment& hfo, dqn::DQN& dqn) {
std::vector<double> scores;
for (int i = 0; i < FLAGS_repeat_games; ++i) {
double score = PlayOneEpisode(hfo, dqn, FLAGS_evaluate_with_epsilon, false);
scores.push_back(score);
}
double total_score = 0.0;
for (auto score : scores) {
total_score += score;
}
const auto avg_score = total_score / static_cast<double>(scores.size());
double stddev = 0.0; // Compute the sample standard deviation
for (auto i=0; i<scores.size(); ++i) {
stddev += (scores[i] - avg_score) * (scores[i] - avg_score);
}
stddev = sqrt(stddev / static_cast<double>(FLAGS_repeat_games - 1));
LOG(INFO) << "Evaluation avg_score = " << avg_score << " std = " << stddev;
return avg_score;
}
int main(int argc, char** argv) {
std::string usage(argv[0]);
usage.append(" -[evaluate|save path]");
gflags::SetUsageMessage(usage);
gflags::SetVersionString("0.1");
gflags::ParseCommandLineFlags(&argc, &argv, true);
google::InitGoogleLogging(argv[0]);
google::InstallFailureSignalHandler();
fLI::FLAGS_logbuflevel = -1;
if (FLAGS_evaluate) {
google::LogToStderr();
}
if (!is_regular_file(FLAGS_actor_solver)) {
LOG(ERROR) << "Invalid solver: " << FLAGS_actor_solver;
exit(1);
}
if (FLAGS_save.empty() && !FLAGS_evaluate) {
LOG(ERROR) << "Save path (or evaluate) required but not set.";
LOG(ERROR) << "Usage: " << gflags::ProgramUsage();
exit(1);
}
path save_path(FLAGS_save);
// Set the logging destinations
google::SetLogDestination(google::GLOG_INFO,
(save_path.native() + "_INFO_").c_str());
google::SetLogDestination(google::GLOG_WARNING,
(save_path.native() + "_WARNING_").c_str());
google::SetLogDestination(google::GLOG_ERROR,
(save_path.native() + "_ERROR_").c_str());
google::SetLogDestination(google::GLOG_FATAL,
(save_path.native() + "_FATAL_").c_str());
if (FLAGS_gpu) {
caffe::Caffe::set_mode(caffe::Caffe::GPU);
} else {
caffe::Caffe::set_mode(caffe::Caffe::CPU);
}
// Look for a recent snapshot to resume
LOG(INFO) << "Save path: " << save_path.native();
if (FLAGS_resume && FLAGS_actor_snapshot.empty()
&& FLAGS_critic_snapshot.empty() && FLAGS_memory_snapshot.empty()) {
std::tuple<std::string,std::string,std::string> snapshot =
dqn::FindLatestSnapshot(save_path.native());
FLAGS_actor_snapshot = std::get<0>(snapshot);
FLAGS_critic_snapshot = std::get<1>(snapshot);
FLAGS_memory_snapshot = std::get<2>(snapshot);
}
HFOEnvironment hfo;
hfo.connectToAgentServer(6008);
// Get the vector of legal actions
std::vector<int> legal_actions(dqn::kOutputCount);
std::iota(legal_actions.begin(), legal_actions.end(), 0);
CHECK((FLAGS_critic_snapshot.empty() || FLAGS_critic_weights.empty()) &&
(FLAGS_actor_snapshot.empty() || FLAGS_actor_weights.empty()))
<< "Give a snapshot to resume training or weights to finetune "
"but not both.";
// Construct the solver
caffe::SolverParameter actor_solver_param;
caffe::SolverParameter critic_solver_param;
caffe::ReadProtoFromTextFileOrDie(FLAGS_actor_solver, &actor_solver_param);
caffe::ReadProtoFromTextFileOrDie(FLAGS_critic_solver, &critic_solver_param);
actor_solver_param.set_snapshot_prefix((save_path.native() + "_actor").c_str());
critic_solver_param.set_snapshot_prefix((save_path.native() + "_critic").c_str());
dqn::DQN dqn(legal_actions, actor_solver_param, critic_solver_param,
FLAGS_memory, FLAGS_gamma, FLAGS_clone_freq);
dqn.Initialize();
if (!FLAGS_critic_snapshot.empty() && !FLAGS_actor_snapshot.empty()) {
CHECK(is_regular_file(FLAGS_memory_snapshot))
<< "Unable to find .replaymemory: " << FLAGS_memory_snapshot;
LOG(INFO) << "Actor solver state resuming from " << FLAGS_actor_snapshot;
LOG(INFO) << "Critic solver state resuming from " << FLAGS_critic_snapshot;
dqn.RestoreSolver(FLAGS_actor_snapshot, FLAGS_critic_snapshot);
LOG(INFO) << "Loading replay memory from " << FLAGS_memory_snapshot;
dqn.LoadReplayMemory(FLAGS_memory_snapshot);
} else if (!FLAGS_critic_weights.empty() || !FLAGS_actor_weights.empty()) {
LOG(INFO) << "Actor weights finetuning from " << FLAGS_actor_weights;
LOG(INFO) << "Critic weights finetuning from " << FLAGS_critic_weights;
dqn.LoadTrainedModel(FLAGS_actor_weights, FLAGS_critic_weights);
}
if (FLAGS_evaluate) {
if (FLAGS_gui) {
auto score = PlayOneEpisode(hfo, dqn, FLAGS_evaluate_with_epsilon, false);
LOG(INFO) << "Score " << score;
} else {
Evaluate(hfo, dqn);
}
return 0;
}
int last_eval_iter = 0;
int episode = 0;
double best_score = std::numeric_limits<double>::min();
while (dqn.current_iteration() < actor_solver_param.max_iter()) {
double epsilon = CalculateEpsilon(dqn.current_iteration());
double score = PlayOneEpisode(hfo, dqn, epsilon, true);
LOG(INFO) << "Episode " << episode << " score = " << score
<< ", epsilon = " << epsilon
<< ", iter = " << dqn.current_iteration()
<< ", replay_mem_size = " << dqn.memory_size();
episode++;
if (dqn.current_iteration() >= last_eval_iter + FLAGS_evaluate_freq) {
double avg_score = Evaluate(hfo, dqn);
if (avg_score > best_score) {
LOG(INFO) << "iter " << dqn.current_iteration()
<< " New High Score: " << avg_score;
best_score = avg_score;
std::string fname = save_path.native() + "_HiScore" +
std::to_string(int(avg_score));
dqn.Snapshot(fname, false, false);
}
dqn.Snapshot(save_path.native(), true, true);
last_eval_iter = dqn.current_iteration();
}
}
if (dqn.current_iteration() >= last_eval_iter) {
Evaluate(hfo, dqn);
}
};
<commit_msg>Now dqn starts the server internally.<commit_after>#include <cmath>
#include <iostream>
#include <HFO.hpp>
#include <glog/logging.h>
#include <gflags/gflags.h>
#include "dqn.hpp"
#include <boost/filesystem.hpp>
#include <thread>
#include <mutex>
#include <algorithm>
#include <chrono>
#include <limits>
#include <stdlib.h>
using namespace boost::filesystem;
// DQN Parameters
DEFINE_bool(gpu, true, "Use GPU to brew Caffe");
DEFINE_bool(gui, false, "Open a GUI window");
DEFINE_string(save, "", "Prefix for saving snapshots");
DEFINE_int32(memory, 400000, "Capacity of replay memory");
DEFINE_int32(explore, 1000000, "Iterations for epsilon to reach given value.");
DEFINE_double(epsilon, .1, "Value of epsilon after explore iterations.");
DEFINE_double(gamma, .99, "Discount factor of future rewards (0,1]");
DEFINE_int32(clone_freq, 10000, "Frequency (steps) of cloning the target network.");
DEFINE_int32(memory_threshold, 50000, "Number of transitions to start learning");
DEFINE_string(actor_weights, "", "The actor pretrained weights load (*.caffemodel).");
DEFINE_string(critic_weights, "", "The critic pretrained weights load (*.caffemodel).");
DEFINE_string(actor_snapshot, "", "The actor solver state to load (*.solverstate).");
DEFINE_string(critic_snapshot, "", "The critic solver state to load (*.solverstate).");
DEFINE_string(memory_snapshot, "", "The replay memory to load (*.replaymemory).");
DEFINE_bool(resume, true, "Automatically resume training from latest snapshot.");
DEFINE_bool(evaluate, false, "Evaluation mode: only playing a game, no updates");
DEFINE_bool(delay_reward, true, "If false will skip the timesteps between shooting EOT. ");
DEFINE_double(evaluate_with_epsilon, 0, "Epsilon value to be used in evaluation mode");
DEFINE_int32(evaluate_freq, 250000, "Frequency (steps) between evaluations");
DEFINE_int32(repeat_games, 32, "Number of games played in evaluation mode");
DEFINE_int32(actor_update_factor, 4, "Number of actor updates per critic update");
DEFINE_string(actor_solver, "dqn_actor_solver.prototxt", "Actor solver parameter file (*.prototxt)");
DEFINE_string(critic_solver, "dqn_critic_solver.prototxt", "Critic solver parameter file (*.prototxt)");
DEFINE_string(server_cmd, "./scripts/start.py --offense 1 --defense 0 --headless &",
"Command executed to start the HFO server.");
double CalculateEpsilon(const int iter) {
if (iter < FLAGS_explore) {
return 1.0 - (1.0 - FLAGS_epsilon) * (static_cast<double>(iter) / FLAGS_explore);
} else {
return FLAGS_epsilon;
}
}
/**
* Converts a discrete action into a continuous HFO-action
x*/
Action GetAction(float kickangle) {
// CHECK_LT(kickangle, 90);
// CHECK_GT(kickangle, -90);
Action a;
a = {KICK, 100., kickangle};
return a;
}
/**
* Play one episode and return the total score
*/
double PlayOneEpisode(HFOEnvironment& hfo, dqn::DQN& dqn, const double epsilon,
const bool update) {
std::deque<dqn::ActorStateDataSp> past_states;
double total_score;
hfo_status_t status = IN_GAME;
while (status == IN_GAME) {
const std::vector<float>& current_state = hfo.getState();
CHECK_EQ(current_state.size(),dqn::kStateDataSize);
dqn::ActorStateDataSp current_state_sp = std::make_shared<dqn::ActorStateData>();
std::copy(current_state.begin(), current_state.end(), current_state_sp->begin());
past_states.push_back(current_state_sp);
if (past_states.size() < dqn::kStateInputCount) {
// If there are not past states enough for DQN input, just select DASH
Action a;
a = {DASH, 0., 0.};
status = hfo.act(a);
} else {
while (past_states.size() > dqn::kStateInputCount) {
past_states.pop_front();
}
dqn::ActorInputStates input_states;
std::copy(past_states.begin(), past_states.end(), input_states.begin());
const float kickangle = dqn.SelectAction(input_states, epsilon);
Action action = GetAction(kickangle);
status = hfo.act(action);
if (!FLAGS_delay_reward) { // Skip to EOT if not delayed reward
while (status == IN_GAME) {
status = hfo.act(action);
}
}
// Rewards for DQN are normalized as follows:
// 1 for scoring a goal, -1 for captured by defense, out of bounds, out of time
// 0 for other middle states
float reward = 0;
if (status == GOAL) {
reward = 1;
} else if (status == CAPTURED_BY_DEFENSE || status == OUT_OF_BOUNDS ||
status == OUT_OF_TIME) {
reward = -1;
}
total_score = reward;
if (update) {
// Add the current transition to replay memory
const std::vector<float>& next_state = hfo.getState();
CHECK_EQ(next_state.size(),dqn::kStateDataSize);
dqn::ActorStateDataSp next_state_sp = std::make_shared<dqn::ActorStateData>();
std::copy(next_state.begin(), next_state.end(), next_state_sp->begin());
const auto transition = (status == IN_GAME) ?
dqn::Transition(input_states, kickangle, reward, next_state_sp):
dqn::Transition(input_states, kickangle, reward, boost::none);
dqn.AddTransition(transition);
// If the size of replay memory is large enough, update DQN
if (dqn.memory_size() > FLAGS_memory_threshold) {
dqn.UpdateCritic();
for (int u = 0; u < FLAGS_actor_update_factor; ++u) {
dqn.UpdateActor();
}
}
}
}
}
return total_score;
}
/**
* Evaluate the current player
*/
double Evaluate(HFOEnvironment& hfo, dqn::DQN& dqn) {
std::vector<double> scores;
for (int i = 0; i < FLAGS_repeat_games; ++i) {
double score = PlayOneEpisode(hfo, dqn, FLAGS_evaluate_with_epsilon, false);
scores.push_back(score);
}
double total_score = 0.0;
for (auto score : scores) {
total_score += score;
}
const auto avg_score = total_score / static_cast<double>(scores.size());
double stddev = 0.0; // Compute the sample standard deviation
for (auto i=0; i<scores.size(); ++i) {
stddev += (scores[i] - avg_score) * (scores[i] - avg_score);
}
stddev = sqrt(stddev / static_cast<double>(FLAGS_repeat_games - 1));
LOG(INFO) << "Evaluation avg_score = " << avg_score << " std = " << stddev;
return avg_score;
}
int main(int argc, char** argv) {
std::string usage(argv[0]);
usage.append(" -[evaluate|save path]");
gflags::SetUsageMessage(usage);
gflags::SetVersionString("0.1");
gflags::ParseCommandLineFlags(&argc, &argv, true);
google::InitGoogleLogging(argv[0]);
google::InstallFailureSignalHandler();
fLI::FLAGS_logbuflevel = -1;
if (FLAGS_evaluate) {
google::LogToStderr();
}
if (!is_regular_file(FLAGS_actor_solver)) {
LOG(ERROR) << "Invalid solver: " << FLAGS_actor_solver;
exit(1);
}
if (FLAGS_save.empty() && !FLAGS_evaluate) {
LOG(ERROR) << "Save path (or evaluate) required but not set.";
LOG(ERROR) << "Usage: " << gflags::ProgramUsage();
exit(1);
}
path save_path(FLAGS_save);
// Set the logging destinations
google::SetLogDestination(google::GLOG_INFO,
(save_path.native() + "_INFO_").c_str());
google::SetLogDestination(google::GLOG_WARNING,
(save_path.native() + "_WARNING_").c_str());
google::SetLogDestination(google::GLOG_ERROR,
(save_path.native() + "_ERROR_").c_str());
google::SetLogDestination(google::GLOG_FATAL,
(save_path.native() + "_FATAL_").c_str());
if (FLAGS_gpu) {
caffe::Caffe::set_mode(caffe::Caffe::GPU);
} else {
caffe::Caffe::set_mode(caffe::Caffe::CPU);
}
// Look for a recent snapshot to resume
LOG(INFO) << "Save path: " << save_path.native();
if (FLAGS_resume && FLAGS_actor_snapshot.empty()
&& FLAGS_critic_snapshot.empty() && FLAGS_memory_snapshot.empty()) {
std::tuple<std::string,std::string,std::string> snapshot =
dqn::FindLatestSnapshot(save_path.native());
FLAGS_actor_snapshot = std::get<0>(snapshot);
FLAGS_critic_snapshot = std::get<1>(snapshot);
FLAGS_memory_snapshot = std::get<2>(snapshot);
}
// Start the server
CHECK_EQ(system(FLAGS_server_cmd.c_str()), 0) << "Unable to start the HFO server.";
HFOEnvironment hfo;
hfo.connectToAgentServer(6008);
// Get the vector of legal actions
std::vector<int> legal_actions(dqn::kOutputCount);
std::iota(legal_actions.begin(), legal_actions.end(), 0);
CHECK((FLAGS_critic_snapshot.empty() || FLAGS_critic_weights.empty()) &&
(FLAGS_actor_snapshot.empty() || FLAGS_actor_weights.empty()))
<< "Give a snapshot to resume training or weights to finetune "
"but not both.";
// Construct the solver
caffe::SolverParameter actor_solver_param;
caffe::SolverParameter critic_solver_param;
caffe::ReadProtoFromTextFileOrDie(FLAGS_actor_solver, &actor_solver_param);
caffe::ReadProtoFromTextFileOrDie(FLAGS_critic_solver, &critic_solver_param);
actor_solver_param.set_snapshot_prefix((save_path.native() + "_actor").c_str());
critic_solver_param.set_snapshot_prefix((save_path.native() + "_critic").c_str());
dqn::DQN dqn(legal_actions, actor_solver_param, critic_solver_param,
FLAGS_memory, FLAGS_gamma, FLAGS_clone_freq);
dqn.Initialize();
if (!FLAGS_critic_snapshot.empty() && !FLAGS_actor_snapshot.empty()) {
CHECK(is_regular_file(FLAGS_memory_snapshot))
<< "Unable to find .replaymemory: " << FLAGS_memory_snapshot;
LOG(INFO) << "Actor solver state resuming from " << FLAGS_actor_snapshot;
LOG(INFO) << "Critic solver state resuming from " << FLAGS_critic_snapshot;
dqn.RestoreSolver(FLAGS_actor_snapshot, FLAGS_critic_snapshot);
LOG(INFO) << "Loading replay memory from " << FLAGS_memory_snapshot;
dqn.LoadReplayMemory(FLAGS_memory_snapshot);
} else if (!FLAGS_critic_weights.empty() || !FLAGS_actor_weights.empty()) {
LOG(INFO) << "Actor weights finetuning from " << FLAGS_actor_weights;
LOG(INFO) << "Critic weights finetuning from " << FLAGS_critic_weights;
dqn.LoadTrainedModel(FLAGS_actor_weights, FLAGS_critic_weights);
}
if (FLAGS_evaluate) {
if (FLAGS_gui) {
auto score = PlayOneEpisode(hfo, dqn, FLAGS_evaluate_with_epsilon, false);
LOG(INFO) << "Score " << score;
} else {
Evaluate(hfo, dqn);
}
return 0;
}
int last_eval_iter = 0;
int episode = 0;
double best_score = std::numeric_limits<double>::min();
while (dqn.current_iteration() < actor_solver_param.max_iter()) {
double epsilon = CalculateEpsilon(dqn.current_iteration());
double score = PlayOneEpisode(hfo, dqn, epsilon, true);
LOG(INFO) << "Episode " << episode << " score = " << score
<< ", epsilon = " << epsilon
<< ", iter = " << dqn.current_iteration()
<< ", replay_mem_size = " << dqn.memory_size();
episode++;
if (dqn.current_iteration() >= last_eval_iter + FLAGS_evaluate_freq) {
double avg_score = Evaluate(hfo, dqn);
if (avg_score > best_score) {
LOG(INFO) << "iter " << dqn.current_iteration()
<< " New High Score: " << avg_score;
best_score = avg_score;
std::string fname = save_path.native() + "_HiScore" +
std::to_string(int(avg_score));
dqn.Snapshot(fname, false, false);
}
dqn.Snapshot(save_path.native(), true, true);
last_eval_iter = dqn.current_iteration();
}
}
if (dqn.current_iteration() >= last_eval_iter) {
Evaluate(hfo, dqn);
}
};
<|endoftext|> |
<commit_before>//===------------------------- Redefinition.cpp ---------------------------===//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "redef"
#include "Redefinition.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include <set>
STATISTIC(NumCreatedSigmas, "Number of sigma-phis created");
STATISTIC(NumCreatedFrontierPhis, "Number of non-sigma-phis created");
using namespace llvm;
static RegisterPass<Redefinition> X("redef", "Integer live-range splitting");
char Redefinition::ID = 0;
// Values are redefinable if they're integers and not constants.
static bool IsRedefinable(Value *V) {
return V->getType()->isIntegerTy() && !isa<Constant>(V);
}
static PHINode *CreateNamedPhi(Value *V, Twine Prefix,
BasicBlock::iterator Position) {
Twine Name = Prefix;
if (V->hasName())
Name = Prefix + "." + V->getName();
return PHINode::Create(V->getType(), 1, Name, Position);
}
void Redefinition::getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequired<DominatorTree>();
AU.addRequired<DominanceFrontier>();
AU.setPreservesCFG();
}
bool Redefinition::runOnFunction(Function &F) {
DT_ = &getAnalysis<DominatorTree>();
DF_ = &getAnalysis<DominanceFrontier>();
createSigmasInFunction(&F);
for (auto &BB : F)
for (auto &I : BB)
if (PHINode *Phi = dyn_cast<PHINode>(&I))
if (Phi->getNumIncomingValues() == 1)
Redef_[&BB][Phi->getIncomingValue(0)] = Phi;
return true;
}
PHINode *Redefinition::getRedef(Value *V, BasicBlock *BB) {
auto BBIt = Redef_.find(BB);
if (BBIt == Redef_.end())
return nullptr;
auto Map = BBIt->second.find(V);
return Map == BBIt->second.end() ? Map->second : nullptr;
}
// Create sigma nodes for all branches in the function.
void Redefinition::createSigmasInFunction(Function *F) {
for (auto& BB : *F) {
// Rename operands used in conditional branches and their dependencies.
TerminatorInst *TI = BB.getTerminator();
if (BranchInst *BI = dyn_cast<BranchInst>(TI))
if (BI->isConditional())
createSigmasForCondBranch(BI);
}
}
void Redefinition::createSigmasForCondBranch(BranchInst *BI) {
assert(BI->isConditional() && "Expected conditional branch");
ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition());
if (!ICI || !ICI->getOperand(0)->getType()->isIntegerTy())
return;
DEBUG(dbgs() << "createSigmasForCondBranch: " << *BI << "\n");
Value *Left = ICI->getOperand(0);
Value *Right = ICI->getOperand(1);
BasicBlock *TB = BI->getSuccessor(0);
BasicBlock *FB = BI->getSuccessor(1);
bool HasSinglePredTB = TB->getSinglePredecessor() != nullptr;
bool HasSinglePredFB = FB->getSinglePredecessor() != nullptr;
bool IsRedefinableRight = IsRedefinable(Right);
if (IsRedefinable(Left)) {
// We don't want to place extranius definitions of a value, so only
// place the sigma once if the branch operands are the same.
Value *Second = Left != Right && IsRedefinableRight ? Right : nullptr;
if (HasSinglePredTB)
createSigmaNodesForValueAt(Left, Second, TB);
if (HasSinglePredFB)
createSigmaNodesForValueAt(Left, Second, FB);
}
if (IsRedefinableRight) {
if (HasSinglePredTB)
createSigmaNodesForValueAt(Right, nullptr, TB);
if (HasSinglePredFB)
createSigmaNodesForValueAt(Right, nullptr, FB);
}
}
// Creates sigma nodes for the value and the transitive closure of its
// dependencies.
// To avoid extra redefinitions, we pass in both branch values so that the
// and use the union of both redefinition sets.
void Redefinition::createSigmaNodesForValueAt(Value *V, Value *C,
BasicBlock *BB) {
assert(BB->getSinglePredecessor() && "Block has multiple predecessors");
DEBUG(dbgs() << "createSigmaNodesForValueAt: " << *V << " and "
<< *C << " at " << BB->getName() << "\n");
auto Position = BB->getFirstInsertionPt();
if (IsRedefinable(V) && dominatesUse(V, BB))
createSigmaNodeForValueAt(V, BB, Position);
if (C && IsRedefinable(C) && dominatesUse(C, BB))
createSigmaNodeForValueAt(C, BB, Position);
}
void Redefinition::createSigmaNodeForValueAt(Value *V, BasicBlock *BB,
BasicBlock::iterator Position) {
DEBUG(dbgs() << "createSigmaNodeForValueAt: " << *V << "\n");
auto I = BB->begin();
while (!isa<PHINode>(&(*I)) && I != BB->end()) ++I;
while (isa<PHINode>(&(*I)) && I != BB->end()) {
PHINode *Phi = cast<PHINode>(&(*I));
if (Phi->getNumIncomingValues() == 1 &&
Phi->getIncomingValue(0) == V)
return;
++I;
}
PHINode *BranchRedef = CreateNamedPhi(V, GetRedefPrefix(), Position);
BranchRedef->addIncoming(V, BB->getSinglePredecessor());
NumCreatedSigmas++;
//Redef_[BB][V] = BranchRedef;
//dbgs() << "Redef of " << *V << " at " << BB->getName() << "\n";
// Phi nodes should be created on all blocks in the dominance frontier of BB
// where V is defined.
auto DI = DF_->find(BB);
if (DI != DF_->end())
for (auto& BI : DI->second)
// If the block in the frontier dominates a use of V, then a phi node
// should be created at said block.
if (dominatesUse(V, BI))
if (PHINode *FrontierRedef = createPhiNodeAt(V, BI))
// Replace all incoming definitions with the omega node for every
// predecessor where the omega node is defined.
for (auto PI = pred_begin(BI), PE = pred_end(BI); PI != PE; ++PI)
if (DT_->dominates(BB, *PI)) {
FrontierRedef->removeIncomingValue(*PI);
FrontierRedef->addIncoming(BranchRedef, *PI);
}
// Replace all users of the V with the new sigma, starting at BB.
replaceUsesOfWithAfter(V, BranchRedef, BB);
}
// Creates a phi node for the given value at the given block.
PHINode *Redefinition::createPhiNodeAt(Value *V, BasicBlock *BB) {
assert(!V->getType()->isPointerTy() && "Value must not be a pointer");
DEBUG(dbgs() << "createPhiNodeAt: " << *V << " at "
<< BB->getName() << "\n");
// Return null if V isn't defined on all predecessors of BB.
if (Instruction *I = dyn_cast<Instruction>(V))
for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI)
if (!DT_->dominates(I->getParent(), *PI))
return nullptr;
PHINode *Phi = CreateNamedPhi(V, GetPhiPrefix(), BB->begin());
// Add the default incoming values.
for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI)
Phi->addIncoming(V, *PI);
// Replace all uses of V with the phi node, starting at BB.
replaceUsesOfWithAfter(V, Phi, BB);
NumCreatedFrontierPhis++;
return Phi;
}
// Returns true if BB dominates a use of V.
bool Redefinition::dominatesUse(Value *V, BasicBlock *BB) {
for (auto UI = V->use_begin(), UE = V->use_end(); UI != UE; ++UI)
// Disregard phi nodes, since they can dominate their operands.
if (isa<PHINode>(*UI) || V == *UI)
continue;
else if (Instruction *I = dyn_cast<Instruction>(*UI))
if (DT_->dominates(BB, I->getParent()))
return true;
return false;
}
void Redefinition::replaceUsesOfWithAfter(Value *V, Value *R, BasicBlock *BB) {
DEBUG(dbgs() << "Redefinition: replaceUsesOfWithAfter: " << *V << " to "
<< *R << " after " << BB->getName() << "\n");
std::set<Instruction*> Replace;
for (auto UI = V->use_begin(), UE = V->use_end(); UI != UE; ++UI)
if (Instruction *I = dyn_cast<Instruction>(*UI)) {
// If the instruction's parent dominates BB, mark the instruction to
// be replaced.
if (I != R && DT_->dominates(BB, I->getParent()))
Replace.insert(I);
// If the parent does not dominate BB, check if the use is a phi and
// replace the incoming value.
else if (PHINode *Phi = dyn_cast<PHINode>(*UI))
for (unsigned Idx = 0; Idx < Phi->getNumIncomingValues(); ++Idx)
if (Phi->getIncomingValue(Idx) == V &&
DT_->dominates(BB, Phi->getIncomingBlock(Idx)))
Phi->setIncomingValue(Idx, R);
}
// Replace V with R on all marked instructions.
for (auto& I : Replace)
I->replaceUsesOfWith(V, R);
}
<commit_msg>Fixed bug in Redefinition::getRedef<commit_after>//===------------------------- Redefinition.cpp ---------------------------===//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "redef"
#include "Redefinition.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include <set>
STATISTIC(NumCreatedSigmas, "Number of sigma-phis created");
STATISTIC(NumCreatedFrontierPhis, "Number of non-sigma-phis created");
using namespace llvm;
static RegisterPass<Redefinition> X("redef", "Integer live-range splitting");
char Redefinition::ID = 0;
// Values are redefinable if they're integers and not constants.
static bool IsRedefinable(Value *V) {
return V->getType()->isIntegerTy() && !isa<Constant>(V);
}
static PHINode *CreateNamedPhi(Value *V, Twine Prefix,
BasicBlock::iterator Position) {
Twine Name = Prefix;
if (V->hasName())
Name = Prefix + "." + V->getName();
return PHINode::Create(V->getType(), 1, Name, Position);
}
void Redefinition::getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequired<DominatorTree>();
AU.addRequired<DominanceFrontier>();
AU.setPreservesCFG();
}
bool Redefinition::runOnFunction(Function &F) {
DT_ = &getAnalysis<DominatorTree>();
DF_ = &getAnalysis<DominanceFrontier>();
createSigmasInFunction(&F);
for (auto &BB : F)
for (auto &I : BB)
if (PHINode *Phi = dyn_cast<PHINode>(&I))
if (Phi->getNumIncomingValues() == 1)
Redef_[&BB][Phi->getIncomingValue(0)] = Phi;
return true;
}
PHINode *Redefinition::getRedef(Value *V, BasicBlock *BB) {
auto BBIt = Redef_.find(BB);
if (BBIt == Redef_.end())
return nullptr;
auto Map = BBIt->second.find(V);
return Map != BBIt->second.end() ? Map->second : nullptr;
}
// Create sigma nodes for all branches in the function.
void Redefinition::createSigmasInFunction(Function *F) {
for (auto& BB : *F) {
// Rename operands used in conditional branches and their dependencies.
TerminatorInst *TI = BB.getTerminator();
if (BranchInst *BI = dyn_cast<BranchInst>(TI))
if (BI->isConditional())
createSigmasForCondBranch(BI);
}
}
void Redefinition::createSigmasForCondBranch(BranchInst *BI) {
assert(BI->isConditional() && "Expected conditional branch");
ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition());
if (!ICI || !ICI->getOperand(0)->getType()->isIntegerTy())
return;
DEBUG(dbgs() << "createSigmasForCondBranch: " << *BI << "\n");
Value *Left = ICI->getOperand(0);
Value *Right = ICI->getOperand(1);
BasicBlock *TB = BI->getSuccessor(0);
BasicBlock *FB = BI->getSuccessor(1);
bool HasSinglePredTB = TB->getSinglePredecessor() != nullptr;
bool HasSinglePredFB = FB->getSinglePredecessor() != nullptr;
bool IsRedefinableRight = IsRedefinable(Right);
if (IsRedefinable(Left)) {
// We don't want to place extranius definitions of a value, so only
// place the sigma once if the branch operands are the same.
Value *Second = Left != Right && IsRedefinableRight ? Right : nullptr;
if (HasSinglePredTB)
createSigmaNodesForValueAt(Left, Second, TB);
if (HasSinglePredFB)
createSigmaNodesForValueAt(Left, Second, FB);
}
if (IsRedefinableRight) {
if (HasSinglePredTB)
createSigmaNodesForValueAt(Right, nullptr, TB);
if (HasSinglePredFB)
createSigmaNodesForValueAt(Right, nullptr, FB);
}
}
// Creates sigma nodes for the value and the transitive closure of its
// dependencies.
// To avoid extra redefinitions, we pass in both branch values so that the
// and use the union of both redefinition sets.
void Redefinition::createSigmaNodesForValueAt(Value *V, Value *C,
BasicBlock *BB) {
assert(BB->getSinglePredecessor() && "Block has multiple predecessors");
DEBUG(dbgs() << "createSigmaNodesForValueAt: " << *V << " and "
<< *C << " at " << BB->getName() << "\n");
auto Position = BB->getFirstInsertionPt();
if (IsRedefinable(V) && dominatesUse(V, BB))
createSigmaNodeForValueAt(V, BB, Position);
if (C && IsRedefinable(C) && dominatesUse(C, BB))
createSigmaNodeForValueAt(C, BB, Position);
}
void Redefinition::createSigmaNodeForValueAt(Value *V, BasicBlock *BB,
BasicBlock::iterator Position) {
DEBUG(dbgs() << "createSigmaNodeForValueAt: " << *V << "\n");
auto I = BB->begin();
while (!isa<PHINode>(&(*I)) && I != BB->end()) ++I;
while (isa<PHINode>(&(*I)) && I != BB->end()) {
PHINode *Phi = cast<PHINode>(&(*I));
if (Phi->getNumIncomingValues() == 1 &&
Phi->getIncomingValue(0) == V)
return;
++I;
}
PHINode *BranchRedef = CreateNamedPhi(V, GetRedefPrefix(), Position);
BranchRedef->addIncoming(V, BB->getSinglePredecessor());
NumCreatedSigmas++;
//Redef_[BB][V] = BranchRedef;
//dbgs() << "Redef of " << *V << " at " << BB->getName() << "\n";
// Phi nodes should be created on all blocks in the dominance frontier of BB
// where V is defined.
auto DI = DF_->find(BB);
if (DI != DF_->end())
for (auto& BI : DI->second)
// If the block in the frontier dominates a use of V, then a phi node
// should be created at said block.
if (dominatesUse(V, BI))
if (PHINode *FrontierRedef = createPhiNodeAt(V, BI))
// Replace all incoming definitions with the omega node for every
// predecessor where the omega node is defined.
for (auto PI = pred_begin(BI), PE = pred_end(BI); PI != PE; ++PI)
if (DT_->dominates(BB, *PI)) {
FrontierRedef->removeIncomingValue(*PI);
FrontierRedef->addIncoming(BranchRedef, *PI);
}
// Replace all users of the V with the new sigma, starting at BB.
replaceUsesOfWithAfter(V, BranchRedef, BB);
}
// Creates a phi node for the given value at the given block.
PHINode *Redefinition::createPhiNodeAt(Value *V, BasicBlock *BB) {
assert(!V->getType()->isPointerTy() && "Value must not be a pointer");
DEBUG(dbgs() << "createPhiNodeAt: " << *V << " at "
<< BB->getName() << "\n");
// Return null if V isn't defined on all predecessors of BB.
if (Instruction *I = dyn_cast<Instruction>(V))
for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI)
if (!DT_->dominates(I->getParent(), *PI))
return nullptr;
PHINode *Phi = CreateNamedPhi(V, GetPhiPrefix(), BB->begin());
// Add the default incoming values.
for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI)
Phi->addIncoming(V, *PI);
// Replace all uses of V with the phi node, starting at BB.
replaceUsesOfWithAfter(V, Phi, BB);
NumCreatedFrontierPhis++;
return Phi;
}
// Returns true if BB dominates a use of V.
bool Redefinition::dominatesUse(Value *V, BasicBlock *BB) {
for (auto UI = V->use_begin(), UE = V->use_end(); UI != UE; ++UI)
// Disregard phi nodes, since they can dominate their operands.
if (isa<PHINode>(*UI) || V == *UI)
continue;
else if (Instruction *I = dyn_cast<Instruction>(*UI))
if (DT_->dominates(BB, I->getParent()))
return true;
return false;
}
void Redefinition::replaceUsesOfWithAfter(Value *V, Value *R, BasicBlock *BB) {
DEBUG(dbgs() << "Redefinition: replaceUsesOfWithAfter: " << *V << " to "
<< *R << " after " << BB->getName() << "\n");
std::set<Instruction*> Replace;
for (auto UI = V->use_begin(), UE = V->use_end(); UI != UE; ++UI)
if (Instruction *I = dyn_cast<Instruction>(*UI)) {
// If the instruction's parent dominates BB, mark the instruction to
// be replaced.
if (I != R && DT_->dominates(BB, I->getParent()))
Replace.insert(I);
// If the parent does not dominate BB, check if the use is a phi and
// replace the incoming value.
else if (PHINode *Phi = dyn_cast<PHINode>(*UI))
for (unsigned Idx = 0; Idx < Phi->getNumIncomingValues(); ++Idx)
if (Phi->getIncomingValue(Idx) == V &&
DT_->dominates(BB, Phi->getIncomingBlock(Idx)))
Phi->setIncomingValue(Idx, R);
}
// Replace V with R on all marked instructions.
for (auto& I : Replace)
I->replaceUsesOfWith(V, R);
}
<|endoftext|> |
<commit_before>#include <lib/auto_test.hpp>
#include "../src/libs/steam_vdf_parse.hpp"
class VdfTest : public QObject
{
Q_OBJECT
private:
std::unordered_map<int, SteamVdfParse::GameHeader> map;
SteamVdfParse::GameHeader gameTest;
private slots:
void init();
void testAppId();
void testSize();
void testInfoState();
void testLastUpdated();
void testAccessToken();
void testChangeNumber();
void testSha();
};
void VdfTest::init()
{
map = SteamVdfParse::parseVdf("appinfo.vdf");
gameTest = map.at(208050);
}
void VdfTest::testAppId()
{
QVERIFY(gameTest.appID == 208050);
}
void VdfTest::testSize()
{
QVERIFY(gameTest.size == 1239);
}
void VdfTest::testInfoState()
{
QVERIFY(gameTest.infoState == 2);
}
void VdfTest::testLastUpdated()
{
QVERIFY(gameTest.lastUpdated == 1439232482);
}
void VdfTest::testAccessToken()
{
QVERIFY(gameTest.accessToken == 0);
}
void VdfTest::testChangeNumber()
{
QVERIFY(gameTest.changeNumber == 1127960);
}
void VdfTest::testSha()
{
int codes[20] = {42,74,-65,28,19,82,-64,-39,80,82,-8,-54,-48,-21,83,1,97,-126,-125,-60};
bool shaFlag = true;
for (auto i=0;i<20;i++)
{
if (!int(gameTest.sha[i]) == codes[i])
{
shaFlag = false;
break;
}
}
QVERIFY(shaFlag);
}
DECLARE_TEST(VdfTest)
#include "vdf_test.moc"<commit_msg>Supress warning about incorrect logic<commit_after>#include <lib/auto_test.hpp>
#include "../src/libs/steam_vdf_parse.hpp"
class VdfTest : public QObject
{
Q_OBJECT
private:
std::unordered_map<int, SteamVdfParse::GameHeader> map;
SteamVdfParse::GameHeader gameTest;
private slots:
void init();
void testAppId();
void testSize();
void testInfoState();
void testLastUpdated();
void testAccessToken();
void testChangeNumber();
void testSha();
};
void VdfTest::init()
{
map = SteamVdfParse::parseVdf("appinfo.vdf");
gameTest = map.at(208050);
}
void VdfTest::testAppId()
{
QVERIFY(gameTest.appID == 208050);
}
void VdfTest::testSize()
{
QVERIFY(gameTest.size == 1239);
}
void VdfTest::testInfoState()
{
QVERIFY(gameTest.infoState == 2);
}
void VdfTest::testLastUpdated()
{
QVERIFY(gameTest.lastUpdated == 1439232482);
}
void VdfTest::testAccessToken()
{
QVERIFY(gameTest.accessToken == 0);
}
void VdfTest::testChangeNumber()
{
QVERIFY(gameTest.changeNumber == 1127960);
}
void VdfTest::testSha()
{
int codes[20] = {42, 74, -65, 28, 19, 82, -64, -39, 80, 82, -8, -54, -48, -21, 83, 1, 97, -126, -125, -60};
bool shaFlag = true;
for (auto i = 0; i < 20; i++)
{
if (!(int(gameTest.sha[i]) == codes[i]))
{
shaFlag = false;
break;
}
}
QVERIFY(shaFlag);
}
DECLARE_TEST(VdfTest)
#include "vdf_test.moc"
<|endoftext|> |
<commit_before>#include <iostream>
#include "EdmondsKarp.h"
#include "ReadGraph.h"
#include "WriteResult.h"
void writeResult(Graph& Go, Graph& Gr, FlightEdgeDict& fed, bool file, char* outfile){
WriteResult wr(Go, Gr, fed);
wr.process();
if(file){
wr.writeToFile(std::string(outfile));
}
else{
wr.print();
}
}
int main (int argc, char* argv[])
{
char* outfile;
bool isfileout = false;
char* infile;
bool isfilein = false;
if (argc == 2 or argc == 4 or argc > 5) {
std::cout << "Usage is: " << argv[0] << " [-i <infile>][-o <outfile>]" << std::endl;
exit(0);
}
else if(argc == 3 or argc == 5){
for (int i = 1; i < argc; i+=2) {
if (i + 1 != argc){
if (std::string(argv[i]) == "-o") {
outfile = argv[i+1];
isfileout = true;
}
else if (std::string(argv[i]) == "-i"){
infile = argv[i+1];
isfilein = true;
}
else if (std::string(argv[i]) == "-h")
{
std::cout << "Usage is: " << argv[0] << " [-i <infile>][-o <outfile>]" << std::endl;
exit(0);
}
else {
std::cout << "Invalid arguments" << std::endl;
exit(0);
}
}
}
}
else{
isfilein = isfileout = false;
}
ReadGraph rg;
if(isfilein){
rg.readFromFile(infile);
}
else{
rg.read();
}
int f = rg.getNumFlights();
int n = rg.getSize();
int i, j;
i = 1;
j = f;
int mat[n*n];
rg.parametrize(mat);
//binary search
int n = rg.getSize();
int i, j;
i = 1;
j = f;
int mat[n*n];
rg.parametrize(mat);
while(not(i > j)){
int k = (i+j)/2;
rg.reallyParametrize(mat,k,n);
std::vector<Flight> flights = rg.getFlights();
FlightEdgeDict fed(flights);
rg.makeFED(fed);
int source = rg.getSource();
int sink = rg.getSink();
Graph G = Graph(mat,n,source,sink);
EdmondsKarp ek = EdmondsKarp(G);
ek.solve();
if(ek.isMaxFlow())
{
if(k == i){
Graph g = ek.getResult();
int m[(n-2)*(n-2)];
rg.getUpperBoundsRawAdjMatrix(m);
Graph G = Graph(m,n-2,source-2,sink-2);
writeResult(G, g, fed, isfileout, outfile);
std::cout << k << std::endl;
break;
}
else{
j = k;
}
}
else
{
i = k+1;
}
}
}
<commit_msg>fix repeated code<commit_after>#include <iostream>
#include "EdmondsKarp.h"
#include "ReadGraph.h"
#include "WriteResult.h"
void writeResult(Graph& Go, Graph& Gr, FlightEdgeDict& fed, bool file, char* outfile){
WriteResult wr(Go, Gr, fed);
wr.process();
if(file){
wr.writeToFile(std::string(outfile));
}
else{
wr.print();
}
}
int main (int argc, char* argv[])
{
char* outfile;
bool isfileout = false;
char* infile;
bool isfilein = false;
if (argc == 2 or argc == 4 or argc > 5) {
std::cout << "Usage is: " << argv[0] << " [-i <infile>][-o <outfile>]" << std::endl;
exit(0);
}
else if(argc == 3 or argc == 5){
for (int i = 1; i < argc; i+=2) {
if (i + 1 != argc){
if (std::string(argv[i]) == "-o") {
outfile = argv[i+1];
isfileout = true;
}
else if (std::string(argv[i]) == "-i"){
infile = argv[i+1];
isfilein = true;
}
else if (std::string(argv[i]) == "-h")
{
std::cout << "Usage is: " << argv[0] << " [-i <infile>][-o <outfile>]" << std::endl;
exit(0);
}
else {
std::cout << "Invalid arguments" << std::endl;
exit(0);
}
}
}
}
else{
isfilein = isfileout = false;
}
ReadGraph rg;
if(isfilein){
rg.readFromFile(infile);
}
else{
rg.read();
}
int f = rg.getNumFlights();
int n = rg.getSize();
int i, j;
i = 1;
j = f;
int mat[n*n];
rg.parametrize(mat);
//binary search
while(not(i > j)){
int k = (i+j)/2;
rg.reallyParametrize(mat,k,n);
std::vector<Flight> flights = rg.getFlights();
FlightEdgeDict fed(flights);
rg.makeFED(fed);
int source = rg.getSource();
int sink = rg.getSink();
Graph G = Graph(mat,n,source,sink);
EdmondsKarp ek = EdmondsKarp(G);
ek.solve();
if(ek.isMaxFlow())
{
if(k == i){
Graph g = ek.getResult();
int m[(n-2)*(n-2)];
rg.getUpperBoundsRawAdjMatrix(m);
Graph G = Graph(m,n-2,source-2,sink-2);
writeResult(G, g, fed, isfileout, outfile);
std::cout << k << std::endl;
break;
}
else{
j = k;
}
}
else
{
i = k+1;
}
}
}
<|endoftext|> |
<commit_before>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2008 Scientific Computing and Imaging Institute,
University of Utah.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
/**
\file VFFConverter.cpp
\author Jens Krueger
SCI Institute
University of Utah
\date December 2008
*/
#include <fstream>
#include "VFFConverter.h"
#include <Controller/Controller.h>
#include <IO/KeyValueFileParser.h>
using namespace std;
VFFConverter::VFFConverter()
{
m_vConverterDesc = "Visualization File Format";
m_vSupportedExt.push_back("VFF");
}
bool VFFConverter::ConvertToRAW(const std::string& strSourceFilename,
const std::string&, bool,
UINT64& iHeaderSkip, UINT64& iComponentSize, UINT64& iComponentCount,
bool& bConvertEndianess, bool& bSigned, bool& bIsFloat, UINT64VECTOR3& vVolumeSize,
FLOATVECTOR3& vVolumeAspect, std::string& strTitle,
UVFTables::ElementSemanticTable& eType, std::string& strIntermediateFile,
bool& bDeleteIntermediateFile) {
MESSAGE("Attempting to convert VFF dataset %s", strSourceFilename.c_str());
// Check Magic value in VFF File first
ifstream fileData(strSourceFilename.c_str());
string strFirstLine;
if (fileData.is_open())
{
getline (fileData,strFirstLine);
if (strFirstLine.substr(0,4) != "ncaa") {
WARNING("The file %s is not a VFF file (missing magic)", strSourceFilename.c_str());
return false;
}
} else {
WARNING("Could not open VFF file %s", strSourceFilename.c_str());
return false;
}
fileData.close();
// init data
strIntermediateFile = strSourceFilename;
bDeleteIntermediateFile = false;
iComponentSize = 8;
iComponentCount = 1;
vVolumeSize = UINT64VECTOR3(1,1,1);
vVolumeAspect = FLOATVECTOR3(1,1,1);
bConvertEndianess = EndianConvert::IsLittleEndian();
bSigned = true;
eType = UVFTables::ES_UNDEFINED;
bIsFloat = false; /// \todo check if VFF can store float values
// read data
string strHeaderEnd;
strHeaderEnd.push_back(12); // header end char of vffs is ^L = 0C = 12
KeyValueFileParser parser(strSourceFilename, false, "=", strHeaderEnd);
if (!parser.FileReadable()) {
WARNING("Could not open VFF file %s", strSourceFilename.c_str());
return false;
}
KeyValPair* kvp = parser.GetData("TYPE");
if (kvp == NULL) {
T_ERROR("Could not find token \"type\" in file %s", strSourceFilename.c_str());
return false;
} else {
if (kvp->strValueUpper != "RASTER;") {
T_ERROR("Only raster VFFs are supported at the moment");
return false;
}
}
int iDim;
kvp = parser.GetData("RANK");
if (kvp == NULL) {
T_ERROR("Could not find token \"rank\" in file %s", strSourceFilename.c_str());
return false;
} else {
iDim = kvp->iValue;
}
kvp = parser.GetData("BANDS");
if (kvp == NULL) {
T_ERROR("Could not find token \"bands\" in file %s", strSourceFilename.c_str());
return false;
} else {
if (kvp->iValue != 1) {
T_ERROR("Only scalar VFFs are supported at the moment");
return false;
}
}
kvp = parser.GetData("FORMAT");
if (kvp == NULL) {
T_ERROR("Could not find token \"format\" in file %s", strSourceFilename.c_str());
return false;
} else {
if (kvp->strValueUpper != "SLICE;") {
T_ERROR("Only VFFs with slice layout are supported at the moment");
return false;
}
}
kvp = parser.GetData("BITS");
if (kvp == NULL) {
T_ERROR("Could not find token \"bands\" in file %s", strSourceFilename.c_str());
return false;
} else {
iComponentSize = kvp->iValue;
}
kvp = parser.GetData("SIZE");
if (kvp == NULL) {
T_ERROR("Could not find token \"size\" in file %s", strSourceFilename.c_str());
return false;
} else {
vVolumeSize[0] = kvp->viValue[0];
vVolumeSize[1] = kvp->viValue[1];
if (iDim == 3) vVolumeSize[2] = kvp->viValue[2];
}
kvp = parser.GetData("SPACING");
if (kvp == NULL) {
T_ERROR("Could not find token \"size\" in file %s", strSourceFilename.c_str());
return false;
} else {
vVolumeAspect[0] = kvp->vfValue[0];
vVolumeAspect[1] = kvp->vfValue[1];
if (iDim == 3) vVolumeAspect[2] = kvp->vfValue[2];
}
kvp = parser.GetData("TITLE");
if (kvp == NULL) {
strTitle = "VFF data";
} else {
strTitle = kvp->strValue;
}
iHeaderSkip = parser.GetStopPos();
return true;
}
bool VFFConverter::ConvertToNative(const std::string& strRawFilename, const std::string& strTargetFilename, UINT64 iHeaderSkip,
UINT64 iComponentSize, UINT64 iComponentCount, bool bSigned, bool bFloatingPoint,
UINT64VECTOR3 vVolumeSize,FLOATVECTOR3 vVolumeAspect, bool, bool bQuantizeTo8Bit) {
// create header textfile from metadata
ofstream fAsciiTarget(strTargetFilename.c_str());
if (!fAsciiTarget.is_open()) {
T_ERROR("Unable to open target file %s.", strTargetFilename.c_str());
return false;
}
if (bFloatingPoint) {
T_ERROR("Floating point formats are not avaliable for vff files.");
return false;
}
fAsciiTarget << "ncaa" << endl;
fAsciiTarget << "type=raster;" << endl;
fAsciiTarget << "rank=3;" << endl;
fAsciiTarget << "bands=" << iComponentCount << ";"<< endl;
fAsciiTarget << "format=slice;" << endl;
fAsciiTarget << "bits=" << iComponentSize << ";" << endl;
fAsciiTarget << "size=" << vVolumeSize.x << " " << vVolumeSize.y << " "<< vVolumeSize.z << ";" << endl;
fAsciiTarget << "spacing=" << vVolumeAspect.x << " " << vVolumeAspect.y << " "<< vVolumeAspect.z << ";" << endl;
// add the ^L header delimiter
string strHeaderEnd;
strHeaderEnd.push_back(12); // header end char of vffs is ^L = 0C = 12
fAsciiTarget << strHeaderEnd << endl;
fAsciiTarget.close();
// append RAW data using the parent's call
bool bRAWSuccess = AppendRAW(strRawFilename, iHeaderSkip, strTargetFilename, iComponentSize, !EndianConvert::IsBigEndian(), !bSigned, bQuantizeTo8Bit);
if (bRAWSuccess) {
return true;
} else {
T_ERROR("Error appaneding raw data to header file %s.", strTargetFilename.c_str());
remove(strTargetFilename.c_str());
return false;
}
}
<commit_msg>Provide a default for the VFF's third dimension size.<commit_after>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2008 Scientific Computing and Imaging Institute,
University of Utah.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
/**
\file VFFConverter.cpp
\author Jens Krueger
SCI Institute
University of Utah
\date December 2008
*/
#include <fstream>
#include "VFFConverter.h"
#include <Controller/Controller.h>
#include <IO/KeyValueFileParser.h>
using namespace std;
VFFConverter::VFFConverter()
{
m_vConverterDesc = "Visualization File Format";
m_vSupportedExt.push_back("VFF");
}
bool VFFConverter::ConvertToRAW(const std::string& strSourceFilename,
const std::string&, bool,
UINT64& iHeaderSkip, UINT64& iComponentSize, UINT64& iComponentCount,
bool& bConvertEndianess, bool& bSigned, bool& bIsFloat, UINT64VECTOR3& vVolumeSize,
FLOATVECTOR3& vVolumeAspect, std::string& strTitle,
UVFTables::ElementSemanticTable& eType, std::string& strIntermediateFile,
bool& bDeleteIntermediateFile) {
MESSAGE("Attempting to convert VFF dataset %s", strSourceFilename.c_str());
// Check Magic value in VFF File first
ifstream fileData(strSourceFilename.c_str());
string strFirstLine;
if (fileData.is_open())
{
getline (fileData,strFirstLine);
if (strFirstLine.substr(0,4) != "ncaa") {
WARNING("The file %s is not a VFF file (missing magic)", strSourceFilename.c_str());
return false;
}
} else {
WARNING("Could not open VFF file %s", strSourceFilename.c_str());
return false;
}
fileData.close();
// init data
strIntermediateFile = strSourceFilename;
bDeleteIntermediateFile = false;
iComponentSize = 8;
iComponentCount = 1;
vVolumeSize = UINT64VECTOR3(1,1,1);
vVolumeAspect = FLOATVECTOR3(1,1,1);
bConvertEndianess = EndianConvert::IsLittleEndian();
bSigned = true;
eType = UVFTables::ES_UNDEFINED;
bIsFloat = false; /// \todo check if VFF can store float values
// read data
string strHeaderEnd;
strHeaderEnd.push_back(12); // header end char of vffs is ^L = 0C = 12
KeyValueFileParser parser(strSourceFilename, false, "=", strHeaderEnd);
if (!parser.FileReadable()) {
WARNING("Could not open VFF file %s", strSourceFilename.c_str());
return false;
}
KeyValPair* kvp = parser.GetData("TYPE");
if (kvp == NULL) {
T_ERROR("Could not find token \"type\" in file %s", strSourceFilename.c_str());
return false;
} else {
if (kvp->strValueUpper != "RASTER;") {
T_ERROR("Only raster VFFs are supported at the moment");
return false;
}
}
int iDim;
kvp = parser.GetData("RANK");
if (kvp == NULL) {
T_ERROR("Could not find token \"rank\" in file %s", strSourceFilename.c_str());
return false;
} else {
iDim = kvp->iValue;
}
kvp = parser.GetData("BANDS");
if (kvp == NULL) {
T_ERROR("Could not find token \"bands\" in file %s", strSourceFilename.c_str());
return false;
} else {
if (kvp->iValue != 1) {
T_ERROR("Only scalar VFFs are supported at the moment");
return false;
}
}
kvp = parser.GetData("FORMAT");
if (kvp == NULL) {
T_ERROR("Could not find token \"format\" in file %s", strSourceFilename.c_str());
return false;
} else {
if (kvp->strValueUpper != "SLICE;") {
T_ERROR("Only VFFs with slice layout are supported at the moment");
return false;
}
}
kvp = parser.GetData("BITS");
if (kvp == NULL) {
T_ERROR("Could not find token \"bands\" in file %s", strSourceFilename.c_str());
return false;
} else {
iComponentSize = kvp->iValue;
}
kvp = parser.GetData("SIZE");
if (kvp == NULL) {
T_ERROR("Could not find token \"size\" in file %s", strSourceFilename.c_str());
return false;
} else {
vVolumeSize[0] = kvp->viValue[0];
vVolumeSize[1] = kvp->viValue[1];
vVolumeSize[2] = 1;
if (iDim == 3) vVolumeSize[2] = kvp->viValue[2];
MESSAGE("%llu x %llu x %llu volume.", vVolumeSize[0], vVolumeSize[1],
vVolumeSize[2]);
}
kvp = parser.GetData("SPACING");
if (kvp == NULL) {
T_ERROR("Could not find token \"size\" in file %s", strSourceFilename.c_str());
return false;
} else {
vVolumeAspect[0] = kvp->vfValue[0];
vVolumeAspect[1] = kvp->vfValue[1];
if (iDim == 3) vVolumeAspect[2] = kvp->vfValue[2];
}
kvp = parser.GetData("TITLE");
if (kvp == NULL) {
strTitle = "VFF data";
} else {
strTitle = kvp->strValue;
}
iHeaderSkip = parser.GetStopPos();
return true;
}
bool VFFConverter::ConvertToNative(const std::string& strRawFilename, const std::string& strTargetFilename, UINT64 iHeaderSkip,
UINT64 iComponentSize, UINT64 iComponentCount, bool bSigned, bool bFloatingPoint,
UINT64VECTOR3 vVolumeSize,FLOATVECTOR3 vVolumeAspect, bool, bool bQuantizeTo8Bit) {
// create header textfile from metadata
ofstream fAsciiTarget(strTargetFilename.c_str());
if (!fAsciiTarget.is_open()) {
T_ERROR("Unable to open target file %s.", strTargetFilename.c_str());
return false;
}
if (bFloatingPoint) {
T_ERROR("Floating point formats are not avaliable for vff files.");
return false;
}
fAsciiTarget << "ncaa" << endl;
fAsciiTarget << "type=raster;" << endl;
fAsciiTarget << "rank=3;" << endl;
fAsciiTarget << "bands=" << iComponentCount << ";"<< endl;
fAsciiTarget << "format=slice;" << endl;
fAsciiTarget << "bits=" << iComponentSize << ";" << endl;
fAsciiTarget << "size=" << vVolumeSize.x << " " << vVolumeSize.y << " "<< vVolumeSize.z << ";" << endl;
fAsciiTarget << "spacing=" << vVolumeAspect.x << " " << vVolumeAspect.y << " "<< vVolumeAspect.z << ";" << endl;
// add the ^L header delimiter
string strHeaderEnd;
strHeaderEnd.push_back(12); // header end char of vffs is ^L = 0C = 12
fAsciiTarget << strHeaderEnd << endl;
fAsciiTarget.close();
// append RAW data using the parent's call
bool bRAWSuccess = AppendRAW(strRawFilename, iHeaderSkip, strTargetFilename, iComponentSize, !EndianConvert::IsBigEndian(), !bSigned, bQuantizeTo8Bit);
if (bRAWSuccess) {
return true;
} else {
T_ERROR("Error appaneding raw data to header file %s.", strTargetFilename.c_str());
remove(strTargetFilename.c_str());
return false;
}
}
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/usr/expaccess/test/ocmbcommtest.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2018,2020 */
/* [+] 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 __OCMBCOMMTEST_H
#define __OCMBCOMMTEST_H
/**
* @file ocmbcommtest.H
*
* @brief Test cases for OCMB communication protocol
*/
#include <cxxtest/TestSuite.H>
#include <errl/errlmanager.H>
#include <errl/errlentry.H>
#include <fapi2.H>
#include <plat_hwp_invoker.H>
#include <exp_inband.H>
#include <exp_data_structs.H>
#include <generic/memory/lib/utils/endian_utils.H>
#include "exptest_utils.H"
// EXP_FW_ADAPTER_PROPERTIES_GET data response format
#define FW_ADAPTER_MAX_FW_IMAGE 4
#define FW_ADAPTER_CHIP_VERSION_SIZE 128
#define FW_ADAPTER_SPI_FLASH_ID_SIZE 32
typedef struct
{
uint32_t fw_number_of_images; // number of FW images
uint32_t boot_partion_id; // ID of current boot partion
struct fw_version_string
{
uint32_t major; // FW version - Major release
uint32_t minor; // FW version - Minor release
uint32_t build_num; // FW build number
uint32_t build_patch; // FW build path number
uint32_t sector_size; // FW sector size
} fw_ver_str[FW_ADAPTER_MAX_FW_IMAGE];
uint32_t ram_size_in_bytes; // RAM size in bytes
unsigned char chip_version[FW_ADAPTER_CHIP_VERSION_SIZE]; // Explorer chip revision
unsigned char spi_flash_id[FW_ADAPTER_SPI_FLASH_ID_SIZE]; // SPI flash ID
uint32_t spi_flash_size; // SPI flash size in bytes
uint32_t error_buffer_offset; // FW error buffer offset in SPI flash
uint32_t error_buffer_size; // FW error buffer size in bytes
} FW_ADAPTER_PROPERTIES_type;
class OCMBCommTest: public CxxTest::TestSuite
{
public:
/**
* @brief Fills in command structure for the EXP_FW_ADAPTER_PROPERTIES_GET cmd
* @param io_cmd -- command that gets filled in
*/
void buildPropertiesGetCmd(host_fw_command_struct & io_cmd)
{
io_cmd.cmd_id = 0x07; // EXP_FW_ADAPTER_PROPERTIES_GET
io_cmd.cmd_flags = 0x00; // no additional data
io_cmd.request_identifier = 0x0203; // host generated id number
io_cmd.cmd_length = 0x00000000; // length of addditional data
io_cmd.cmd_crc = 0xFFFFFFFF; // CRC-32 of no additional data
io_cmd.host_work_area = 0x00000000;
io_cmd.cmd_work_area = 0x00000000;
memset(io_cmd.padding, 0, sizeof(io_cmd.padding));
memset(io_cmd.command_argument, 0, sizeof(io_cmd.command_argument));
}
/**
* @brief Convert structure from little endian format into big endian
* @param o_data -- big endian output
* @param i_data -- vector of little endian data
* @return true if successful, else false
*/
bool fw_adapter_properties_struct_from_little_endian(
FW_ADAPTER_PROPERTIES_type & o_data,
std::vector<uint8_t>& i_data)
{
bool l_rc = false;
// make sure we don't go outside i_data range
if (i_data.size() >= sizeof(o_data))
{
uint32_t l_idx = 0;
l_rc = mss::readLE(i_data, l_idx, o_data.fw_number_of_images);
l_rc &= mss::readLE(i_data, l_idx, o_data.boot_partion_id);
for (int i = 0; i < FW_ADAPTER_MAX_FW_IMAGE; ++i)
{
l_rc &= mss::readLE(i_data, l_idx, o_data.fw_ver_str[i].major);
l_rc &= mss::readLE(i_data, l_idx, o_data.fw_ver_str[i].minor);
l_rc &= mss::readLE(i_data, l_idx, o_data.fw_ver_str[i].build_num);
l_rc &= mss::readLE(i_data, l_idx, o_data.fw_ver_str[i].build_patch);
l_rc &= mss::readLE(i_data, l_idx, o_data.fw_ver_str[i].sector_size);
}
l_rc &= mss::readLE(i_data, l_idx, o_data.ram_size_in_bytes);
l_rc &= mss::readLEArray(i_data, FW_ADAPTER_CHIP_VERSION_SIZE, l_idx, o_data.chip_version);
l_rc &= mss::readLEArray(i_data, FW_ADAPTER_SPI_FLASH_ID_SIZE, l_idx, o_data.spi_flash_id);
l_rc &= mss::readLE(i_data, l_idx, o_data.spi_flash_size);
l_rc &= mss::readLE(i_data, l_idx, o_data.error_buffer_offset);
l_rc &= mss::readLE(i_data, l_idx, o_data.error_buffer_size);
}
else
{
TS_FAIL("fw_adapter_properties_struct_from_little_endian(): "
"not enough data present (%d, expected %d)",
i_data.size(), sizeof(o_data) );
}
return l_rc;
}
/**
* @brief Send and check get_properties Explorer inband command
* @return Number of failures
*/
int sendOcmbInbandCmdRsp(bool setScomI2c)
{
errlHndl_t l_errl = nullptr;
uint8_t failures = 0;
// Create a vector of TARGETING::Target pointers
TARGETING::TargetHandleList l_chipList;
// Get a list of all of the functioning ocmb chips
TARGETING::getAllChips(l_chipList, TARGETING::TYPE_OCMB_CHIP, true);
host_fw_command_struct l_cmd;
host_fw_response_struct l_rsp;
std::vector<uint8_t> l_rsp_data;
// Create a non-destructive get_properties command
buildPropertiesGetCmd(l_cmd);
for (auto & l_ocmb: l_chipList)
{
do
{
if (setScomI2c)
{
FAPI_INF("sendOcmbInbandCmdRsp: testing 0x%.8X OCMB using I2C", TARGETING::get_huid(l_ocmb));
// disable inband and use i2c when possible
exptest::disableInbandScomsOcmb(l_ocmb);
}
else
{
FAPI_INF("sendOcmbInbandCmdRsp: testing 0x%.8X OCMB using MMIO", TARGETING::get_huid(l_ocmb));
// just incase some other test disabled inband scoms
exptest::enableInbandScomsOcmb(l_ocmb);
}
fapi2::Target<fapi2::TARGET_TYPE_OCMB_CHIP>l_fapi2_target( l_ocmb );
TRACFBIN(g_trac_expscom, "l_cmd: ", &l_cmd, sizeof(host_fw_command_struct));
// send the command
FAPI_INVOKE_HWP(l_errl, mss::exp::ib::putCMD, l_fapi2_target,
l_cmd);
if (l_errl)
{
TS_FAIL("Error from putCMD for 0x%.8X target",
TARGETING::get_huid(l_ocmb));
failures++;
break;
}
FAPI_INF("sendOcmbInbandCmdRsp: reading response");
// grab the response
FAPI_INVOKE_HWP(l_errl, mss::exp::ib::getRSP, l_fapi2_target,
l_rsp, l_rsp_data);
if (l_errl)
{
TS_FAIL("Error from getRSP for 0x%.8X target, plid=0x%X rc=0x%X",
TARGETING::get_huid(l_ocmb),
ERRL_GETPLID_SAFE(l_errl), ERRL_GETRC_SAFE(l_errl));
failures++;
break;
}
TRACFBIN(g_trac_expscom, "l_rsp: ", &l_rsp, sizeof(host_fw_response_struct));
TRACFBIN(g_trac_expscom, "l_rsp_data: ", l_rsp_data.data(), l_rsp_data.size());
// Check for a valid data response length
if (l_rsp.response_length != sizeof(FW_ADAPTER_PROPERTIES_type))
{
TS_FAIL("Unexpected response length 0x%.8X (expected 0x%.8X)",
l_rsp.response_length, sizeof(FW_ADAPTER_PROPERTIES_type));
failures++;
break;
}
// Now convert the little endian response data into big endian
FW_ADAPTER_PROPERTIES_type l_fw_adapter_data;
fw_adapter_properties_struct_from_little_endian(l_fw_adapter_data,
l_rsp_data);
// Check for some expected response values
// Simics should return 0x88 as the first byte of chip_version
if (l_fw_adapter_data.chip_version[0] != 0x88 )
{
TS_FAIL("Expected chip_version to start with 0x88, found 0x%02X",
l_fw_adapter_data.chip_version[0]);
failures++;
}
} while (0);
if (l_errl)
{
// Commit the error as this is NOT expected and
// needs to be investigated
errlCommit( l_errl, TARG_COMP_ID );
}
if (setScomI2c)
{
// Default the ocmb back to inband communication
exptest::enableInbandScomsOcmb(l_ocmb);
}
}
FAPI_INF("sendOcmbInbandCmdRsp: exiting");
return failures;
};
/**
* @brief Test the Explorer inband command/response path over MMIO
*/
void testOcmbInbandCmdRspOverMMIO( void )
{
if (!iv_serializeTestMutex)
{
TS_FAIL("iv_serializedTestMutex is not setup, unable to continue");
}
else
{
// Inband operations can't be run at the same time
// atomic section >>
mutex_lock(iv_serializeTestMutex);
int failures = sendOcmbInbandCmdRsp(false);
if (failures)
{
TS_FAIL("testOcmbInbandCmdRspOverMMIO() failed: %d", failures);
}
mutex_unlock(iv_serializeTestMutex);
}
}
/**
* @brief Test the Explorer inband command/response path over I2C
* using ATTR_FORCE_SRAM_MMIO_OVER_I2C
*/
void testOcmbInbandCmdRspOverI2c_via_force( void )
{
FAPI_INF("testOcmbInbandCmdRspOverI2c_via_force: entering");
if (!iv_serializeTestMutex)
{
TS_FAIL("iv_serializedTestMutex is not setup, unable to continue");
}
else
{
// Inband operations can't be run at the same time
// atomic section >>
mutex_lock(iv_serializeTestMutex);
// Set FORCE_SRAM_MMIO_OVER_I2C to change to use I2C instead of MMIO
TARGETING::Target * l_sys = nullptr;
TARGETING::targetService().getTopLevelTarget(l_sys);
crit_assert(l_sys != nullptr);
l_sys->setAttr<TARGETING::ATTR_FORCE_SRAM_MMIO_OVER_I2C>(0x01);
int failures = sendOcmbInbandCmdRsp(false);
if (failures)
{
TS_FAIL("testOcmbInbandCmdRspOverI2c_via_force() failed: %d", failures);
}
// Restore using MMIO instead of I2C
l_sys->setAttr<TARGETING::ATTR_FORCE_SRAM_MMIO_OVER_I2C>(0x00);
mutex_unlock(iv_serializeTestMutex);
}
FAPI_INF("testOcmbInbandCmdRspOverI2c_via_force: exiting");
}
/**
* @brief Test the Explorer inband command/response path over I2C
* using scom setting to i2c
*/
void testOcmbInbandCmdRspOverI2c_via_scom_switch( void )
{
FAPI_INF("testOcmbInbandCmdRspOverI2c_via_scom_switch: entering");
if (!iv_serializeTestMutex)
{
TS_FAIL("iv_serializedTestMutex is not setup, unable to continue");
}
else
{
// Inband operations can't be run at the same time
// atomic section >>
mutex_lock(iv_serializeTestMutex);
// Set SCOM_SWITCHES to use i2c instead of MMMIO when
// running the inband cmd/rsp operations
int failures = sendOcmbInbandCmdRsp(true);
if (failures)
{
TS_FAIL("testOcmbInbandCmdRspOverI2c_via_scom_switch() failed: %d", failures);
}
mutex_unlock(iv_serializeTestMutex);
}
FAPI_INF("testOcmbInbandCmdRspOverI2c_via_scom_switch: exiting");
}
/**
* @brief Constructor
*/
OCMBCommTest() : CxxTest::TestSuite()
{
// All modules are loaded by runtime,
// so testcase loading of modules is not required
#ifndef __HOSTBOOT_RUNTIME
errlHndl_t err = nullptr;
err = exptest::loadModule(exptest::MSS_LIBRARY_NAME);
if(err)
{
TS_FAIL("OCMBCommTest() - Constuctor: failed to load MSS module");
errlCommit( err, TARG_COMP_ID );
}
#endif
iv_serializeTestMutex = exptest::getTestMutex();
};
/**
* @brief Destructor
*/
~OCMBCommTest()
{
};
private:
// This is used for tests that need to not run operations at the same time
TARGETING::HB_MUTEX_SERIALIZE_TEST_LOCK_ATTR iv_serializeTestMutex;
};
#endif
<commit_msg>Temporarily disable OCMB comm tests<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/usr/expaccess/test/ocmbcommtest.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2018,2020 */
/* [+] 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 __OCMBCOMMTEST_H
#define __OCMBCOMMTEST_H
/**
* @file ocmbcommtest.H
*
* @brief Test cases for OCMB communication protocol
*/
#include <cxxtest/TestSuite.H>
#include <errl/errlmanager.H>
#include <errl/errlentry.H>
#include <fapi2.H>
#include <plat_hwp_invoker.H>
#include <exp_inband.H>
#include <exp_data_structs.H>
#include <generic/memory/lib/utils/endian_utils.H>
#include "exptest_utils.H"
// EXP_FW_ADAPTER_PROPERTIES_GET data response format
#define FW_ADAPTER_MAX_FW_IMAGE 4
#define FW_ADAPTER_CHIP_VERSION_SIZE 128
#define FW_ADAPTER_SPI_FLASH_ID_SIZE 32
typedef struct
{
uint32_t fw_number_of_images; // number of FW images
uint32_t boot_partion_id; // ID of current boot partion
struct fw_version_string
{
uint32_t major; // FW version - Major release
uint32_t minor; // FW version - Minor release
uint32_t build_num; // FW build number
uint32_t build_patch; // FW build path number
uint32_t sector_size; // FW sector size
} fw_ver_str[FW_ADAPTER_MAX_FW_IMAGE];
uint32_t ram_size_in_bytes; // RAM size in bytes
unsigned char chip_version[FW_ADAPTER_CHIP_VERSION_SIZE]; // Explorer chip revision
unsigned char spi_flash_id[FW_ADAPTER_SPI_FLASH_ID_SIZE]; // SPI flash ID
uint32_t spi_flash_size; // SPI flash size in bytes
uint32_t error_buffer_offset; // FW error buffer offset in SPI flash
uint32_t error_buffer_size; // FW error buffer size in bytes
} FW_ADAPTER_PROPERTIES_type;
class OCMBCommTest: public CxxTest::TestSuite
{
public:
/**
* @brief Fills in command structure for the EXP_FW_ADAPTER_PROPERTIES_GET cmd
* @param io_cmd -- command that gets filled in
*/
void buildPropertiesGetCmd(host_fw_command_struct & io_cmd)
{
io_cmd.cmd_id = 0x07; // EXP_FW_ADAPTER_PROPERTIES_GET
io_cmd.cmd_flags = 0x00; // no additional data
io_cmd.request_identifier = 0x0203; // host generated id number
io_cmd.cmd_length = 0x00000000; // length of addditional data
io_cmd.cmd_crc = 0xFFFFFFFF; // CRC-32 of no additional data
io_cmd.host_work_area = 0x00000000;
io_cmd.cmd_work_area = 0x00000000;
memset(io_cmd.padding, 0, sizeof(io_cmd.padding));
memset(io_cmd.command_argument, 0, sizeof(io_cmd.command_argument));
}
/**
* @brief Convert structure from little endian format into big endian
* @param o_data -- big endian output
* @param i_data -- vector of little endian data
* @return true if successful, else false
*/
bool fw_adapter_properties_struct_from_little_endian(
FW_ADAPTER_PROPERTIES_type & o_data,
std::vector<uint8_t>& i_data)
{
bool l_rc = false;
// make sure we don't go outside i_data range
if (i_data.size() >= sizeof(o_data))
{
uint32_t l_idx = 0;
l_rc = mss::readLE(i_data, l_idx, o_data.fw_number_of_images);
l_rc &= mss::readLE(i_data, l_idx, o_data.boot_partion_id);
for (int i = 0; i < FW_ADAPTER_MAX_FW_IMAGE; ++i)
{
l_rc &= mss::readLE(i_data, l_idx, o_data.fw_ver_str[i].major);
l_rc &= mss::readLE(i_data, l_idx, o_data.fw_ver_str[i].minor);
l_rc &= mss::readLE(i_data, l_idx, o_data.fw_ver_str[i].build_num);
l_rc &= mss::readLE(i_data, l_idx, o_data.fw_ver_str[i].build_patch);
l_rc &= mss::readLE(i_data, l_idx, o_data.fw_ver_str[i].sector_size);
}
l_rc &= mss::readLE(i_data, l_idx, o_data.ram_size_in_bytes);
l_rc &= mss::readLEArray(i_data, FW_ADAPTER_CHIP_VERSION_SIZE, l_idx, o_data.chip_version);
l_rc &= mss::readLEArray(i_data, FW_ADAPTER_SPI_FLASH_ID_SIZE, l_idx, o_data.spi_flash_id);
l_rc &= mss::readLE(i_data, l_idx, o_data.spi_flash_size);
l_rc &= mss::readLE(i_data, l_idx, o_data.error_buffer_offset);
l_rc &= mss::readLE(i_data, l_idx, o_data.error_buffer_size);
}
else
{
TS_FAIL("fw_adapter_properties_struct_from_little_endian(): "
"not enough data present (%d, expected %d)",
i_data.size(), sizeof(o_data) );
}
return l_rc;
}
/**
* @brief Send and check get_properties Explorer inband command
* @return Number of failures
*/
int sendOcmbInbandCmdRsp(bool setScomI2c)
{
errlHndl_t l_errl = nullptr;
uint8_t failures = 0;
// Create a vector of TARGETING::Target pointers
TARGETING::TargetHandleList l_chipList;
// Get a list of all of the functioning ocmb chips
TARGETING::getAllChips(l_chipList, TARGETING::TYPE_OCMB_CHIP, true);
host_fw_command_struct l_cmd;
host_fw_response_struct l_rsp;
std::vector<uint8_t> l_rsp_data;
// Create a non-destructive get_properties command
buildPropertiesGetCmd(l_cmd);
for (auto & l_ocmb: l_chipList)
{
do
{
if (setScomI2c)
{
FAPI_INF("sendOcmbInbandCmdRsp: testing 0x%.8X OCMB using I2C", TARGETING::get_huid(l_ocmb));
// disable inband and use i2c when possible
exptest::disableInbandScomsOcmb(l_ocmb);
}
else
{
FAPI_INF("sendOcmbInbandCmdRsp: testing 0x%.8X OCMB using MMIO", TARGETING::get_huid(l_ocmb));
// just incase some other test disabled inband scoms
exptest::enableInbandScomsOcmb(l_ocmb);
}
fapi2::Target<fapi2::TARGET_TYPE_OCMB_CHIP>l_fapi2_target( l_ocmb );
TRACFBIN(g_trac_expscom, "l_cmd: ", &l_cmd, sizeof(host_fw_command_struct));
// send the command
FAPI_INVOKE_HWP(l_errl, mss::exp::ib::putCMD, l_fapi2_target,
l_cmd);
if (l_errl)
{
TS_FAIL("Error from putCMD for 0x%.8X target",
TARGETING::get_huid(l_ocmb));
failures++;
break;
}
FAPI_INF("sendOcmbInbandCmdRsp: reading response");
// grab the response
FAPI_INVOKE_HWP(l_errl, mss::exp::ib::getRSP, l_fapi2_target,
l_rsp, l_rsp_data);
if (l_errl)
{
TS_FAIL("Error from getRSP for 0x%.8X target, plid=0x%X rc=0x%X",
TARGETING::get_huid(l_ocmb),
ERRL_GETPLID_SAFE(l_errl), ERRL_GETRC_SAFE(l_errl));
failures++;
break;
}
TRACFBIN(g_trac_expscom, "l_rsp: ", &l_rsp, sizeof(host_fw_response_struct));
TRACFBIN(g_trac_expscom, "l_rsp_data: ", l_rsp_data.data(), l_rsp_data.size());
// Check for a valid data response length
if (l_rsp.response_length != sizeof(FW_ADAPTER_PROPERTIES_type))
{
TS_FAIL("Unexpected response length 0x%.8X (expected 0x%.8X)",
l_rsp.response_length, sizeof(FW_ADAPTER_PROPERTIES_type));
failures++;
break;
}
// Now convert the little endian response data into big endian
FW_ADAPTER_PROPERTIES_type l_fw_adapter_data;
fw_adapter_properties_struct_from_little_endian(l_fw_adapter_data,
l_rsp_data);
// Check for some expected response values
// Simics should return 0x88 as the first byte of chip_version
if (l_fw_adapter_data.chip_version[0] != 0x88 )
{
TS_FAIL("Expected chip_version to start with 0x88, found 0x%02X",
l_fw_adapter_data.chip_version[0]);
failures++;
}
} while (0);
if (l_errl)
{
// Commit the error as this is NOT expected and
// needs to be investigated
errlCommit( l_errl, TARG_COMP_ID );
}
if (setScomI2c)
{
// Default the ocmb back to inband communication
exptest::enableInbandScomsOcmb(l_ocmb);
}
}
FAPI_INF("sendOcmbInbandCmdRsp: exiting");
return failures;
};
/**
* @brief Test the Explorer inband command/response path over MMIO
*/
void testOcmbInbandCmdRspOverMMIO( void )
{
#if 0 //@fixme-RTC:255444-Reenable (and fix expectations) when we get a new Simics level
if (!iv_serializeTestMutex)
{
TS_FAIL("iv_serializedTestMutex is not setup, unable to continue");
}
else
{
// Inband operations can't be run at the same time
// atomic section >>
mutex_lock(iv_serializeTestMutex);
int failures = sendOcmbInbandCmdRsp(false);
if (failures)
{
TS_FAIL("testOcmbInbandCmdRspOverMMIO() failed: %d", failures);
}
mutex_unlock(iv_serializeTestMutex);
}
#else
TS_INFO("Skipping testOcmbInbandCmdRspOverMMIO - RTC:255444");
#endif
}
/**
* @brief Test the Explorer inband command/response path over I2C
* using ATTR_FORCE_SRAM_MMIO_OVER_I2C
*/
void testOcmbInbandCmdRspOverI2c_via_force( void )
{
#if 0 //@fixme-RTC:255444-Reenable (and fix expectations) when we get a new Simics level
FAPI_INF("testOcmbInbandCmdRspOverI2c_via_force: entering");
if (!iv_serializeTestMutex)
{
TS_FAIL("iv_serializedTestMutex is not setup, unable to continue");
}
else
{
// Inband operations can't be run at the same time
// atomic section >>
mutex_lock(iv_serializeTestMutex);
// Set FORCE_SRAM_MMIO_OVER_I2C to change to use I2C instead of MMIO
TARGETING::Target * l_sys = nullptr;
TARGETING::targetService().getTopLevelTarget(l_sys);
crit_assert(l_sys != nullptr);
l_sys->setAttr<TARGETING::ATTR_FORCE_SRAM_MMIO_OVER_I2C>(0x01);
int failures = sendOcmbInbandCmdRsp(false);
if (failures)
{
TS_FAIL("testOcmbInbandCmdRspOverI2c_via_force() failed: %d", failures);
}
// Restore using MMIO instead of I2C
l_sys->setAttr<TARGETING::ATTR_FORCE_SRAM_MMIO_OVER_I2C>(0x00);
mutex_unlock(iv_serializeTestMutex);
}
FAPI_INF("testOcmbInbandCmdRspOverI2c_via_force: exiting");
#else
TS_INFO("Skipping testOcmbInbandCmdRspOverMMIO - RTC:255444");
#endif
}
/**
* @brief Test the Explorer inband command/response path over I2C
* using scom setting to i2c
*/
void testOcmbInbandCmdRspOverI2c_via_scom_switch( void )
{
#if 0 //@fixme-RTC:255444-Reenable (and fix expectations) when we get a new Simics level
FAPI_INF("testOcmbInbandCmdRspOverI2c_via_scom_switch: entering");
if (!iv_serializeTestMutex)
{
TS_FAIL("iv_serializedTestMutex is not setup, unable to continue");
}
else
{
// Inband operations can't be run at the same time
// atomic section >>
mutex_lock(iv_serializeTestMutex);
// Set SCOM_SWITCHES to use i2c instead of MMMIO when
// running the inband cmd/rsp operations
int failures = sendOcmbInbandCmdRsp(true);
if (failures)
{
TS_FAIL("testOcmbInbandCmdRspOverI2c_via_scom_switch() failed: %d", failures);
}
mutex_unlock(iv_serializeTestMutex);
}
FAPI_INF("testOcmbInbandCmdRspOverI2c_via_scom_switch: exiting");
#else
TS_INFO("Skipping testOcmbInbandCmdRspOverMMIO - RTC:255444");
#endif
}
/**
* @brief Constructor
*/
OCMBCommTest() : CxxTest::TestSuite()
{
// All modules are loaded by runtime,
// so testcase loading of modules is not required
#ifndef __HOSTBOOT_RUNTIME
errlHndl_t err = nullptr;
err = exptest::loadModule(exptest::MSS_LIBRARY_NAME);
if(err)
{
TS_FAIL("OCMBCommTest() - Constuctor: failed to load MSS module");
errlCommit( err, TARG_COMP_ID );
}
#endif
iv_serializeTestMutex = exptest::getTestMutex();
};
/**
* @brief Destructor
*/
~OCMBCommTest()
{
};
private:
// This is used for tests that need to not run operations at the same time
TARGETING::HB_MUTEX_SERIALIZE_TEST_LOCK_ATTR iv_serializeTestMutex;
};
#endif
<|endoftext|> |
<commit_before>// Copyright ***********************************************************
//
// File ecmdMiscUser.C
//
// IBM Confidential
// OCO Source Materials
// 9400 Licensed Internal Code
// (C) COPYRIGHT IBM CORP. 1996
//
// The source code for this program is not published or otherwise
// divested of its trade secrets, irrespective of what has been
// deposited with the U.S. Copyright Office.
//
// End Copyright *******************************************************
/* $Header$ */
// Module Description **************************************************
//
// Description:
//
// End Module Description **********************************************
//----------------------------------------------------------------------
// Includes
//----------------------------------------------------------------------
#define ecmdMiscUser_C
#include <ecmdCommandUtils.H>
#include <ecmdReturnCodes.H>
#include <ecmdClientCapi.H>
#include <ecmdUtils.H>
#include <ecmdDataBuffer.H>
#include <ecmdSharedUtils.H>
#undef ecmdMiscUser_C
//----------------------------------------------------------------------
// User Types
//----------------------------------------------------------------------
//----------------------------------------------------------------------
// Constants
//----------------------------------------------------------------------
//----------------------------------------------------------------------
// Macros
//----------------------------------------------------------------------
//----------------------------------------------------------------------
// Internal Function Prototypes
//----------------------------------------------------------------------
//----------------------------------------------------------------------
// Global Variables
//----------------------------------------------------------------------
//---------------------------------------------------------------------
// Member Function Specifications
//---------------------------------------------------------------------
uint32_t ecmdGetConfigUser(int argc, char * argv[]) {
uint32_t rc = ECMD_SUCCESS;
ecmdChipTarget target; ///< Current target
std::string configName; ///< Name of config variable to fetch
bool validPosFound = false; ///< Did we find something to actually execute on ?
ecmdConfigValid_t validOutput; ///< Indicator if valueAlpha, valueNumeric (or both) are valid
std::string valueAlpha; ///< Alpha value of setting (if appropriate)
uint32_t valueNumeric; ///< Numeric value of setting (if appropriate)
ecmdDataBuffer numData; ///< Initialise data buffer with the numeric value
std::string printed; ///< Print Buffer
ecmdLooperData looperdata; ///< Store internal Looper data
/* get format flag, if it's there */
std::string format;
char * formatPtr = ecmdParseOptionWithArgs(&argc, &argv, "-o");
if (formatPtr == NULL) {
format = "x";
}
else {
format = formatPtr;
}
/************************************************************************/
/* Parse Common Cmdline Args */
/************************************************************************/
rc = ecmdCommandArgs(&argc, &argv);
if (rc) return rc;
/************************************************************************/
/* Parse Local ARGS here! */
/************************************************************************/
if (argc < 1) {
ecmdOutputError("getconfig - Too few arguments specified; you need at least a ConfigName.\n");
ecmdOutputError("getconfig - Type 'getconfig -h' for usage.\n");
return ECMD_INVALID_ARGS;
}
//Setup the target that will be used to query the system config
if( argc == 2) {
target.chipType = argv[0];
target.chipTypeState = ECMD_TARGET_QUERY_FIELD_VALID;
configName = argv[1];
}
else {
target.chipTypeState = ECMD_TARGET_QUERY_IGNORE;
configName = argv[0];
}
target.cageState = target.nodeState = target.slotState = target.posState = target.coreState = ECMD_TARGET_QUERY_WILDCARD;
target.threadState = ECMD_TARGET_FIELD_UNUSED;
rc = ecmdConfigLooperInit(target, ECMD_SELECTED_TARGETS_LOOP, looperdata);
if (rc) return rc;
while ( ecmdConfigLooperNext(target, looperdata) ) {
/* Actually go fetch the data */
rc = ecmdGetConfiguration(target, configName, validOutput, valueAlpha, valueNumeric);
if (rc == ECMD_TARGET_NOT_CONFIGURED) {
continue;
}
else if (rc) {
printed = "getconfig - Error occured performing ecmdGetConfiguration on ";
printed += ecmdWriteTarget(target) + "\n";
ecmdOutputError( printed.c_str() );
return rc;
}
else {
validPosFound = true;
}
printed = ecmdWriteTarget(target) + "\n";
if( validOutput == ECMD_CONFIG_VALID_FIELD_ALPHA) {
printed += configName + " = " + valueAlpha + "\n";
ecmdOutput(printed.c_str());
}
else if(( validOutput == ECMD_CONFIG_VALID_FIELD_NUMERIC) || (validOutput == ECMD_CONFIG_VALID_FIELD_BOTH)) {
numData.setWord(0, valueNumeric);
printed += configName + " = ";
printed += ecmdWriteDataFormatted(numData, format);
printed += "\n";
ecmdOutput(printed.c_str());
}
}
if (!validPosFound) {
//this is an error common across all UI functions
ecmdOutputError("getconfig - Unable to find a valid chip to execute command on\n");
return ECMD_TARGET_NOT_CONFIGURED;
}
return rc;
}
uint32_t ecmdSetConfigUser(int argc, char * argv[]) {
uint32_t rc = ECMD_SUCCESS;
ecmdChipTarget target; ///< Current target
std::string configName; ///< Name of config variable to fetch
bool validPosFound = false; ///< Did we find something to actually execute on ?
ecmdConfigValid_t validInput; ///< Indicator if valueAlpha, valueNumeric (or both) are valid
std::string valueAlpha; ///< Input of type Ascii
uint32_t valueNumeric; ///< Input of type Numeric
ecmdDataBuffer inputBuffer; ///< Initialise data buffer with the numeric value(if input is Numeric)
char inputVal[400]; ///< Value to set configuration variable to
std::string printed; ///< Print Buffer
ecmdLooperData looperdata; ///< Store internal Looper data
/* get format flag, if it's there */
std::string format;
char * formatPtr = ecmdParseOptionWithArgs(&argc, &argv, "-i");
if (formatPtr == NULL) {
format = "a";
}
else {
format = formatPtr;
}
/************************************************************************/
/* Parse Common Cmdline Args */
/************************************************************************/
rc = ecmdCommandArgs(&argc, &argv);
if (rc) return rc;
/************************************************************************/
/* Parse Local ARGS here! */
/************************************************************************/
if (argc < 2) {
ecmdOutputError("setconfig - Too few arguments specified; you need at least a ConfigName, Value to set it to.\n");
ecmdOutputError("setconfig - Type 'setconfig -h' for usage.\n");
return ECMD_INVALID_ARGS;
}
//Setup the target that will be used to query the system config
if( argc == 3) {
target.chipType = argv[0];
target.chipTypeState = ECMD_TARGET_QUERY_FIELD_VALID;
configName = argv[1];
strcpy(inputVal, argv[2]);
}
else {
target.chipTypeState = ECMD_TARGET_QUERY_IGNORE;
configName = argv[0];
strcpy(inputVal, argv[1]);
}
if(format == "a") {
valueAlpha = inputVal;
validInput = ECMD_CONFIG_VALID_FIELD_ALPHA;
} else {
rc = ecmdReadDataFormatted(inputBuffer, inputVal, format);
if (rc) {
ecmdOutputError("setconfig - Problems occurred parsing input data, must be an invalid format\n");
return rc;
}
int numBits = inputBuffer.getBitLength();
if(numBits > 32 ) {
ecmdOutputError("setconfig - Problems occurred parsing input data, Bitlength should be <= 32 bits\n");
return ECMD_INVALID_ARGS;
}
inputBuffer.shiftRightAndResize(32-numBits);
valueNumeric = inputBuffer.getWord(0);
validInput = ECMD_CONFIG_VALID_FIELD_NUMERIC;
}
target.cageState = target.nodeState = target.slotState = target.posState = target.coreState = ECMD_TARGET_QUERY_WILDCARD;
target.threadState = ECMD_TARGET_FIELD_UNUSED;
rc = ecmdConfigLooperInit(target, ECMD_SELECTED_TARGETS_LOOP, looperdata);
if (rc) return rc;
while ( ecmdConfigLooperNext(target, looperdata) ) {
/* Actually go fetch the data */
rc = ecmdSetConfiguration(target, configName, validInput, valueAlpha, valueNumeric);
if (rc == ECMD_TARGET_NOT_CONFIGURED) {
continue;
}
else if (rc) {
printed = "setconfig - Error occured performing ecmdSetConfiguration on ";
printed += ecmdWriteTarget(target) + "\n";
ecmdOutputError( printed.c_str() );
return rc;
}
else {
validPosFound = true;
}
printed = ecmdWriteTarget(target) + "\n";
ecmdOutput( printed.c_str() );
}
if (!validPosFound) {
//this is an error common across all UI functions
ecmdOutputError("setconfig - Unable to find a valid chip to execute command on\n");
return ECMD_TARGET_NOT_CONFIGURED;
}
return rc;
}
// Change Log *********************************************************
//
// Flag Reason Vers Date Coder Description
// ---- -------- ---- -------- -------- ------------------------------
// CENGEL Initial Creation
//
// End Change Log *****************************************************
<commit_msg>*** empty log message ***<commit_after>// Copyright ***********************************************************
//
// File ecmdMiscUser.C
//
// IBM Confidential
// OCO Source Materials
// 9400 Licensed Internal Code
// (C) COPYRIGHT IBM CORP. 1996
//
// The source code for this program is not published or otherwise
// divested of its trade secrets, irrespective of what has been
// deposited with the U.S. Copyright Office.
//
// End Copyright *******************************************************
/* $Header$ */
// Module Description **************************************************
//
// Description:
//
// End Module Description **********************************************
//----------------------------------------------------------------------
// Includes
//----------------------------------------------------------------------
#define ecmdMiscUser_C
#include <ecmdCommandUtils.H>
#include <ecmdReturnCodes.H>
#include <ecmdClientCapi.H>
#include <ecmdUtils.H>
#include <ecmdDataBuffer.H>
#include <ecmdSharedUtils.H>
#undef ecmdMiscUser_C
//----------------------------------------------------------------------
// User Types
//----------------------------------------------------------------------
//----------------------------------------------------------------------
// Constants
//----------------------------------------------------------------------
//----------------------------------------------------------------------
// Macros
//----------------------------------------------------------------------
//----------------------------------------------------------------------
// Internal Function Prototypes
//----------------------------------------------------------------------
//----------------------------------------------------------------------
// Global Variables
//----------------------------------------------------------------------
//---------------------------------------------------------------------
// Member Function Specifications
//---------------------------------------------------------------------
uint32_t ecmdGetConfigUser(int argc, char * argv[]) {
uint32_t rc = ECMD_SUCCESS;
ecmdChipTarget target; ///< Current target
std::string configName; ///< Name of config variable to fetch
bool validPosFound = false; ///< Did we find something to actually execute on ?
bool formatSpecfied = false; ///< Was the -o option specified
ecmdConfigValid_t validOutput; ///< Indicator if valueAlpha, valueNumeric (or both) are valid
std::string valueAlpha; ///< Alpha value of setting (if appropriate)
uint32_t valueNumeric; ///< Numeric value of setting (if appropriate)
ecmdDataBuffer numData; ///< Initialise data buffer with the numeric value
std::string printed; ///< Print Buffer
ecmdLooperData looperdata; ///< Store internal Looper data
/* get format flag, if it's there */
std::string format;
char * formatPtr = ecmdParseOptionWithArgs(&argc, &argv, "-o");
if (formatPtr == NULL) {
format = "x";
}
else {
format = formatPtr;
formatSpecfied = true;
}
/************************************************************************/
/* Parse Common Cmdline Args */
/************************************************************************/
rc = ecmdCommandArgs(&argc, &argv);
if (rc) return rc;
/************************************************************************/
/* Parse Local ARGS here! */
/************************************************************************/
if (argc < 1) {
ecmdOutputError("getconfig - Too few arguments specified; you need at least a ConfigName.\n");
ecmdOutputError("getconfig - Type 'getconfig -h' for usage.\n");
return ECMD_INVALID_ARGS;
}
//Setup the target that will be used to query the system config
if( argc == 2) {
target.chipType = argv[0];
target.chipTypeState = ECMD_TARGET_QUERY_FIELD_VALID;
configName = argv[1];
}
else {
target.chipTypeState = ECMD_TARGET_QUERY_IGNORE;
configName = argv[0];
}
target.cageState = target.nodeState = target.slotState = target.posState = target.coreState = ECMD_TARGET_QUERY_WILDCARD;
target.threadState = ECMD_TARGET_FIELD_UNUSED;
rc = ecmdConfigLooperInit(target, ECMD_SELECTED_TARGETS_LOOP, looperdata);
if (rc) return rc;
while ( ecmdConfigLooperNext(target, looperdata) ) {
/* Actually go fetch the data */
rc = ecmdGetConfiguration(target, configName, validOutput, valueAlpha, valueNumeric);
if (rc == ECMD_TARGET_NOT_CONFIGURED) {
continue;
}
else if (rc) {
printed = "getconfig - Error occured performing ecmdGetConfiguration on ";
printed += ecmdWriteTarget(target) + "\n";
ecmdOutputError( printed.c_str() );
return rc;
}
else {
validPosFound = true;
}
printed = ecmdWriteTarget(target) + "\n";
if( (validOutput == ECMD_CONFIG_VALID_FIELD_ALPHA) || ((validOutput == ECMD_CONFIG_VALID_FIELD_BOTH) &&
(!formatSpecfied))) {
printed += configName + " = " + valueAlpha + "\n";
ecmdOutput(printed.c_str());
}
else if(( validOutput == ECMD_CONFIG_VALID_FIELD_NUMERIC) || ((validOutput == ECMD_CONFIG_VALID_FIELD_BOTH) && (formatSpecfied))) {
numData.setWord(0, valueNumeric);
printed += configName + " = ";
printed += ecmdWriteDataFormatted(numData, format);
printed += "\n";
ecmdOutput(printed.c_str());
}
}
if (!validPosFound) {
//this is an error common across all UI functions
ecmdOutputError("getconfig - Unable to find a valid chip to execute command on\n");
return ECMD_TARGET_NOT_CONFIGURED;
}
return rc;
}
uint32_t ecmdSetConfigUser(int argc, char * argv[]) {
uint32_t rc = ECMD_SUCCESS;
ecmdChipTarget target; ///< Current target
std::string configName; ///< Name of config variable to fetch
bool validPosFound = false; ///< Did we find something to actually execute on ?
ecmdConfigValid_t validInput; ///< Indicator if valueAlpha, valueNumeric (or both) are valid
std::string valueAlpha; ///< Input of type Ascii
uint32_t valueNumeric; ///< Input of type Numeric
ecmdDataBuffer inputBuffer; ///< Initialise data buffer with the numeric value(if input is Numeric)
char inputVal[400]; ///< Value to set configuration variable to
std::string printed; ///< Print Buffer
ecmdLooperData looperdata; ///< Store internal Looper data
/* get format flag, if it's there */
std::string format;
char * formatPtr = ecmdParseOptionWithArgs(&argc, &argv, "-i");
if (formatPtr == NULL) {
format = "a";
}
else {
format = formatPtr;
}
/************************************************************************/
/* Parse Common Cmdline Args */
/************************************************************************/
rc = ecmdCommandArgs(&argc, &argv);
if (rc) return rc;
/************************************************************************/
/* Parse Local ARGS here! */
/************************************************************************/
if (argc < 2) {
ecmdOutputError("setconfig - Too few arguments specified; you need at least a ConfigName, Value to set it to.\n");
ecmdOutputError("setconfig - Type 'setconfig -h' for usage.\n");
return ECMD_INVALID_ARGS;
}
//Setup the target that will be used to query the system config
if( argc == 3) {
target.chipType = argv[0];
target.chipTypeState = ECMD_TARGET_QUERY_FIELD_VALID;
configName = argv[1];
strcpy(inputVal, argv[2]);
}
else {
target.chipTypeState = ECMD_TARGET_QUERY_IGNORE;
configName = argv[0];
strcpy(inputVal, argv[1]);
}
if(format == "a") {
valueAlpha = inputVal;
validInput = ECMD_CONFIG_VALID_FIELD_ALPHA;
} else {
rc = ecmdReadDataFormatted(inputBuffer, inputVal, format);
if (rc) {
ecmdOutputError("setconfig - Problems occurred parsing input data, must be an invalid format\n");
return rc;
}
int numBits = inputBuffer.getBitLength();
if(numBits > 32 ) {
ecmdOutputError("setconfig - Problems occurred parsing input data, Bitlength should be <= 32 bits\n");
return ECMD_INVALID_ARGS;
}
inputBuffer.shiftRightAndResize(32-numBits);
valueNumeric = inputBuffer.getWord(0);
validInput = ECMD_CONFIG_VALID_FIELD_NUMERIC;
}
target.cageState = target.nodeState = target.slotState = target.posState = target.coreState = ECMD_TARGET_QUERY_WILDCARD;
target.threadState = ECMD_TARGET_FIELD_UNUSED;
rc = ecmdConfigLooperInit(target, ECMD_SELECTED_TARGETS_LOOP, looperdata);
if (rc) return rc;
while ( ecmdConfigLooperNext(target, looperdata) ) {
/* Actually go fetch the data */
rc = ecmdSetConfiguration(target, configName, validInput, valueAlpha, valueNumeric);
if (rc == ECMD_TARGET_NOT_CONFIGURED) {
continue;
}
else if (rc) {
printed = "setconfig - Error occured performing ecmdSetConfiguration on ";
printed += ecmdWriteTarget(target) + "\n";
ecmdOutputError( printed.c_str() );
return rc;
}
else {
validPosFound = true;
}
printed = ecmdWriteTarget(target) + "\n";
ecmdOutput( printed.c_str() );
}
if (!validPosFound) {
//this is an error common across all UI functions
ecmdOutputError("setconfig - Unable to find a valid chip to execute command on\n");
return ECMD_TARGET_NOT_CONFIGURED;
}
return rc;
}
// Change Log *********************************************************
//
// Flag Reason Vers Date Coder Description
// ---- -------- ---- -------- -------- ------------------------------
// CENGEL Initial Creation
//
// End Change Log *****************************************************
<|endoftext|> |
<commit_before>#include <boost/cast.hpp>
#include "libwatcher/messageStatus.h"
#include "serverMessageHandler.h"
using namespace std;
using namespace watcher;
using namespace watcher::event;
using namespace boost;
INIT_LOGGER(ServerMessageHandler, "MessageHandler.ServerMessageHandler");
ServerMessageHandler::ServerMessageHandler()
{
TRACE_ENTER();
TRACE_EXIT();
}
ServerMessageHandler::~ServerMessageHandler()
{
TRACE_ENTER();
TRACE_EXIT();
}
bool ServerMessageHandler::handleMessageArrive(const MessagePtr &message)
{
TRACE_ENTER();
bool retVal=MessageHandler::handleMessageArrive(message);
// If it's a feeder API message, close connection, otherwise keep open
// to push out a message stream
switch(message->type)
{
// feeder API messages - close connection
case UNKNOWN_MESSAGE_TYPE:
case MESSAGE_STATUS_TYPE:
case TEST_MESSAGE_TYPE:
case GPS_MESSAGE_TYPE:
case LABEL_MESSAGE_TYPE:
case EDGE_MESSAGE_TYPE:
case COLOR_MESSAGE_TYPE:
case DATA_REQUEST_MESSAGE_TYPE:
retVal=false;
break;
// watcherdAPI messages - keep connection open
case SEEK_MESSAGE_TYPE:
case START_MESSAGE_TYPE:
case STOP_MESSAGE_TYPE:
case SPEED_MESSAGE_TYPE:
case NODE_STATUS_MESSAGE_TYPE:
retVal=true;
break;
// No idea.
case USER_DEFINED_MESSAGE_TYPE:
retVal=false;
break;
}
TRACE_EXIT_RET((retVal?"true":"false"));
return retVal;
}
bool ServerMessageHandler::handleMessagesArrive(const vector<MessagePtr> &messages)
{
TRACE_ENTER();
for(vector<MessagePtr>::const_iterator i=messages.begin(); i!=messages.end(); ++i)
{
if(!handleMessageArrive(*i))
{
// This means if any message is a feeder api message, we cut the connection.
// This may or may not be correct.
TRACE_EXIT_RET("false");
return false;
}
}
TRACE_EXIT_RET("true");
return true;
}
bool ServerMessageHandler::handleMessageSent(const MessagePtr &message)
{
TRACE_ENTER();
// Log the message.
MessageHandler::handleMessageArrive(message);
TRACE_EXIT_RET("true");
return true;
}
// virtual
bool ServerMessageHandler::handleMessagesSent(const std::vector<event::MessagePtr> &messages)
{
TRACE_ENTER();
for(vector<MessagePtr>::const_iterator i=messages.begin(); i!=messages.end(); ++i)
handleMessageSent(*i);
// Server currently never wants a response, but does want the connection to remain open.
TRACE_EXIT_RET("true");
return true;
}
<commit_msg>server message handler always keeps the connection open (waits for new messages). Client must close connection.<commit_after>#include <boost/cast.hpp>
#include "libwatcher/messageStatus.h"
#include "serverMessageHandler.h"
using namespace std;
using namespace watcher;
using namespace watcher::event;
using namespace boost;
INIT_LOGGER(ServerMessageHandler, "MessageHandler.ServerMessageHandler");
ServerMessageHandler::ServerMessageHandler()
{
TRACE_ENTER();
TRACE_EXIT();
}
ServerMessageHandler::~ServerMessageHandler()
{
TRACE_ENTER();
TRACE_EXIT();
}
bool ServerMessageHandler::handleMessageArrive(const MessagePtr &message)
{
TRACE_ENTER();
MessageHandler::handleMessageArrive(message);
// Server always keeps the connection open - client closes it when it is through with it.
TRACE_EXIT_RET("true");
return true;
}
bool ServerMessageHandler::handleMessagesArrive(const vector<MessagePtr> &messages)
{
TRACE_ENTER();
for(vector<MessagePtr>::const_iterator i=messages.begin(); i!=messages.end(); ++i)
{
if(!handleMessageArrive(*i))
{
// This means if any message is a feeder api message, we cut the connection.
// This may or may not be correct.
TRACE_EXIT_RET("false");
return false;
}
}
TRACE_EXIT_RET("true");
return true;
}
bool ServerMessageHandler::handleMessageSent(const MessagePtr &message)
{
TRACE_ENTER();
// Log the message.
MessageHandler::handleMessageArrive(message);
TRACE_EXIT_RET("true");
return true;
}
// virtual
bool ServerMessageHandler::handleMessagesSent(const std::vector<event::MessagePtr> &messages)
{
TRACE_ENTER();
for(vector<MessagePtr>::const_iterator i=messages.begin(); i!=messages.end(); ++i)
handleMessageSent(*i);
// Server currently never wants a response, but does want the connection to remain open.
TRACE_EXIT_RET("true");
return true;
}
<|endoftext|> |
<commit_before>#ifndef ENTT_SIGNAL_DISPATCHER_HPP
#define ENTT_SIGNAL_DISPATCHER_HPP
#include <cstddef>
#include <memory>
#include <type_traits>
#include <utility>
#include <vector>
#include "../config/config.h"
#include "../container/dense_map.hpp"
#include "../core/fwd.hpp"
#include "../core/type_info.hpp"
#include "../core/utility.hpp"
#include "sigh.hpp"
namespace entt {
/**
* @brief Basic dispatcher implementation.
*
* A dispatcher can be used either to trigger an immediate event or to enqueue
* events to be published all together once per tick.<br/>
* Listeners are provided in the form of member functions. For each event of
* type `Event`, listeners are such that they can be invoked with an argument of
* type `Event &`, no matter what the return type is.
*
* The dispatcher creates instances of the `sigh` class internally. Refer to the
* documentation of the latter for more details.
*/
class dispatcher {
struct basic_pool {
virtual ~basic_pool() = default;
virtual void publish() = 0;
virtual void disconnect(void *) = 0;
virtual void clear() ENTT_NOEXCEPT = 0;
};
template<typename Event>
struct pool_handler final: basic_pool {
static_assert(std::is_same_v<Event, std::decay_t<Event>>, "Invalid event type");
using signal_type = sigh<void(Event &)>;
using sink_type = typename signal_type::sink_type;
void publish() override {
const auto length = events.size();
for(std::size_t pos{}; pos < length; ++pos) {
signal.publish(events[pos]);
}
events.erase(events.cbegin(), events.cbegin() + length);
}
void disconnect(void *instance) override {
bucket().disconnect(instance);
}
void clear() ENTT_NOEXCEPT override {
events.clear();
}
[[nodiscard]] sink_type bucket() ENTT_NOEXCEPT {
return sink_type{signal};
}
template<typename... Args>
void trigger(Args &&...args) {
Event instance{std::forward<Args>(args)...};
signal.publish(instance);
}
template<typename... Args>
void enqueue(Args &&...args) {
if constexpr(std::is_aggregate_v<Event>) {
events.push_back(Event{std::forward<Args>(args)...});
} else {
events.emplace_back(std::forward<Args>(args)...);
}
}
private:
signal_type signal{};
std::vector<Event> events;
};
template<typename Event>
[[nodiscard]] pool_handler<Event> &assure() {
if(auto &&ptr = pools[type_hash<Event>::value()]; !ptr) {
auto *cpool = new pool_handler<Event>{};
ptr.reset(cpool);
return *cpool;
} else {
return static_cast<pool_handler<Event> &>(*ptr);
}
}
public:
/*! @brief Default constructor. */
dispatcher() = default;
/*! @brief Default move constructor. */
dispatcher(dispatcher &&) = default;
/*! @brief Default move assignment operator. @return This dispatcher. */
dispatcher &operator=(dispatcher &&) = default;
/**
* @brief Returns a sink object for the given event.
*
* A sink is an opaque object used to connect listeners to events.
*
* The function type for a listener is _compatible_ with:
* @code{.cpp}
* void(Event &);
* @endcode
*
* The order of invocation of the listeners isn't guaranteed.
*
* @sa sink
*
* @tparam Event Type of event of which to get the sink.
* @return A temporary sink object.
*/
template<typename Event>
[[nodiscard]] auto sink() {
return assure<Event>().bucket();
}
/**
* @brief Triggers an immediate event of the given type.
*
* All the listeners registered for the given type are immediately notified.
* The event is discarded after the execution.
*
* @tparam Event Type of event to trigger.
* @tparam Args Types of arguments to use to construct the event.
* @param args Arguments to use to construct the event.
*/
template<typename Event, typename... Args>
void trigger(Args &&...args) {
assure<Event>().trigger(std::forward<Args>(args)...);
}
/**
* @brief Triggers an immediate event of the given type.
*
* All the listeners registered for the given type are immediately notified.
* The event is discarded after the execution.
*
* @tparam Event Type of event to trigger.
* @param event An instance of the given type of event.
*/
template<typename Event>
void trigger(Event &&event) {
assure<std::decay_t<Event>>().trigger(std::forward<Event>(event));
}
/**
* @brief Enqueues an event of the given type.
*
* An event of the given type is queued. No listener is invoked. Use the
* `update` member function to notify listeners when ready.
*
* @tparam Event Type of event to enqueue.
* @tparam Args Types of arguments to use to construct the event.
* @param args Arguments to use to construct the event.
*/
template<typename Event, typename... Args>
void enqueue(Args &&...args) {
assure<Event>().enqueue(std::forward<Args>(args)...);
}
/**
* @brief Enqueues an event of the given type.
*
* An event of the given type is queued. No listener is invoked. Use the
* `update` member function to notify listeners when ready.
*
* @tparam Event Type of event to enqueue.
* @param event An instance of the given type of event.
*/
template<typename Event>
void enqueue(Event &&event) {
assure<std::decay_t<Event>>().enqueue(std::forward<Event>(event));
}
/**
* @brief Utility function to disconnect everything related to a given value
* or instance from a dispatcher.
* @tparam Type Type of class or type of payload.
* @param value_or_instance A valid object that fits the purpose.
*/
template<typename Type>
void disconnect(Type &value_or_instance) {
disconnect(&value_or_instance);
}
/**
* @brief Utility function to disconnect everything related to a given value
* or instance from a dispatcher.
* @tparam Type Type of class or type of payload.
* @param value_or_instance A valid object that fits the purpose.
*/
template<typename Type>
void disconnect(Type *value_or_instance) {
for(auto &&cpool: pools) {
cpool.second->disconnect(value_or_instance);
}
}
/**
* @brief Discards all the events queued so far.
*
* If no types are provided, the dispatcher will clear all the existing
* pools.
*
* @tparam Event Type of events to discard.
*/
template<typename... Event>
void clear() {
if constexpr(sizeof...(Event) == 0) {
for(auto &&cpool: pools) {
cpool.second->clear();
}
} else {
(assure<Event>().clear(), ...);
}
}
/**
* @brief Delivers all the pending events of the given type.
*
* This method is blocking and it doesn't return until all the events are
* delivered to the registered listeners. It's responsibility of the users
* to reduce at a minimum the time spent in the bodies of the listeners.
*
* @tparam Event Type of events to send.
*/
template<typename Event>
void update() {
assure<Event>().publish();
}
/**
* @brief Delivers all the pending events.
*
* This method is blocking and it doesn't return until all the events are
* delivered to the registered listeners. It's responsibility of the users
* to reduce at a minimum the time spent in the bodies of the listeners.
*/
void update() const {
for(auto &&cpool: pools) {
cpool.second->publish();
}
}
private:
dense_map<id_type, std::unique_ptr<basic_pool>, identity> pools;
};
} // namespace entt
#endif
<commit_msg>dispatcher: minor changes<commit_after>#ifndef ENTT_SIGNAL_DISPATCHER_HPP
#define ENTT_SIGNAL_DISPATCHER_HPP
#include <cstddef>
#include <memory>
#include <type_traits>
#include <utility>
#include <vector>
#include "../config/config.h"
#include "../container/dense_map.hpp"
#include "../core/fwd.hpp"
#include "../core/type_info.hpp"
#include "../core/utility.hpp"
#include "sigh.hpp"
namespace entt {
/**
* @brief Basic dispatcher implementation.
*
* A dispatcher can be used either to trigger an immediate event or to enqueue
* events to be published all together once per tick.<br/>
* Listeners are provided in the form of member functions. For each event of
* type `Event`, listeners are such that they can be invoked with an argument of
* type `Event &`, no matter what the return type is.
*
* The dispatcher creates instances of the `sigh` class internally. Refer to the
* documentation of the latter for more details.
*/
class dispatcher {
struct basic_pool {
virtual ~basic_pool() = default;
virtual void publish() = 0;
virtual void disconnect(void *) = 0;
virtual void clear() ENTT_NOEXCEPT = 0;
};
template<typename Event>
struct pool_handler final: basic_pool {
static_assert(std::is_same_v<Event, std::decay_t<Event>>, "Invalid event type");
using signal_type = sigh<void(Event &)>;
using sink_type = typename signal_type::sink_type;
void publish() override {
const auto length = events.size();
for(std::size_t pos{}; pos < length; ++pos) {
signal.publish(events[pos]);
}
events.erase(events.cbegin(), events.cbegin() + length);
}
void disconnect(void *instance) override {
bucket().disconnect(instance);
}
void clear() ENTT_NOEXCEPT override {
events.clear();
}
[[nodiscard]] sink_type bucket() ENTT_NOEXCEPT {
return sink_type{signal};
}
void trigger(Event event) {
signal.publish(event);
}
template<typename... Args>
void enqueue(Args &&...args) {
if constexpr(std::is_aggregate_v<Event>) {
events.push_back(Event{std::forward<Args>(args)...});
} else {
events.emplace_back(std::forward<Args>(args)...);
}
}
private:
signal_type signal{};
std::vector<Event> events;
};
template<typename Event>
[[nodiscard]] pool_handler<Event> &assure() {
if(auto &&ptr = pools[type_hash<Event>::value()]; !ptr) {
auto *cpool = new pool_handler<Event>{};
ptr.reset(cpool);
return *cpool;
} else {
return static_cast<pool_handler<Event> &>(*ptr);
}
}
public:
/*! @brief Default constructor. */
dispatcher() = default;
/*! @brief Default move constructor. */
dispatcher(dispatcher &&) = default;
/*! @brief Default move assignment operator. @return This dispatcher. */
dispatcher &operator=(dispatcher &&) = default;
/**
* @brief Returns a sink object for the given event.
*
* A sink is an opaque object used to connect listeners to events.
*
* The function type for a listener is _compatible_ with:
* @code{.cpp}
* void(Event &);
* @endcode
*
* The order of invocation of the listeners isn't guaranteed.
*
* @sa sink
*
* @tparam Event Type of event of which to get the sink.
* @return A temporary sink object.
*/
template<typename Event>
[[nodiscard]] auto sink() {
return assure<Event>().bucket();
}
/**
* @brief Triggers an immediate event of the given type.
*
* All the listeners registered for the given type are immediately notified.
* The event is discarded after the execution.
*
* @tparam Event Type of event to trigger.
* @tparam Args Types of arguments to use to construct the event.
* @param args Arguments to use to construct the event.
*/
template<typename Event, typename... Args>
void trigger(Args &&...args) {
assure<Event>().trigger(Event{std::forward<Args>(args)...});
}
/**
* @brief Triggers an immediate event of the given type.
*
* All the listeners registered for the given type are immediately notified.
* The event is discarded after the execution.
*
* @tparam Event Type of event to trigger.
* @param event An instance of the given type of event.
*/
template<typename Event>
void trigger(Event &&event) {
assure<std::decay_t<Event>>().trigger(std::forward<Event>(event));
}
/**
* @brief Enqueues an event of the given type.
*
* An event of the given type is queued. No listener is invoked. Use the
* `update` member function to notify listeners when ready.
*
* @tparam Event Type of event to enqueue.
* @tparam Args Types of arguments to use to construct the event.
* @param args Arguments to use to construct the event.
*/
template<typename Event, typename... Args>
void enqueue(Args &&...args) {
assure<Event>().enqueue(std::forward<Args>(args)...);
}
/**
* @brief Enqueues an event of the given type.
*
* An event of the given type is queued. No listener is invoked. Use the
* `update` member function to notify listeners when ready.
*
* @tparam Event Type of event to enqueue.
* @param event An instance of the given type of event.
*/
template<typename Event>
void enqueue(Event &&event) {
assure<std::decay_t<Event>>().enqueue(std::forward<Event>(event));
}
/**
* @brief Utility function to disconnect everything related to a given value
* or instance from a dispatcher.
* @tparam Type Type of class or type of payload.
* @param value_or_instance A valid object that fits the purpose.
*/
template<typename Type>
void disconnect(Type &value_or_instance) {
disconnect(&value_or_instance);
}
/**
* @brief Utility function to disconnect everything related to a given value
* or instance from a dispatcher.
* @tparam Type Type of class or type of payload.
* @param value_or_instance A valid object that fits the purpose.
*/
template<typename Type>
void disconnect(Type *value_or_instance) {
for(auto &&cpool: pools) {
cpool.second->disconnect(value_or_instance);
}
}
/**
* @brief Discards all the events queued so far.
*
* If no types are provided, the dispatcher will clear all the existing
* pools.
*
* @tparam Event Type of events to discard.
*/
template<typename... Event>
void clear() {
if constexpr(sizeof...(Event) == 0) {
for(auto &&cpool: pools) {
cpool.second->clear();
}
} else {
(assure<Event>().clear(), ...);
}
}
/**
* @brief Delivers all the pending events of the given type.
*
* This method is blocking and it doesn't return until all the events are
* delivered to the registered listeners. It's responsibility of the users
* to reduce at a minimum the time spent in the bodies of the listeners.
*
* @tparam Event Type of events to send.
*/
template<typename Event>
void update() {
assure<Event>().publish();
}
/**
* @brief Delivers all the pending events.
*
* This method is blocking and it doesn't return until all the events are
* delivered to the registered listeners. It's responsibility of the users
* to reduce at a minimum the time spent in the bodies of the listeners.
*/
void update() const {
for(auto &&cpool: pools) {
cpool.second->publish();
}
}
private:
dense_map<id_type, std::unique_ptr<basic_pool>, identity> pools;
};
} // namespace entt
#endif
<|endoftext|> |
<commit_before>/*
QWebSockets implements the WebSocket protocol as defined in RFC 6455.
Copyright (C) 2013 Kurt Pattyn ([email protected])
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "qwebsocketprotocol.h"
#include <QString>
#include <QSet>
#include <QtEndian>
/*!
\enum QWebSocketProtocol::CloseCode
\inmodule QtWebSockets
The close codes supported by WebSockets V13
\value CC_NORMAL Normal closure
\value CC_GOING_AWAY Going away
\value CC_PROTOCOL_ERROR Protocol error
\value CC_DATATYPE_NOT_SUPPORTED Unsupported data
\value CC_RESERVED_1004 Reserved
\value CC_MISSING_STATUS_CODE No status received
\value CC_ABNORMAL_DISCONNECTION Abnormal closure
\value CC_WRONG_DATATYPE Invalid frame payload data
\value CC_POLICY_VIOLATED Policy violation
\value CC_TOO_MUCH_DATA Message too big
\value CC_MISSING_EXTENSION Mandatory extension missing
\value CC_BAD_OPERATION Internal server error
\value CC_TLS_HANDSHAKE_FAILED TLS handshake failed
\sa \l{QWebSocket::} {close()}
*/
/*!
\enum QWebSocketProtocol::Version
\inmodule QtWebSockets
\brief The different defined versions of the Websocket protocol.
For an overview of the differences between the different protocols, see
<http://code.google.com/p/pywebsocket/wiki/WebSocketProtocolSpec>
\value V_Unknow
\value V_0 hixie76: http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76 & hybi-00: http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-00.
Works with key1, key2 and a key in the payload.
Attribute: Sec-WebSocket-Draft value 0.
\value V_4 hybi-04: http://tools.ietf.org/id/draft-ietf-hybi-thewebsocketprotocol-04.txt.
Changed handshake: key1, key2, key3 ==> Sec-WebSocket-Key, Sec-WebSocket-Nonce, Sec-WebSocket-Accept
Sec-WebSocket-Draft renamed to Sec-WebSocket-Version
Sec-WebSocket-Version = 4
\value V_5 hybi-05: http://tools.ietf.org/id/draft-ietf-hybi-thewebsocketprotocol-05.txt.
Sec-WebSocket-Version = 5
Removed Sec-WebSocket-Nonce
Added Sec-WebSocket-Accept
\value V_6 Sec-WebSocket-Version = 6.
\value V_7 hybi-07: http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-07.
Sec-WebSocket-Version = 7
\value V_8 hybi-8, hybi-9, hybi-10, hybi-11 and hybi-12.
Status codes 1005 and 1006 are added and all codes are now unsigned
Internal error results in 1006
\value V_13 hybi-13, hybi14, hybi-15, hybi-16, hybi-17 and RFC 6455.
Sec-WebSocket-Version = 13
Status code 1004 is now reserved
Added 1008, 1009 and 1010
Must support TLS
Clarify multiple version support
\value V_LATEST Refers to the latest know version to QWebSockets.
*/
/*!
\fn QWebSocketProtocol::isOpCodeReserved(OpCode code)
Checks if \a code is a valid OpCode
\internal
*/
/*!
\fn QWebSocketProtocol::isCloseCodeValid(int closeCode)
Checks if \a closeCode is a valid web socket close code
\internal
*/
/*!
\fn QWebSocketProtocol::currentVersion()
Returns the latest version that WebSocket is supporting
\internal
*/
QT_BEGIN_NAMESPACE
/**
* @brief Contains constants related to the WebSocket standard.
*/
namespace QWebSocketProtocol
{
/*!
Parses the \a versionString and converts it to a Version value
\internal
*/
Version versionFromString(const QString &versionString)
{
bool ok = false;
Version version = V_Unknow;
const int ver = versionString.toInt(&ok);
QSet<Version> supportedVersions;
supportedVersions << V_0 << V_4 << V_5 << V_6 << V_7 << V_8 << V_13;
if (ok)
{
if (supportedVersions.contains(static_cast<Version>(ver)))
{
version = static_cast<Version>(ver);
}
}
return version;
}
/*!
Mask the \a payload with the given \a maskingKey and stores the result back in \a payload.
\internal
*/
void mask(QByteArray *payload, quint32 maskingKey)
{
quint32 *payloadData = reinterpret_cast<quint32 *>(payload->data());
const quint32 numIterations = static_cast<quint32>(payload->size()) / sizeof(quint32);
const quint32 remainder = static_cast<quint32>(payload->size()) % sizeof(quint32);
quint32 i;
for (i = 0; i < numIterations; ++i)
{
*(payloadData + i) ^= maskingKey;
}
if (remainder)
{
const quint32 offset = i * static_cast<quint32>(sizeof(quint32));
char *payloadBytes = payload->data();
const uchar *mask = reinterpret_cast<uchar *>(&maskingKey);
for (quint32 i = 0; i < remainder; ++i)
{
*(payloadBytes + offset + i) ^= static_cast<char>(mask[(i + offset) % 4]);
}
}
}
/*!
Masks the \a payload of length \a size with the given \a maskingKey and stores the result back in \a payload.
\internal
*/
void mask(char *payload, quint64 size, quint32 maskingKey)
{
quint32 *payloadData = reinterpret_cast<quint32 *>(payload);
const quint32 numIterations = static_cast<quint32>(size / sizeof(quint32));
const quint32 remainder = size % sizeof(quint32);
quint32 i;
for (i = 0; i < numIterations; ++i)
{
*(payloadData + i) ^= maskingKey;
}
if (remainder)
{
const quint32 offset = i * static_cast<quint32>(sizeof(quint32));
const uchar *mask = reinterpret_cast<uchar *>(&maskingKey);
for (quint32 i = 0; i < remainder; ++i)
{
*(payload + offset + i) ^= static_cast<char>(mask[(i + offset) % 4]);
}
}
}
} //end namespace WebSocketProtocol
QT_END_NAMESPACE
<commit_msg>Call other mask function instead of implementing it twice<commit_after>/*
QWebSockets implements the WebSocket protocol as defined in RFC 6455.
Copyright (C) 2013 Kurt Pattyn ([email protected])
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "qwebsocketprotocol.h"
#include <QString>
#include <QSet>
#include <QtEndian>
/*!
\enum QWebSocketProtocol::CloseCode
\inmodule QtWebSockets
The close codes supported by WebSockets V13
\value CC_NORMAL Normal closure
\value CC_GOING_AWAY Going away
\value CC_PROTOCOL_ERROR Protocol error
\value CC_DATATYPE_NOT_SUPPORTED Unsupported data
\value CC_RESERVED_1004 Reserved
\value CC_MISSING_STATUS_CODE No status received
\value CC_ABNORMAL_DISCONNECTION Abnormal closure
\value CC_WRONG_DATATYPE Invalid frame payload data
\value CC_POLICY_VIOLATED Policy violation
\value CC_TOO_MUCH_DATA Message too big
\value CC_MISSING_EXTENSION Mandatory extension missing
\value CC_BAD_OPERATION Internal server error
\value CC_TLS_HANDSHAKE_FAILED TLS handshake failed
\sa \l{QWebSocket::} {close()}
*/
/*!
\enum QWebSocketProtocol::Version
\inmodule QtWebSockets
\brief The different defined versions of the Websocket protocol.
For an overview of the differences between the different protocols, see
<http://code.google.com/p/pywebsocket/wiki/WebSocketProtocolSpec>
\value V_Unknow
\value V_0 hixie76: http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76 & hybi-00: http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-00.
Works with key1, key2 and a key in the payload.
Attribute: Sec-WebSocket-Draft value 0.
\value V_4 hybi-04: http://tools.ietf.org/id/draft-ietf-hybi-thewebsocketprotocol-04.txt.
Changed handshake: key1, key2, key3 ==> Sec-WebSocket-Key, Sec-WebSocket-Nonce, Sec-WebSocket-Accept
Sec-WebSocket-Draft renamed to Sec-WebSocket-Version
Sec-WebSocket-Version = 4
\value V_5 hybi-05: http://tools.ietf.org/id/draft-ietf-hybi-thewebsocketprotocol-05.txt.
Sec-WebSocket-Version = 5
Removed Sec-WebSocket-Nonce
Added Sec-WebSocket-Accept
\value V_6 Sec-WebSocket-Version = 6.
\value V_7 hybi-07: http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-07.
Sec-WebSocket-Version = 7
\value V_8 hybi-8, hybi-9, hybi-10, hybi-11 and hybi-12.
Status codes 1005 and 1006 are added and all codes are now unsigned
Internal error results in 1006
\value V_13 hybi-13, hybi14, hybi-15, hybi-16, hybi-17 and RFC 6455.
Sec-WebSocket-Version = 13
Status code 1004 is now reserved
Added 1008, 1009 and 1010
Must support TLS
Clarify multiple version support
\value V_LATEST Refers to the latest know version to QWebSockets.
*/
/*!
\fn QWebSocketProtocol::isOpCodeReserved(OpCode code)
Checks if \a code is a valid OpCode
\internal
*/
/*!
\fn QWebSocketProtocol::isCloseCodeValid(int closeCode)
Checks if \a closeCode is a valid web socket close code
\internal
*/
/*!
\fn QWebSocketProtocol::currentVersion()
Returns the latest version that WebSocket is supporting
\internal
*/
QT_BEGIN_NAMESPACE
/**
* @brief Contains constants related to the WebSocket standard.
*/
namespace QWebSocketProtocol
{
/*!
Parses the \a versionString and converts it to a Version value
\internal
*/
Version versionFromString(const QString &versionString)
{
bool ok = false;
Version version = V_Unknow;
const int ver = versionString.toInt(&ok);
QSet<Version> supportedVersions;
supportedVersions << V_0 << V_4 << V_5 << V_6 << V_7 << V_8 << V_13;
if (ok)
{
if (supportedVersions.contains(static_cast<Version>(ver)))
{
version = static_cast<Version>(ver);
}
}
return version;
}
/*!
Mask the \a payload with the given \a maskingKey and stores the result back in \a payload.
\internal
*/
void mask(QByteArray *payload, quint32 maskingKey)
{
mask(payload->data(), payload->size(), maskingKey);
}
/*!
Masks the \a payload of length \a size with the given \a maskingKey and stores the result back in \a payload.
\internal
*/
void mask(char *payload, quint64 size, quint32 maskingKey)
{
quint32 *payloadData = reinterpret_cast<quint32 *>(payload);
const quint32 numIterations = static_cast<quint32>(size / sizeof(quint32));
const quint32 remainder = size % sizeof(quint32);
quint32 i;
for (i = 0; i < numIterations; ++i)
{
*(payloadData + i) ^= maskingKey;
}
if (remainder)
{
const quint32 offset = i * static_cast<quint32>(sizeof(quint32));
const uchar *mask = reinterpret_cast<uchar *>(&maskingKey);
for (quint32 i = 0; i < remainder; ++i)
{
*(payload + offset + i) ^= static_cast<char>(mask[(i + offset) % 4]);
}
}
}
} //end namespace WebSocketProtocol
QT_END_NAMESPACE
<|endoftext|> |
<commit_before>/***************************************************************************
* Copyright © 2007 Jason Kivlighn <[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 "xsltexporter.h"
#include "kreexporter.h"
#include <q3ptrdict.h>
#include <QImage>
#include <QFileInfo>
#include <QDir>
#include <q3stylesheet.h>
#include <QList>
#include <QPixmap>
#include <kconfig.h>
#include <kdebug.h>
#include <klocale.h>
#include <kglobal.h>
#include <khtml_part.h>
#include <khtmlview.h>
#include <kprogressdialog.h>
#include <kstandarddirs.h>
#include <kurl.h>
#include <kiconloader.h>
#include <libxml/parser.h>
#include <libxml/tree.h>
#include <libxslt/xslt.h>
#include <libxslt/xsltInternals.h>
#include <libxslt/transform.h>
#include <libxslt/xsltutils.h>
#include <cmath> //round
#include "backends/recipedb.h"
#include "dialogs/setupdisplay.h"
#include "image.h"
#include "krepagelayout.h"
const char* i18n_strings[] = {
"I18N_INSTRUCTIONS", I18N_NOOP("Instructions"),
"I18N_OVERALL_RATING", I18N_NOOP("Overall Rating"),
"I18N_CATEGORIES", I18N_NOOP("Categories"),
"I18N_YIELD", I18N_NOOP("Yield"),
"I18N_PREP", I18N_NOOP("Prep"),
"I18N_AUTHORS", I18N_NOOP("Authors"),
"I18N_AMOUNT", I18N_NOOP("Amount"),
"I18N_INGREDIENT", I18N_NOOP("Ingredient"),
"I18N_INGREDIENTS", I18N_NOOP("Ingredients"),
"I18N_PREPARATION", I18N_NOOP("Preparation"),
"I18N_PROPERTIES", I18N_NOOP("Properties"),
"I18N_RATINGS", I18N_NOOP("Ratings"),
"I18N_OR", I18N_NOOP("OR"),
"I18N_REVIEWS", I18N_NOOP("reviews"),
NULL
};
#define NUM_I18N_STRINGS 28
XSLTExporter::XSLTExporter( const QString& filename, const QString &format ) :
BaseExporter( filename, format )
{
KConfigGroup config = KGlobal::config()->group( "Page Setup" );
//let's do everything we can to be sure at least some layout is loaded
QString template_filename = config.readEntry( "Template", KStandardDirs::locate( "appdata", "layouts/Default.xsl" ) );
if ( template_filename.isEmpty() || !QFile::exists( template_filename )
|| template_filename.endsWith(".template") ) //handle the transition to xslt
template_filename = KStandardDirs::locate( "appdata", "layouts/Default.xsl" );
kDebug() << "Using template file: " << template_filename ;
setTemplate( template_filename );
//let's do everything we can to be sure at least some layout is loaded
m_layoutFilename = config.readEntry( "Layout", KStandardDirs::locate( "appdata", "layouts/None.klo" ) );
if ( m_layoutFilename.isEmpty() || !QFile::exists( m_layoutFilename ) )
m_layoutFilename = KStandardDirs::locate( "appdata", "layouts/None.klo" );
}
XSLTExporter::~XSLTExporter()
{
}
void XSLTExporter::setStyle( const QString &filename )
{
m_layoutFilename = filename;
}
void XSLTExporter::setTemplate( const QString &filename )
{
QFile templateFile( filename );
if ( templateFile.open( QIODevice::ReadOnly ) ) {
m_templateFilename = filename;
}
else
kDebug()<<"couldn't find/open template file";
}
int XSLTExporter::supportedItems() const
{
int items = RecipeDB::All;
QMap<QString,bool>::const_iterator it;
for ( it = m_visibilityMap.begin(); it != m_visibilityMap.end(); ++it ) {
if (it.value() == false) {
if (it.key() == "authors") {
items ^= RecipeDB::Authors;
} else if (it.key() == "categories") {
items ^= RecipeDB::Categories;
} else if (it.key() == "ingredients") {
items ^= RecipeDB::Ingredients;
} else if (it.key() == "instructions") {
items ^= RecipeDB::Instructions;
} else if (it.key() == "photo") {
items ^= RecipeDB::Photo;
} else if (it.key() == "prep_time") {
items ^= RecipeDB::PrepTime;
} else if (it.key() == "properties") {
items ^= RecipeDB::Properties;
} else if (it.key() == "ratings") {
items ^= RecipeDB::Ratings;
} else if (it.key() == "title") {
items ^= RecipeDB::Title;
} else if (it.key() == "yield") {
items ^= RecipeDB::Yield;
}
}
}
return items;
}
QString XSLTExporter::createFooter()
{
xsltCleanupGlobals();
xmlCleanupParser();
return QString::null;
}
QString XSLTExporter::createHeader( const RecipeList & )
{
QFile layoutFile( m_layoutFilename );
QString error; int line; int column;
QDomDocument doc;
if ( !doc.setContent( &layoutFile, &error, &line, &column ) ) {
kDebug()<<"Unable to load style information. Will create HTML without it...";
}
else
processDocument(doc);
return QString::null;
}
QString XSLTExporter::createContent( const RecipeList &recipes )
{
m_error = false;
//put all the recipe photos into this directory
QDir dir;
QFileInfo fi(fileName());
dir.mkdir( fi.absolutePath() + "/" + fi.baseName() + "_photos" );
RecipeList::const_iterator recipe_it;
for ( recipe_it = recipes.begin(); recipe_it != recipes.end(); ++recipe_it ) {
storePhoto( *recipe_it );
int rating_total = 0;
double rating_sum = 0;
for ( RatingList::const_iterator rating_it = (*recipe_it).ratingList.begin(); rating_it != (*recipe_it).ratingList.end(); ++rating_it ) {
for ( RatingCriteriaList::const_iterator rc_it = (*rating_it).ratingCriteriaList.begin(); rc_it != (*rating_it).ratingCriteriaList.end(); ++rc_it ) {
QString image_url = fi.baseName() + "_photos/" + QString::number((*rc_it).stars) + "-stars.png";
if ( !QFile::exists( fi.absolutePath() + "/" + image_url ) ) {
QPixmap starPixmap = Rating::starsPixmap((*rc_it).stars);
starPixmap.save( fi.absolutePath() + "/" + image_url, "PNG" );
}
rating_total++;
rating_sum += (*rc_it).stars;
}
}
if ( rating_total > 0 ) {
double average = round(2*rating_sum/rating_total)/2;
QString image_url = fi.baseName() + "_photos/" + QString::number(average) + "-stars.png";
if ( !QFile::exists( fi.absolutePath() + "/" + image_url ) ) {
QPixmap starPixmap = Rating::starsPixmap(average);
starPixmap.save( fi.absolutePath() + "/" + image_url, "PNG" );
}
}
}
KLocale*loc = KGlobal::locale();
QString encoding = loc->encoding();
QString cssContent;
QFileInfo info(m_templateFilename);
QFile cssFile(info.absolutePath() + "/" + info.baseName() + ".css");
kDebug()<<info.absolutePath() + "/" + info.baseName() + ".css";
if ( cssFile.open( QIODevice::ReadOnly ) ) {
cssContent = QString( cssFile.readAll() );
}
cssContent += m_cachedCSS;
QFile linkedCSSFile(fi.absolutePath() + "/style.css");
if (linkedCSSFile.open(QIODevice::WriteOnly)) {
QTextStream stream( &linkedCSSFile );
stream << cssContent;
}
m_cachedCSS = QString::null;
KreExporter *exporter = new KreExporter( NULL, "unused", "*.kreml", false );
QString buffer;
QTextStream stream(&buffer,QIODevice::WriteOnly);
exporter->writeStream(stream,recipes);
delete exporter;
QByteArray content = buffer.toUtf8();
xmlDocPtr kremlDoc = xmlReadMemory(content, content.length(), "noname.xml", "utf-8", 0);
if (kremlDoc == NULL) {
kDebug() << "Failed to parse document" ;
return i18n("<html><b>Error:</b> Problem with KreML exporter. Please export the recipe you are trying to view as KreML and attach it to a bug report to a Krecipes developer.</html>");
}
//const char *filename = "/home/jason/svn/utils/krecipes/layouts/Default.xsl";
QByteArray filename = m_templateFilename.toUtf8();
xsltStylesheetPtr xslt = xsltParseStylesheetFile((const xmlChar*)filename.constData());
if ( !xslt ) {
return i18n("<html><b>Error:</b> Bad template: %1. Use \"Edit->Page Setup...\" to select a new template.</html>",QString( filename ));
}
QFileInfo imgDirInfo(m_templateFilename);
const char *params[NUM_I18N_STRINGS+3];
int i = 0;
params[i++] = "imgDir";
QByteArray imgDir = "'"+imgDirInfo.absolutePath().toUtf8()+"'";
params[i++] = imgDir.data();
for ( uint j = 0; j < NUM_I18N_STRINGS; j+=2 ) {
params[i++] = i18n_strings[j];
QString translatedString = "'"+i18n(i18n_strings[j+1])+"'";
params[i++] = qstrdup(translatedString.toUtf8());
}
params[i] = NULL;
xmlDocPtr htmlDoc = xsltApplyStylesheet(xslt, kremlDoc, (const char**)params);
for ( uint j = 0; j < NUM_I18N_STRINGS; j+=2 ) {
delete[] params[2+j+1];
}
xmlChar *xmlOutput;
int length;
xsltSaveResultToString(&xmlOutput, &length, htmlDoc, xslt);
QString output = QString::fromUtf8((char*)xmlOutput);
xsltFreeStylesheet(xslt);
xmlFreeDoc(kremlDoc);
xmlFreeDoc(htmlDoc);
return output;
}
void XSLTExporter::beginObject( const QString &object )
{
m_cachedCSS += "."+object+", ."+object+" td { \n";
}
void XSLTExporter::endObject()
{
m_cachedCSS += " } \n";
}
void XSLTExporter::loadBackgroundColor( const QString &/*object*/, const QColor& color )
{
m_cachedCSS += bgColorAsCSS(color);
}
void XSLTExporter::loadFont( const QString &/*object*/, const QFont& font )
{
m_cachedCSS += fontAsCSS(font);
}
void XSLTExporter::loadTextColor( const QString &/*object*/, const QColor& color )
{
m_cachedCSS += textColorAsCSS(color);
}
void XSLTExporter::loadVisibility( const QString &object, bool visible )
{
m_cachedCSS += visibilityAsCSS(visible);
m_visibilityMap.insert(object,visible);
}
void XSLTExporter::loadAlignment( const QString &/*object*/, int alignment )
{
m_cachedCSS += alignmentAsCSS(alignment);
}
void XSLTExporter::loadBorder( const QString &/*object*/, const KreBorder& border )
{
m_cachedCSS += borderAsCSS(border);
}
void XSLTExporter::loadColumns( const QString & object, int cols )
{
m_columnsMap.insert(object,cols);
}
void XSLTExporter::storePhoto( const Recipe &recipe )
{
QImage image;
QString photo_name;
if ( recipe.photo.isNull() ) {
image = QImage( defaultPhoto );
photo_name = "default_photo";
}
else {
image = recipe.photo.toImage();
photo_name = QString::number(recipe.recipeID);
}
QPixmap pm = QPixmap::fromImage( image );//image.smoothScale( phwidth, 0, QImage::ScaleMax );
QFileInfo fi(fileName());
QString photo_path = fi.absolutePath() + "/" + fi.baseName() + "_photos/" + photo_name + ".png";
if ( !QFile::exists( photo_path ) ) {
kDebug() << "photo: " << photo_path ;
pm.save( photo_path, "PNG" );
}
}
void XSLTExporter::removeHTMLFiles( const QString &filename, int recipe_id )
{
QList<int> id;
id << recipe_id;
removeHTMLFiles( filename, id );
}
void XSLTExporter::removeHTMLFiles( const QString &filename, const QList<int> &recipe_ids )
{
kDebug() << "removing html files" ;
//remove HTML file
QFile old_file( filename + ".html" );
if ( old_file.exists() )
old_file.remove();
//remove photos
for ( QList<int>::const_iterator it = recipe_ids.begin(); it != recipe_ids.end(); ++it ) {
QFile photo( filename + "_photos/" + QString::number(*it) + ".png" );
if ( photo.exists() )
photo.remove(); //remove photos in directory before removing it
}
//take care of the default photo
QFile photo( filename + "_photos/default_photo.png" );
if ( photo.exists() ) photo.remove();
//remove photo directory
QDir photo_dir;
photo_dir.rmdir( filename + "_photos" );
for ( double d = 0.5; d < 5.5; d += 0.5 ) {
if ( QFile::exists(filename+"_photos/"+QString::number(d)+"-stars.png") ) photo.remove(filename+"_photos/"+QString::number(d)+"-stars.png");
}
}
<commit_msg>Fix Krazy warnings: doublequote_chars - src/exporters/xsltexporter.cpp<commit_after>/***************************************************************************
* Copyright © 2007 Jason Kivlighn <[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 "xsltexporter.h"
#include "kreexporter.h"
#include <q3ptrdict.h>
#include <QImage>
#include <QFileInfo>
#include <QDir>
#include <q3stylesheet.h>
#include <QList>
#include <QPixmap>
#include <kconfig.h>
#include <kdebug.h>
#include <klocale.h>
#include <kglobal.h>
#include <khtml_part.h>
#include <khtmlview.h>
#include <kprogressdialog.h>
#include <kstandarddirs.h>
#include <kurl.h>
#include <kiconloader.h>
#include <libxml/parser.h>
#include <libxml/tree.h>
#include <libxslt/xslt.h>
#include <libxslt/xsltInternals.h>
#include <libxslt/transform.h>
#include <libxslt/xsltutils.h>
#include <cmath> //round
#include "backends/recipedb.h"
#include "dialogs/setupdisplay.h"
#include "image.h"
#include "krepagelayout.h"
const char* i18n_strings[] = {
"I18N_INSTRUCTIONS", I18N_NOOP("Instructions"),
"I18N_OVERALL_RATING", I18N_NOOP("Overall Rating"),
"I18N_CATEGORIES", I18N_NOOP("Categories"),
"I18N_YIELD", I18N_NOOP("Yield"),
"I18N_PREP", I18N_NOOP("Prep"),
"I18N_AUTHORS", I18N_NOOP("Authors"),
"I18N_AMOUNT", I18N_NOOP("Amount"),
"I18N_INGREDIENT", I18N_NOOP("Ingredient"),
"I18N_INGREDIENTS", I18N_NOOP("Ingredients"),
"I18N_PREPARATION", I18N_NOOP("Preparation"),
"I18N_PROPERTIES", I18N_NOOP("Properties"),
"I18N_RATINGS", I18N_NOOP("Ratings"),
"I18N_OR", I18N_NOOP("OR"),
"I18N_REVIEWS", I18N_NOOP("reviews"),
NULL
};
#define NUM_I18N_STRINGS 28
XSLTExporter::XSLTExporter( const QString& filename, const QString &format ) :
BaseExporter( filename, format )
{
KConfigGroup config = KGlobal::config()->group( "Page Setup" );
//let's do everything we can to be sure at least some layout is loaded
QString template_filename = config.readEntry( "Template", KStandardDirs::locate( "appdata", "layouts/Default.xsl" ) );
if ( template_filename.isEmpty() || !QFile::exists( template_filename )
|| template_filename.endsWith(".template") ) //handle the transition to xslt
template_filename = KStandardDirs::locate( "appdata", "layouts/Default.xsl" );
kDebug() << "Using template file: " << template_filename ;
setTemplate( template_filename );
//let's do everything we can to be sure at least some layout is loaded
m_layoutFilename = config.readEntry( "Layout", KStandardDirs::locate( "appdata", "layouts/None.klo" ) );
if ( m_layoutFilename.isEmpty() || !QFile::exists( m_layoutFilename ) )
m_layoutFilename = KStandardDirs::locate( "appdata", "layouts/None.klo" );
}
XSLTExporter::~XSLTExporter()
{
}
void XSLTExporter::setStyle( const QString &filename )
{
m_layoutFilename = filename;
}
void XSLTExporter::setTemplate( const QString &filename )
{
QFile templateFile( filename );
if ( templateFile.open( QIODevice::ReadOnly ) ) {
m_templateFilename = filename;
}
else
kDebug()<<"couldn't find/open template file";
}
int XSLTExporter::supportedItems() const
{
int items = RecipeDB::All;
QMap<QString,bool>::const_iterator it;
for ( it = m_visibilityMap.begin(); it != m_visibilityMap.end(); ++it ) {
if (it.value() == false) {
if (it.key() == "authors") {
items ^= RecipeDB::Authors;
} else if (it.key() == "categories") {
items ^= RecipeDB::Categories;
} else if (it.key() == "ingredients") {
items ^= RecipeDB::Ingredients;
} else if (it.key() == "instructions") {
items ^= RecipeDB::Instructions;
} else if (it.key() == "photo") {
items ^= RecipeDB::Photo;
} else if (it.key() == "prep_time") {
items ^= RecipeDB::PrepTime;
} else if (it.key() == "properties") {
items ^= RecipeDB::Properties;
} else if (it.key() == "ratings") {
items ^= RecipeDB::Ratings;
} else if (it.key() == "title") {
items ^= RecipeDB::Title;
} else if (it.key() == "yield") {
items ^= RecipeDB::Yield;
}
}
}
return items;
}
QString XSLTExporter::createFooter()
{
xsltCleanupGlobals();
xmlCleanupParser();
return QString::null;
}
QString XSLTExporter::createHeader( const RecipeList & )
{
QFile layoutFile( m_layoutFilename );
QString error; int line; int column;
QDomDocument doc;
if ( !doc.setContent( &layoutFile, &error, &line, &column ) ) {
kDebug()<<"Unable to load style information. Will create HTML without it...";
}
else
processDocument(doc);
return QString::null;
}
QString XSLTExporter::createContent( const RecipeList &recipes )
{
m_error = false;
//put all the recipe photos into this directory
QDir dir;
QFileInfo fi(fileName());
dir.mkdir( fi.absolutePath() + '/' + fi.baseName() + "_photos" );
RecipeList::const_iterator recipe_it;
for ( recipe_it = recipes.begin(); recipe_it != recipes.end(); ++recipe_it ) {
storePhoto( *recipe_it );
int rating_total = 0;
double rating_sum = 0;
for ( RatingList::const_iterator rating_it = (*recipe_it).ratingList.begin(); rating_it != (*recipe_it).ratingList.end(); ++rating_it ) {
for ( RatingCriteriaList::const_iterator rc_it = (*rating_it).ratingCriteriaList.begin(); rc_it != (*rating_it).ratingCriteriaList.end(); ++rc_it ) {
QString image_url = fi.baseName() + "_photos/" + QString::number((*rc_it).stars) + "-stars.png";
if ( !QFile::exists( fi.absolutePath() + '/' + image_url ) ) {
QPixmap starPixmap = Rating::starsPixmap((*rc_it).stars);
starPixmap.save( fi.absolutePath() + '/' + image_url, "PNG" );
}
rating_total++;
rating_sum += (*rc_it).stars;
}
}
if ( rating_total > 0 ) {
double average = round(2*rating_sum/rating_total)/2;
QString image_url = fi.baseName() + "_photos/" + QString::number(average) + "-stars.png";
if ( !QFile::exists( fi.absolutePath() + '/' + image_url ) ) {
QPixmap starPixmap = Rating::starsPixmap(average);
starPixmap.save( fi.absolutePath() + '/' + image_url, "PNG" );
}
}
}
KLocale*loc = KGlobal::locale();
QString encoding = loc->encoding();
QString cssContent;
QFileInfo info(m_templateFilename);
QFile cssFile(info.absolutePath() + '/' + info.baseName() + ".css");
kDebug()<<info.absolutePath() + '/' + info.baseName() + ".css";
if ( cssFile.open( QIODevice::ReadOnly ) ) {
cssContent = QString( cssFile.readAll() );
}
cssContent += m_cachedCSS;
QFile linkedCSSFile(fi.absolutePath() + "/style.css");
if (linkedCSSFile.open(QIODevice::WriteOnly)) {
QTextStream stream( &linkedCSSFile );
stream << cssContent;
}
m_cachedCSS = QString::null;
KreExporter *exporter = new KreExporter( NULL, "unused", "*.kreml", false );
QString buffer;
QTextStream stream(&buffer,QIODevice::WriteOnly);
exporter->writeStream(stream,recipes);
delete exporter;
QByteArray content = buffer.toUtf8();
xmlDocPtr kremlDoc = xmlReadMemory(content, content.length(), "noname.xml", "utf-8", 0);
if (kremlDoc == NULL) {
kDebug() << "Failed to parse document" ;
return i18n("<html><b>Error:</b> Problem with KreML exporter. Please export the recipe you are trying to view as KreML and attach it to a bug report to a Krecipes developer.</html>");
}
//const char *filename = "/home/jason/svn/utils/krecipes/layouts/Default.xsl";
QByteArray filename = m_templateFilename.toUtf8();
xsltStylesheetPtr xslt = xsltParseStylesheetFile((const xmlChar*)filename.constData());
if ( !xslt ) {
return i18n("<html><b>Error:</b> Bad template: %1. Use \"Edit->Page Setup...\" to select a new template.</html>",QString( filename ));
}
QFileInfo imgDirInfo(m_templateFilename);
const char *params[NUM_I18N_STRINGS+3];
int i = 0;
params[i++] = "imgDir";
QByteArray imgDir = '\''+imgDirInfo.absolutePath().toUtf8()+'\'';
params[i++] = imgDir.data();
for ( uint j = 0; j < NUM_I18N_STRINGS; j+=2 ) {
params[i++] = i18n_strings[j];
QString translatedString = '\''+i18n(i18n_strings[j+1])+'\'';
params[i++] = qstrdup(translatedString.toUtf8());
}
params[i] = NULL;
xmlDocPtr htmlDoc = xsltApplyStylesheet(xslt, kremlDoc, (const char**)params);
for ( uint j = 0; j < NUM_I18N_STRINGS; j+=2 ) {
delete[] params[2+j+1];
}
xmlChar *xmlOutput;
int length;
xsltSaveResultToString(&xmlOutput, &length, htmlDoc, xslt);
QString output = QString::fromUtf8((char*)xmlOutput);
xsltFreeStylesheet(xslt);
xmlFreeDoc(kremlDoc);
xmlFreeDoc(htmlDoc);
return output;
}
void XSLTExporter::beginObject( const QString &object )
{
m_cachedCSS += '.'+object+", ."+object+" td { \n";
}
void XSLTExporter::endObject()
{
m_cachedCSS += " } \n";
}
void XSLTExporter::loadBackgroundColor( const QString &/*object*/, const QColor& color )
{
m_cachedCSS += bgColorAsCSS(color);
}
void XSLTExporter::loadFont( const QString &/*object*/, const QFont& font )
{
m_cachedCSS += fontAsCSS(font);
}
void XSLTExporter::loadTextColor( const QString &/*object*/, const QColor& color )
{
m_cachedCSS += textColorAsCSS(color);
}
void XSLTExporter::loadVisibility( const QString &object, bool visible )
{
m_cachedCSS += visibilityAsCSS(visible);
m_visibilityMap.insert(object,visible);
}
void XSLTExporter::loadAlignment( const QString &/*object*/, int alignment )
{
m_cachedCSS += alignmentAsCSS(alignment);
}
void XSLTExporter::loadBorder( const QString &/*object*/, const KreBorder& border )
{
m_cachedCSS += borderAsCSS(border);
}
void XSLTExporter::loadColumns( const QString & object, int cols )
{
m_columnsMap.insert(object,cols);
}
void XSLTExporter::storePhoto( const Recipe &recipe )
{
QImage image;
QString photo_name;
if ( recipe.photo.isNull() ) {
image = QImage( defaultPhoto );
photo_name = "default_photo";
}
else {
image = recipe.photo.toImage();
photo_name = QString::number(recipe.recipeID);
}
QPixmap pm = QPixmap::fromImage( image );//image.smoothScale( phwidth, 0, QImage::ScaleMax );
QFileInfo fi(fileName());
QString photo_path = fi.absolutePath() + '/' + fi.baseName() + "_photos/" + photo_name + ".png";
if ( !QFile::exists( photo_path ) ) {
kDebug() << "photo: " << photo_path ;
pm.save( photo_path, "PNG" );
}
}
void XSLTExporter::removeHTMLFiles( const QString &filename, int recipe_id )
{
QList<int> id;
id << recipe_id;
removeHTMLFiles( filename, id );
}
void XSLTExporter::removeHTMLFiles( const QString &filename, const QList<int> &recipe_ids )
{
kDebug() << "removing html files" ;
//remove HTML file
QFile old_file( filename + ".html" );
if ( old_file.exists() )
old_file.remove();
//remove photos
for ( QList<int>::const_iterator it = recipe_ids.begin(); it != recipe_ids.end(); ++it ) {
QFile photo( filename + "_photos/" + QString::number(*it) + ".png" );
if ( photo.exists() )
photo.remove(); //remove photos in directory before removing it
}
//take care of the default photo
QFile photo( filename + "_photos/default_photo.png" );
if ( photo.exists() ) photo.remove();
//remove photo directory
QDir photo_dir;
photo_dir.rmdir( filename + "_photos" );
for ( double d = 0.5; d < 5.5; d += 0.5 ) {
if ( QFile::exists(filename+"_photos/"+QString::number(d)+"-stars.png") ) photo.remove(filename+"_photos/"+QString::number(d)+"-stars.png");
}
}
<|endoftext|> |
<commit_before>// Copyright 2010-2013 RethinkDB, all rights reserved.
#include <sys/wait.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <signal.h>
#include <unistd.h>
#include "extproc/extproc_spawner.hpp"
#include "extproc/extproc_worker.hpp"
#include "arch/fd_send_recv.hpp"
extproc_spawner_t *extproc_spawner_t::instance = NULL;
// This is the class that runs in the external process, doing all the work
class worker_run_t {
public:
worker_run_t(fd_t _socket, pid_t _spawner_pid) :
socket(_socket), socket_stream(socket.get(), &blocking_watcher) {
guarantee(spawner_pid == -1);
spawner_pid = _spawner_pid;
// Set ourselves to get interrupted when our parent dies
struct sigaction sa = make_sa_handler(0, check_ppid_for_death);
const int sigaction_res = sigaction(SIGALRM, &sa, NULL);
guarantee_err(sigaction_res == 0, "worker: could not set action for ALRM signal");
struct itimerval timerval;
timerval.it_interval.tv_sec = 0;
timerval.it_interval.tv_usec = 500 * THOUSAND;
timerval.it_value = timerval.it_interval;
struct itimerval old_timerval;
const int itimer_res = setitimer(ITIMER_REAL, &timerval, &old_timerval);
guarantee_err(itimer_res == 0, "worker: setitimer failed");
guarantee(old_timerval.it_value.tv_sec == 0 && old_timerval.it_value.tv_usec == 0,
"worker: setitimer saw that we already had an itimer!");
// Send our pid over to the main process (because it didn't fork us directly)
write_message_t msg;
msg << getpid();
int res = send_write_message(&socket_stream, &msg);
guarantee(res == 0);
}
~worker_run_t() {
guarantee(spawner_pid != -1);
spawner_pid = -1;
}
// Returning from this indicates an error, orderly shutdown will exit() manually
void main_loop() {
// Receive and run a function from the main process until one returns false
bool (*fn) (read_stream_t *, write_stream_t *);
while (true) {
int64_t read_size = sizeof(fn);
int64_t read_res = force_read(&socket_stream, &fn, read_size);
if (read_res != read_size) {
break;
}
if (!fn(&socket_stream, &socket_stream)) {
break;
}
// Trade magic numbers with the parent
uint64_t magic_from_parent;
read_res = deserialize(&socket_stream, &magic_from_parent);
if (read_res != ARCHIVE_SUCCESS ||
magic_from_parent != extproc_worker_t::parent_to_worker_magic) {
break;
}
write_message_t msg;
msg << extproc_worker_t::worker_to_parent_magic;
int res = send_write_message(&socket_stream, &msg);
if (res != 0) {
break;
}
}
}
private:
static pid_t spawner_pid;
static void check_ppid_for_death(int) {
pid_t ppid = getppid();
if (spawner_pid != -1 && spawner_pid != ppid) {
debugf("check_ppid_for_death found death\n");
::_exit(EXIT_FAILURE);
}
}
scoped_fd_t socket;
blocking_fd_watcher_t blocking_watcher;
socket_stream_t socket_stream;
};
pid_t worker_run_t::spawner_pid = -1;
class spawner_run_t {
public:
explicit spawner_run_t(fd_t _socket) :
socket(_socket) {
// We set our PGID to our own PID (rather than inheriting our parent's PGID)
// so that a signal (eg. SIGINT) sent to the parent's PGID (by eg. hitting
// Ctrl-C at a terminal) will not propagate to us or our children.
//
// This is desirable because the RethinkDB engine deliberately crashes with
// an error message if the spawner or a worker process dies; but a
// command-line SIGINT should trigger a clean shutdown, not a crash.
const int setpgid_res = setpgid(0, 0);
guarantee_err(setpgid_res == 0, "spawner could not set PGID");
// We ignore SIGCHLD so that we don't accumulate zombie children.
{
// NB. According to `man 2 sigaction` on linux, POSIX.1-2001 says that
// this will prevent zombies, but may not be "fully portable".
struct sigaction sa = make_sa_handler(0, SIG_IGN);
const int res = sigaction(SIGCHLD, &sa, NULL);
guarantee_err(res == 0, "spawner: Could not ignore SIGCHLD");
}
}
void main_loop() {
pid_t spawner_pid = getpid();
while(true) {
fd_t worker_socket;
fd_recv_result_t recv_res = recv_fds(socket.get(), 1, &worker_socket);
if (recv_res != FD_RECV_OK) {
break;
}
pid_t res = ::fork();
if (res == 0) {
// Worker process here
socket.reset(); // Don't need the spawner's pipe
worker_run_t worker_runner(worker_socket, spawner_pid);
worker_runner.main_loop();
::_exit(EXIT_FAILURE);
}
guarantee_err(res != -1, "could not fork worker process");
scoped_fd_t closer(worker_socket);
}
}
private:
scoped_fd_t socket;
};
extproc_spawner_t::extproc_spawner_t() :
spawner_pid(-1)
{
// TODO: guarantee we aren't in a thread pool
guarantee(instance == NULL);
instance = this;
fork_spawner();
}
extproc_spawner_t::~extproc_spawner_t() {
// TODO: guarantee we aren't in a thread pool
guarantee(instance == this);
instance = NULL;
// This should trigger the spawner to exit
spawner_socket.reset();
// Wait on the spawner's return value to clean up the process
int status;
int res = waitpid(spawner_pid, &status, 0);
guarantee_err(res == spawner_pid, "failed to wait for extproc spawner process to exit");
}
extproc_spawner_t *extproc_spawner_t::get_instance() {
return instance;
}
void extproc_spawner_t::fork_spawner() {
guarantee(spawner_socket.get() == INVALID_FD);
fd_t fds[2];
int res = socketpair(AF_UNIX, SOCK_STREAM, 0, fds);
guarantee_err(res == 0, "could not create socket pair for spawner process");
res = ::fork();
if (res == 0) {
// This is the spawner process, just instantiate ourselves and handle requests
do {
res = ::close(fds[0]);
} while (res == 0 && errno == EINTR);
spawner_run_t spawner(fds[1]);
spawner.main_loop();
::_exit(EXIT_SUCCESS);
}
spawner_pid = res;
guarantee_err(spawner_pid != -1, "could not fork spawner process");
scoped_fd_t closer(fds[1]);
spawner_socket.reset(fds[0]);
}
// Spawns a new worker process and returns the fd of the socket used to communicate with it
fd_t extproc_spawner_t::spawn(object_buffer_t<socket_stream_t> *stream_out, pid_t *pid_out) {
guarantee(spawner_socket.get() != INVALID_FD);
fd_t fds[2];
int res = socketpair(AF_UNIX, SOCK_STREAM, 0, fds);
guarantee_err(res == 0, "could not create socket pair for worker process");
res = send_fds(spawner_socket.get(), 1, &fds[1]);
guarantee_err(res == 0, "could not send socket file descriptor to worker process");
stream_out->create(fds[0], reinterpret_cast<fd_watcher_t*>(NULL));
// Get the pid of the new worker process
archive_result_t archive_res;
archive_res = deserialize(stream_out->get(), pid_out);
guarantee_deserialization(archive_res, "pid_out");
guarantee(archive_res == ARCHIVE_SUCCESS);
guarantee(*pid_out != -1);
scoped_fd_t closer(fds[1]);
return fds[0];
}
<commit_msg>Remove a guarantee that survived the purge.<commit_after>// Copyright 2010-2013 RethinkDB, all rights reserved.
#include <sys/wait.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <signal.h>
#include <unistd.h>
#include "extproc/extproc_spawner.hpp"
#include "extproc/extproc_worker.hpp"
#include "arch/fd_send_recv.hpp"
extproc_spawner_t *extproc_spawner_t::instance = NULL;
// This is the class that runs in the external process, doing all the work
class worker_run_t {
public:
worker_run_t(fd_t _socket, pid_t _spawner_pid) :
socket(_socket), socket_stream(socket.get(), &blocking_watcher) {
guarantee(spawner_pid == -1);
spawner_pid = _spawner_pid;
// Set ourselves to get interrupted when our parent dies
struct sigaction sa = make_sa_handler(0, check_ppid_for_death);
const int sigaction_res = sigaction(SIGALRM, &sa, NULL);
guarantee_err(sigaction_res == 0, "worker: could not set action for ALRM signal");
struct itimerval timerval;
timerval.it_interval.tv_sec = 0;
timerval.it_interval.tv_usec = 500 * THOUSAND;
timerval.it_value = timerval.it_interval;
struct itimerval old_timerval;
const int itimer_res = setitimer(ITIMER_REAL, &timerval, &old_timerval);
guarantee_err(itimer_res == 0, "worker: setitimer failed");
guarantee(old_timerval.it_value.tv_sec == 0 && old_timerval.it_value.tv_usec == 0,
"worker: setitimer saw that we already had an itimer!");
// Send our pid over to the main process (because it didn't fork us directly)
write_message_t msg;
msg << getpid();
int res = send_write_message(&socket_stream, &msg);
guarantee(res == 0);
}
~worker_run_t() {
guarantee(spawner_pid != -1);
spawner_pid = -1;
}
// Returning from this indicates an error, orderly shutdown will exit() manually
void main_loop() {
// Receive and run a function from the main process until one returns false
bool (*fn) (read_stream_t *, write_stream_t *);
while (true) {
int64_t read_size = sizeof(fn);
int64_t read_res = force_read(&socket_stream, &fn, read_size);
if (read_res != read_size) {
break;
}
if (!fn(&socket_stream, &socket_stream)) {
break;
}
// Trade magic numbers with the parent
uint64_t magic_from_parent;
read_res = deserialize(&socket_stream, &magic_from_parent);
if (read_res != ARCHIVE_SUCCESS ||
magic_from_parent != extproc_worker_t::parent_to_worker_magic) {
break;
}
write_message_t msg;
msg << extproc_worker_t::worker_to_parent_magic;
int res = send_write_message(&socket_stream, &msg);
if (res != 0) {
break;
}
}
}
private:
static pid_t spawner_pid;
static void check_ppid_for_death(int) {
pid_t ppid = getppid();
if (spawner_pid != -1 && spawner_pid != ppid) {
debugf("check_ppid_for_death found death\n");
::_exit(EXIT_FAILURE);
}
}
scoped_fd_t socket;
blocking_fd_watcher_t blocking_watcher;
socket_stream_t socket_stream;
};
pid_t worker_run_t::spawner_pid = -1;
class spawner_run_t {
public:
explicit spawner_run_t(fd_t _socket) :
socket(_socket) {
// We set our PGID to our own PID (rather than inheriting our parent's PGID)
// so that a signal (eg. SIGINT) sent to the parent's PGID (by eg. hitting
// Ctrl-C at a terminal) will not propagate to us or our children.
//
// This is desirable because the RethinkDB engine deliberately crashes with
// an error message if the spawner or a worker process dies; but a
// command-line SIGINT should trigger a clean shutdown, not a crash.
const int setpgid_res = setpgid(0, 0);
guarantee_err(setpgid_res == 0, "spawner could not set PGID");
// We ignore SIGCHLD so that we don't accumulate zombie children.
{
// NB. According to `man 2 sigaction` on linux, POSIX.1-2001 says that
// this will prevent zombies, but may not be "fully portable".
struct sigaction sa = make_sa_handler(0, SIG_IGN);
const int res = sigaction(SIGCHLD, &sa, NULL);
guarantee_err(res == 0, "spawner: Could not ignore SIGCHLD");
}
}
void main_loop() {
pid_t spawner_pid = getpid();
while(true) {
fd_t worker_socket;
fd_recv_result_t recv_res = recv_fds(socket.get(), 1, &worker_socket);
if (recv_res != FD_RECV_OK) {
break;
}
pid_t res = ::fork();
if (res == 0) {
// Worker process here
socket.reset(); // Don't need the spawner's pipe
worker_run_t worker_runner(worker_socket, spawner_pid);
worker_runner.main_loop();
::_exit(EXIT_FAILURE);
}
guarantee_err(res != -1, "could not fork worker process");
scoped_fd_t closer(worker_socket);
}
}
private:
scoped_fd_t socket;
};
extproc_spawner_t::extproc_spawner_t() :
spawner_pid(-1)
{
// TODO: guarantee we aren't in a thread pool
guarantee(instance == NULL);
instance = this;
fork_spawner();
}
extproc_spawner_t::~extproc_spawner_t() {
// TODO: guarantee we aren't in a thread pool
guarantee(instance == this);
instance = NULL;
// This should trigger the spawner to exit
spawner_socket.reset();
// Wait on the spawner's return value to clean up the process
int status;
int res = waitpid(spawner_pid, &status, 0);
guarantee_err(res == spawner_pid, "failed to wait for extproc spawner process to exit");
}
extproc_spawner_t *extproc_spawner_t::get_instance() {
return instance;
}
void extproc_spawner_t::fork_spawner() {
guarantee(spawner_socket.get() == INVALID_FD);
fd_t fds[2];
int res = socketpair(AF_UNIX, SOCK_STREAM, 0, fds);
guarantee_err(res == 0, "could not create socket pair for spawner process");
res = ::fork();
if (res == 0) {
// This is the spawner process, just instantiate ourselves and handle requests
do {
res = ::close(fds[0]);
} while (res == 0 && errno == EINTR);
spawner_run_t spawner(fds[1]);
spawner.main_loop();
::_exit(EXIT_SUCCESS);
}
spawner_pid = res;
guarantee_err(spawner_pid != -1, "could not fork spawner process");
scoped_fd_t closer(fds[1]);
spawner_socket.reset(fds[0]);
}
// Spawns a new worker process and returns the fd of the socket used to communicate with it
fd_t extproc_spawner_t::spawn(object_buffer_t<socket_stream_t> *stream_out, pid_t *pid_out) {
guarantee(spawner_socket.get() != INVALID_FD);
fd_t fds[2];
int res = socketpair(AF_UNIX, SOCK_STREAM, 0, fds);
guarantee_err(res == 0, "could not create socket pair for worker process");
res = send_fds(spawner_socket.get(), 1, &fds[1]);
guarantee_err(res == 0, "could not send socket file descriptor to worker process");
stream_out->create(fds[0], reinterpret_cast<fd_watcher_t*>(NULL));
// Get the pid of the new worker process
archive_result_t archive_res;
archive_res = deserialize(stream_out->get(), pid_out);
guarantee_deserialization(archive_res, "pid_out");
guarantee(*pid_out != -1);
scoped_fd_t closer(fds[1]);
return fds[0];
}
<|endoftext|> |
<commit_before>/// fileistream
// An istream interface for reading files.
// @module fileistream
#include "FileIStream.h"
#include "Poco/Exception.h"
#include <iostream>
int luaopen_poco_fileistream(lua_State* L)
{
return LuaPoco::loadConstructor(L, LuaPoco::FileIStreamUserdata::FileIStream);
}
namespace LuaPoco
{
const char* POCO_FILEISTREAM_METATABLE_NAME = "Poco.FileIStream.metatable";
FileIStreamUserdata::FileIStreamUserdata(const std::string& path)
: mFileInputStream(path)
{
}
FileIStreamUserdata::~FileIStreamUserdata()
{
}
std::istream& FileIStreamUserdata::istream()
{
return mFileInputStream;
}
// register metatable for this class
bool FileIStreamUserdata::registerFileIStream(lua_State* L)
{
struct UserdataMethod methods[] =
{
{ "__gc", metamethod__gc },
{ "__tostring", metamethod__tostring },
{ "read", read },
{ "lines", lines },
{ "seek", seek },
{ "close", close },
{ NULL, NULL}
};
setupUserdataMetatable(L, POCO_FILEISTREAM_METATABLE_NAME, methods);
return true;
}
/// Constructs a new fileistream userdata.
// @string path to file.
// @return userdata or nil. (error)
// @return error message.
// @function new
// @see istream
int FileIStreamUserdata::FileIStream(lua_State* L)
{
int rv = 0;
int firstArg = lua_istable(L, 1) ? 2 : 1;
const char* path = luaL_checkstring(L, firstArg);
try
{
FileIStreamUserdata* fisud = new(lua_newuserdata(L, sizeof *fisud)) FileIStreamUserdata(path);
setupPocoUserdata(L, fisud, POCO_FILEISTREAM_METATABLE_NAME);
rv = 1;
}
catch (const Poco::Exception& e)
{
rv = pushPocoException(L, e);
}
catch (...)
{
rv = pushUnknownException(L);
}
return rv;
}
// metamethod infrastructure
int FileIStreamUserdata::metamethod__tostring(lua_State* L)
{
FileIStreamUserdata* fisud = checkPrivateUserdata<FileIStreamUserdata>(L, 1);
lua_pushfstring(L, "Poco.FileIStream (%p)", static_cast<void*>(fisud));
return 1;
}
// methods
/// Closes fileinputstream.
// @function close
int FileIStreamUserdata::close(lua_State* L)
{
FileIStreamUserdata* fisud = checkPrivateUserdata<FileIStreamUserdata>(L, 1);
fisud->mFileInputStream.close();
return 0;
}
} // LuaPoco
<commit_msg>fix some ldoc on FileIStream.<commit_after>/// fileistream
// An istream interface for reading files.
// @module fileistream
#include "FileIStream.h"
#include "Poco/Exception.h"
int luaopen_poco_fileistream(lua_State* L)
{
return LuaPoco::loadConstructor(L, LuaPoco::FileIStreamUserdata::FileIStream);
}
namespace LuaPoco
{
const char* POCO_FILEISTREAM_METATABLE_NAME = "Poco.FileIStream.metatable";
FileIStreamUserdata::FileIStreamUserdata(const std::string& path)
: mFileInputStream(path)
{
}
FileIStreamUserdata::~FileIStreamUserdata()
{
}
std::istream& FileIStreamUserdata::istream()
{
return mFileInputStream;
}
// register metatable for this class
bool FileIStreamUserdata::registerFileIStream(lua_State* L)
{
struct UserdataMethod methods[] =
{
{ "__gc", metamethod__gc },
{ "__tostring", metamethod__tostring },
{ "read", read },
{ "lines", lines },
{ "seek", seek },
{ "close", close },
{ NULL, NULL}
};
setupUserdataMetatable(L, POCO_FILEISTREAM_METATABLE_NAME, methods);
return true;
}
/// Constructs a new fileistream userdata.
// @string path to file.
// @return userdata or nil. (error)
// @return error message.
// @function new
// @see istream
int FileIStreamUserdata::FileIStream(lua_State* L)
{
int rv = 0;
int firstArg = lua_istable(L, 1) ? 2 : 1;
const char* path = luaL_checkstring(L, firstArg);
try
{
FileIStreamUserdata* fisud = new(lua_newuserdata(L, sizeof *fisud)) FileIStreamUserdata(path);
setupPocoUserdata(L, fisud, POCO_FILEISTREAM_METATABLE_NAME);
rv = 1;
}
catch (const Poco::Exception& e)
{
rv = pushPocoException(L, e);
}
catch (...)
{
rv = pushUnknownException(L);
}
return rv;
}
// metamethod infrastructure
int FileIStreamUserdata::metamethod__tostring(lua_State* L)
{
FileIStreamUserdata* fisud = checkPrivateUserdata<FileIStreamUserdata>(L, 1);
lua_pushfstring(L, "Poco.FileIStream (%p)", static_cast<void*>(fisud));
return 1;
}
// methods
/// Closes fileistream.
// @function close
int FileIStreamUserdata::close(lua_State* L)
{
FileIStreamUserdata* fisud = checkPrivateUserdata<FileIStreamUserdata>(L, 1);
fisud->mFileInputStream.close();
return 0;
}
} // LuaPoco
<|endoftext|> |
<commit_before>// Copyright (c) 2020 ASMlover. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list ofconditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materialsprovided 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 "harness.hh"
#include "token.hh"
TADPOLE_TEST(TadpoleToken) {
using TK = tadpole::TokenKind;
#define NEWTK2(k, s) tadpole::Token(k, s, 0)
#define NEWTK3(k, s, n) tadpole::Token(k, s, n)
#define TEST_EQ(a, b) TADPOLE_CHECK_EQ(a, b)
#define TEST_TK(k, s) {\
auto t = NEWTK2(k, s);\
TEST_EQ(t.kind(), k);\
TEST_EQ(t.literal(), s);\
TEST_EQ(t.lineno(), 0);\
}
#define TEST_STR(s, n) {\
auto t = NEWTK3(TK::TK_STRING, s, n);\
TEST_EQ(t.kind(), TK::TK_STRING);\
TEST_EQ(t.as_string(), s);\
TEST_EQ(t.lineno(), n);\
}
TEST_TK(TK::TK_LPAREN, "(")
TEST_TK(TK::TK_RPAREN, ")")
TEST_TK(TK::TK_LBRACE, "{")
TEST_TK(TK::TK_RBRACE, "}")
TEST_TK(TK::TK_COMMA, ",")
TEST_TK(TK::TK_MINUS, "-")
TEST_TK(TK::TK_PLUS, "+")
TEST_TK(TK::TK_SEMI, ";")
TEST_TK(TK::TK_SLASH, "/")
TEST_TK(TK::TK_STAR, "*")
TEST_TK(TK::TK_EQ, "=")
TEST_TK(TK::KW_FALSE, "false")
TEST_TK(TK::KW_FN, "fn")
TEST_TK(TK::KW_NIL, "nil")
TEST_TK(TK::KW_TRUE, "true")
TEST_TK(TK::KW_VAR, "var")
TEST_TK(TK::TK_EOF, "")
TEST_TK(TK::TK_ERR, "")
// test for TK_IDENTIFIER
TEST_TK(TK::TK_IDENTIFIER, "foo")
TEST_TK(TK::TK_IDENTIFIER, "bar")
TEST_TK(TK::TK_IDENTIFIER, "_Count")
TEST_TK(TK::TK_IDENTIFIER, "_Foo1")
TEST_TK(TK::TK_IDENTIFIER, "_Bar1")
// test for TK_NUMERIC
{
auto t = NEWTK2(TK::TK_NUMERIC, "100");
TEST_EQ(t.kind(), TK::TK_NUMERIC);
TEST_EQ(t.as_numeric(), 100);
TEST_EQ(t.lineno(), 0);
auto t2 = NEWTK2(TK::TK_NUMERIC, "3.14");
TEST_EQ(t2.kind(), TK::TK_NUMERIC);
TEST_EQ(t2.as_numeric(), 3.14);
TEST_EQ(t2.lineno(), 0);
}
// test for TK_STRING
TEST_STR("Hello", 5)
TEST_STR("This is a test string", 56)
TEST_STR("xxx", 3)
#undef TEST_STR
#undef TEST_EQ
#undef NEWTK3
#undef NEWTK2
}
<commit_msg>:white_check_mark: test(token): updated the token testing<commit_after>// Copyright (c) 2020 ASMlover. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list ofconditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materialsprovided 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 "harness.hh"
#include "token.hh"
TADPOLE_TEST(TadpoleToken) {
using TK = tadpole::TokenKind;
#define NEWTK2(k, s) tadpole::Token(k, s, 0)
#define NEWTK3(k, s, n) tadpole::Token(k, s, n)
#define TEST_EQ(a, b) TADPOLE_CHECK_EQ(a, b)
#define TEST_TK(k, s) do {\
auto t = NEWTK2(k, s);\
TEST_EQ(t.kind(), k);\
TEST_EQ(t.literal(), s);\
TEST_EQ(t.lineno(), 0);\
} while (false)
#define TEST_STR(s, n) do {\
auto t = NEWTK3(TK::TK_STRING, s, n);\
TEST_EQ(t.kind(), TK::TK_STRING);\
TEST_EQ(t.as_string(), s);\
TEST_EQ(t.lineno(), n);\
} while (false)
TEST_TK(TK::TK_LPAREN, "(");
TEST_TK(TK::TK_RPAREN, ")");
TEST_TK(TK::TK_LBRACE, "{");
TEST_TK(TK::TK_RBRACE, "}");
TEST_TK(TK::TK_COMMA, ",");
TEST_TK(TK::TK_MINUS, "-");
TEST_TK(TK::TK_PLUS, "+");
TEST_TK(TK::TK_SEMI, ";");
TEST_TK(TK::TK_SLASH, "/");
TEST_TK(TK::TK_STAR, "*");
TEST_TK(TK::TK_EQ, "=");
TEST_TK(TK::KW_FALSE, "false");
TEST_TK(TK::KW_FN, "fn");
TEST_TK(TK::KW_NIL, "nil");
TEST_TK(TK::KW_TRUE, "true");
TEST_TK(TK::KW_VAR, "var");
TEST_TK(TK::TK_EOF, "");
TEST_TK(TK::TK_ERR, "");
// test for TK_IDENTIFIER
TEST_TK(TK::TK_IDENTIFIER, "foo");
TEST_TK(TK::TK_IDENTIFIER, "bar");
TEST_TK(TK::TK_IDENTIFIER, "_Count");
TEST_TK(TK::TK_IDENTIFIER, "_Foo1");
TEST_TK(TK::TK_IDENTIFIER, "_Bar1");
// test for TK_NUMERIC
{
auto t = NEWTK2(TK::TK_NUMERIC, "100");
TEST_EQ(t.kind(), TK::TK_NUMERIC);
TEST_EQ(t.as_numeric(), 100);
TEST_EQ(t.lineno(), 0);
auto t2 = NEWTK2(TK::TK_NUMERIC, "3.14");
TEST_EQ(t2.kind(), TK::TK_NUMERIC);
TEST_EQ(t2.as_numeric(), 3.14);
TEST_EQ(t2.lineno(), 0);
}
// test for TK_STRING
TEST_STR("Hello", 5);
TEST_STR("This is a test string", 56);
TEST_STR("xxx", 3);
#undef TEST_STR
#undef TEST_EQ
#undef NEWTK3
#undef NEWTK2
}
<|endoftext|> |
<commit_before>/** \file patch_up_ppns_for_k10plus.cc
* \brief Swaps out all persistent old PPN's with new PPN's.
* \author Dr. Johannes Ruscheinski
*/
/*
Copyright (C) 2019, Library of the University of Tübingen
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero 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, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <memory>
#include <unordered_map>
#include <unordered_set>
#include <cstdlib>
#include <cstring>
#include <kchashdb.h>
#include "Compiler.h"
#include "ControlNumberGuesser.h"
#include "DbConnection.h"
#include "DbResultSet.h"
#include "DbRow.h"
#include "FileUtil.h"
#include "MARC.h"
#include "StringUtil.h"
#include "UBTools.h"
#include "util.h"
#include "VuFind.h"
namespace {
void UpdateKyotokabinetDB(const std::string &db_path, const std::unordered_map<std::string, std::string> &old_to_new_map) {
kyotocabinet::HashDB db;
if (not (db.open(db_path, kyotocabinet::HashDB::OWRITER | kyotocabinet::HashDB::OREADER | kyotocabinet::HashDB::OCREATE)))
LOG_ERROR("Failed to open or create \"" + db_path + "\"!");
unsigned new_entry_count(0);
for (const auto &old_and_new : old_to_new_map) {
std::string value;
if (db.get(old_and_new.first, &value)) {
if (unlikely(value != old_and_new.second))
LOG_ERROR("entry for key \"" + old_and_new.first + "\" in database \"" + value + "\" is different from new new PPN \""
+ old_and_new.second + "\"!");
} else {
if (unlikely(not db.add(old_and_new.first, old_and_new.second)))
LOG_ERROR("failed to insert a new entry (\"" + old_and_new.first + "\",\"" + old_and_new.second + "\") into \"" + db_path
+ "\"!");
++new_entry_count;
}
}
LOG_INFO("Updated \"" + db_path + "\" with " + std::to_string(new_entry_count) + " entry/entries.");
}
const std::string OLD_PPN_LIST_FILE(UBTools::GetTuelibPath() + "alread_replaced_old_ppns.blob");
constexpr size_t OLD_PPN_LENGTH(9);
void LoadAlreadyProcessedPPNs(std::unordered_set<std::string> * const alread_processed_ppns) {
if (not FileUtil::Exists(OLD_PPN_LIST_FILE))
return;
std::string blob;
FileUtil::ReadStringOrDie(OLD_PPN_LIST_FILE, &blob);
if (unlikely((blob.length() % OLD_PPN_LENGTH) != 0))
LOG_ERROR("fractional PPN's are not possible!");
const size_t count(blob.length() / OLD_PPN_LENGTH);
alread_processed_ppns->reserve(count);
for (size_t i(0); i < count; ++i)
alread_processed_ppns->emplace(blob.substr(i * OLD_PPN_LENGTH, OLD_PPN_LENGTH));
}
void LoadMapping(MARC::Reader * const marc_reader, const std::unordered_set<std::string> &alread_processed_ppns,
std::unordered_map<std::string, std::string> * const old_to_new_map)
{
while (const auto record = marc_reader->read()) {
for (const auto &field : record.getTagRange("035")) {
const auto subfield_a(field.getFirstSubfieldWithCode('a'));
if (StringUtil::StartsWith(subfield_a, "(DE-627)")) {
const auto old_ppn(subfield_a.substr(__builtin_strlen("(DE-627)")));
if (alread_processed_ppns.find(old_ppn) == alread_processed_ppns.cend())
old_to_new_map->emplace(old_ppn, record.getControlNumber());
}
}
}
LOG_INFO("Found " + std::to_string(old_to_new_map->size()) + " new mappings of old PPN's to new PPN's in \"" + marc_reader->getPath()
+ "\".\n");
}
void PatchTable(DbConnection * const db_connection, const std::string &table, const std::string &column,
const std::unordered_map<std::string, std::string> &old_to_new_map)
{
db_connection->queryOrDie("SELECT DISTINCT " + column + " FROM " + table);
auto result_set(db_connection->getLastResultSet());
unsigned replacement_count(0);
while (const DbRow row = result_set.getNextRow()) {
const auto old_and_new(old_to_new_map.find(row[column]));
if (old_and_new != old_to_new_map.cend()) {
db_connection->queryOrDie("UPDATE IGNORE " + table + " SET " + column + "='" + old_and_new->second
+ "' WHERE " + column + "='" + old_and_new->first + "'");
++replacement_count;
}
}
LOG_INFO("Replaced " + std::to_string(replacement_count) + " PPN's in ixtheo.keyword_translations.");
}
void StoreNewAlreadyProcessedPPNs(const std::unordered_set<std::string> &alread_processed_ppns,
const std::unordered_map<std::string, std::string> &old_to_new_map)
{
std::string blob;
blob.reserve(alread_processed_ppns.size() * OLD_PPN_LENGTH + old_to_new_map.size() * OLD_PPN_LENGTH);
for (const auto &alread_processed_ppn : alread_processed_ppns)
blob += alread_processed_ppn;
for (const auto &old_and_new_ppns : old_to_new_map)
blob += old_and_new_ppns.first;
FileUtil::WriteStringOrDie(OLD_PPN_LIST_FILE, blob);
}
void PatchNotifiedDB(const std::string &user_type, const std::unordered_map<std::string, std::string> &old_to_new_map) {
const std::string DB_FILENAME(UBTools::GetTuelibPath() + user_type + "_notified.db");
std::unique_ptr<kyotocabinet::HashDB> db(new kyotocabinet::HashDB());
if (not (db->open(DB_FILENAME, kyotocabinet::HashDB::OWRITER | kyotocabinet::HashDB::OREADER))) {
LOG_INFO("\"" + DB_FILENAME + "\" not found!");
return;
}
unsigned updated_count(0);
for (const auto &old_and_new : old_to_new_map) {
std::string value;
if (db->get(old_and_new.first, &value)) {
if (unlikely(not db->remove(old_and_new.first)))
LOG_ERROR("failed to remove key \"" + old_and_new.first + "\" from \"" + DB_FILENAME + "\"!");
if (unlikely(not db->add(old_and_new.second, value)))
LOG_ERROR("failed to add key \"" + old_and_new.second + "\" from \"" + DB_FILENAME + "\"!");
++updated_count;
}
}
LOG_INFO("Updated " + std::to_string(updated_count) + " entries in \"" + DB_FILENAME + "\".");
}
} // unnamed namespace
int Main(int argc, char **argv) {
::progname = argv[0];
if (argc < 3)
::Usage("kyotokabinet_db_path marc_input1 [marc_input2 .. marc_inputN]");
std::unordered_set<std::string> alread_processed_ppns;
LoadAlreadyProcessedPPNs(&alread_processed_ppns);
std::unordered_map<std::string, std::string> old_to_new_map;
for (int arg_no(1); arg_no < argc; ++arg_no) {
const auto marc_reader(MARC::Reader::Factory(argv[arg_no]));
LoadMapping(marc_reader.get(), alread_processed_ppns, &old_to_new_map);
}
if (old_to_new_map.empty()) {
LOG_INFO("nothing to do!");
return EXIT_SUCCESS;
}
UpdateKyotokabinetDB(argv[1], old_to_new_map);
PatchNotifiedDB("ixtheo", old_to_new_map);
PatchNotifiedDB("relbib", old_to_new_map);
ControlNumberGuesser control_number_guesser;
control_number_guesser.swapControlNumbers(old_to_new_map);
std::shared_ptr<DbConnection> db_connection(VuFind::GetDbConnection());
PatchTable(db_connection.get(), "vufind.resource", "record_id", old_to_new_map);
PatchTable(db_connection.get(), "vufind.record", "record_id", old_to_new_map);
PatchTable(db_connection.get(), "vufind.change_tracker", "id", old_to_new_map);
if (VuFind::GetTueFindFlavour() == "ixtheo") {
PatchTable(db_connection.get(), "ixtheo.keyword_translations", "ppn", old_to_new_map);
PatchTable(db_connection.get(), "vufind.ixtheo_journal_subscriptions", "journal_control_number_or_bundle_name", old_to_new_map);
PatchTable(db_connection.get(), "vufind.ixtheo_pda_subscriptions", "book_ppn", old_to_new_map);
PatchTable(db_connection.get(), "vufind.relbib_ids", "record_id", old_to_new_map);
PatchTable(db_connection.get(), "vufind.bibstudies_ids", "record_id", old_to_new_map);
} else {
PatchTable(db_connection.get(), "vufind.full_text_cache", "id", old_to_new_map);
PatchTable(db_connection.get(), "vufind.full_text_cache_urls", "id", old_to_new_map);
}
StoreNewAlreadyProcessedPPNs(alread_processed_ppns, old_to_new_map);
return EXIT_SUCCESS;
}
<commit_msg>Microoptimization.<commit_after>/** \file patch_up_ppns_for_k10plus.cc
* \brief Swaps out all persistent old PPN's with new PPN's.
* \author Dr. Johannes Ruscheinski
*/
/*
Copyright (C) 2019, Library of the University of Tübingen
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero 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, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <memory>
#include <unordered_map>
#include <unordered_set>
#include <cstdlib>
#include <cstring>
#include <kchashdb.h>
#include "Compiler.h"
#include "ControlNumberGuesser.h"
#include "DbConnection.h"
#include "DbResultSet.h"
#include "DbRow.h"
#include "FileUtil.h"
#include "MARC.h"
#include "StringUtil.h"
#include "UBTools.h"
#include "util.h"
#include "VuFind.h"
namespace {
void UpdateKyotokabinetDB(const std::string &db_path, const std::unordered_map<std::string, std::string> &old_to_new_map) {
kyotocabinet::HashDB db;
if (not (db.open(db_path, kyotocabinet::HashDB::OWRITER | kyotocabinet::HashDB::OREADER | kyotocabinet::HashDB::OCREATE)))
LOG_ERROR("Failed to open or create \"" + db_path + "\"!");
unsigned new_entry_count(0);
for (const auto &old_and_new : old_to_new_map) {
std::string value;
if (db.get(old_and_new.first, &value)) {
if (unlikely(value != old_and_new.second))
LOG_ERROR("entry for key \"" + old_and_new.first + "\" in database \"" + value + "\" is different from new new PPN \""
+ old_and_new.second + "\"!");
} else {
if (unlikely(not db.add(old_and_new.first, old_and_new.second)))
LOG_ERROR("failed to insert a new entry (\"" + old_and_new.first + "\",\"" + old_and_new.second + "\") into \"" + db_path
+ "\"!");
++new_entry_count;
}
}
LOG_INFO("Updated \"" + db_path + "\" with " + std::to_string(new_entry_count) + " entry/entries.");
}
const std::string OLD_PPN_LIST_FILE(UBTools::GetTuelibPath() + "alread_replaced_old_ppns.blob");
constexpr size_t OLD_PPN_LENGTH(9);
void LoadAlreadyProcessedPPNs(std::unordered_set<std::string> * const alread_processed_ppns) {
if (not FileUtil::Exists(OLD_PPN_LIST_FILE))
return;
std::string blob;
FileUtil::ReadStringOrDie(OLD_PPN_LIST_FILE, &blob);
if (unlikely((blob.length() % OLD_PPN_LENGTH) != 0))
LOG_ERROR("fractional PPN's are not possible!");
const size_t count(blob.length() / OLD_PPN_LENGTH);
alread_processed_ppns->reserve(count);
for (size_t i(0); i < count; ++i)
alread_processed_ppns->emplace(blob.substr(i * OLD_PPN_LENGTH, OLD_PPN_LENGTH));
}
void LoadMapping(MARC::Reader * const marc_reader, const std::unordered_set<std::string> &alread_processed_ppns,
std::unordered_map<std::string, std::string> * const old_to_new_map)
{
while (const auto record = marc_reader->read()) {
for (const auto &field : record.getTagRange("035")) {
const auto subfield_a(field.getFirstSubfieldWithCode('a'));
if (StringUtil::StartsWith(subfield_a, "(DE-627)")) {
const auto old_ppn(subfield_a.substr(__builtin_strlen("(DE-627)")));
if (alread_processed_ppns.find(old_ppn) == alread_processed_ppns.cend())
old_to_new_map->emplace(old_ppn, record.getControlNumber());
}
}
}
LOG_INFO("Found " + std::to_string(old_to_new_map->size()) + " new mappings of old PPN's to new PPN's in \"" + marc_reader->getPath()
+ "\".\n");
}
void PatchTable(DbConnection * const db_connection, const std::string &table, const std::string &column,
const std::unordered_map<std::string, std::string> &old_to_new_map)
{
db_connection->queryOrDie("SELECT DISTINCT " + column + " FROM " + table);
auto result_set(db_connection->getLastResultSet());
unsigned replacement_count(0);
while (const DbRow row = result_set.getNextRow()) {
const auto old_and_new(old_to_new_map.find(row[column]));
if (old_and_new != old_to_new_map.cend()) {
db_connection->queryOrDie("UPDATE IGNORE " + table + " SET " + column + "='" + old_and_new->second
+ "' WHERE " + column + "='" + old_and_new->first + "'");
++replacement_count;
}
}
LOG_INFO("Replaced " + std::to_string(replacement_count) + " PPN's in ixtheo.keyword_translations.");
}
void StoreNewAlreadyProcessedPPNs(const std::unordered_set<std::string> &alread_processed_ppns,
const std::unordered_map<std::string, std::string> &old_to_new_map)
{
std::string blob;
blob.reserve(alread_processed_ppns.size() * OLD_PPN_LENGTH + old_to_new_map.size() * OLD_PPN_LENGTH);
for (const auto &alread_processed_ppn : alread_processed_ppns)
blob += alread_processed_ppn;
for (const auto &old_and_new_ppns : old_to_new_map)
blob += old_and_new_ppns.first;
FileUtil::WriteStringOrDie(OLD_PPN_LIST_FILE, blob);
}
void PatchNotifiedDB(const std::string &user_type, const std::unordered_map<std::string, std::string> &old_to_new_map) {
const std::string DB_FILENAME(UBTools::GetTuelibPath() + user_type + "_notified.db");
std::unique_ptr<kyotocabinet::HashDB> db(new kyotocabinet::HashDB());
if (not (db->open(DB_FILENAME, kyotocabinet::HashDB::OWRITER | kyotocabinet::HashDB::OREADER))) {
LOG_INFO("\"" + DB_FILENAME + "\" not found!");
return;
}
unsigned updated_count(0);
for (const auto &old_and_new : old_to_new_map) {
std::string value;
if (db->get(old_and_new.first, &value)) {
if (unlikely(not db->remove(old_and_new.first)))
LOG_ERROR("failed to remove key \"" + old_and_new.first + "\" from \"" + DB_FILENAME + "\"!");
if (unlikely(not db->add(old_and_new.second, value)))
LOG_ERROR("failed to add key \"" + old_and_new.second + "\" from \"" + DB_FILENAME + "\"!");
++updated_count;
}
}
LOG_INFO("Updated " + std::to_string(updated_count) + " entries in \"" + DB_FILENAME + "\".");
}
} // unnamed namespace
int Main(int argc, char **argv) {
if (argc < 3)
::Usage("kyotokabinet_db_path marc_input1 [marc_input2 .. marc_inputN]");
std::unordered_set<std::string> alread_processed_ppns;
LoadAlreadyProcessedPPNs(&alread_processed_ppns);
std::unordered_map<std::string, std::string> old_to_new_map;
for (int arg_no(1); arg_no < argc; ++arg_no) {
const auto marc_reader(MARC::Reader::Factory(argv[arg_no]));
LoadMapping(marc_reader.get(), alread_processed_ppns, &old_to_new_map);
}
if (old_to_new_map.empty()) {
LOG_INFO("nothing to do!");
return EXIT_SUCCESS;
}
UpdateKyotokabinetDB(argv[1], old_to_new_map);
PatchNotifiedDB("ixtheo", old_to_new_map);
PatchNotifiedDB("relbib", old_to_new_map);
ControlNumberGuesser control_number_guesser;
control_number_guesser.swapControlNumbers(old_to_new_map);
std::shared_ptr<DbConnection> db_connection(VuFind::GetDbConnection());
PatchTable(db_connection.get(), "vufind.resource", "record_id", old_to_new_map);
PatchTable(db_connection.get(), "vufind.record", "record_id", old_to_new_map);
PatchTable(db_connection.get(), "vufind.change_tracker", "id", old_to_new_map);
if (VuFind::GetTueFindFlavour() == "ixtheo") {
PatchTable(db_connection.get(), "ixtheo.keyword_translations", "ppn", old_to_new_map);
PatchTable(db_connection.get(), "vufind.ixtheo_journal_subscriptions", "journal_control_number_or_bundle_name", old_to_new_map);
PatchTable(db_connection.get(), "vufind.ixtheo_pda_subscriptions", "book_ppn", old_to_new_map);
PatchTable(db_connection.get(), "vufind.relbib_ids", "record_id", old_to_new_map);
PatchTable(db_connection.get(), "vufind.bibstudies_ids", "record_id", old_to_new_map);
} else {
PatchTable(db_connection.get(), "vufind.full_text_cache", "id", old_to_new_map);
PatchTable(db_connection.get(), "vufind.full_text_cache_urls", "id", old_to_new_map);
}
StoreNewAlreadyProcessedPPNs(alread_processed_ppns, old_to_new_map);
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/***********************************************************************************************************************
* Copyright (C) 2016 Andrew Zonenberg and contributors *
* *
* This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General *
* Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) *
* any later version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for *
* more details. *
* *
* You should have received a copy of the GNU Lesser General Public License along with this program; if not, you may *
* find one here: *
* https://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt *
* or you may search the http://www.gnu.org website for the version 2.1 license, or you may write to the Free Software *
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA *
**********************************************************************************************************************/
#include "Greenpak4.h"
using namespace std;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Construction / destruction
Greenpak4LUT::Greenpak4LUT(
Greenpak4Device* device,
unsigned int lutnum,
unsigned int matrix,
unsigned int ibase,
unsigned int oword,
unsigned int cbase,
unsigned int order)
: Greenpak4BitstreamEntity(device, matrix, ibase, oword, cbase)
, m_lutnum(lutnum)
, m_order(order)
, m_inputs({device->GetGround(), device->GetGround(), device->GetGround(), device->GetGround()})
{
for(unsigned int i=0; i<16; i++)
m_truthtable[i] = false;
}
Greenpak4LUT::~Greenpak4LUT()
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Serialization of the truth table
bool Greenpak4LUT::Load(bool* bitstream)
{
//TODO: Do our inputs
//Do the LUT
unsigned int nmax = 1 << m_order;
for(unsigned int i=0; i<nmax; i++)
m_truthtable[i] = bitstream[m_configBase + i];
return true;
}
bool Greenpak4LUT::Save(bool* bitstream)
{
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// INPUT BUS
for(unsigned int i=0; i<m_order; i++)
{
if(!WriteMatrixSelector(bitstream, m_inputBaseWord + i, m_inputs[i]))
return false;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// LUT CONTENTS
unsigned int nmax = 1 << m_order;
for(unsigned int i=0; i<nmax; i++)
bitstream[m_configBase + i] = m_truthtable[i];
return true;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Accessors
void Greenpak4LUT::CommitChanges()
{
//Get our cell, or bail if we're unassigned
auto ncell = dynamic_cast<Greenpak4NetlistCell*>(GetNetlistEntity());
if(ncell == NULL)
return;
for(auto x : ncell->m_parameters)
{
//LUT initialization value, as decimal
if(x.first == "INIT")
{
//convert to bit array format for the bitstream library
uint32_t truth_table = atoi(x.second.c_str());
unsigned int nbits = 1 << m_order;
for(unsigned int i=0; i<nbits; i++)
{
bool a3 = (i & 8) ? true : false;
bool a2 = (i & 4) ? true : false;
bool a1 = (i & 2) ? true : false;
bool a0 = (i & 1) ? true : false;
m_truthtable[a3*8 | a2*4 | a1*2 | a0] = (truth_table & (1 << i)) ? true : false;
}
}
else
{
printf("WARNING: Cell\"%s\" has unrecognized parameter %s, ignoring\n",
ncell->m_name.c_str(), x.first.c_str());
}
}
}
vector<string> Greenpak4LUT::GetInputPorts() const
{
vector<string> r;
switch(m_order)
{
case 4: r.push_back("IN3");
case 3: r.push_back("IN2");
case 2: r.push_back("IN1");
case 1: r.push_back("IN0");
default:
break;
}
return r;
}
void Greenpak4LUT::SetInput(string port, Greenpak4EntityOutput src)
{
if(port == "IN0")
m_inputs[0] = src;
else if(port == "IN1")
m_inputs[1] = src;
else if(port == "IN2")
m_inputs[2] = src;
else if(port == "IN3")
m_inputs[3] = src;
//ignore anything else silently (should not be possible since synthesis would error out)
}
vector<string> Greenpak4LUT::GetOutputPorts() const
{
vector<string> r;
r.push_back("OUT");
return r;
}
unsigned int Greenpak4LUT::GetOutputNetNumber(string port)
{
if(port == "OUT")
return m_outputBaseWord;
else
return -1;
}
string Greenpak4LUT::GetDescription()
{
char buf[128];
snprintf(buf, sizeof(buf), "LUT%d_%d", m_order, m_lutnum);
return string(buf);
}
<commit_msg>Fix GNU-ism (parenthesized initialization of a member array).<commit_after>/***********************************************************************************************************************
* Copyright (C) 2016 Andrew Zonenberg and contributors *
* *
* This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General *
* Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) *
* any later version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for *
* more details. *
* *
* You should have received a copy of the GNU Lesser General Public License along with this program; if not, you may *
* find one here: *
* https://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt *
* or you may search the http://www.gnu.org website for the version 2.1 license, or you may write to the Free Software *
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA *
**********************************************************************************************************************/
#include "Greenpak4.h"
using namespace std;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Construction / destruction
Greenpak4LUT::Greenpak4LUT(
Greenpak4Device* device,
unsigned int lutnum,
unsigned int matrix,
unsigned int ibase,
unsigned int oword,
unsigned int cbase,
unsigned int order)
: Greenpak4BitstreamEntity(device, matrix, ibase, oword, cbase)
, m_lutnum(lutnum)
, m_order(order)
, m_inputs{device->GetGround(), device->GetGround(), device->GetGround(), device->GetGround()}
{
for(unsigned int i=0; i<16; i++)
m_truthtable[i] = false;
}
Greenpak4LUT::~Greenpak4LUT()
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Serialization of the truth table
bool Greenpak4LUT::Load(bool* bitstream)
{
//TODO: Do our inputs
//Do the LUT
unsigned int nmax = 1 << m_order;
for(unsigned int i=0; i<nmax; i++)
m_truthtable[i] = bitstream[m_configBase + i];
return true;
}
bool Greenpak4LUT::Save(bool* bitstream)
{
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// INPUT BUS
for(unsigned int i=0; i<m_order; i++)
{
if(!WriteMatrixSelector(bitstream, m_inputBaseWord + i, m_inputs[i]))
return false;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// LUT CONTENTS
unsigned int nmax = 1 << m_order;
for(unsigned int i=0; i<nmax; i++)
bitstream[m_configBase + i] = m_truthtable[i];
return true;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Accessors
void Greenpak4LUT::CommitChanges()
{
//Get our cell, or bail if we're unassigned
auto ncell = dynamic_cast<Greenpak4NetlistCell*>(GetNetlistEntity());
if(ncell == NULL)
return;
for(auto x : ncell->m_parameters)
{
//LUT initialization value, as decimal
if(x.first == "INIT")
{
//convert to bit array format for the bitstream library
uint32_t truth_table = atoi(x.second.c_str());
unsigned int nbits = 1 << m_order;
for(unsigned int i=0; i<nbits; i++)
{
bool a3 = (i & 8) ? true : false;
bool a2 = (i & 4) ? true : false;
bool a1 = (i & 2) ? true : false;
bool a0 = (i & 1) ? true : false;
m_truthtable[a3*8 | a2*4 | a1*2 | a0] = (truth_table & (1 << i)) ? true : false;
}
}
else
{
printf("WARNING: Cell\"%s\" has unrecognized parameter %s, ignoring\n",
ncell->m_name.c_str(), x.first.c_str());
}
}
}
vector<string> Greenpak4LUT::GetInputPorts() const
{
vector<string> r;
switch(m_order)
{
case 4: r.push_back("IN3");
case 3: r.push_back("IN2");
case 2: r.push_back("IN1");
case 1: r.push_back("IN0");
default:
break;
}
return r;
}
void Greenpak4LUT::SetInput(string port, Greenpak4EntityOutput src)
{
if(port == "IN0")
m_inputs[0] = src;
else if(port == "IN1")
m_inputs[1] = src;
else if(port == "IN2")
m_inputs[2] = src;
else if(port == "IN3")
m_inputs[3] = src;
//ignore anything else silently (should not be possible since synthesis would error out)
}
vector<string> Greenpak4LUT::GetOutputPorts() const
{
vector<string> r;
r.push_back("OUT");
return r;
}
unsigned int Greenpak4LUT::GetOutputNetNumber(string port)
{
if(port == "OUT")
return m_outputBaseWord;
else
return -1;
}
string Greenpak4LUT::GetDescription()
{
char buf[128];
snprintf(buf, sizeof(buf), "LUT%d_%d", m_order, m_lutnum);
return string(buf);
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <julia.h>
#include "Values.h"
#include "lvalue.h"
using namespace std;
template <typename V,typename E> static shared_ptr<nj::Value> reboxArray(jl_value_t *jlarray)
{
shared_ptr<nj::Value> value;
V *p = (V*)jl_array_data(jlarray);
int ndims = jl_array_ndims(jlarray);
vector<size_t> dims;
cout << "array element type " << E::instance()->getId() << endl;
for(int dim = 0;dim < ndims;dim++) dims.push_back(jl_array_dim(jlarray,dim));
nj::Array<V,E> *array = new nj::Array<V,E>(dims);
value.reset(array);
memcpy(array->ptr(),p,array->size()*sizeof(V));
return value;
}
static shared_ptr<nj::Value> getArrayValue(jl_value_t *jlarray)
{
shared_ptr<nj::Value> value;
jl_value_t *elementType = jl_tparam0(jl_typeof(jlarray));
if(elementType == (jl_value_t*)jl_float64_type) value = reboxArray<double,nj::Float64_t>(jlarray);
else if(elementType == (jl_value_t*)jl_int64_type) value = reboxArray<int64_t,nj::Int64_t>(jlarray);
else if(elementType == (jl_value_t*)jl_int32_type) value = reboxArray<int,nj::Int32_t>(jlarray);
else if(elementType == (jl_value_t*)jl_int8_type) value = reboxArray<char,nj::Char_t>(jlarray);
else if(elementType == (jl_value_t*)jl_float32_type) value = reboxArray<float,nj::Float32_t>(jlarray);
else if(elementType == (jl_value_t*)jl_uint64_type) value = reboxArray<uint64_t,nj::UInt64_t>(jlarray);
else if(elementType == (jl_value_t*)jl_uint32_type) value = reboxArray<unsigned,nj::UInt32_t>(jlarray);
else if(elementType == (jl_value_t*)jl_int16_type) value = reboxArray<short,nj::Int16_t>(jlarray);
else if(elementType == (jl_value_t*)jl_uint8_type) value = reboxArray<unsigned char,nj::UChar_t>(jlarray);
else if(elementType == (jl_value_t*)jl_uint16_type) value = reboxArray<unsigned short,nj::UInt16_t>(jlarray);
return value;
}
vector<shared_ptr<nj::Value>> nj::lvalue(jl_value_t *jlvalue)
{
vector<shared_ptr<nj::Value>> res;
if(jl_is_null(jlvalue))
{
shared_ptr<nj::Value> value(new nj::Null);
res.push_back(value);
}
else if(jl_is_array(jlvalue))
{
cout << "lvalue is array" << endl;
res.push_back(getArrayValue(jlvalue));
}
else
{
shared_ptr<nj::Value> value;
if(jl_is_float64(jlvalue)) value.reset(new nj::Float64(jl_unbox_float64(jlvalue)));
else if(jl_is_int64(jlvalue)) value.reset(new nj::Int64(jl_unbox_int64(jlvalue)));
else if(jl_is_int32(jlvalue)) value.reset(new nj::Int32(jl_unbox_int32(jlvalue)));
else if(jl_is_int8(jlvalue)) value.reset(new nj::Char(jl_unbox_int8(jlvalue)));
else if(jl_is_ascii_string(jlvalue)) value.reset(new nj::String((char*)jl_unbox_voidpointer(jlvalue)));
else if(jl_is_float32(jlvalue)) value.reset(new nj::Float32(jl_unbox_float32(jlvalue)));
else if(jl_is_uint64(jlvalue)) value.reset(new nj::UInt64(jl_unbox_uint64(jlvalue)));
else if(jl_is_uint32(jlvalue)) value.reset(new nj::UInt32(jl_unbox_uint32(jlvalue)));
else if(jl_is_int16(jlvalue)) value.reset(new nj::Int16(jl_unbox_int16(jlvalue)));
else if(jl_is_uint8(jlvalue)) value.reset(new nj::UChar(jl_unbox_uint8(jlvalue)));
else if(jl_is_uint16(jlvalue)) value.reset(new nj::UInt16(jl_unbox_uint16(jlvalue)));
if(value.get()) res.push_back(value);
}
return res;
}
<commit_msg>Debugging ... Added check for null input value in lvalue<commit_after>#include <iostream>
#include <julia.h>
#include "Values.h"
#include "lvalue.h"
using namespace std;
template <typename V,typename E> static shared_ptr<nj::Value> reboxArray(jl_value_t *jlarray)
{
shared_ptr<nj::Value> value;
V *p = (V*)jl_array_data(jlarray);
int ndims = jl_array_ndims(jlarray);
vector<size_t> dims;
cout << "array element type " << E::instance()->getId() << endl;
for(int dim = 0;dim < ndims;dim++) dims.push_back(jl_array_dim(jlarray,dim));
nj::Array<V,E> *array = new nj::Array<V,E>(dims);
value.reset(array);
memcpy(array->ptr(),p,array->size()*sizeof(V));
return value;
}
static shared_ptr<nj::Value> getArrayValue(jl_value_t *jlarray)
{
shared_ptr<nj::Value> value;
jl_value_t *elementType = jl_tparam0(jl_typeof(jlarray));
if(elementType == (jl_value_t*)jl_float64_type) value = reboxArray<double,nj::Float64_t>(jlarray);
else if(elementType == (jl_value_t*)jl_int64_type) value = reboxArray<int64_t,nj::Int64_t>(jlarray);
else if(elementType == (jl_value_t*)jl_int32_type) value = reboxArray<int,nj::Int32_t>(jlarray);
else if(elementType == (jl_value_t*)jl_int8_type) value = reboxArray<char,nj::Char_t>(jlarray);
else if(elementType == (jl_value_t*)jl_float32_type) value = reboxArray<float,nj::Float32_t>(jlarray);
else if(elementType == (jl_value_t*)jl_uint64_type) value = reboxArray<uint64_t,nj::UInt64_t>(jlarray);
else if(elementType == (jl_value_t*)jl_uint32_type) value = reboxArray<unsigned,nj::UInt32_t>(jlarray);
else if(elementType == (jl_value_t*)jl_int16_type) value = reboxArray<short,nj::Int16_t>(jlarray);
else if(elementType == (jl_value_t*)jl_uint8_type) value = reboxArray<unsigned char,nj::UChar_t>(jlarray);
else if(elementType == (jl_value_t*)jl_uint16_type) value = reboxArray<unsigned short,nj::UInt16_t>(jlarray);
return value;
}
vector<shared_ptr<nj::Value>> nj::lvalue(jl_value_t *jl_value)
{
vector<shared_ptr<nj::Value>> res;
if(!jl_value) return res;
if(jl_is_null(jl_value))
{
cout << "lvalue is null" << endl;
shared_ptr<nj::Value> value(new nj::Null);
res.push_back(value);
}
else if(jl_is_array(jl_value))
{
cout << "lvalue is array" << endl;
res.push_back(getArrayValue(jl_value));
}
else
{
cout << "lvalue is not array" << endl;
shared_ptr<nj::Value> value;
if(jl_is_float64(jl_value)) value.reset(new nj::Float64(jl_unbox_float64(jl_value)));
else if(jl_is_int64(jl_value)) value.reset(new nj::Int64(jl_unbox_int64(jl_value)));
else if(jl_is_int32(jl_value)) value.reset(new nj::Int32(jl_unbox_int32(jl_value)));
else if(jl_is_int8(jl_value)) value.reset(new nj::Char(jl_unbox_int8(jl_value)));
else if(jl_is_ascii_string(jl_value)) value.reset(new nj::String((char*)jl_unbox_voidpointer(jl_value)));
else if(jl_is_float32(jl_value)) value.reset(new nj::Float32(jl_unbox_float32(jl_value)));
else if(jl_is_uint64(jl_value)) value.reset(new nj::UInt64(jl_unbox_uint64(jl_value)));
else if(jl_is_uint32(jl_value)) value.reset(new nj::UInt32(jl_unbox_uint32(jl_value)));
else if(jl_is_int16(jl_value)) value.reset(new nj::Int16(jl_unbox_int16(jl_value)));
else if(jl_is_uint8(jl_value)) value.reset(new nj::UChar(jl_unbox_uint8(jl_value)));
else if(jl_is_uint16(jl_value)) value.reset(new nj::UInt16(jl_unbox_uint16(jl_value)));
if(value.get()) res.push_back(value);
}
return res;
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the QtXmlPatterns module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QVariant>
#include "qabstractdatetime_p.h"
#include "qabstractfloat_p.h"
#include "qatomicstring_p.h"
#include "qatomictype_p.h"
#include "qboolean_p.h"
#include "qbuiltintypes_p.h"
#include "qdate_p.h"
#include "qschemadatetime_p.h"
#include "qderivedinteger_p.h"
#include "qdynamiccontext_p.h"
#include "qgenericsequencetype_p.h"
#include "qhexbinary_p.h"
#include "qinteger_p.h"
#include "qpatternistlocale_p.h"
#include "qqnamevalue_p.h"
#include "qschematime_p.h"
#include "qvalidationerror_p.h"
#include "qitem_p.h"
QT_BEGIN_NAMESPACE
/**
* @file
* @short Contains the implementation for AtomicValue. The defintion is in qitem_p.h.
*/
using namespace QPatternist;
AtomicValue::~AtomicValue()
{
}
bool AtomicValue::evaluateEBV(const QExplicitlySharedDataPointer<DynamicContext> &context) const
{
context->error(QtXmlPatterns::tr("A value of type %1 cannot have an "
"Effective Boolean Value.")
.arg(formatType(context->namePool(), type())),
ReportContext::FORG0006,
QSourceLocation());
return false; /* Silence GCC warning. */
}
bool AtomicValue::hasError() const
{
return false;
}
QVariant AtomicValue::toQt(const AtomicValue *const value)
{
Q_ASSERT_X(value, Q_FUNC_INFO,
"Internal error, a null pointer cannot be passed.");
const ItemType::Ptr t(value->type());
if(BuiltinTypes::xsString->xdtTypeMatches(t)
|| BuiltinTypes::xsUntypedAtomic->xdtTypeMatches(t)
|| BuiltinTypes::xsAnyURI->xdtTypeMatches(t))
return value->stringValue();
/* Note, this occurs before the xsInteger test, since xs:unsignedLong
* is a subtype of it. */
else if(*BuiltinTypes::xsUnsignedLong == *t)
return QVariant(value->as<DerivedInteger<TypeUnsignedLong> >()->storedValue());
else if(BuiltinTypes::xsInteger->xdtTypeMatches(t))
return QVariant(value->as<Numeric>()->toInteger());
else if(BuiltinTypes::xsFloat->xdtTypeMatches(t)
|| BuiltinTypes::xsDouble->xdtTypeMatches(t)
|| BuiltinTypes::xsDecimal->xdtTypeMatches(t))
return QVariant(value->as<Numeric>()->toDouble());
/* We currently does not support xs:time. */
else if(BuiltinTypes::xsDateTime->xdtTypeMatches(t))
return QVariant(value->as<AbstractDateTime>()->toDateTime());
else if(BuiltinTypes::xsDate->xdtTypeMatches(t))
return QVariant(value->as<AbstractDateTime>()->toDateTime().toUTC().date());
else if(BuiltinTypes::xsBoolean->xdtTypeMatches(t))
return QVariant(value->as<Boolean>()->value());
else if(BuiltinTypes::xsBase64Binary->xdtTypeMatches(t)
|| BuiltinTypes::xsHexBinary->xdtTypeMatches(t))
return QVariant(value->as<Base64Binary>()->asByteArray());
else if(BuiltinTypes::xsQName->xdtTypeMatches(t))
return qVariantFromValue(value->as<QNameValue>()->qName());
else
{
/* A type we don't support in Qt. Includes xs:time currently. */
return QVariant();
}
}
Item AtomicValue::toXDM(const QVariant &value)
{
Q_ASSERT_X(value.isValid(), Q_FUNC_INFO,
"QVariants sent to Patternist must be valid.");
switch(value.userType())
{
case QVariant::Char:
/* Fallthrough. A single codepoint is a string in XQuery. */
case QVariant::String:
return AtomicString::fromValue(value.toString());
case QVariant::Url:
{
/* QUrl doesn't follow the spec properly, so we
* have to let it be an xs:string. Calling QVariant::toString()
* on a QVariant that contains a QUrl returns, surprisingly,
* an empty string. */
return AtomicString::fromValue(value.toUrl().toString());
}
case QVariant::ByteArray:
return HexBinary::fromValue(value.toByteArray());
case QVariant::Int:
/* Fallthrough. */
case QVariant::LongLong:
/* Fallthrough. */
case QVariant::UInt:
return Integer::fromValue(value.toLongLong());
case QVariant::ULongLong:
return DerivedInteger<TypeUnsignedLong>::fromValueUnchecked(value.toULongLong());
case QVariant::Bool:
return Boolean::fromValue(value.toBool());
case QVariant::Time:
return SchemaTime::fromDateTime(value.toDateTime());
case QVariant::Date:
return Date::fromDateTime(QDateTime(value.toDate(), QTime(), Qt::UTC));
case QVariant::DateTime:
return DateTime::fromDateTime(value.toDateTime());
case QMetaType::Float:
return Item(Double::fromValue(value.toFloat()));
case QVariant::Double:
return Item(Double::fromValue(value.toDouble()));
default:
{
if (value.userType() == qMetaTypeId<float>())
{
return Item(Float::fromValue(value.value<float>()));
}
else {
Q_ASSERT_X(false,
Q_FUNC_INFO,
qPrintable(QString::fromLatin1(
"QVariants of type %1 are not supported in "
"Patternist, see the documentation")
.arg(QLatin1String(value.typeName()))));
return AtomicValue::Ptr();
}
}
}
}
ItemType::Ptr AtomicValue::qtToXDMType(const QXmlItem &item)
{
Q_ASSERT(!item.isNull());
if(item.isNull())
return ItemType::Ptr();
if(item.isNode())
return BuiltinTypes::node;
Q_ASSERT(item.isAtomicValue());
const QVariant v(item.toAtomicValue());
switch(v.type())
{
case QVariant::Char:
/* Fallthrough. */
case QVariant::String:
/* Fallthrough. */
case QVariant::Url:
return BuiltinTypes::xsString;
case QVariant::Bool:
return BuiltinTypes::xsBoolean;
case QVariant::ByteArray:
return BuiltinTypes::xsBase64Binary;
case QVariant::Int:
/* Fallthrough. */
case QVariant::LongLong:
return BuiltinTypes::xsInteger;
case QVariant::ULongLong:
return BuiltinTypes::xsUnsignedLong;
case QVariant::Date:
return BuiltinTypes::xsDate;
case QVariant::DateTime:
/* Fallthrough. */
case QVariant::Time:
return BuiltinTypes::xsDateTime;
case QVariant::Double:
return BuiltinTypes::xsDouble;
default:
return ItemType::Ptr();
}
}
QT_END_NAMESPACE
<commit_msg>Fix Float Conversion in xmlpatterns<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the QtXmlPatterns module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QVariant>
#include "qabstractdatetime_p.h"
#include "qabstractfloat_p.h"
#include "qatomicstring_p.h"
#include "qatomictype_p.h"
#include "qboolean_p.h"
#include "qbuiltintypes_p.h"
#include "qdate_p.h"
#include "qschemadatetime_p.h"
#include "qderivedinteger_p.h"
#include "qdynamiccontext_p.h"
#include "qgenericsequencetype_p.h"
#include "qhexbinary_p.h"
#include "qinteger_p.h"
#include "qpatternistlocale_p.h"
#include "qqnamevalue_p.h"
#include "qschematime_p.h"
#include "qvalidationerror_p.h"
#include "qitem_p.h"
QT_BEGIN_NAMESPACE
/**
* @file
* @short Contains the implementation for AtomicValue. The defintion is in qitem_p.h.
*/
using namespace QPatternist;
AtomicValue::~AtomicValue()
{
}
bool AtomicValue::evaluateEBV(const QExplicitlySharedDataPointer<DynamicContext> &context) const
{
context->error(QtXmlPatterns::tr("A value of type %1 cannot have an "
"Effective Boolean Value.")
.arg(formatType(context->namePool(), type())),
ReportContext::FORG0006,
QSourceLocation());
return false; /* Silence GCC warning. */
}
bool AtomicValue::hasError() const
{
return false;
}
QVariant AtomicValue::toQt(const AtomicValue *const value)
{
Q_ASSERT_X(value, Q_FUNC_INFO,
"Internal error, a null pointer cannot be passed.");
const ItemType::Ptr t(value->type());
if(BuiltinTypes::xsString->xdtTypeMatches(t)
|| BuiltinTypes::xsUntypedAtomic->xdtTypeMatches(t)
|| BuiltinTypes::xsAnyURI->xdtTypeMatches(t))
return value->stringValue();
/* Note, this occurs before the xsInteger test, since xs:unsignedLong
* is a subtype of it. */
else if(*BuiltinTypes::xsUnsignedLong == *t)
return QVariant(value->as<DerivedInteger<TypeUnsignedLong> >()->storedValue());
else if(BuiltinTypes::xsInteger->xdtTypeMatches(t))
return QVariant(value->as<Numeric>()->toInteger());
else if(BuiltinTypes::xsFloat->xdtTypeMatches(t)
|| BuiltinTypes::xsDouble->xdtTypeMatches(t)
|| BuiltinTypes::xsDecimal->xdtTypeMatches(t))
return QVariant(value->as<Numeric>()->toDouble());
/* We currently does not support xs:time. */
else if(BuiltinTypes::xsDateTime->xdtTypeMatches(t))
return QVariant(value->as<AbstractDateTime>()->toDateTime());
else if(BuiltinTypes::xsDate->xdtTypeMatches(t))
return QVariant(value->as<AbstractDateTime>()->toDateTime().toUTC().date());
else if(BuiltinTypes::xsBoolean->xdtTypeMatches(t))
return QVariant(value->as<Boolean>()->value());
else if(BuiltinTypes::xsBase64Binary->xdtTypeMatches(t)
|| BuiltinTypes::xsHexBinary->xdtTypeMatches(t))
return QVariant(value->as<Base64Binary>()->asByteArray());
else if(BuiltinTypes::xsQName->xdtTypeMatches(t))
return qVariantFromValue(value->as<QNameValue>()->qName());
else
{
/* A type we don't support in Qt. Includes xs:time currently. */
return QVariant();
}
}
Item AtomicValue::toXDM(const QVariant &value)
{
Q_ASSERT_X(value.isValid(), Q_FUNC_INFO,
"QVariants sent to Patternist must be valid.");
switch(value.userType())
{
case QVariant::Char:
/* Fallthrough. A single codepoint is a string in XQuery. */
case QVariant::String:
return AtomicString::fromValue(value.toString());
case QVariant::Url:
{
/* QUrl doesn't follow the spec properly, so we
* have to let it be an xs:string. Calling QVariant::toString()
* on a QVariant that contains a QUrl returns, surprisingly,
* an empty string. */
return AtomicString::fromValue(value.toUrl().toString());
}
case QVariant::ByteArray:
return HexBinary::fromValue(value.toByteArray());
case QVariant::Int:
/* Fallthrough. */
case QVariant::LongLong:
/* Fallthrough. */
case QVariant::UInt:
return Integer::fromValue(value.toLongLong());
case QVariant::ULongLong:
return DerivedInteger<TypeUnsignedLong>::fromValueUnchecked(value.toULongLong());
case QVariant::Bool:
return Boolean::fromValue(value.toBool());
case QVariant::Time:
return SchemaTime::fromDateTime(value.toDateTime());
case QVariant::Date:
return Date::fromDateTime(QDateTime(value.toDate(), QTime(), Qt::UTC));
case QVariant::DateTime:
return DateTime::fromDateTime(value.toDateTime());
case QMetaType::Float:
return Item(Double::fromValue(value.toFloat()));
case QVariant::Double:
return Item(Double::fromValue(value.toDouble()));
default:
{
if (value.userType() == qMetaTypeId<float>())
{
return Item(Float::fromValue(value.value<float>()));
}
else {
Q_ASSERT_X(false,
Q_FUNC_INFO,
qPrintable(QString::fromLatin1(
"QVariants of type %1 are not supported in "
"Patternist, see the documentation")
.arg(QLatin1String(value.typeName()))));
return AtomicValue::Ptr();
}
}
}
}
ItemType::Ptr AtomicValue::qtToXDMType(const QXmlItem &item)
{
Q_ASSERT(!item.isNull());
if(item.isNull())
return ItemType::Ptr();
if(item.isNode())
return BuiltinTypes::node;
Q_ASSERT(item.isAtomicValue());
const QVariant v(item.toAtomicValue());
switch(v.type())
{
case QVariant::Char:
/* Fallthrough. */
case QVariant::String:
/* Fallthrough. */
case QVariant::Url:
return BuiltinTypes::xsString;
case QVariant::Bool:
return BuiltinTypes::xsBoolean;
case QVariant::ByteArray:
return BuiltinTypes::xsBase64Binary;
case QVariant::Int:
/* Fallthrough. */
case QVariant::LongLong:
return BuiltinTypes::xsInteger;
case QVariant::ULongLong:
return BuiltinTypes::xsUnsignedLong;
case QVariant::Date:
return BuiltinTypes::xsDate;
case QVariant::DateTime:
/* Fallthrough. */
case QVariant::Time:
return BuiltinTypes::xsDateTime;
case QMetaType::Float:
return BuiltinTypes::xsFloat;
case QVariant::Double:
return BuiltinTypes::xsDouble;
default:
return ItemType::Ptr();
}
}
QT_END_NAMESPACE
<|endoftext|> |
<commit_before>//===--- GlobalObjects.cpp - Statically-initialized objects ---------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// Objects that are allocated at global scope instead of on the heap,
// and statically initialized to avoid synchronization costs, are
// defined here.
//
//===----------------------------------------------------------------------===//
#include "../SwiftShims/GlobalObjects.h"
#include "../SwiftShims/LibcShims.h"
#include "swift/Runtime/Metadata.h"
#include "swift/Runtime/Debug.h"
#include <stdlib.h>
namespace swift {
// FIXME(ABI)#76 : does this declaration need SWIFT_RUNTIME_STDLIB_API?
// _direct type metadata for Swift._EmptyArrayStorage
SWIFT_RUNTIME_STDLIB_API
ClassMetadata CLASS_METADATA_SYM(s18_EmptyArrayStorage);
// _direct type metadata for Swift._RawNativeDictionaryStorage
SWIFT_RUNTIME_STDLIB_API
ClassMetadata CLASS_METADATA_SYM(s27_RawNativeDictionaryStorage);
// _direct type metadata for Swift._RawNativeSetStorage
SWIFT_RUNTIME_STDLIB_API
ClassMetadata CLASS_METADATA_SYM(s20_RawNativeSetStorage);
} // namespace swift
SWIFT_RUNTIME_STDLIB_API
swift::_SwiftEmptyArrayStorage swift::_swiftEmptyArrayStorage = {
// HeapObject header;
{
&swift::CLASS_METADATA_SYM(s18_EmptyArrayStorage), // isa pointer
},
// _SwiftArrayBodyStorage body;
{
0, // int count;
1 // unsigned int _capacityAndFlags; 1 means elementTypeIsBridgedVerbatim
}
};
SWIFT_RUNTIME_STDLIB_API
swift::_SwiftEmptyDictionaryStorage swift::_swiftEmptyDictionaryStorage = {
// HeapObject header;
{
&swift::CLASS_METADATA_SYM(s27_RawNativeDictionaryStorage), // isa pointer
},
// _SwiftDictionaryBodyStorage body;
{
// We set the capacity to 1 so that there's an empty hole to search.
// Any insertion will lead to a real storage being allocated, because
// Dictionary guarantees there's always another empty hole after insertion.
1, // int capacity;
0, // int count;
// _SwiftUnsafeBitMap initializedEntries
{
&swift::_swiftEmptyDictionaryStorage.entries, // unsigned int* values;
1 // int bitCount; (1 so there's something for iterators to read)
},
(void*)1, // void* keys; (non-null garbage)
(void*)1 // void* values; (non-null garbage)
},
0 // int entries; (zero'd bits)
};
SWIFT_RUNTIME_STDLIB_API
swift::_SwiftEmptySetStorage swift::_swiftEmptySetStorage = {
// HeapObject header;
{
&swift::CLASS_METADATA_SYM(s20_RawNativeSetStorage), // isa pointer
},
// _SwiftDictionaryBodyStorage body;
{
// We set the capacity to 1 so that there's an empty hole to search.
// Any insertion will lead to a real storage being allocated, because
// Dictionary guarantees there's always another empty hole after insertion.
1, // int capacity;
0, // int count;
// _SwiftUnsafeBitMap initializedEntries
{
&swift::_swiftEmptySetStorage.entries, // unsigned int* values;
1 // int bitCount; (1 so there's something for iterators to read)
},
(void*)1 // void* keys; (non-null garbage)
},
0 // int entries; (zero'd bits)
};
static swift::_SwiftHashingParameters initializeHashingParameters() {
// Setting the environment variable SWIFT_DETERMINISTIC_HASHING to "1"
// disables randomized hash seeding. This is useful in cases we need to ensure
// results are repeatable, e.g., in certain test environments. (Note that
// even if the seed override is enabled, hash values aren't guaranteed to
// remain stable across even minor stdlib releases.)
auto determinism = getenv("SWIFT_DETERMINISTIC_HASHING");
if (determinism && 0 == strcmp(determinism, "1")) {
return { 0, 0, true };
}
__swift_uint64_t seed0 = 0, seed1 = 0;
swift::_stdlib_random(&seed0, sizeof(seed0));
swift::_stdlib_random(&seed1, sizeof(seed1));
return { seed0, seed1, false };
}
SWIFT_ALLOWED_RUNTIME_GLOBAL_CTOR_BEGIN
swift::_SwiftHashingParameters swift::_swift_stdlib_Hashing_parameters =
initializeHashingParameters();
SWIFT_ALLOWED_RUNTIME_GLOBAL_CTOR_END
SWIFT_RUNTIME_STDLIB_API
void swift::_swift_instantiateInertHeapObject(void *address,
const HeapMetadata *metadata) {
::new (address) HeapObject{metadata};
}
namespace llvm { namespace hashing { namespace detail {
// An extern variable expected by LLVM's hashing templates. We don't link any
// LLVM libs into the runtime, so define it as a weak symbol.
//
// Systems that compile this code into a dynamic library will do so with
// hidden visibility, making this all internal to the dynamic library.
// Systems that statically link the Swift runtime into applications (e.g. on
// Linux) need this to handle the case when the app already uses LLVM.
size_t LLVM_ATTRIBUTE_WEAK fixed_seed_override = 0;
} // namespace detail
} // namespace hashing
} // namespace llvm
<commit_msg>[Stdlib] Update the declaration of llvm::fixed_seed_override to uint64_t to match the change in LLVM commit 4b757883e611d95d4580cd21fd6fb78471f4936e.<commit_after>//===--- GlobalObjects.cpp - Statically-initialized objects ---------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// Objects that are allocated at global scope instead of on the heap,
// and statically initialized to avoid synchronization costs, are
// defined here.
//
//===----------------------------------------------------------------------===//
#include "../SwiftShims/GlobalObjects.h"
#include "../SwiftShims/LibcShims.h"
#include "swift/Runtime/Metadata.h"
#include "swift/Runtime/Debug.h"
#include <stdlib.h>
namespace swift {
// FIXME(ABI)#76 : does this declaration need SWIFT_RUNTIME_STDLIB_API?
// _direct type metadata for Swift._EmptyArrayStorage
SWIFT_RUNTIME_STDLIB_API
ClassMetadata CLASS_METADATA_SYM(s18_EmptyArrayStorage);
// _direct type metadata for Swift._RawNativeDictionaryStorage
SWIFT_RUNTIME_STDLIB_API
ClassMetadata CLASS_METADATA_SYM(s27_RawNativeDictionaryStorage);
// _direct type metadata for Swift._RawNativeSetStorage
SWIFT_RUNTIME_STDLIB_API
ClassMetadata CLASS_METADATA_SYM(s20_RawNativeSetStorage);
} // namespace swift
SWIFT_RUNTIME_STDLIB_API
swift::_SwiftEmptyArrayStorage swift::_swiftEmptyArrayStorage = {
// HeapObject header;
{
&swift::CLASS_METADATA_SYM(s18_EmptyArrayStorage), // isa pointer
},
// _SwiftArrayBodyStorage body;
{
0, // int count;
1 // unsigned int _capacityAndFlags; 1 means elementTypeIsBridgedVerbatim
}
};
SWIFT_RUNTIME_STDLIB_API
swift::_SwiftEmptyDictionaryStorage swift::_swiftEmptyDictionaryStorage = {
// HeapObject header;
{
&swift::CLASS_METADATA_SYM(s27_RawNativeDictionaryStorage), // isa pointer
},
// _SwiftDictionaryBodyStorage body;
{
// We set the capacity to 1 so that there's an empty hole to search.
// Any insertion will lead to a real storage being allocated, because
// Dictionary guarantees there's always another empty hole after insertion.
1, // int capacity;
0, // int count;
// _SwiftUnsafeBitMap initializedEntries
{
&swift::_swiftEmptyDictionaryStorage.entries, // unsigned int* values;
1 // int bitCount; (1 so there's something for iterators to read)
},
(void*)1, // void* keys; (non-null garbage)
(void*)1 // void* values; (non-null garbage)
},
0 // int entries; (zero'd bits)
};
SWIFT_RUNTIME_STDLIB_API
swift::_SwiftEmptySetStorage swift::_swiftEmptySetStorage = {
// HeapObject header;
{
&swift::CLASS_METADATA_SYM(s20_RawNativeSetStorage), // isa pointer
},
// _SwiftDictionaryBodyStorage body;
{
// We set the capacity to 1 so that there's an empty hole to search.
// Any insertion will lead to a real storage being allocated, because
// Dictionary guarantees there's always another empty hole after insertion.
1, // int capacity;
0, // int count;
// _SwiftUnsafeBitMap initializedEntries
{
&swift::_swiftEmptySetStorage.entries, // unsigned int* values;
1 // int bitCount; (1 so there's something for iterators to read)
},
(void*)1 // void* keys; (non-null garbage)
},
0 // int entries; (zero'd bits)
};
static swift::_SwiftHashingParameters initializeHashingParameters() {
// Setting the environment variable SWIFT_DETERMINISTIC_HASHING to "1"
// disables randomized hash seeding. This is useful in cases we need to ensure
// results are repeatable, e.g., in certain test environments. (Note that
// even if the seed override is enabled, hash values aren't guaranteed to
// remain stable across even minor stdlib releases.)
auto determinism = getenv("SWIFT_DETERMINISTIC_HASHING");
if (determinism && 0 == strcmp(determinism, "1")) {
return { 0, 0, true };
}
__swift_uint64_t seed0 = 0, seed1 = 0;
swift::_stdlib_random(&seed0, sizeof(seed0));
swift::_stdlib_random(&seed1, sizeof(seed1));
return { seed0, seed1, false };
}
SWIFT_ALLOWED_RUNTIME_GLOBAL_CTOR_BEGIN
swift::_SwiftHashingParameters swift::_swift_stdlib_Hashing_parameters =
initializeHashingParameters();
SWIFT_ALLOWED_RUNTIME_GLOBAL_CTOR_END
SWIFT_RUNTIME_STDLIB_API
void swift::_swift_instantiateInertHeapObject(void *address,
const HeapMetadata *metadata) {
::new (address) HeapObject{metadata};
}
namespace llvm { namespace hashing { namespace detail {
// An extern variable expected by LLVM's hashing templates. We don't link any
// LLVM libs into the runtime, so define it as a weak symbol.
//
// Systems that compile this code into a dynamic library will do so with
// hidden visibility, making this all internal to the dynamic library.
// Systems that statically link the Swift runtime into applications (e.g. on
// Linux) need this to handle the case when the app already uses LLVM.
uint64_t LLVM_ATTRIBUTE_WEAK fixed_seed_override = 0;
} // namespace detail
} // namespace hashing
} // namespace llvm
<|endoftext|> |
<commit_before>#include "gui/squaredetailwindow.hpp"
#include "gui/ng/label.hpp"
#include "gui/texturemanager.hpp"
#include "gui/guihelper.hpp"
#include "engine/square.hpp"
namespace qrw
{
SquareDetailWindow::SquareDetailWindow()
{
setSize({400.0f, 150.0f});
setAnchor({0.0f, 1.0f});
setParentAnchor({0.0f, 1.0f});
float labelHeight = 50;
// ------------------
// Labels for displaying unit information
// ------------------
namelessgui::Label* label;
label = new namelessgui::Label();
label->setSize({100, labelHeight});
label->setText("Unit name");
label->setImage(TextureManager::getInstance()->getTexture("p1swordman"));
label->setRelativePosition({0, 0});
_unitTitleLabel = label;
addWidget(_unitTitleLabel);
label = new namelessgui::Label();
label->setSize({100, labelHeight});
label->setText("20 / 100 HP");
label->setImage(TextureManager::getInstance()->getTexture("health"));
label->setRelativePosition({0, labelHeight});
_unitHealthLabel = label;
addWidget(_unitHealthLabel);
label = new namelessgui::Label();
label->setSize({100, labelHeight});
label->setText("3");
label->setImage(TextureManager::getInstance()->getTexture("attack"));
label->setRelativePosition({0, 2 * labelHeight});
_unitAttackLabel = label;
addWidget(_unitAttackLabel);
label = new namelessgui::Label();
label->setSize({100, labelHeight});
label->setText("2");
label->setImage(TextureManager::getInstance()->getTexture("defense"));
label->setRelativePosition({100, 2 * labelHeight});
_unitDefenseLabel = label;
addWidget(_unitDefenseLabel);
// ------------------
// Labels for displaying terrain information
// ------------------
label = new namelessgui::Label();
label->setSize({100, labelHeight});
label->setText("Wall");
label->setImage(TextureManager::getInstance()->getTexture("wall"));
label->setParentAnchor({1, 0});
label->setRelativePosition({-200, 0});
_terrainTitleLabel = label;
addWidget(_terrainTitleLabel);
label = new namelessgui::Label();
label->setSize({100, labelHeight});
label->setText("+1");
label->setImage(TextureManager::getInstance()->getTexture("attack"));
label->setParentAnchor({1, 0});
label->setRelativePosition({-200, labelHeight});
_terrainAttackLabel = label;
addWidget(_terrainAttackLabel);
label = new namelessgui::Label();
label->setSize({100, labelHeight});
label->setText("-1");
label->setImage(TextureManager::getInstance()->getTexture("defense"));
label->setParentAnchor({1, 0});
label->setRelativePosition({-100, labelHeight});
_terrainDefenseLabel = label;
addWidget(_terrainDefenseLabel);
}
void SquareDetailWindow::setSquare(Square *square)
{
if(square)
{
// Hide window if there's nothing to display
if(square->getUnit() == nullptr && square->getTerrain() == nullptr)
setVisible(false);
else
setVisible(true);
setUnit(square->getUnit());
setTerrain(square->getTerrain());
}
}
void SquareDetailWindow::setUnit(Unit::Ptr unit)
{
if(unit)
{
_unitTitleLabel->setVisible(true);
_unitTitleLabel->setImage(GuiHelper::getUnitTexture(unit));
_unitTitleLabel->setText(GuiHelper::getUnitName(unit));
_unitHealthLabel->setVisible(true);
_unitHealthLabel->setText(std::to_string(unit->getHP()) + "/" + std::to_string(unit->getMaxHp()) + "HP");
_unitAttackLabel->setVisible(true);
_unitAttackLabel->setText(std::to_string(unit->getBaseAttack()));
_unitDefenseLabel->setVisible(true);
_unitDefenseLabel->setText(std::to_string(unit->getBaseDefense()));
}
else
{
_unitTitleLabel->setVisible(false);
_unitHealthLabel->setVisible(false);
_unitAttackLabel->setVisible(false);
_unitDefenseLabel->setVisible(false);
}
}
void SquareDetailWindow::setTerrain(Terrain::Ptr terrain)
{
if(terrain)
{
_terrainTitleLabel->setVisible(true);
_terrainTitleLabel->setImage(GuiHelper::getTerrainTexture(terrain));
_terrainTitleLabel->setText(GuiHelper::getTerrainName(terrain));
_terrainAttackLabel->setVisible(true);
_terrainAttackLabel->setText(std::to_string(terrain->getModificator(MODIFICATORS::EM_ATTACK)));
_terrainDefenseLabel->setVisible(true);
_terrainDefenseLabel->setText(std::to_string(terrain->getModificator(MODIFICATORS::EM_DEFENSE)));
}
else
{
_terrainTitleLabel->setVisible(false);
_terrainAttackLabel->setVisible(false);
_terrainDefenseLabel->setVisible(false);
}
}
} // namespace qrw
<commit_msg>Square detail window hides if cursor does not select a square.<commit_after>#include "gui/squaredetailwindow.hpp"
#include "gui/ng/label.hpp"
#include "gui/texturemanager.hpp"
#include "gui/guihelper.hpp"
#include "engine/square.hpp"
namespace qrw
{
SquareDetailWindow::SquareDetailWindow()
{
setSize({400.0f, 150.0f});
setAnchor({0.0f, 1.0f});
setParentAnchor({0.0f, 1.0f});
float labelHeight = 50;
// ------------------
// Labels for displaying unit information
// ------------------
namelessgui::Label* label;
label = new namelessgui::Label();
label->setSize({100, labelHeight});
label->setText("Unit name");
label->setImage(TextureManager::getInstance()->getTexture("p1swordman"));
label->setRelativePosition({0, 0});
_unitTitleLabel = label;
addWidget(_unitTitleLabel);
label = new namelessgui::Label();
label->setSize({100, labelHeight});
label->setText("20 / 100 HP");
label->setImage(TextureManager::getInstance()->getTexture("health"));
label->setRelativePosition({0, labelHeight});
_unitHealthLabel = label;
addWidget(_unitHealthLabel);
label = new namelessgui::Label();
label->setSize({100, labelHeight});
label->setText("3");
label->setImage(TextureManager::getInstance()->getTexture("attack"));
label->setRelativePosition({0, 2 * labelHeight});
_unitAttackLabel = label;
addWidget(_unitAttackLabel);
label = new namelessgui::Label();
label->setSize({100, labelHeight});
label->setText("2");
label->setImage(TextureManager::getInstance()->getTexture("defense"));
label->setRelativePosition({100, 2 * labelHeight});
_unitDefenseLabel = label;
addWidget(_unitDefenseLabel);
// ------------------
// Labels for displaying terrain information
// ------------------
label = new namelessgui::Label();
label->setSize({100, labelHeight});
label->setText("Wall");
label->setImage(TextureManager::getInstance()->getTexture("wall"));
label->setParentAnchor({1, 0});
label->setRelativePosition({-200, 0});
_terrainTitleLabel = label;
addWidget(_terrainTitleLabel);
label = new namelessgui::Label();
label->setSize({100, labelHeight});
label->setText("+1");
label->setImage(TextureManager::getInstance()->getTexture("attack"));
label->setParentAnchor({1, 0});
label->setRelativePosition({-200, labelHeight});
_terrainAttackLabel = label;
addWidget(_terrainAttackLabel);
label = new namelessgui::Label();
label->setSize({100, labelHeight});
label->setText("-1");
label->setImage(TextureManager::getInstance()->getTexture("defense"));
label->setParentAnchor({1, 0});
label->setRelativePosition({-100, labelHeight});
_terrainDefenseLabel = label;
addWidget(_terrainDefenseLabel);
}
void SquareDetailWindow::setSquare(Square *square)
{
if(square)
{
// Hide window if there's nothing to display
if(square->getUnit() == nullptr && square->getTerrain() == nullptr)
setVisible(false);
else
setVisible(true);
setUnit(square->getUnit());
setTerrain(square->getTerrain());
}
else
setVisible(false);
}
void SquareDetailWindow::setUnit(Unit::Ptr unit)
{
if(unit)
{
_unitTitleLabel->setVisible(true);
_unitTitleLabel->setImage(GuiHelper::getUnitTexture(unit));
_unitTitleLabel->setText(GuiHelper::getUnitName(unit));
_unitHealthLabel->setVisible(true);
_unitHealthLabel->setText(std::to_string(unit->getHP()) + "/" + std::to_string(unit->getMaxHp()) + "HP");
_unitAttackLabel->setVisible(true);
_unitAttackLabel->setText(std::to_string(unit->getBaseAttack()));
_unitDefenseLabel->setVisible(true);
_unitDefenseLabel->setText(std::to_string(unit->getBaseDefense()));
}
else
{
_unitTitleLabel->setVisible(false);
_unitHealthLabel->setVisible(false);
_unitAttackLabel->setVisible(false);
_unitDefenseLabel->setVisible(false);
}
}
void SquareDetailWindow::setTerrain(Terrain::Ptr terrain)
{
if(terrain)
{
_terrainTitleLabel->setVisible(true);
_terrainTitleLabel->setImage(GuiHelper::getTerrainTexture(terrain));
_terrainTitleLabel->setText(GuiHelper::getTerrainName(terrain));
_terrainAttackLabel->setVisible(true);
_terrainAttackLabel->setText(std::to_string(terrain->getModificator(MODIFICATORS::EM_ATTACK)));
_terrainDefenseLabel->setVisible(true);
_terrainDefenseLabel->setText(std::to_string(terrain->getModificator(MODIFICATORS::EM_DEFENSE)));
}
else
{
_terrainTitleLabel->setVisible(false);
_terrainAttackLabel->setVisible(false);
_terrainDefenseLabel->setVisible(false);
}
}
} // namespace qrw
<|endoftext|> |
<commit_before>#include <Socket/SocketSerialized.hpp>
#include <Socket/define.hpp>
namespace ntw {
SocketSerialized::SocketSerialized(Socket::Dommaine dommaine,Socket::Type type,int protocole): Serializer(255), Socket(dommaine,type,protocole), status(0)
{
//reserver les 2 premier bits pour la taille
_cursor_end =_cursor_begin = 4;
//is_send=false;
};
SocketSerialized::SocketSerialized(Socket&& s) : Serializer(255)
{
std::swap(s.sock,sock);
std::swap(s.sock_cfg,sock_cfg);
_cursor_end =_cursor_begin = 4;
};
void SocketSerialized::send()
{
//écrire la taille dans les 2 premier oct
uint16_t size = _cursor_end - _cursor_begin;
uint8_t *d = (uint8_t *)&size;
#if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
_buffer[_cursor_begin - 4] = d[0];
_buffer[_cursor_begin - 3] = d[1];
#elif __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
_buffer[_cursor_begin - 4] = d[1];
_buffer[_cursor_begin - 3] = d[0];
#else
#error "byte orden not suported (PDP endian)"
#endif
{
uint16_t st = status;
d = (uint8_t*)&st;
#if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
_buffer[_cursor_begin - 2] = d[0];
_buffer[_cursor_begin - 1] = d[1];
#elif __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
_buffer[_cursor_begin - 2] = d[1];
_buffer[_cursor_begin - 1] = d[0];
#else
#error "byte orden not suported (PDP endian)"
#endif
}
//envoyer
//std::cout<<"send: "<<*this<<std::endl;
int res = Socket::send(_buffer+_cursor_begin-4, 4+size);
std::cout<<"Send : "<<res<<"/"<<int(4+size)<<std::endl;
//reset
//clear();
};
int SocketSerialized::receive()
{
//recuperer la taille dans les 4 premier oct
int res = Socket::receive(_buffer,4);
if (res > 0)
{
uint8_t d[2];
#if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
d[0]= _buffer[0];
d[1]= _buffer[1];
#elif __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
d[1]= _buffer[0];
d[0]= _buffer[1];
#else
#error "byte orden not suported (PDP endian)"
#endif
uint16_t size = *(uint16_t*)&d;
#if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
d[0]= _buffer[2];
d[1]= _buffer[3];
#elif __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
d[1]= _buffer[2];
d[0]= _buffer[3];
#else
#error "byte orden not suported (PDP endian)"
#endif
status = *(uint16_t*)&d;
//reset
if (int(_buffer_size) < 4+size)
resize(4+size);
//else _buffer_size ne change pas
_cursor_begin = 4;
_cursor_end = 4+size;
//remplacer le buffer
if(size>0)
{
int recv_left = size;
int recv = 0;
while(recv_left > 0)
{
recv = Socket::receive(_buffer+res,recv_left);
if(recv<0)
break;
std::cout<<"Recv size: "<<recv<<std::endl;
res+=recv;
recv_left -=recv;
}
}
}
else
{
clear();
setStatus(NTW_STOP_CONNEXION);
}
//std::cout<<"recv: "<<*this<<std::endl;
std::cout<<"Recv real: "<<res<<std::endl;
return res;
};
void SocketSerialized::setStatus(short int st)
{
status = st;
}
short int SocketSerialized::getStatus()const
{
return status;
}
void SocketSerialized::clear()
{
_cursor_begin = _cursor_end = 4;
}
std::ostream& operator<<(std::ostream& output,const SocketSerialized& self)
{
output<<"["<<self.size()<<":"<<self.status<<"]";
for(unsigned int i=self._cursor_begin; i<self._cursor_end;++i)
{
if(self._buffer[i] < 33 or self._buffer[i] >126)
output<<"<"<<(int)self._buffer[i]<<">";
else
output<<"'"<<(char)self._buffer[i]<<"'";
}
return output;
};
};
<commit_msg>fix recv big buffer size<commit_after>#include <Socket/SocketSerialized.hpp>
#include <Socket/define.hpp>
namespace ntw {
SocketSerialized::SocketSerialized(Socket::Dommaine dommaine,Socket::Type type,int protocole): Serializer(255), Socket(dommaine,type,protocole), status(0)
{
//reserver les 2 premier bits pour la taille
_cursor_end =_cursor_begin = 4;
//is_send=false;
};
SocketSerialized::SocketSerialized(Socket&& s) : Serializer(255)
{
std::swap(s.sock,sock);
std::swap(s.sock_cfg,sock_cfg);
_cursor_end =_cursor_begin = 4;
};
void SocketSerialized::send()
{
//écrire la taille dans les 2 premier oct
uint16_t size = _cursor_end - _cursor_begin;
uint8_t *d = (uint8_t *)&size;
#if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
_buffer[_cursor_begin - 4] = d[0];
_buffer[_cursor_begin - 3] = d[1];
#elif __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
_buffer[_cursor_begin - 4] = d[1];
_buffer[_cursor_begin - 3] = d[0];
#else
#error "byte orden not suported (PDP endian)"
#endif
{
uint16_t st = status;
d = (uint8_t*)&st;
#if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
_buffer[_cursor_begin - 2] = d[0];
_buffer[_cursor_begin - 1] = d[1];
#elif __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
_buffer[_cursor_begin - 2] = d[1];
_buffer[_cursor_begin - 1] = d[0];
#else
#error "byte orden not suported (PDP endian)"
#endif
}
//envoyer
//std::cout<<"send: "<<*this<<std::endl;
int res = Socket::send(_buffer+_cursor_begin-4, 4+size);
//reset
//clear();
};
int SocketSerialized::receive()
{
//recuperer la taille dans les 4 premier oct
int res = Socket::receive(_buffer,4);
if (res > 0)
{
uint8_t d[2];
#if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
d[0]= _buffer[0];
d[1]= _buffer[1];
#elif __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
d[1]= _buffer[0];
d[0]= _buffer[1];
#else
#error "byte orden not suported (PDP endian)"
#endif
uint16_t size = *(uint16_t*)&d;
#if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
d[0]= _buffer[2];
d[1]= _buffer[3];
#elif __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
d[1]= _buffer[2];
d[0]= _buffer[3];
#else
#error "byte orden not suported (PDP endian)"
#endif
status = *(uint16_t*)&d;
//reset
if (int(_buffer_size) < 4+size)
resize(4+size);
//else _buffer_size ne change pas
_cursor_begin = 4;
_cursor_end = 4+size;
//remplacer le buffer
if(size>0)
{
int recv_left = size;
int recv = 0;
while(recv_left > 0)
{
recv = Socket::receive(_buffer+res,recv_left);
if(recv<0)
break;
res+=recv;
recv_left -=recv;
}
}
}
else
{
clear();
setStatus(NTW_STOP_CONNEXION);
}
//std::cout<<"recv: "<<*this<<std::endl;
return res;
};
void SocketSerialized::setStatus(short int st)
{
status = st;
}
short int SocketSerialized::getStatus()const
{
return status;
}
void SocketSerialized::clear()
{
_cursor_begin = _cursor_end = 4;
}
std::ostream& operator<<(std::ostream& output,const SocketSerialized& self)
{
output<<"["<<self.size()<<":"<<self.status<<"]";
for(unsigned int i=self._cursor_begin; i<self._cursor_end;++i)
{
if(self._buffer[i] < 33 or self._buffer[i] >126)
output<<"<"<<(int)self._buffer[i]<<">";
else
output<<"'"<<(char)self._buffer[i]<<"'";
}
return output;
};
};
<|endoftext|> |
<commit_before>#include "Play.hpp"
#include <functional>
#include "../../ResourceManager/AssetManager.hpp"
/* GUI headers */
#include "../../GUI/Containers/Column.hpp"
#include "../../GUI/Containers/Row.hpp"
#include "../../GUI/Widgets/Label.hpp"
#include "../../GUI/Widgets/Button.hpp"
#include "../../GUI/Widgets/Spacer.hpp"
namespace swift
{
Play::Play(sf::RenderWindow& win, AssetManager& am)
: State(win, am),
state(SubState::Play),
world(window.getSize(), assets)
{
returnType = State::Type::Play;
}
Play::~Play()
{
}
void Play::setup()
{
window.setKeyRepeatEnabled(false);
Script* playSetup = &assets.getScript("./data/scripts/play.lua");
Script* pauseSetup = &assets.getScript("./data/scripts/pause.lua");
if(playSetup == nullptr)
std::cerr << "Play script isn't being loaded\n";
if(pauseSetup == nullptr)
std::cerr << "Pause script isn't being loaded\n";
playSetup->setGUI(hud);
playSetup->setStateReturn(returnType);
playSetup->setKeyboard(keyboard);
playSetup->start();
pauseSetup->setGUI(pauseMenu);
pauseSetup->setStateReturn(returnType);
pauseSetup->setKeyboard(keyboard);
pauseSetup->start();
setupKeyBindings();
// setup pause menu GUI
cstr::Column& pauseColumn = pauseMenu.addContainer(new cstr::Column({static_cast<int>(window.getSize().x) / 2 - 50, static_cast<int>(window.getSize().y / 2) - 50, 100, 125}, false));
pauseColumn.addWidget(new cstr::Button({100, 50}, assets.getTexture("./data/textures/button.png"), [&]()
{
state = SubState::Play;
})).setString("Resume", assets.getFont("./data/fonts/segoeuisl.ttf"));
pauseColumn.addWidget(new cstr::Spacer({100, 25}));
pauseColumn.addWidget(new cstr::Button({100, 50}, assets.getTexture("./data/textures/button.png"), [&]()
{
returnType = State::Type::MainMenu;
})).setString("Main Menu", assets.getFont("./data/fonts/segoeuisl.ttf"));
world.load("");
player = &world.getEntities()[0];
}
void Play::handleEvent(sf::Event& event)
{
switch(state)
{
case SubState::Play:
hud.update(event);
break;
case SubState::Pause:
pauseMenu.update(event);
break;
default:
break;
}
keyboard(event);
mouse(event);
}
void Play::update(sf::Time dt)
{
Script* playLogic = &assets.getScript("./data/scripts/play.lua");
Script* pauseLogic = &assets.getScript("./data/scripts/pause.lua");
switch(state)
{
case SubState::Play:
world.update(dt.asSeconds());
playLogic->run();
break;
case SubState::Pause:
pauseLogic->run();
break;
}
}
void Play::draw(float /*e*/)
{
switch(state)
{
case SubState::Play:
world.draw(window);
window.draw(hud);
break;
case SubState::Pause:
window.draw(pauseMenu);
break;
default:
break;
}
}
bool Play::switchFrom()
{
return returnType != State::Type::Play;
}
State::Type Play::finish()
{
return returnType;
}
void Play::setupKeyBindings()
{
keyboard.newBinding("PauseMenu", sf::Keyboard::Escape, [&]()
{
state = (state == SubState::Pause) ? SubState::Play : SubState::Pause;
}, false);
// move up press and release
keyboard.newBinding("moveUpStart", sf::Keyboard::Up, [&]()
{
player->get<Movable>()->velocity += {0, -player->get<Movable>()->moveVelocity};
}, true);
keyboard.newBinding("moveUpStop", sf::Keyboard::Up, [&]()
{
player->get<Movable>()->velocity += {0, player->get<Movable>()->moveVelocity};
}, false);
// move down press and release
keyboard.newBinding("moveDownStart", sf::Keyboard::Down, [&]()
{
player->get<Movable>()->velocity += {0, player->get<Movable>()->moveVelocity};
}, true);
keyboard.newBinding("moveDownStop", sf::Keyboard::Down, [&]()
{
player->get<Movable>()->velocity += {0, -player->get<Movable>()->moveVelocity};
}, false);
// move left press and release
keyboard.newBinding("moveLeftStart", sf::Keyboard::Left, [&]()
{
player->get<Movable>()->velocity += {-player->get<Movable>()->moveVelocity, 0};
}, true);
keyboard.newBinding("moveLeftStop", sf::Keyboard::Left, [&]()
{
player->get<Movable>()->velocity += {player->get<Movable>()->moveVelocity, 0};
}, false);
// move right press and release
keyboard.newBinding("moveRightStart", sf::Keyboard::Right, [&]()
{
player->get<Movable>()->velocity += {player->get<Movable>()->moveVelocity, 0};
}, true);
keyboard.newBinding("moveRightStop", sf::Keyboard::Right, [&]()
{
player->get<Movable>()->velocity += {-player->get<Movable>()->moveVelocity, 0};
}, false);
}
}
<commit_msg>Added a few comments<commit_after>#include "Play.hpp"
#include <functional>
#include "../../ResourceManager/AssetManager.hpp"
/* GUI headers */
#include "../../GUI/Containers/Column.hpp"
#include "../../GUI/Containers/Row.hpp"
#include "../../GUI/Widgets/Label.hpp"
#include "../../GUI/Widgets/Button.hpp"
#include "../../GUI/Widgets/Spacer.hpp"
namespace swift
{
Play::Play(sf::RenderWindow& win, AssetManager& am)
: State(win, am),
state(SubState::Play),
world({static_cast<int>(window.getSize().x), static_cast<int>(window.getSize().y)}, assets)
{
returnType = State::Type::Play;
}
Play::~Play()
{
}
void Play::setup()
{
window.setKeyRepeatEnabled(false);
Script* playSetup = &assets.getScript("./data/scripts/play.lua");
Script* pauseSetup = &assets.getScript("./data/scripts/pause.lua");
if(playSetup == nullptr)
std::cerr << "Play script isn't being loaded\n";
if(pauseSetup == nullptr)
std::cerr << "Pause script isn't being loaded\n";
playSetup->setGUI(hud);
playSetup->setStateReturn(returnType);
playSetup->setKeyboard(keyboard);
playSetup->start();
pauseSetup->setGUI(pauseMenu);
pauseSetup->setStateReturn(returnType);
pauseSetup->setKeyboard(keyboard);
pauseSetup->start();
setupKeyBindings();
// setup pause menu GUI
cstr::Column& pauseColumn = pauseMenu.addContainer(new cstr::Column({static_cast<int>(window.getSize().x) / 2 - 50, static_cast<int>(window.getSize().y / 2) - 50, 100, 125}, false));
pauseColumn.addWidget(new cstr::Button({100, 50}, assets.getTexture("./data/textures/button.png"), [&]()
{
state = SubState::Play;
})).setString("Resume", assets.getFont("./data/fonts/segoeuisl.ttf"));
pauseColumn.addWidget(new cstr::Spacer({100, 25}));
pauseColumn.addWidget(new cstr::Button({100, 50}, assets.getTexture("./data/textures/button.png"), [&]()
{
returnType = State::Type::MainMenu;
})).setString("Main Menu", assets.getFont("./data/fonts/segoeuisl.ttf"));
world.load("");
player = &world.getEntities()[0];
}
void Play::handleEvent(sf::Event& event)
{
switch(state)
{
case SubState::Play:
hud.update(event);
break;
case SubState::Pause:
pauseMenu.update(event);
break;
default:
break;
}
keyboard(event);
mouse(event);
}
void Play::update(sf::Time dt)
{
Script* playLogic = &assets.getScript("./data/scripts/play.lua");
Script* pauseLogic = &assets.getScript("./data/scripts/pause.lua");
switch(state)
{
case SubState::Play:
world.update(dt.asSeconds());
playLogic->run();
break;
case SubState::Pause:
pauseLogic->run();
break;
}
}
void Play::draw(float /*e*/)
{
switch(state)
{
case SubState::Play:
world.draw(window);
window.draw(hud);
break;
case SubState::Pause:
window.draw(pauseMenu);
break;
default:
break;
}
}
bool Play::switchFrom()
{
return returnType != State::Type::Play;
}
State::Type Play::finish()
{
return returnType;
}
void Play::setupKeyBindings()
{
keyboard.newBinding("PauseMenu", sf::Keyboard::Escape, [&]()
{
state = (state == SubState::Pause) ? SubState::Play : SubState::Pause;
}, false);
// move up press and release
keyboard.newBinding("moveUpStart", sf::Keyboard::Up, [&]()
{
player->get<Movable>()->velocity += {0, -player->get<Movable>()->moveVelocity};
}, true);
keyboard.newBinding("moveUpStop", sf::Keyboard::Up, [&]()
{
player->get<Movable>()->velocity += {0, player->get<Movable>()->moveVelocity};
}, false);
// move down press and release
keyboard.newBinding("moveDownStart", sf::Keyboard::Down, [&]()
{
player->get<Movable>()->velocity += {0, player->get<Movable>()->moveVelocity};
}, true);
keyboard.newBinding("moveDownStop", sf::Keyboard::Down, [&]()
{
player->get<Movable>()->velocity += {0, -player->get<Movable>()->moveVelocity};
}, false);
// move left press and release
keyboard.newBinding("moveLeftStart", sf::Keyboard::Left, [&]()
{
player->get<Movable>()->velocity += {-player->get<Movable>()->moveVelocity, 0};
}, true);
keyboard.newBinding("moveLeftStop", sf::Keyboard::Left, [&]()
{
player->get<Movable>()->velocity += {player->get<Movable>()->moveVelocity, 0};
}, false);
// move right press and release
keyboard.newBinding("moveRightStart", sf::Keyboard::Right, [&]()
{
player->get<Movable>()->velocity += {player->get<Movable>()->moveVelocity, 0};
}, true);
keyboard.newBinding("moveRightStop", sf::Keyboard::Right, [&]()
{
player->get<Movable>()->velocity += {-player->get<Movable>()->moveVelocity, 0};
}, false);
}
}
<|endoftext|> |
<commit_before>#include "instxyplot.h"
const QString InstXYPlot::TAG_NAME = "XY_PLOT";
void InstXYPlot::renderAxis(QPainter* painter)
{
int dx = cWidth / cMajorCnt;
int dy = cHeight / cMajorCnt;
int x = 0;
int y = 0;
for (int i=0; i<cMajorCnt + 1; ++i)
{
painter->drawLine(x, mCenterY-cMajorLen, x, mCenterY+cMajorLen);
painter->drawLine(mCenterX-cMajorLen, y, mCenterX+cMajorLen, y);
x += dx;
y += dy;
}
}
void InstXYPlot::renderBall(QPainter* painter)
{
setPen(painter, cColorStatic);
setBrush(painter, cColorForeground);
QRect rect(mLastValX * (cWidth-cBallSize), mLastValY * (cHeight-cBallSize), cBallSize, cBallSize);
painter->drawEllipse(rect);
}
void InstXYPlot::renderStatic(QPainter *painter)
{
painter->fillRect(0, 0, cWidth, cHeight, cColorBackground);
mCenterX = cWidth / 2;
mCenterY = cHeight / 2;
painter->drawLine(0, mCenterY, cWidth, mCenterY);
painter->drawLine(mCenterX, 0, mCenterX, cHeight);
renderAxis(painter);
painter->drawText(0, mCenterY-cMajorLen, cLabelX);
painter->drawText(mCenterX+cMajorLen, cHeight, cLabelY);
}
void InstXYPlot::renderDynamic(QPainter *painter)
{
if (mSignal->getId() == cSignalId)
{
mLastValX = mSignal->getNormalizedValue(); // primary signal shown on X axis
}
else
{
mLastValY = mSignal->getNormalizedValue(); // additional signal shown on Y axis
}
renderBall(painter);
}
quint16 InstXYPlot::getSignalYId()
{
return cSignalYId;
}
<commit_msg>XY Plot color fixes<commit_after>#include "instxyplot.h"
const QString InstXYPlot::TAG_NAME = "XY_PLOT";
void InstXYPlot::renderAxis(QPainter* painter)
{
int dx = cWidth / cMajorCnt;
int dy = cHeight / cMajorCnt;
int x = 0;
int y = 0;
for (int i=0; i<cMajorCnt + 1; ++i)
{
painter->drawLine(x, mCenterY-cMajorLen, x, mCenterY+cMajorLen);
painter->drawLine(mCenterX-cMajorLen, y, mCenterX+cMajorLen, y);
x += dx;
y += dy;
}
}
void InstXYPlot::renderBall(QPainter* painter)
{
setPen(painter, cColorStatic);
setBrush(painter, cColorForeground);
QRect rect(mLastValX * (cWidth-cBallSize), mLastValY * (cHeight-cBallSize), cBallSize, cBallSize);
painter->drawEllipse(rect);
}
void InstXYPlot::renderStatic(QPainter *painter)
{
setPen(painter, cColorStatic);
clear(painter);
mCenterX = cWidth / 2;
mCenterY = cHeight / 2;
painter->drawLine(0, mCenterY, cWidth, mCenterY);
painter->drawLine(mCenterX, 0, mCenterX, cHeight);
renderAxis(painter);
painter->drawText(0, mCenterY-cMajorLen, cLabelX);
painter->drawText(mCenterX+cMajorLen, cHeight, cLabelY);
}
void InstXYPlot::renderDynamic(QPainter *painter)
{
if (mSignal->getId() == cSignalId)
{
mLastValX = mSignal->getNormalizedValue(); // primary signal shown on X axis
}
else
{
mLastValY = mSignal->getNormalizedValue(); // additional signal shown on Y axis
}
renderBall(painter);
}
quint16 InstXYPlot::getSignalYId()
{
return cSignalYId;
}
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#include "thumbv_itm.hxx"
#include "thumbv_acc.hxx"
#include <vcl/svapp.hxx>
using namespace ::com::sun::star;
ThumbnailViewItem::ThumbnailViewItem( ThumbnailView& rParent )
: mrParent(rParent)
, mnId(0)
, mbVisible(true)
, mpData(NULL)
, mpxAcc(NULL)
{
}
ThumbnailViewItem::~ThumbnailViewItem()
{
if( mpxAcc )
{
static_cast< ThumbnailViewItemAcc* >( mpxAcc->get() )->ParentDestroyed();
delete mpxAcc;
}
}
uno::Reference< accessibility::XAccessible > ThumbnailViewItem::GetAccessible( bool bIsTransientChildrenDisabled )
{
if( !mpxAcc )
mpxAcc = new uno::Reference< accessibility::XAccessible >( new ThumbnailViewItemAcc( this, bIsTransientChildrenDisabled ) );
return *mpxAcc;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Make default color for items transparent.<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#include "thumbv_itm.hxx"
#include "thumbv_acc.hxx"
#include <vcl/svapp.hxx>
using namespace ::com::sun::star;
ThumbnailViewItem::ThumbnailViewItem( ThumbnailView& rParent )
: mrParent(rParent)
, mnId(0)
, mbVisible(true)
, maColor (COL_TRANSPARENT)
, mpData(NULL)
, mpxAcc(NULL)
{
}
ThumbnailViewItem::~ThumbnailViewItem()
{
if( mpxAcc )
{
static_cast< ThumbnailViewItemAcc* >( mpxAcc->get() )->ParentDestroyed();
delete mpxAcc;
}
}
uno::Reference< accessibility::XAccessible > ThumbnailViewItem::GetAccessible( bool bIsTransientChildrenDisabled )
{
if( !mpxAcc )
mpxAcc = new uno::Reference< accessibility::XAccessible >( new ThumbnailViewItemAcc( this, bIsTransientChildrenDisabled ) );
return *mpxAcc;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before> /*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: accfootnote.cxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: obo $ $Date: 2006-09-16 20:34:52 $
*
* 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_sw.hxx"
#ifndef _VOS_MUTEX_HXX_ //autogen
#include <vos/mutex.hxx>
#endif
#ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLEROLE_HPP_
#include <com/sun/star/accessibility/AccessibleRole.hpp>
#endif
#ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLESTATETYPE_HPP_
#include <com/sun/star/accessibility/AccessibleStateType.hpp>
#endif
#ifndef _UTL_ACCESSIBLESTATESETHELPER_HXX_
#include <unotools/accessiblestatesethelper.hxx>
#endif
#ifndef _RTL_UUID_H_
#include <rtl/uuid.h>
#endif
#ifndef _SV_SVAPP_HXX //autogen
#include <vcl/svapp.hxx>
#endif
#ifndef _FTNFRM_HXX
#include <ftnfrm.hxx>
#endif
#ifndef _FMTFTN_HXX //autogen
#include <fmtftn.hxx>
#endif
#ifndef _TXTFTN_HXX //autogen
#include <txtftn.hxx>
#endif
#ifndef _VIEWSH_HXX
#include <viewsh.hxx>
#endif
#ifndef _PAGEFRM_HXX
//#include <pagefrm.hxx>
#endif
#ifndef _PAGEDESC_HXX
//#include <pagedesc.hxx>
#endif
#ifndef _FLDBAS_HXX
//#include <fldbas.hxx>
#endif
#ifndef _ACCMAP_HXX
#include <accmap.hxx>
#endif
#ifndef _ACCFOOTNOTE_HXX
#include "accfootnote.hxx"
#endif
#ifndef _ACCESS_HRC
#include "access.hrc"
#endif
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::accessibility;
using namespace ::rtl;
const sal_Char sServiceNameFootnote[] = "com.sun.star.text.AccessibleFootnoteView";
const sal_Char sServiceNameEndnote[] = "com.sun.star.text.AccessibleEndnoteView";
const sal_Char sImplementationNameFootnote[] = "com.sun.star.comp.Writer.SwAccessibleFootnoteView";
const sal_Char sImplementationNameEndnote[] = "com.sun.star.comp.Writer.SwAccessibleEndnoteView";
SwAccessibleFootnote::SwAccessibleFootnote(
SwAccessibleMap *pMap,
sal_Bool bIsEndnote,
sal_Int32 nFootEndNote,
const SwFtnFrm *pFtnFrm ) :
SwAccessibleContext( pMap,
bIsEndnote ? AccessibleRole::END_NOTE : AccessibleRole::FOOTNOTE,
pFtnFrm )
{
vos::OGuard aGuard(Application::GetSolarMutex());
sal_uInt16 nResId = bIsEndnote ? STR_ACCESS_ENDNOTE_NAME
: STR_ACCESS_FOOTNOTE_NAME;
OUString sArg( OUString::valueOf( nFootEndNote ) );
SetName( GetResource( nResId, &sArg ) );
}
SwAccessibleFootnote::~SwAccessibleFootnote()
{
}
OUString SAL_CALL SwAccessibleFootnote::getAccessibleDescription (void)
throw (::com::sun::star::uno::RuntimeException)
{
vos::OGuard aGuard(Application::GetSolarMutex());
CHECK_FOR_DEFUNC( XAccessibleContext )
sal_uInt16 nResId = AccessibleRole::END_NOTE == GetRole()
? STR_ACCESS_ENDNOTE_DESC
: STR_ACCESS_FOOTNOTE_DESC ;
OUString sArg;
const SwTxtFtn *pTxtFtn =
static_cast< const SwFtnFrm *>( GetFrm() )->GetAttr();
if( pTxtFtn )
{
const SwDoc *pDoc = GetMap()->GetShell()->GetDoc();
sArg = pTxtFtn->GetFtn().GetViewNumStr( *pDoc );
}
return GetResource( nResId, &sArg );
}
OUString SAL_CALL SwAccessibleFootnote::getImplementationName()
throw( RuntimeException )
{
if( AccessibleRole::END_NOTE == GetRole() )
return OUString(RTL_CONSTASCII_USTRINGPARAM(sImplementationNameEndnote));
else
return OUString(RTL_CONSTASCII_USTRINGPARAM(sImplementationNameFootnote));
}
sal_Bool SAL_CALL SwAccessibleFootnote::supportsService(
const ::rtl::OUString& sTestServiceName)
throw (::com::sun::star::uno::RuntimeException)
{
if( sTestServiceName.equalsAsciiL( sAccessibleServiceName,
sizeof(sAccessibleServiceName)-1 ) )
return sal_True;
else if( AccessibleRole::END_NOTE == GetRole() )
return sTestServiceName.equalsAsciiL( sServiceNameEndnote, sizeof(sServiceNameEndnote)-1 );
else
return sTestServiceName.equalsAsciiL( sServiceNameFootnote, sizeof(sServiceNameFootnote)-1 );
}
Sequence< OUString > SAL_CALL SwAccessibleFootnote::getSupportedServiceNames()
throw( ::com::sun::star::uno::RuntimeException )
{
Sequence< OUString > aRet(2);
OUString* pArray = aRet.getArray();
if( AccessibleRole::END_NOTE == GetRole() )
pArray[0] = OUString( RTL_CONSTASCII_USTRINGPARAM(sServiceNameEndnote) );
else
pArray[0] = OUString( RTL_CONSTASCII_USTRINGPARAM(sServiceNameFootnote) );
pArray[1] = OUString( RTL_CONSTASCII_USTRINGPARAM(sAccessibleServiceName) );
return aRet;
}
Sequence< sal_Int8 > SAL_CALL SwAccessibleFootnote::getImplementationId()
throw(RuntimeException)
{
vos::OGuard aGuard(Application::GetSolarMutex());
static Sequence< sal_Int8 > aId( 16 );
static sal_Bool bInit = sal_False;
if(!bInit)
{
rtl_createUuid( (sal_uInt8 *)(aId.getArray() ), 0, sal_True );
bInit = sal_True;
}
return aId;
}
sal_Bool SwAccessibleFootnote::IsEndnote( const SwFtnFrm *pFtnFrm )
{
const SwTxtFtn *pTxtFtn = pFtnFrm ->GetAttr();
return pTxtFtn && pTxtFtn->GetFtn().IsEndNote() ;
}
<commit_msg>INTEGRATION: CWS swwarnings (1.12.222); FILE MERGED 2007/04/11 07:02:38 tl 1.12.222.2: #i69287# warning-free code 2007/03/08 15:18:40 od 1.12.222.1: #i69287# warning free code<commit_after> /*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: accfootnote.cxx,v $
*
* $Revision: 1.13 $
*
* last change: $Author: hr $ $Date: 2007-09-27 08:20:12 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"
#ifndef _VOS_MUTEX_HXX_ //autogen
#include <vos/mutex.hxx>
#endif
#ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLEROLE_HPP_
#include <com/sun/star/accessibility/AccessibleRole.hpp>
#endif
#ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLESTATETYPE_HPP_
#include <com/sun/star/accessibility/AccessibleStateType.hpp>
#endif
#ifndef _UTL_ACCESSIBLESTATESETHELPER_HXX_
#include <unotools/accessiblestatesethelper.hxx>
#endif
#ifndef _RTL_UUID_H_
#include <rtl/uuid.h>
#endif
#ifndef _SV_SVAPP_HXX //autogen
#include <vcl/svapp.hxx>
#endif
#ifndef _FTNFRM_HXX
#include <ftnfrm.hxx>
#endif
#ifndef _FMTFTN_HXX //autogen
#include <fmtftn.hxx>
#endif
#ifndef _TXTFTN_HXX //autogen
#include <txtftn.hxx>
#endif
#ifndef _VIEWSH_HXX
#include <viewsh.hxx>
#endif
#ifndef _PAGEFRM_HXX
//#include <pagefrm.hxx>
#endif
#ifndef _PAGEDESC_HXX
//#include <pagedesc.hxx>
#endif
#ifndef _FLDBAS_HXX
//#include <fldbas.hxx>
#endif
#ifndef _ACCMAP_HXX
#include <accmap.hxx>
#endif
#ifndef _ACCFOOTNOTE_HXX
#include "accfootnote.hxx"
#endif
#ifndef _ACCESS_HRC
#include "access.hrc"
#endif
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::accessibility;
using namespace ::rtl;
const sal_Char sServiceNameFootnote[] = "com.sun.star.text.AccessibleFootnoteView";
const sal_Char sServiceNameEndnote[] = "com.sun.star.text.AccessibleEndnoteView";
const sal_Char sImplementationNameFootnote[] = "com.sun.star.comp.Writer.SwAccessibleFootnoteView";
const sal_Char sImplementationNameEndnote[] = "com.sun.star.comp.Writer.SwAccessibleEndnoteView";
SwAccessibleFootnote::SwAccessibleFootnote(
SwAccessibleMap* pInitMap,
sal_Bool bIsEndnote,
sal_Int32 nFootEndNote,
const SwFtnFrm *pFtnFrm ) :
SwAccessibleContext( pInitMap,
bIsEndnote ? AccessibleRole::END_NOTE : AccessibleRole::FOOTNOTE,
pFtnFrm )
{
vos::OGuard aGuard(Application::GetSolarMutex());
sal_uInt16 nResId = bIsEndnote ? STR_ACCESS_ENDNOTE_NAME
: STR_ACCESS_FOOTNOTE_NAME;
OUString sArg( OUString::valueOf( nFootEndNote ) );
SetName( GetResource( nResId, &sArg ) );
}
SwAccessibleFootnote::~SwAccessibleFootnote()
{
}
OUString SAL_CALL SwAccessibleFootnote::getAccessibleDescription (void)
throw (uno::RuntimeException)
{
vos::OGuard aGuard(Application::GetSolarMutex());
CHECK_FOR_DEFUNC( XAccessibleContext )
sal_uInt16 nResId = AccessibleRole::END_NOTE == GetRole()
? STR_ACCESS_ENDNOTE_DESC
: STR_ACCESS_FOOTNOTE_DESC ;
OUString sArg;
const SwTxtFtn *pTxtFtn =
static_cast< const SwFtnFrm *>( GetFrm() )->GetAttr();
if( pTxtFtn )
{
const SwDoc *pDoc = GetMap()->GetShell()->GetDoc();
sArg = pTxtFtn->GetFtn().GetViewNumStr( *pDoc );
}
return GetResource( nResId, &sArg );
}
OUString SAL_CALL SwAccessibleFootnote::getImplementationName()
throw( RuntimeException )
{
if( AccessibleRole::END_NOTE == GetRole() )
return OUString(RTL_CONSTASCII_USTRINGPARAM(sImplementationNameEndnote));
else
return OUString(RTL_CONSTASCII_USTRINGPARAM(sImplementationNameFootnote));
}
sal_Bool SAL_CALL SwAccessibleFootnote::supportsService(
const ::rtl::OUString& sTestServiceName)
throw (uno::RuntimeException)
{
if( sTestServiceName.equalsAsciiL( sAccessibleServiceName,
sizeof(sAccessibleServiceName)-1 ) )
return sal_True;
else if( AccessibleRole::END_NOTE == GetRole() )
return sTestServiceName.equalsAsciiL( sServiceNameEndnote, sizeof(sServiceNameEndnote)-1 );
else
return sTestServiceName.equalsAsciiL( sServiceNameFootnote, sizeof(sServiceNameFootnote)-1 );
}
Sequence< OUString > SAL_CALL SwAccessibleFootnote::getSupportedServiceNames()
throw( uno::RuntimeException )
{
Sequence< OUString > aRet(2);
OUString* pArray = aRet.getArray();
if( AccessibleRole::END_NOTE == GetRole() )
pArray[0] = OUString( RTL_CONSTASCII_USTRINGPARAM(sServiceNameEndnote) );
else
pArray[0] = OUString( RTL_CONSTASCII_USTRINGPARAM(sServiceNameFootnote) );
pArray[1] = OUString( RTL_CONSTASCII_USTRINGPARAM(sAccessibleServiceName) );
return aRet;
}
Sequence< sal_Int8 > SAL_CALL SwAccessibleFootnote::getImplementationId()
throw(RuntimeException)
{
vos::OGuard aGuard(Application::GetSolarMutex());
static Sequence< sal_Int8 > aId( 16 );
static sal_Bool bInit = sal_False;
if(!bInit)
{
rtl_createUuid( (sal_uInt8 *)(aId.getArray() ), 0, sal_True );
bInit = sal_True;
}
return aId;
}
sal_Bool SwAccessibleFootnote::IsEndnote( const SwFtnFrm *pFtnFrm )
{
const SwTxtFtn *pTxtFtn = pFtnFrm ->GetAttr();
return pTxtFtn && pTxtFtn->GetFtn().IsEndNote() ;
}
<|endoftext|> |
<commit_before>//..............................................................................
//
// This file is part of the Jancy toolkit.
//
// Jancy is distributed under the MIT license.
// For details see accompanying license.txt file,
// the public copy of which is also available at:
// http://tibbo.com/downloads/archive/jancy/license.txt
//
//..............................................................................
#include "pch.h"
#include "jnc_ClassType.h"
#ifdef _JNC_DYNAMIC_EXTENSION_LIB
# include "jnc_ExtensionLib.h"
#elif defined(_JNC_CORE)
# include "jnc_ct_CapabilityMgr.h"
#endif
//..............................................................................
JNC_EXTERN_C
JNC_EXPORT_O
bool_t
jnc_failWithCapabilityError(const char* capability)
{
err::setFormatStringError("capability '%s' is required but not enabled", capability);
return false;
}
#ifdef _JNC_DYNAMIC_EXTENSION_LIB
// extensions should only have read-only access to capabilities
JNC_EXTERN_C
bool_t
jnc_isEveryCapabilityEnabled()
{
return jnc_g_dynamicExtensionLibHost->m_capabilityFuncTable->m_isEveryCapabilityEnabledFunc();
}
JNC_EXTERN_C
bool_t
jnc_isCapabilityEnabled(const char* capability)
{
return jnc_g_dynamicExtensionLibHost->m_capabilityFuncTable->m_isCapabilityEnabledFunc(capability);
}
JNC_EXTERN_C
size_t
jnc_readCapabilityParam(
const char* param,
void* value,
size_t size
)
{
return jnc_g_dynamicExtensionLibHost->m_capabilityFuncTable->m_readCapabilityParamFunc(param, value, size);
}
#else // _JNC_DYNAMIC_EXTENSION_LIB
JNC_EXTERN_C
JNC_EXPORT_O
bool_t
jnc_isEveryCapabilityEnabled()
{
return jnc::ct::getCapabilityMgr()->isEverythingEnabled();
}
JNC_EXTERN_C
JNC_EXPORT_O
bool_t
jnc_isCapabilityEnabled(const char* capability)
{
return jnc::ct::getCapabilityMgr()->isCapabilityEnabled(capability);
}
JNC_EXTERN_C
JNC_EXPORT_O
size_t
jnc_readCapabilityParam(
const char* param,
void* value,
size_t size
)
{
return jnc::ct::getCapabilityMgr()->readCapabilityParam(param, value, size);
}
JNC_EXTERN_C
JNC_EXPORT_O
size_t
jnc_writeCapabilityParam(
const char* param,
const void* value,
size_t size
)
{
return jnc::ct::getCapabilityMgr()->writeCapabilityParam(param, value, size);
}
JNC_EXTERN_C
JNC_EXPORT_O
void
jnc_enableCapability(
const char* capability,
bool_t isEnabled
)
{
jnc::ct::getCapabilityMgr()->enableCapability(capability, isEnabled);
}
JNC_EXTERN_C
JNC_EXPORT_O
void
jnc_initializeCapabilities(const char* initializer)
{
jnc::ct::getCapabilityMgr()->initializeCapabilities(initializer);
}
#endif // _JNC_DYNAMIC_EXTENSION_LIB
//..............................................................................
<commit_msg>[jnc_api] warning fix: forcing 'int' to 'bool'<commit_after>//..............................................................................
//
// This file is part of the Jancy toolkit.
//
// Jancy is distributed under the MIT license.
// For details see accompanying license.txt file,
// the public copy of which is also available at:
// http://tibbo.com/downloads/archive/jancy/license.txt
//
//..............................................................................
#include "pch.h"
#include "jnc_ClassType.h"
#ifdef _JNC_DYNAMIC_EXTENSION_LIB
# include "jnc_ExtensionLib.h"
#elif defined(_JNC_CORE)
# include "jnc_ct_CapabilityMgr.h"
#endif
//..............................................................................
JNC_EXTERN_C
JNC_EXPORT_O
bool_t
jnc_failWithCapabilityError(const char* capability)
{
err::setFormatStringError("capability '%s' is required but not enabled", capability);
return false;
}
#ifdef _JNC_DYNAMIC_EXTENSION_LIB
// extensions should only have read-only access to capabilities
JNC_EXTERN_C
bool_t
jnc_isEveryCapabilityEnabled()
{
return jnc_g_dynamicExtensionLibHost->m_capabilityFuncTable->m_isEveryCapabilityEnabledFunc();
}
JNC_EXTERN_C
bool_t
jnc_isCapabilityEnabled(const char* capability)
{
return jnc_g_dynamicExtensionLibHost->m_capabilityFuncTable->m_isCapabilityEnabledFunc(capability);
}
JNC_EXTERN_C
size_t
jnc_readCapabilityParam(
const char* param,
void* value,
size_t size
)
{
return jnc_g_dynamicExtensionLibHost->m_capabilityFuncTable->m_readCapabilityParamFunc(param, value, size);
}
#else // _JNC_DYNAMIC_EXTENSION_LIB
JNC_EXTERN_C
JNC_EXPORT_O
bool_t
jnc_isEveryCapabilityEnabled()
{
return jnc::ct::getCapabilityMgr()->isEverythingEnabled();
}
JNC_EXTERN_C
JNC_EXPORT_O
bool_t
jnc_isCapabilityEnabled(const char* capability)
{
return jnc::ct::getCapabilityMgr()->isCapabilityEnabled(capability);
}
JNC_EXTERN_C
JNC_EXPORT_O
size_t
jnc_readCapabilityParam(
const char* param,
void* value,
size_t size
)
{
return jnc::ct::getCapabilityMgr()->readCapabilityParam(param, value, size);
}
JNC_EXTERN_C
JNC_EXPORT_O
size_t
jnc_writeCapabilityParam(
const char* param,
const void* value,
size_t size
)
{
return jnc::ct::getCapabilityMgr()->writeCapabilityParam(param, value, size);
}
JNC_EXTERN_C
JNC_EXPORT_O
void
jnc_enableCapability(
const char* capability,
bool_t isEnabled
)
{
jnc::ct::getCapabilityMgr()->enableCapability(capability, isEnabled != 0);
}
JNC_EXTERN_C
JNC_EXPORT_O
void
jnc_initializeCapabilities(const char* initializer)
{
jnc::ct::getCapabilityMgr()->initializeCapabilities(initializer);
}
#endif // _JNC_DYNAMIC_EXTENSION_LIB
//..............................................................................
<|endoftext|> |
<commit_before>#ifndef _SDD_DD_CONTEXT_HH_
#define _SDD_DD_CONTEXT_HH_
/// @cond INTERNAL_DOC
#include <memory> // make_shared, shared_ptr
#include "sdd/dd/context_fwd.hh"
#include "sdd/dd/definition_fwd.hh"
#include "sdd/dd/difference.hh"
#include "sdd/dd/intersection.hh"
#include "sdd/dd/sum.hh"
#include "sdd/dd/top.hh"
#include "sdd/internal/mem/cache.hh"
namespace sdd { namespace dd {
/*-------------------------------------------------------------------------------------------*/
/// @brief The evaluation context of operations on SDD (union, intersection, difference).
///
/// Its purpose is to be able to create local caches at different points of the evaluation.
/// There is a cache per operation type, each of them being wrapped in a std::shared_ptr
/// to enable cheap copy if we want to transmit caches from context to context.
template <typename C>
class context
{
public:
/// @brief Cache parameterized by the difference operation and the top error.
typedef internal::mem::cache<difference_op<C>, top<C>> difference_cache_type;
/// @brief Cache parameterized by the intersection operation and the top error.
typedef internal::mem::cache<intersection_op<C>, top<C>> intersection_cache_type;
/// @brief Cache parameterized by the sum operation and the top error.
typedef internal::mem::cache<sum_op<C>, top<C>> sum_cache_type;
private:
/// @brief Cache of difference on SDD.
std::shared_ptr<difference_cache_type> difference_cache_;
/// @brief Cache of intersection on SDD.
std::shared_ptr<intersection_cache_type> intersection_cache_;
/// @brief Cache of union on SDD.
std::shared_ptr<sum_cache_type> sum_cache_;
public:
/// @brief Create a new empty context.
context(std::size_t difference_size, std::size_t intersection_size, std::size_t sum_size)
: difference_cache_(std::make_shared<difference_cache_type>(difference_size))
, intersection_cache_(std::make_shared<intersection_cache_type>(intersection_size))
, sum_cache_(std::make_shared<sum_cache_type>(sum_size))
{
}
/// @brief Default constructor.
///
/// There are usually more sum operations than intersections and differencies, thus we choose
/// a bigger default size for it.
context()
: context(10000, 10000, 20000)
{
}
/// @brief Construct a context with already existing caches.
context( std::shared_ptr<difference_cache_type> diff
, std::shared_ptr<intersection_cache_type> inter
, std::shared_ptr<sum_cache_type> sum)
: difference_cache_(diff)
, intersection_cache_(inter)
, sum_cache_(sum)
{
}
/// @brief Return the difference cache.
difference_cache_type&
difference_cache()
noexcept
{
return *difference_cache_;
}
/// @brief Return the intersection cache.
intersection_cache_type&
intersection_cache()
noexcept
{
return *intersection_cache_;
}
/// @brief Return the sum cache.
sum_cache_type&
sum_cache()
noexcept
{
return *sum_cache_;
}
/// @brief Remove all entries from all caches.
void
clear()
noexcept
{
difference_cache_->clear();
intersection_cache_->clear();
sum_cache_->clear();
}
};
/*-------------------------------------------------------------------------------------------*/
/// @brief Return the context that serves as an entry point for the evaluation of operations on
/// SDD.
/// @related context
template <typename C>
context<C>&
initial_context()
noexcept
{
static context<C> initial_context;
return initial_context;
}
/*-------------------------------------------------------------------------------------------*/
}} // namespace sdd::dd
/// @endcond
#endif // _SDD_DD_CONTEXT_HH_
<commit_msg>Change the copy constructor of an SDD operation context .<commit_after>#ifndef _SDD_DD_CONTEXT_HH_
#define _SDD_DD_CONTEXT_HH_
/// @cond INTERNAL_DOC
#include <memory> // make_shared, shared_ptr
#include "sdd/dd/context_fwd.hh"
#include "sdd/dd/definition_fwd.hh"
#include "sdd/dd/difference.hh"
#include "sdd/dd/intersection.hh"
#include "sdd/dd/sum.hh"
#include "sdd/dd/top.hh"
#include "sdd/internal/mem/cache.hh"
namespace sdd { namespace dd {
/*-------------------------------------------------------------------------------------------*/
/// @brief The evaluation context of operations on SDD (union, intersection, difference).
///
/// Its purpose is to be able to create local caches at different points of the evaluation.
/// There is a cache per operation type, each of them being wrapped in a std::shared_ptr
/// to enable cheap copy if we want to transmit caches from context to context.
template <typename C>
class context
{
public:
/// @brief Cache parameterized by the difference operation and the top error.
typedef internal::mem::cache<difference_op<C>, top<C>> difference_cache_type;
/// @brief Cache parameterized by the intersection operation and the top error.
typedef internal::mem::cache<intersection_op<C>, top<C>> intersection_cache_type;
/// @brief Cache parameterized by the sum operation and the top error.
typedef internal::mem::cache<sum_op<C>, top<C>> sum_cache_type;
private:
/// @brief Cache of difference on SDD.
std::shared_ptr<difference_cache_type> difference_cache_;
/// @brief Cache of intersection on SDD.
std::shared_ptr<intersection_cache_type> intersection_cache_;
/// @brief Cache of union on SDD.
std::shared_ptr<sum_cache_type> sum_cache_;
public:
/// @brief Create a new empty context.
context(std::size_t difference_size, std::size_t intersection_size, std::size_t sum_size)
: difference_cache_(std::make_shared<difference_cache_type>(difference_size))
, intersection_cache_(std::make_shared<intersection_cache_type>(intersection_size))
, sum_cache_(std::make_shared<sum_cache_type>(sum_size))
{
}
/// @brief Default constructor.
///
/// There are usually more sum operations than intersections and differencies, thus we choose
/// a bigger default size for it.
context()
: context(10000, 10000, 20000)
{
}
/// @brief Copy constructor.
context(const context& other)
: difference_cache_(other.difference_cache_)
, intersection_cache_(other.intersection_cache_)
, sum_cache_(other.sum_cache_)
{
}
/// @brief Return the difference cache.
difference_cache_type&
difference_cache()
noexcept
{
return *difference_cache_;
}
/// @brief Return the intersection cache.
intersection_cache_type&
intersection_cache()
noexcept
{
return *intersection_cache_;
}
/// @brief Return the sum cache.
sum_cache_type&
sum_cache()
noexcept
{
return *sum_cache_;
}
/// @brief Remove all entries from all caches.
void
clear()
noexcept
{
difference_cache_->clear();
intersection_cache_->clear();
sum_cache_->clear();
}
};
/*-------------------------------------------------------------------------------------------*/
/// @brief Return the context that serves as an entry point for the evaluation of operations on
/// SDD.
/// @related context
template <typename C>
context<C>&
initial_context()
noexcept
{
static context<C> initial_context;
return initial_context;
}
/*-------------------------------------------------------------------------------------------*/
}} // namespace sdd::dd
/// @endcond
#endif // _SDD_DD_CONTEXT_HH_
<|endoftext|> |
<commit_before>/*
Copyright (c) 2006, Arvid Norberg & Daniel Wallin
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/pch.hpp"
#include <libtorrent/kademlia/closest_nodes.hpp>
#include <libtorrent/kademlia/routing_table.hpp>
#include <libtorrent/kademlia/rpc_manager.hpp>
#include "libtorrent/assert.hpp"
namespace libtorrent { namespace dht
{
using asio::ip::udp;
closest_nodes_observer::~closest_nodes_observer()
{
if (m_algorithm) m_algorithm->failed(m_self, true);
}
void closest_nodes_observer::reply(msg const& in)
{
if (!m_algorithm)
{
TORRENT_ASSERT(false);
return;
}
if (!in.nodes.empty())
{
for (msg::nodes_t::const_iterator i = in.nodes.begin()
, end(in.nodes.end()); i != end; ++i)
{
m_algorithm->traverse(i->id, i->addr);
}
}
m_algorithm->finished(m_self);
m_algorithm = 0;
}
void closest_nodes_observer::timeout()
{
if (!m_algorithm) return;
m_algorithm->failed(m_self);
m_algorithm = 0;
}
closest_nodes::closest_nodes(
node_id target
, int branch_factor
, int max_results
, routing_table& table
, rpc_manager& rpc
, done_callback const& callback
)
: traversal_algorithm(
target
, branch_factor
, max_results
, table
, rpc
, table.begin()
, table.end()
)
, m_done_callback(callback)
{
boost::intrusive_ptr<closest_nodes> self(this);
add_requests();
}
void closest_nodes::invoke(node_id const& id, udp::endpoint addr)
{
TORRENT_ASSERT(m_rpc.allocation_size() >= sizeof(closest_nodes_observer));
observer_ptr o(new (m_rpc.allocator().malloc()) closest_nodes_observer(this, id, m_target));
#ifndef NDEBUG
o->m_in_constructor = false;
#endif
m_rpc.invoke(messages::find_node, addr, o);
}
void closest_nodes::done()
{
std::vector<node_entry> results;
int num_results = m_table.bucket_size();
for (std::vector<result>::iterator i = m_results.begin()
, end(m_results.end()); i != end && num_results >= 0; ++i)
{
if (i->flags & result::no_id) continue;
results.push_back(node_entry(i->id, i->addr));
--num_results;
}
m_done_callback(results);
}
void closest_nodes::initiate(
node_id target
, int branch_factor
, int max_results
, routing_table& table
, rpc_manager& rpc
, done_callback const& callback
)
{
new closest_nodes(target, branch_factor, max_results, table, rpc, callback);
}
} } // namespace libtorrent::dht
<commit_msg>dht fix<commit_after>/*
Copyright (c) 2006, Arvid Norberg & Daniel Wallin
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/pch.hpp"
#include <libtorrent/kademlia/closest_nodes.hpp>
#include <libtorrent/kademlia/routing_table.hpp>
#include <libtorrent/kademlia/rpc_manager.hpp>
#include "libtorrent/assert.hpp"
namespace libtorrent { namespace dht
{
using asio::ip::udp;
closest_nodes_observer::~closest_nodes_observer()
{
if (m_algorithm) m_algorithm->failed(m_self, true);
}
void closest_nodes_observer::reply(msg const& in)
{
if (!m_algorithm)
{
TORRENT_ASSERT(false);
return;
}
if (!in.nodes.empty())
{
for (msg::nodes_t::const_iterator i = in.nodes.begin()
, end(in.nodes.end()); i != end; ++i)
{
m_algorithm->traverse(i->id, i->addr);
}
}
m_algorithm->finished(m_self);
m_algorithm = 0;
}
void closest_nodes_observer::timeout()
{
if (!m_algorithm) return;
m_algorithm->failed(m_self);
m_algorithm = 0;
}
closest_nodes::closest_nodes(
node_id target
, int branch_factor
, int max_results
, routing_table& table
, rpc_manager& rpc
, done_callback const& callback
)
: traversal_algorithm(
target
, branch_factor
, max_results
, table
, rpc
, table.begin()
, table.end()
)
, m_done_callback(callback)
{
boost::intrusive_ptr<closest_nodes> self(this);
add_requests();
}
void closest_nodes::invoke(node_id const& id, udp::endpoint addr)
{
TORRENT_ASSERT(m_rpc.allocation_size() >= sizeof(closest_nodes_observer));
observer_ptr o(new (m_rpc.allocator().malloc()) closest_nodes_observer(this, id, m_target));
#ifndef NDEBUG
o->m_in_constructor = false;
#endif
m_rpc.invoke(messages::find_node, addr, o);
}
void closest_nodes::done()
{
std::vector<node_entry> results;
int num_results = m_table.bucket_size();
for (std::vector<result>::iterator i = m_max_results
, end(m_results.end()); i != end && num_results >= 0; ++i)
{
if (i->flags & result::no_id) continue;
if ((i->flags & result::queried) == 0) continue;
results.push_back(node_entry(i->id, i->addr));
--num_results;
}
m_done_callback(results);
}
void closest_nodes::initiate(
node_id target
, int branch_factor
, int max_results
, routing_table& table
, rpc_manager& rpc
, done_callback const& callback
)
{
new closest_nodes(target, branch_factor, max_results, table, rpc, callback);
}
} } // namespace libtorrent::dht
<|endoftext|> |
<commit_before>/* Copyright 2016 Carnegie Mellon University
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "scanner/util/memory.h"
#include <cassert>
#include <mutex>
#include <sys/syscall.h>
#include <unistd.h>
#ifdef HAVE_CUDA
#include <cuda.h>
#include <cuda_runtime_api.h>
#include "scanner/util/cuda.h"
#endif
namespace scanner {
// Allocations in Scanner differ from manual memory management in three respects:
//
// 1. Scanner uses different allocators for different devices, e.g. the `new`
// keyword for CPU allocations and cudaMalloc for GPU memory. The System and
// Pool allocators are parameterized by a DeviceHandle to determine which
// device they are allocating for.
//
// 2. The pool allocator up-front allocates a large memory pool and then does its
// own simple memory allocation in place of the system allocator for the
// respective device. Memory pools avoid potentially expensive and synchronous
// calls to the system allocator, e.g. cudaMalloc which synchronizes the whole
// GPU.
//
// 3. Block allocations allow evaluators to allocate a single block of memory for
// their returned rows instead of allocating individually for each row. This
// again reduces the number of cudaMallocs if not using a memory pool.
// Regardless of pool usage, blocks can also be copied in a single memcpy
// instead of many, which reduces memcpy calls. To avoid complexity in the
// core Scanner engine, it is oblivious to whether a u8* in an output row
// is from a block or an individual allocation. Instead, the allocation
// runtime does reference counting when the engine calls free on a memory
// block, e.g. if a memory block is allocated for 96 rows (96 different
// pointers in the same block), then each free to a pointer into the block
// decrements a reference counter until freeing the block at 0 refs.
//
// The user can dictate usage of the memory pool with the MemoryPoolConfig, but
// cannot directly call into it. Users can only ask for normal memory segments
// or block memory segments, the former of which is allocated by the system
// and the latter by the pool if it exists.
class Allocator {
public:
virtual ~Allocator(){};
virtual u8* allocate(size_t size) = 0;
virtual void free(u8* buffer) = 0;
};
class SystemAllocator : public Allocator {
public:
SystemAllocator(DeviceHandle device) :
device_(device) {
}
u8* allocate(size_t size) {
if (device_.type == DeviceType::CPU) {
return new u8[size];
} else if (device_.type == DeviceType::GPU) {
u8* buffer;
#ifdef HAVE_CUDA
CU_CHECK(cudaSetDevice(device_.id));
CU_CHECK(cudaMalloc((void**) &buffer, size));
#else
LOG(FATAL) << "Cuda not enabled.";
#endif
return buffer;
}
}
void free(u8* buffer) {
if (device_.type == DeviceType::CPU) {
delete buffer;
} else if (device_.type == DeviceType::GPU) {
CU_CHECK(cudaSetDevice(device_.id));
CU_CHECK(cudaFree(buffer));
}
}
private:
DeviceHandle device_;
};
bool pointer_in_buffer(u8* ptr, u8* buf_start, u8* buf_end) {
return (size_t) ptr >= (size_t) buf_start &&
(size_t) ptr < (size_t) buf_end;
}
class PoolAllocator : public Allocator {
public:
PoolAllocator(DeviceHandle device, SystemAllocator* allocator, i64 pool_size) :
device_(device),
system_allocator(allocator),
pool_size_(pool_size) {
pool_ = system_allocator->allocate(pool_size_);
}
~PoolAllocator() {
system_allocator->free(pool_);
}
u8* allocate(size_t size) {
Allocation alloc;
alloc.length = size;
std::lock_guard<std::mutex> guard(lock_);
bool found = false;
i32 num_alloc = allocations_.size();
for (i32 i = 0; i < num_alloc; ++i) {
Allocation lower;
if (i == 0) {
lower.offset = 0;
lower.length = 0;
} else {
lower = allocations_[i-1];
}
Allocation higher = allocations_[i];
assert(higher.offset >= lower.offset + lower.length);
if ((higher.offset - (lower.offset + lower.length)) >= size) {
alloc.offset = lower.offset + lower.length;
allocations_.insert(allocations_.begin() + i, alloc);
found = true;
break;
}
}
if (!found) {
if (num_alloc > 0) {
Allocation& last = allocations_[num_alloc - 1];
alloc.offset = last.offset + last.length;
} else {
alloc.offset = 0;
}
allocations_.push_back(alloc);
}
u8* buffer = pool_ + alloc.offset;
LOG_IF(FATAL, alloc.offset + alloc.length > pool_size_)
<< "Exceeded pool size";
return buffer;
}
void free(u8* buffer) {
LOG_IF(FATAL, !pointer_in_buffer(buffer, pool_, pool_ + pool_size_))
<< "Pool allocator tried to free buffer not in pool";
std::lock_guard<std::mutex> guard(lock_);
i32 index;
bool found = find_buffer(buffer, index);
LOG_IF(FATAL, !found)
<< "Attempted to free unallocated buffer in pool";
Allocation& alloc = allocations_[index];
allocations_.erase(allocations_.begin() + index);
}
private:
bool find_buffer(u8* buffer, i32& index) {
i32 num_alloc = allocations_.size();
for (i32 i = 0; i < num_alloc; ++i) {
Allocation alloc = allocations_[i];
if ((size_t) buffer == (size_t) pool_ + alloc.offset) {
index = i;
return true;
}
}
return false;
}
typedef struct {
i64 offset;
i64 length;
} Allocation;
DeviceHandle device_;
u8* pool_ = nullptr;
i64 pool_size_;
std::mutex lock_;
std::vector<Allocation> allocations_;
SystemAllocator* system_allocator;
};
class BlockAllocator {
public:
BlockAllocator(Allocator* allocator) : allocator_(allocator) {
}
u8* allocate(size_t size, i32 refs) {
u8* buffer = allocator_->allocate(size);
Allocation alloc;
alloc.buffer = buffer;
alloc.size = size;
alloc.refs = refs;
std::lock_guard<std::mutex> guard(lock_);
allocations_.push_back(alloc);
return buffer;
}
void free(u8* buffer) {
std::lock_guard<std::mutex> guard(lock_);
i32 index;
bool found = find_buffer(buffer, index);
LOG_IF(FATAL, !found) << "Block allocator freed non-block buffer";
Allocation& alloc = allocations_[index];
assert(alloc.refs > 0);
alloc.refs -= 1;
if (alloc.refs == 0) {
allocator_->free(alloc.buffer);
allocations_.erase(allocations_.begin() + index);
return;
}
}
bool buffers_in_same_block(std::vector<u8*> buffers) {
assert(buffers.size() > 0);
std::lock_guard<std::mutex> guard(lock_);
i32 base_index;
bool found = find_buffer(buffers[0], base_index);
if (!found) { return false; }
for (i32 i = 1; i < buffers.size(); ++i) {
i32 index;
found = find_buffer(buffers[i], index);
if (!found || base_index != index) {
return false;
}
}
return true;
}
bool buffer_in_block(u8* buffer) {
std::lock_guard<std::mutex> guard(lock_);
i32 index;
return find_buffer(buffer, index);
}
private:
bool find_buffer(u8* buffer, i32& index) {
i32 num_alloc = allocations_.size();
for (i32 i = 0; i < num_alloc; ++i) {
Allocation alloc = allocations_[i];
if (pointer_in_buffer(buffer, alloc.buffer, alloc.buffer + alloc.size)) {
index = i;
return true;
}
}
return false;
}
typedef struct {
u8* buffer;
size_t size;
i32 refs;
} Allocation;
std::mutex lock_;
std::vector<Allocation> allocations_;
Allocator* allocator_;
DeviceHandle device_;
};
static SystemAllocator* cpu_system_allocator = nullptr;
static std::map<i32, SystemAllocator*> gpu_system_allocators;
static BlockAllocator* cpu_block_allocator = nullptr;
static std::map<i32, BlockAllocator*> gpu_block_allocators;
void init_memory_allocators(std::vector<i32> gpu_devices_ids,
MemoryPoolConfig config) {
cpu_system_allocator = new SystemAllocator(CPU_DEVICE);
Allocator* cpu_block_allocator_base = cpu_system_allocator;
if (config.use_pool) {
cpu_block_allocator_base =
new PoolAllocator(CPU_DEVICE, cpu_system_allocator, config.pool_size);
}
cpu_block_allocator = new BlockAllocator(cpu_block_allocator_base);
#ifdef HAVE_CUDA
for (i32 device_id : gpu_devices_ids) {
DeviceHandle device = {DeviceType::GPU, device_id};
SystemAllocator* gpu_system_allocator =
new SystemAllocator(device);
gpu_system_allocators[device.id] = gpu_system_allocator;
Allocator* gpu_block_allocator_base = gpu_system_allocator;
if (config.use_pool) {
gpu_block_allocator_base =
new PoolAllocator(device, gpu_system_allocator, config.pool_size);
}
gpu_block_allocators[device.id] =
new BlockAllocator(gpu_block_allocator_base);
}
#else
assert(gpu_devices_ids.size() == 0);
#endif
}
SystemAllocator* system_allocator_for_device(DeviceHandle device) {
if (device.type == DeviceType::CPU) {
return cpu_system_allocator;
} else if (device.type == DeviceType::GPU) {
#ifndef HAVE_CUDA
LOG(FATAL) << "Cuda not enabled";
#endif
return gpu_system_allocators.at(device.id);
} else {
LOG(FATAL) << "Tried to allocate buffer of unsupported device type";
}
}
BlockAllocator* block_allocator_for_device(DeviceHandle device) {
if (device.type == DeviceType::CPU) {
return cpu_block_allocator;
} else if (device.type == DeviceType::GPU) {
#ifndef HAVE_CUDA
LOG(FATAL) << "Cuda not enabled";
#endif
return gpu_block_allocators.at(device.id);
} else {
LOG(FATAL) << "Tried to allocate buffer of unsupported device type";
}
}
u8* new_buffer(DeviceHandle device, size_t size) {
assert(size > 0);
SystemAllocator* allocator = system_allocator_for_device(device);
return allocator->allocate(size);
}
u8* new_block_buffer(DeviceHandle device, size_t size, i32 refs) {
assert(size > 0);
BlockAllocator* allocator = block_allocator_for_device(device);
return allocator->allocate(size, refs);
}
void delete_buffer(DeviceHandle device, u8* buffer) {
assert(buffer != nullptr);
BlockAllocator* block_allocator = block_allocator_for_device(device);
if (block_allocator->buffer_in_block(buffer)) {
block_allocator->free(buffer);
} else {
SystemAllocator* system_allocator = system_allocator_for_device(device);
system_allocator->free(buffer);
}
}
// FIXME(wcrichto): case if transferring between two different GPUs
void memcpy_buffer(u8* dest_buffer, DeviceHandle dest_device,
const u8* src_buffer, DeviceHandle src_device,
size_t size) {
#ifdef HAVE_CUDA
CU_CHECK(cudaMemcpy(dest_buffer, src_buffer, size, cudaMemcpyDefault));
#else
assert(dest_type == DeviceType::CPU);
assert(dest_type == src_type);
memcpy(dest_buffer, src_buffer, size);
#endif
}
#define NUM_CUDA_STREAMS 32
void memcpy_vec(std::vector<u8*> dest_buffers, DeviceHandle dest_device,
const std::vector<u8*> src_buffers, DeviceHandle src_device,
std::vector<size_t> sizes) {
thread_local std::vector<cudaStream_t> streams;
if (streams.size() == 0) {
streams.resize(NUM_CUDA_STREAMS);
for (i32 i = 0; i < NUM_CUDA_STREAMS; ++i) {
cudaStreamCreateWithFlags(&streams[i], cudaStreamNonBlocking);
}
}
assert(dest_buffers.size() > 0);
assert(src_buffers.size() > 0);
assert(dest_buffers.size() == src_buffers.size());
BlockAllocator* dest_allocator = block_allocator_for_device(dest_device);
BlockAllocator* src_allocator = block_allocator_for_device(src_device);
// In the case where the dest and src vectors are each respectively drawn
// from a single block, we do a single memcpy from one block to the other.
if (dest_allocator->buffers_in_same_block(dest_buffers) &&
src_allocator->buffers_in_same_block(src_buffers))
{
size_t total_size = 0;
for (auto size : sizes) {
total_size += size;
}
CU_CHECK(cudaMemcpyAsync(dest_buffers[0], src_buffers[0], total_size,
cudaMemcpyDefault, streams[0]));
CU_CHECK(cudaStreamSynchronize(streams[0]));
} else {
#ifdef HAVE_CUDA
i32 n = dest_buffers.size();
for (i32 i = 0; i < n; ++i) {
CU_CHECK(cudaMemcpyAsync(dest_buffers[i], src_buffers[i], sizes[i],
cudaMemcpyDefault, streams[i % NUM_CUDA_STREAMS]));
}
for (i32 i = 0; i < std::min(n, NUM_CUDA_STREAMS); ++i) {
cudaStreamSynchronize(streams[i]);
}
#else
LOG(FATAL) << "Not yet implemented";
#endif
}
}
}
<commit_msg>Fixed memcpy not setting cuda device<commit_after>/* Copyright 2016 Carnegie Mellon University
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "scanner/util/memory.h"
#include <cassert>
#include <mutex>
#include <sys/syscall.h>
#include <unistd.h>
#ifdef HAVE_CUDA
#include <cuda.h>
#include <cuda_runtime_api.h>
#include "scanner/util/cuda.h"
#endif
namespace scanner {
// Allocations in Scanner differ from manual memory management in three respects:
//
// 1. Scanner uses different allocators for different devices, e.g. the `new`
// keyword for CPU allocations and cudaMalloc for GPU memory. The System and
// Pool allocators are parameterized by a DeviceHandle to determine which
// device they are allocating for.
//
// 2. The pool allocator up-front allocates a large memory pool and then does its
// own simple memory allocation in place of the system allocator for the
// respective device. Memory pools avoid potentially expensive and synchronous
// calls to the system allocator, e.g. cudaMalloc which synchronizes the whole
// GPU.
//
// 3. Block allocations allow evaluators to allocate a single block of memory for
// their returned rows instead of allocating individually for each row. This
// again reduces the number of cudaMallocs if not using a memory pool.
// Regardless of pool usage, blocks can also be copied in a single memcpy
// instead of many, which reduces memcpy calls. To avoid complexity in the
// core Scanner engine, it is oblivious to whether a u8* in an output row
// is from a block or an individual allocation. Instead, the allocation
// runtime does reference counting when the engine calls free on a memory
// block, e.g. if a memory block is allocated for 96 rows (96 different
// pointers in the same block), then each free to a pointer into the block
// decrements a reference counter until freeing the block at 0 refs.
//
// The user can dictate usage of the memory pool with the MemoryPoolConfig, but
// cannot directly call into it. Users can only ask for normal memory segments
// or block memory segments, the former of which is allocated by the system
// and the latter by the pool if it exists.
class Allocator {
public:
virtual ~Allocator(){};
virtual u8* allocate(size_t size) = 0;
virtual void free(u8* buffer) = 0;
};
class SystemAllocator : public Allocator {
public:
SystemAllocator(DeviceHandle device) :
device_(device) {
}
u8* allocate(size_t size) {
if (device_.type == DeviceType::CPU) {
return new u8[size];
} else if (device_.type == DeviceType::GPU) {
u8* buffer;
#ifdef HAVE_CUDA
CU_CHECK(cudaSetDevice(device_.id));
CU_CHECK(cudaMalloc((void**) &buffer, size));
#else
LOG(FATAL) << "Cuda not enabled.";
#endif
return buffer;
}
}
void free(u8* buffer) {
if (device_.type == DeviceType::CPU) {
delete buffer;
} else if (device_.type == DeviceType::GPU) {
CU_CHECK(cudaSetDevice(device_.id));
CU_CHECK(cudaFree(buffer));
}
}
private:
DeviceHandle device_;
};
bool pointer_in_buffer(u8* ptr, u8* buf_start, u8* buf_end) {
return (size_t) ptr >= (size_t) buf_start &&
(size_t) ptr < (size_t) buf_end;
}
class PoolAllocator : public Allocator {
public:
PoolAllocator(DeviceHandle device, SystemAllocator* allocator, i64 pool_size) :
device_(device),
system_allocator(allocator),
pool_size_(pool_size) {
pool_ = system_allocator->allocate(pool_size_);
}
~PoolAllocator() {
system_allocator->free(pool_);
}
u8* allocate(size_t size) {
Allocation alloc;
alloc.length = size;
std::lock_guard<std::mutex> guard(lock_);
bool found = false;
i32 num_alloc = allocations_.size();
for (i32 i = 0; i < num_alloc; ++i) {
Allocation lower;
if (i == 0) {
lower.offset = 0;
lower.length = 0;
} else {
lower = allocations_[i-1];
}
Allocation higher = allocations_[i];
assert(higher.offset >= lower.offset + lower.length);
if ((higher.offset - (lower.offset + lower.length)) >= size) {
alloc.offset = lower.offset + lower.length;
allocations_.insert(allocations_.begin() + i, alloc);
found = true;
break;
}
}
if (!found) {
if (num_alloc > 0) {
Allocation& last = allocations_[num_alloc - 1];
alloc.offset = last.offset + last.length;
} else {
alloc.offset = 0;
}
allocations_.push_back(alloc);
}
u8* buffer = pool_ + alloc.offset;
LOG_IF(FATAL, alloc.offset + alloc.length >= pool_size_)
<< "Exceeded pool size";
return buffer;
}
void free(u8* buffer) {
LOG_IF(FATAL, !pointer_in_buffer(buffer, pool_, pool_ + pool_size_))
<< "Pool allocator tried to free buffer not in pool";
std::lock_guard<std::mutex> guard(lock_);
i32 index;
bool found = find_buffer(buffer, index);
LOG_IF(FATAL, !found)
<< "Attempted to free unallocated buffer in pool";
Allocation& alloc = allocations_[index];
allocations_.erase(allocations_.begin() + index);
}
private:
bool find_buffer(u8* buffer, i32& index) {
i32 num_alloc = allocations_.size();
for (i32 i = 0; i < num_alloc; ++i) {
Allocation alloc = allocations_[i];
if ((size_t) buffer == (size_t) pool_ + alloc.offset) {
index = i;
return true;
}
}
return false;
}
typedef struct {
i64 offset;
i64 length;
} Allocation;
DeviceHandle device_;
u8* pool_ = nullptr;
i64 pool_size_;
std::mutex lock_;
std::vector<Allocation> allocations_;
SystemAllocator* system_allocator;
};
class BlockAllocator {
public:
BlockAllocator(Allocator* allocator) : allocator_(allocator) {
}
u8* allocate(size_t size, i32 refs) {
u8* buffer = allocator_->allocate(size);
Allocation alloc;
alloc.buffer = buffer;
alloc.size = size;
alloc.refs = refs;
std::lock_guard<std::mutex> guard(lock_);
allocations_.push_back(alloc);
return buffer;
}
void free(u8* buffer) {
std::lock_guard<std::mutex> guard(lock_);
i32 index;
bool found = find_buffer(buffer, index);
LOG_IF(FATAL, !found) << "Block allocator freed non-block buffer";
Allocation& alloc = allocations_[index];
assert(alloc.refs > 0);
alloc.refs -= 1;
if (alloc.refs == 0) {
allocator_->free(alloc.buffer);
allocations_.erase(allocations_.begin() + index);
return;
}
}
bool buffers_in_same_block(std::vector<u8*> buffers) {
assert(buffers.size() > 0);
std::lock_guard<std::mutex> guard(lock_);
i32 base_index;
bool found = find_buffer(buffers[0], base_index);
if (!found) { return false; }
for (i32 i = 1; i < buffers.size(); ++i) {
i32 index;
found = find_buffer(buffers[i], index);
if (!found || base_index != index) {
return false;
}
}
return true;
}
bool buffer_in_block(u8* buffer) {
std::lock_guard<std::mutex> guard(lock_);
i32 index;
return find_buffer(buffer, index);
}
private:
bool find_buffer(u8* buffer, i32& index) {
i32 num_alloc = allocations_.size();
for (i32 i = 0; i < num_alloc; ++i) {
Allocation alloc = allocations_[i];
if (pointer_in_buffer(buffer, alloc.buffer, alloc.buffer + alloc.size)) {
index = i;
return true;
}
}
return false;
}
typedef struct {
u8* buffer;
size_t size;
i32 refs;
} Allocation;
std::mutex lock_;
std::vector<Allocation> allocations_;
Allocator* allocator_;
};
static SystemAllocator* cpu_system_allocator = nullptr;
static std::map<i32, SystemAllocator*> gpu_system_allocators;
static BlockAllocator* cpu_block_allocator = nullptr;
static std::map<i32, BlockAllocator*> gpu_block_allocators;
void init_memory_allocators(std::vector<i32> gpu_devices_ids,
MemoryPoolConfig config) {
cpu_system_allocator = new SystemAllocator(CPU_DEVICE);
Allocator* cpu_block_allocator_base = cpu_system_allocator;
if (config.use_pool) {
cpu_block_allocator_base =
new PoolAllocator(CPU_DEVICE, cpu_system_allocator, config.pool_size);
}
cpu_block_allocator = new BlockAllocator(cpu_block_allocator_base);
#ifdef HAVE_CUDA
for (i32 device_id : gpu_devices_ids) {
DeviceHandle device = {DeviceType::GPU, device_id};
SystemAllocator* gpu_system_allocator =
new SystemAllocator(device);
gpu_system_allocators[device.id] = gpu_system_allocator;
Allocator* gpu_block_allocator_base = gpu_system_allocator;
if (config.use_pool) {
gpu_block_allocator_base =
new PoolAllocator(device, gpu_system_allocator, config.pool_size);
}
gpu_block_allocators[device.id] =
new BlockAllocator(gpu_block_allocator_base);
}
#else
assert(gpu_devices_ids.size() == 0);
#endif
}
SystemAllocator* system_allocator_for_device(DeviceHandle device) {
if (device.type == DeviceType::CPU) {
return cpu_system_allocator;
} else if (device.type == DeviceType::GPU) {
#ifndef HAVE_CUDA
LOG(FATAL) << "Cuda not enabled";
#endif
return gpu_system_allocators.at(device.id);
} else {
LOG(FATAL) << "Tried to allocate buffer of unsupported device type";
}
}
BlockAllocator* block_allocator_for_device(DeviceHandle device) {
if (device.type == DeviceType::CPU) {
return cpu_block_allocator;
} else if (device.type == DeviceType::GPU) {
#ifndef HAVE_CUDA
LOG(FATAL) << "Cuda not enabled";
#endif
return gpu_block_allocators.at(device.id);
} else {
LOG(FATAL) << "Tried to allocate buffer of unsupported device type";
}
}
u8* new_buffer(DeviceHandle device, size_t size) {
assert(size > 0);
SystemAllocator* allocator = system_allocator_for_device(device);
return allocator->allocate(size);
}
u8* new_block_buffer(DeviceHandle device, size_t size, i32 refs) {
assert(size > 0);
BlockAllocator* allocator = block_allocator_for_device(device);
return allocator->allocate(size, refs);
}
void delete_buffer(DeviceHandle device, u8* buffer) {
assert(buffer != nullptr);
BlockAllocator* block_allocator = block_allocator_for_device(device);
if (block_allocator->buffer_in_block(buffer)) {
block_allocator->free(buffer);
} else {
SystemAllocator* system_allocator = system_allocator_for_device(device);
system_allocator->free(buffer);
}
}
// FIXME(wcrichto): case if transferring between two different GPUs
void memcpy_buffer(u8* dest_buffer, DeviceHandle dest_device,
const u8* src_buffer, DeviceHandle src_device,
size_t size) {
assert(!(dest_device.type == DeviceType::GPU &&
src_device.type == DeviceType::GPU &&
dest_device.id != src_device.id));
#ifdef HAVE_CUDA
CU_CHECK(cudaSetDevice(src_device.id));
CU_CHECK(cudaMemcpy(dest_buffer, src_buffer, size, cudaMemcpyDefault));
#else
assert(dest_type == DeviceType::CPU);
assert(dest_type == src_type);
memcpy(dest_buffer, src_buffer, size);
#endif
}
#define NUM_CUDA_STREAMS 32
void memcpy_vec(std::vector<u8*> dest_buffers, DeviceHandle dest_device,
const std::vector<u8*> src_buffers, DeviceHandle src_device,
std::vector<size_t> sizes) {
assert(!(dest_device.type == DeviceType::GPU &&
src_device.type == DeviceType::GPU &&
dest_device.id != src_device.id));
thread_local std::vector<cudaStream_t> streams;
if (streams.size() == 0) {
streams.resize(NUM_CUDA_STREAMS);
for (i32 i = 0; i < NUM_CUDA_STREAMS; ++i) {
cudaStreamCreateWithFlags(&streams[i], cudaStreamNonBlocking);
}
}
assert(dest_buffers.size() > 0);
assert(src_buffers.size() > 0);
assert(dest_buffers.size() == src_buffers.size());
BlockAllocator* dest_allocator = block_allocator_for_device(dest_device);
BlockAllocator* src_allocator = block_allocator_for_device(src_device);
CU_CHECK(cudaSetDevice(src_device.id));
// In the case where the dest and src vectors are each respectively drawn
// from a single block, we do a single memcpy from one block to the other.
if (dest_allocator->buffers_in_same_block(dest_buffers) &&
src_allocator->buffers_in_same_block(src_buffers))
{
size_t total_size = 0;
for (auto size : sizes) {
total_size += size;
}
CU_CHECK(cudaMemcpyAsync(dest_buffers[0], src_buffers[0], total_size,
cudaMemcpyDefault, streams[0]));
CU_CHECK(cudaStreamSynchronize(streams[0]));
} else {
#ifdef HAVE_CUDA
i32 n = dest_buffers.size();
for (i32 i = 0; i < n; ++i) {
CU_CHECK(cudaMemcpyAsync(dest_buffers[i], src_buffers[i], sizes[i],
cudaMemcpyDefault, streams[i % NUM_CUDA_STREAMS]));
}
for (i32 i = 0; i < std::min(n, NUM_CUDA_STREAMS); ++i) {
cudaStreamSynchronize(streams[i]);
}
#else
LOG(FATAL) << "Not yet implemented";
#endif
}
}
}
<|endoftext|> |
<commit_before>/*
* opencog/atoms/core/Checkers.cc
*
* Copyright (C) 2017 Linas Vepstas
* All Rights Reserved
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <opencog/atoms/base/Atom.h>
#include <opencog/atoms/base/ClassServer.h>
using namespace opencog;
// There is a way for the user to pull a fast one, and crash us here.
// avoid null-ptr deref.
static inline void check_null(const Handle& h)
{
if (nullptr == h)
throw InvalidParamException(TRACE_INFO,
"Outgoing set of Link contains null handle\n");
}
/// Provide static factory-time type checking.
/// This only performs a very simple kind of type checking;
/// it does not check deep types, nor does it check arity.
/// Check to see if every input atom is of Evaluatable type.
bool check_evaluatable(const Handle& bool_atom)
{
// Make an exception for AndLink, its used in pattern matcher
// in an unseemly way.
if (bool_atom->get_type() == AND_LINK) return true;
for (const Handle& h: bool_atom->getOutgoingSet())
{
check_null(h);
Type t = h->get_type();
// PutLinks and GetLinks cannot be type-checked statically.
// Checking has to be defered until runtime.
if (PUT_LINK == t) continue;
if (GET_LINK == t) continue;
if (VARIABLE_NODE == t) continue;
if (DEFINED_PREDICATE_NODE == t) continue;
// Allow conjunction, disjunction and negation of
// predicates. Since it cannot inherit from EVALUATABLE_LINK
// (cause it's a Node) we have to add it here.
if (PREDICATE_NODE == t) continue;
// Allow conjunction, disjunction and negation of concepts as
// well, in that case these are interpreted as intersection,
// union and complement. Since it cannot inherit from
// EVALUATABLE_LINK (cause it's a Node) we have to add it here.
if (CONCEPT_NODE == t) continue;
// Fucking quote links. I hate those with a passion.
if (QUOTE_LINK == t) continue;
if (UNQUOTE_LINK == t) continue;
if (not h->is_type(EVALUATABLE_LINK)) return false;
}
return true;
}
/// Check to see if every input atom is of Numeric type.
bool check_numeric(const Handle& bool_atom)
{
for (const Handle& h: bool_atom->getOutgoingSet())
{
check_null(h);
Type t = h->get_type();
// PutLinks and GetLinks cannot be type-checked statically.
// Checking has to be defered until runtime.
if (PUT_LINK == t) continue;
if (GET_LINK == t) continue;
if (EXECUTION_OUTPUT_LINK == t) continue;
if (VARIABLE_NODE == t) continue;
if (NUMBER_NODE == t) continue;
// TODO - look up the schema, and make sure its numeric, also.
if (DEFINED_SCHEMA_NODE == t) continue;
// Oddly enough, sets of numbers are allowed.
if (SET_LINK == t and check_numeric(h)) continue;
if (QUOTE_LINK == t) continue;
if (UNQUOTE_LINK == t) continue;
if (not h->is_type(NUMERIC_OUTPUT_LINK)) return false;
}
return true;
}
/// Check the type constructors that expect types as input.
bool check_type_ctors(const Handle& bool_atom)
{
for (const Handle& h: bool_atom->getOutgoingSet())
{
check_null(h);
Type t = h->get_type();
if (h->is_type(TYPE_NODE)) continue;
// Intervals are commonly used with GlobNodes.
if (INTERVAL_LINK == t) continue;
if (not h->is_type(TYPE_OUTPUT_LINK)) return false;
}
return true;
}
/* This runs when the shared lib is loaded. */
static __attribute__ ((constructor)) void init(void)
{
classserver().addValidator(BOOLEAN_LINK, check_evaluatable);
classserver().addValidator(NUMERIC_LINK, check_numeric);
classserver().addValidator(TYPE_LINK, check_type_ctors);
}
<commit_msg>Allow adding, subtracting, etc schema nodes<commit_after>/*
* opencog/atoms/core/Checkers.cc
*
* Copyright (C) 2017 Linas Vepstas
* All Rights Reserved
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <opencog/atoms/base/Atom.h>
#include <opencog/atoms/base/ClassServer.h>
using namespace opencog;
// There is a way for the user to pull a fast one, and crash us here.
// avoid null-ptr deref.
static inline void check_null(const Handle& h)
{
if (nullptr == h)
throw InvalidParamException(TRACE_INFO,
"Outgoing set of Link contains null handle\n");
}
/// Provide static factory-time type checking.
/// This only performs a very simple kind of type checking;
/// it does not check deep types, nor does it check arity.
/// Check to see if every input atom is of Evaluatable type.
bool check_evaluatable(const Handle& bool_atom)
{
// Make an exception for AndLink, its used in pattern matcher
// in an unseemly way.
if (bool_atom->get_type() == AND_LINK) return true;
for (const Handle& h: bool_atom->getOutgoingSet())
{
check_null(h);
Type t = h->get_type();
// PutLinks and GetLinks cannot be type-checked statically.
// Checking has to be defered until runtime.
if (PUT_LINK == t) continue;
if (GET_LINK == t) continue;
if (VARIABLE_NODE == t) continue;
if (DEFINED_PREDICATE_NODE == t) continue;
// Allow conjunction, disjunction and negation of
// predicates. Since it cannot inherit from EVALUATABLE_LINK
// (cause it's a Node) we have to add it here.
if (PREDICATE_NODE == t) continue;
// Allow conjunction, disjunction and negation of concepts as
// well, in that case these are interpreted as intersection,
// union and complement. Since it cannot inherit from
// EVALUATABLE_LINK (cause it's a Node) we have to add it here.
if (CONCEPT_NODE == t) continue;
// Fucking quote links. I hate those with a passion.
if (QUOTE_LINK == t) continue;
if (UNQUOTE_LINK == t) continue;
if (not h->is_type(EVALUATABLE_LINK)) return false;
}
return true;
}
/// Check to see if every input atom is of Numeric type.
bool check_numeric(const Handle& bool_atom)
{
for (const Handle& h: bool_atom->getOutgoingSet())
{
check_null(h);
Type t = h->get_type();
// PutLinks and GetLinks cannot be type-checked statically.
// Checking has to be defered until runtime.
if (PUT_LINK == t) continue;
if (GET_LINK == t) continue;
if (EXECUTION_OUTPUT_LINK == t) continue;
if (VARIABLE_NODE == t) continue;
if (NUMBER_NODE == t) continue;
// TODO - look up the schema, and make sure its numeric, also.
if (DEFINED_SCHEMA_NODE == t) continue;
// Oddly enough, sets of numbers are allowed.
if (SET_LINK == t and check_numeric(h)) continue;
// Allows to add, subtract, etc functions (used by as-moses)
if (SCHEMA_NODE == t) continue;
if (QUOTE_LINK == t) continue;
if (UNQUOTE_LINK == t) continue;
if (not h->is_type(NUMERIC_OUTPUT_LINK)) return false;
}
return true;
}
/// Check the type constructors that expect types as input.
bool check_type_ctors(const Handle& bool_atom)
{
for (const Handle& h: bool_atom->getOutgoingSet())
{
check_null(h);
Type t = h->get_type();
if (h->is_type(TYPE_NODE)) continue;
// Intervals are commonly used with GlobNodes.
if (INTERVAL_LINK == t) continue;
if (not h->is_type(TYPE_OUTPUT_LINK)) return false;
}
return true;
}
/* This runs when the shared lib is loaded. */
static __attribute__ ((constructor)) void init(void)
{
classserver().addValidator(BOOLEAN_LINK, check_evaluatable);
classserver().addValidator(NUMERIC_LINK, check_numeric);
classserver().addValidator(TYPE_LINK, check_type_ctors);
}
<|endoftext|> |
<commit_before>/* Copyright 2021 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <random>
#include "tensorflow/core/lib/random/philox_random.h"
#include "tensorflow/core/lib/random/random_distributions_utils.h"
#include "tensorflow/lite/c/builtin_op_data.h"
#include "tensorflow/lite/kernels/internal/tensor_ctypes.h"
#include "tensorflow/lite/kernels/kernel_util.h"
namespace tflite {
namespace ops {
namespace builtin {
namespace random {
namespace {
using Generator = ::tensorflow::random::PhiloxRandom;
enum RandomType { kRandomUniform, kRandomStandardNormal, kMultinomial };
struct OpData {
Generator rng;
};
// Initialize the OpData based on the seed and seed2 values.
void InitializeOpData(TfLiteNode* node) {
static std::mt19937_64* seed_generator = []() {
std::random_device device("/dev/urandom");
return new std::mt19937_64(device());
}();
auto* params = static_cast<TfLiteRandomParams*>(node->builtin_data);
OpData* data = reinterpret_cast<OpData*>(node->user_data);
int64_t seed = params->seed;
int64_t seed2 = params->seed2;
if (seed == 0 && seed2 == 0) {
// If both seeds are unspecified, generate non-deterministic random numbers.
seed = (*seed_generator)();
seed2 = (*seed_generator)();
}
Generator rng(seed, seed2);
data->rng = rng;
}
// Generates random numbers following a uniform distribution.
// Source: third_party/tensorflow/core/kernels/random_op.cc
void GenerateRandomUniformNumbers(
Generator& rng, float* buffer, size_t buffer_size) {
size_t current_size = 0;
size_t rng_size = Generator::kResultElementCount;
while (current_size < buffer_size) {
typename Generator::ResultType samples = rng();
const int rng_net_size = std::min(rng_size, buffer_size - current_size);
for (int i = 0; i < rng_net_size; i++) {
buffer[current_size + i] = tensorflow::random::Uint32ToFloat(samples[i]);
}
current_size += rng_net_size;
}
}
// Generates random numbers following a standard normal distribution.
// Source: third_party/tensorflow/core/kernels/random_op.cc
void GenerateRandomStandardNormalNumbers(
Generator& rng, float* buffer, size_t buffer_size) {
size_t current_size = 0;
size_t rng_size = Generator::kResultElementCount;
while (current_size < buffer_size) {
typename Generator::ResultType samples = rng();
const int rng_net_size = std::min(rng_size, buffer_size - current_size);
for (int i = 0; i < rng_net_size; i += 2) {
tensorflow::random::BoxMullerFloat(samples[i], samples[i + 1],
&buffer[current_size + i],
&buffer[current_size + i + 1]);
}
current_size += rng_net_size;
}
}
// Generates random numbers following a multinomial distribution.
// Source: third_party/tensorflow/core/kernels/multinomial_op.cc
void GenerateMultinomialNumbers(Generator& rng, const float* logits,
size_t logits_size, int64_t* output,
size_t num_samples) {
// Compute the maximum logit.
float max = std::numeric_limits<float>::lowest();
for (size_t i = 0; i < logits_size; i++) {
if (isfinite(logits[i])) {
max = std::max(max, logits[i]);
}
}
const double max_logit = static_cast<double>(max);
// Compute the (unnormalized) cumulative probability distribution.
// For numerical stability (as the exponential function grows very fast),
// subtract the maximum logit. Though you can subtract any value without
// changing the output, we use the maximum logit for convenience.
std::vector<double> cdf(logits_size);
double cumulative_total = 0.0f;
for (size_t i = 0; i < logits_size; i++) {
if (isfinite(logits[i])) {
cumulative_total += exp(logits[i] - max_logit);
}
cdf[i] = cumulative_total;
}
// Generate random categorical numbers and populate the output.
size_t current_size = 0;
size_t rng_size = Generator::kResultElementCount;
// Number of skipped 128-bits samples (i.e, number of generator calls)
int num_samples_skipped = 0;
while (current_size < num_samples) {
const int update_size = std::min(rng_size / 2, num_samples - current_size);
typename Generator::ResultType samples = rng();
num_samples_skipped += 1;
for (int i = 0; i < update_size; i += 1) {
const double value = tensorflow::random::Uint64ToDouble(
samples[i * 2], samples[i * 2 + 1]) *
cumulative_total;
output[current_size + i] =
std::upper_bound(cdf.begin(), cdf.end(), value) - cdf.begin();
}
current_size += update_size;
}
// Skip enough 128-bits samples to ensure that the output is always unique.
// Round to a multiple of 4 (+3 ensures a different state in every batch)
int num_samples_ceil_4 = (num_samples + 3) / 4 * 4;
// CPU generates 2 samples per number and 256 is a conservative multiplier.
int num_samples_to_skip_total = num_samples_ceil_4 * 2 * 256;
// Compute the number of 128-bits samples to skip.
int num_samples_to_skip = num_samples_to_skip_total - num_samples_skipped;
rng.Skip(num_samples_to_skip);
}
} // namespace
void* Init(TfLiteContext* context, const char* buffer, size_t length) {
return new OpData();
}
void Free(TfLiteContext* context, void* buffer) {
delete reinterpret_cast<OpData*>(buffer);
}
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
// Validate number of inputs and outputs
TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
// 'shape' is a 1-D int array
const TfLiteTensor* shape;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &shape));
TF_LITE_ENSURE_EQ(context, shape->type, kTfLiteInt32);
TF_LITE_ENSURE_EQ(context, NumDimensions(shape), 1);
// Initialize the random number generator
InitializeOpData(node);
TfLiteTensor* output = GetOutput(context, node, 0);
if (!IsConstantTensor(shape)) {
SetTensorToDynamic(output);
return kTfLiteOk;
}
TfLiteIntArray* output_shape;
TF_LITE_ENSURE_OK(context,
GetOutputShapeFromInput(context, shape, &output_shape));
return context->ResizeTensor(context, output, output_shape);
}
TfLiteStatus PrepareMultinomial(TfLiteContext* context, TfLiteNode* node) {
// Validate number of inputs and outputs
TF_LITE_ENSURE_EQ(context, NumInputs(node), 2);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
// 'logits' is a 2-D input float matrix with shape [batch_size, num_classes]
const TfLiteTensor* logits;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &logits));
TF_LITE_ENSURE(context, logits->type == kTfLiteFloat32);
TF_LITE_ENSURE_EQ(context, NumDimensions(logits), 2);
const int batch_size = SizeOfDimension(logits, 0);
const int num_classes = SizeOfDimension(logits, 1);
TF_LITE_ENSURE(context, num_classes > 0);
// Ensure logits shape isn't too large for int
TF_LITE_ENSURE(context, static_cast<int>(batch_size) == batch_size);
TF_LITE_ENSURE(context, static_cast<int>(num_classes) == num_classes);
// 'num_samples' is a 0-D input int scalar
const TfLiteTensor* num_samples;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 1, &num_samples));
TF_LITE_ENSURE_EQ(context, num_samples->type, kTfLiteInt32);
TF_LITE_ENSURE_EQ(context, NumDimensions(num_samples), 0);
TF_LITE_ENSURE(context, *num_samples->data.i32 >= 0);
// Initialize the random number generator
InitializeOpData(node);
TfLiteTensor* output = GetOutput(context, node, 0);
if (!IsConstantTensor(logits) || !IsConstantTensor(num_samples)) {
SetTensorToDynamic(output);
return kTfLiteOk;
}
// 'output' is a 2-D int64 matrix with shape [batch_size, num_samples]
TfLiteIntArray* output_shape = TfLiteIntArrayCreate(2);
output_shape->data[0] = SizeOfDimension(logits, 0); // batch_size
output_shape->data[1] = *num_samples->data.i32; // num_samples
return context->ResizeTensor(context, output, output_shape);
}
TfLiteStatus EvalRandomType(
TfLiteContext* context, TfLiteNode* node, RandomType random_type) {
TfLiteTensor* output = GetOutput(context, node, 0);
OpData* data = reinterpret_cast<OpData*>(node->user_data);
const size_t output_size = NumElements(output);
switch (random_type) {
case kRandomUniform:
GenerateRandomUniformNumbers(
data->rng, GetTensorData<float>(output), output_size);
break;
case kRandomStandardNormal:
GenerateRandomStandardNormalNumbers(
data->rng, GetTensorData<float>(output), output_size);
break;
default:
return kTfLiteError;
}
return kTfLiteOk;
}
template <RandomType rtype>
TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
TfLiteTensor* output = GetOutput(context, node, 0);
if (IsDynamicTensor(output)) {
const TfLiteTensor* shape = GetInput(context, node, 0);
TfLiteIntArray* output_shape;
TF_LITE_ENSURE_OK(context,
GetOutputShapeFromInput(context, shape, &output_shape));
context->ResizeTensor(context, output, output_shape);
}
switch (output->type) {
case kTfLiteFloat32:
EvalRandomType(context, node, rtype);
break;
default:
TF_LITE_KERNEL_LOG(
context, "Unsupported output datatype for %s op: %s",
rtype == kRandomUniform? "RandomUniform": "RandomStandardNormal",
TfLiteTypeGetName(output->type));
return kTfLiteError;
}
return kTfLiteOk;
}
TfLiteStatus EvalMultinomial(TfLiteContext* context, TfLiteNode* node) {
OpData* params = reinterpret_cast<OpData*>(node->user_data);
TF_LITE_ENSURE(context, params != nullptr);
// 'logits' is a 2-D float matrix with shape [batch_size, num_classes]
const TfLiteTensor* logits_tensor = GetInput(context, node, 0);
const float* logits = GetTensorData<float>(logits_tensor);
int batch_size = SizeOfDimension(logits_tensor, 0);
int num_classes = SizeOfDimension(logits_tensor, 1);
// 'num_samples' is an int scalar
const TfLiteTensor* num_samples = GetInput(context, node, 1);
int num_samples_ = *num_samples->data.i32;
TfLiteTensor* output_tensor = GetOutput(context, node, 0);
if (IsDynamicTensor(output_tensor)) {
// 'output' is a 2-D int64 matrix with shape [batch_size, num_samples]
TfLiteIntArray* output_shape = TfLiteIntArrayCreate(2);
output_shape->data[0] = batch_size;
output_shape->data[1] = num_samples_;
TF_LITE_ENSURE_OK(
context, context->ResizeTensor(context, output_tensor, output_shape));
}
OpData* data = reinterpret_cast<OpData*>(node->user_data);
int64_t* output = GetTensorData<int64_t>(output_tensor);
for (int batch = 0; batch < batch_size; ++batch) {
int logits_offset = num_classes * batch;
int outputs_offset = num_samples_ * batch;
switch (output_tensor->type) {
case kTfLiteInt64:
GenerateMultinomialNumbers(data->rng, logits + logits_offset,
num_classes, output + outputs_offset,
num_samples_);
break;
default:
TF_LITE_KERNEL_LOG(context,
"Unsupported output datatype for Multinomial op: %s",
TfLiteTypeGetName(output_tensor->type));
return kTfLiteError;
}
}
return kTfLiteOk;
}
} // namespace random
TfLiteRegistration* Register_RANDOM_UNIFORM() {
static TfLiteRegistration r = {random::Init, random::Free, random::Prepare,
random::Eval<random::kRandomUniform>};
return &r;
}
TfLiteRegistration* Register_RANDOM_STANDARD_NORMAL() {
static TfLiteRegistration r = {random::Init, random::Free, random::Prepare,
random::Eval<random::kRandomStandardNormal>};
return &r;
}
TfLiteRegistration* Register_MULTINOMIAL() {
static TfLiteRegistration r = {random::Init, random::Free,
random::PrepareMultinomial,
random::EvalMultinomial};
return &r;
}
} // namespace builtin
} // namespace ops
} // namespace tflite
<commit_msg>[Minor Fix] Fix the usage of 'std::finite' function in random op implementation<commit_after>/* Copyright 2021 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <random>
#include "tensorflow/core/lib/random/philox_random.h"
#include "tensorflow/core/lib/random/random_distributions_utils.h"
#include "tensorflow/lite/c/builtin_op_data.h"
#include "tensorflow/lite/kernels/internal/tensor_ctypes.h"
#include "tensorflow/lite/kernels/kernel_util.h"
namespace tflite {
namespace ops {
namespace builtin {
namespace random {
namespace {
using Generator = ::tensorflow::random::PhiloxRandom;
enum RandomType { kRandomUniform, kRandomStandardNormal, kMultinomial };
struct OpData {
Generator rng;
};
// Initialize the OpData based on the seed and seed2 values.
void InitializeOpData(TfLiteNode* node) {
static std::mt19937_64* seed_generator = []() {
std::random_device device("/dev/urandom");
return new std::mt19937_64(device());
}();
auto* params = static_cast<TfLiteRandomParams*>(node->builtin_data);
OpData* data = reinterpret_cast<OpData*>(node->user_data);
int64_t seed = params->seed;
int64_t seed2 = params->seed2;
if (seed == 0 && seed2 == 0) {
// If both seeds are unspecified, generate non-deterministic random numbers.
seed = (*seed_generator)();
seed2 = (*seed_generator)();
}
Generator rng(seed, seed2);
data->rng = rng;
}
// Generates random numbers following a uniform distribution.
// Source: third_party/tensorflow/core/kernels/random_op.cc
void GenerateRandomUniformNumbers(
Generator& rng, float* buffer, size_t buffer_size) {
size_t current_size = 0;
size_t rng_size = Generator::kResultElementCount;
while (current_size < buffer_size) {
typename Generator::ResultType samples = rng();
const int rng_net_size = std::min(rng_size, buffer_size - current_size);
for (int i = 0; i < rng_net_size; i++) {
buffer[current_size + i] = tensorflow::random::Uint32ToFloat(samples[i]);
}
current_size += rng_net_size;
}
}
// Generates random numbers following a standard normal distribution.
// Source: third_party/tensorflow/core/kernels/random_op.cc
void GenerateRandomStandardNormalNumbers(
Generator& rng, float* buffer, size_t buffer_size) {
size_t current_size = 0;
size_t rng_size = Generator::kResultElementCount;
while (current_size < buffer_size) {
typename Generator::ResultType samples = rng();
const int rng_net_size = std::min(rng_size, buffer_size - current_size);
for (int i = 0; i < rng_net_size; i += 2) {
tensorflow::random::BoxMullerFloat(samples[i], samples[i + 1],
&buffer[current_size + i],
&buffer[current_size + i + 1]);
}
current_size += rng_net_size;
}
}
// Generates random numbers following a multinomial distribution.
// Source: third_party/tensorflow/core/kernels/multinomial_op.cc
void GenerateMultinomialNumbers(Generator& rng, const float* logits,
size_t logits_size, int64_t* output,
size_t num_samples) {
// Compute the maximum logit.
float max = std::numeric_limits<float>::lowest();
for (size_t i = 0; i < logits_size; i++) {
if (std::isfinite(logits[i])) {
max = std::max(max, logits[i]);
}
}
const double max_logit = static_cast<double>(max);
// Compute the (unnormalized) cumulative probability distribution.
// For numerical stability (as the exponential function grows very fast),
// subtract the maximum logit. Though you can subtract any value without
// changing the output, we use the maximum logit for convenience.
std::vector<double> cdf(logits_size);
double cumulative_total = 0.0f;
for (size_t i = 0; i < logits_size; i++) {
if (std::isfinite(logits[i])) {
cumulative_total += exp(logits[i] - max_logit);
}
cdf[i] = cumulative_total;
}
// Generate random categorical numbers and populate the output.
size_t current_size = 0;
size_t rng_size = Generator::kResultElementCount;
// Number of skipped 128-bits samples (i.e, number of generator calls)
int num_samples_skipped = 0;
while (current_size < num_samples) {
const int update_size = std::min(rng_size / 2, num_samples - current_size);
typename Generator::ResultType samples = rng();
num_samples_skipped += 1;
for (int i = 0; i < update_size; i += 1) {
const double value = tensorflow::random::Uint64ToDouble(
samples[i * 2], samples[i * 2 + 1]) *
cumulative_total;
output[current_size + i] =
std::upper_bound(cdf.begin(), cdf.end(), value) - cdf.begin();
}
current_size += update_size;
}
// Skip enough 128-bits samples to ensure that the output is always unique.
// Round to a multiple of 4 (+3 ensures a different state in every batch)
int num_samples_ceil_4 = (num_samples + 3) / 4 * 4;
// CPU generates 2 samples per number and 256 is a conservative multiplier.
int num_samples_to_skip_total = num_samples_ceil_4 * 2 * 256;
// Compute the number of 128-bits samples to skip.
int num_samples_to_skip = num_samples_to_skip_total - num_samples_skipped;
rng.Skip(num_samples_to_skip);
}
} // namespace
void* Init(TfLiteContext* context, const char* buffer, size_t length) {
return new OpData();
}
void Free(TfLiteContext* context, void* buffer) {
delete reinterpret_cast<OpData*>(buffer);
}
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
// Validate number of inputs and outputs
TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
// 'shape' is a 1-D int array
const TfLiteTensor* shape;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &shape));
TF_LITE_ENSURE_EQ(context, shape->type, kTfLiteInt32);
TF_LITE_ENSURE_EQ(context, NumDimensions(shape), 1);
// Initialize the random number generator
InitializeOpData(node);
TfLiteTensor* output = GetOutput(context, node, 0);
if (!IsConstantTensor(shape)) {
SetTensorToDynamic(output);
return kTfLiteOk;
}
TfLiteIntArray* output_shape;
TF_LITE_ENSURE_OK(context,
GetOutputShapeFromInput(context, shape, &output_shape));
return context->ResizeTensor(context, output, output_shape);
}
TfLiteStatus PrepareMultinomial(TfLiteContext* context, TfLiteNode* node) {
// Validate number of inputs and outputs
TF_LITE_ENSURE_EQ(context, NumInputs(node), 2);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
// 'logits' is a 2-D input float matrix with shape [batch_size, num_classes]
const TfLiteTensor* logits;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &logits));
TF_LITE_ENSURE(context, logits->type == kTfLiteFloat32);
TF_LITE_ENSURE_EQ(context, NumDimensions(logits), 2);
const int batch_size = SizeOfDimension(logits, 0);
const int num_classes = SizeOfDimension(logits, 1);
TF_LITE_ENSURE(context, num_classes > 0);
// Ensure logits shape isn't too large for int
TF_LITE_ENSURE(context, static_cast<int>(batch_size) == batch_size);
TF_LITE_ENSURE(context, static_cast<int>(num_classes) == num_classes);
// 'num_samples' is a 0-D input int scalar
const TfLiteTensor* num_samples;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 1, &num_samples));
TF_LITE_ENSURE_EQ(context, num_samples->type, kTfLiteInt32);
TF_LITE_ENSURE_EQ(context, NumDimensions(num_samples), 0);
TF_LITE_ENSURE(context, *num_samples->data.i32 >= 0);
// Initialize the random number generator
InitializeOpData(node);
TfLiteTensor* output = GetOutput(context, node, 0);
if (!IsConstantTensor(logits) || !IsConstantTensor(num_samples)) {
SetTensorToDynamic(output);
return kTfLiteOk;
}
// 'output' is a 2-D int64 matrix with shape [batch_size, num_samples]
TfLiteIntArray* output_shape = TfLiteIntArrayCreate(2);
output_shape->data[0] = SizeOfDimension(logits, 0); // batch_size
output_shape->data[1] = *num_samples->data.i32; // num_samples
return context->ResizeTensor(context, output, output_shape);
}
TfLiteStatus EvalRandomType(
TfLiteContext* context, TfLiteNode* node, RandomType random_type) {
TfLiteTensor* output = GetOutput(context, node, 0);
OpData* data = reinterpret_cast<OpData*>(node->user_data);
const size_t output_size = NumElements(output);
switch (random_type) {
case kRandomUniform:
GenerateRandomUniformNumbers(
data->rng, GetTensorData<float>(output), output_size);
break;
case kRandomStandardNormal:
GenerateRandomStandardNormalNumbers(
data->rng, GetTensorData<float>(output), output_size);
break;
default:
return kTfLiteError;
}
return kTfLiteOk;
}
template <RandomType rtype>
TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
TfLiteTensor* output = GetOutput(context, node, 0);
if (IsDynamicTensor(output)) {
const TfLiteTensor* shape = GetInput(context, node, 0);
TfLiteIntArray* output_shape;
TF_LITE_ENSURE_OK(context,
GetOutputShapeFromInput(context, shape, &output_shape));
context->ResizeTensor(context, output, output_shape);
}
switch (output->type) {
case kTfLiteFloat32:
EvalRandomType(context, node, rtype);
break;
default:
TF_LITE_KERNEL_LOG(
context, "Unsupported output datatype for %s op: %s",
rtype == kRandomUniform? "RandomUniform": "RandomStandardNormal",
TfLiteTypeGetName(output->type));
return kTfLiteError;
}
return kTfLiteOk;
}
TfLiteStatus EvalMultinomial(TfLiteContext* context, TfLiteNode* node) {
OpData* params = reinterpret_cast<OpData*>(node->user_data);
TF_LITE_ENSURE(context, params != nullptr);
// 'logits' is a 2-D float matrix with shape [batch_size, num_classes]
const TfLiteTensor* logits_tensor = GetInput(context, node, 0);
const float* logits = GetTensorData<float>(logits_tensor);
int batch_size = SizeOfDimension(logits_tensor, 0);
int num_classes = SizeOfDimension(logits_tensor, 1);
// 'num_samples' is an int scalar
const TfLiteTensor* num_samples = GetInput(context, node, 1);
int num_samples_ = *num_samples->data.i32;
TfLiteTensor* output_tensor = GetOutput(context, node, 0);
if (IsDynamicTensor(output_tensor)) {
// 'output' is a 2-D int64 matrix with shape [batch_size, num_samples]
TfLiteIntArray* output_shape = TfLiteIntArrayCreate(2);
output_shape->data[0] = batch_size;
output_shape->data[1] = num_samples_;
TF_LITE_ENSURE_OK(
context, context->ResizeTensor(context, output_tensor, output_shape));
}
OpData* data = reinterpret_cast<OpData*>(node->user_data);
int64_t* output = GetTensorData<int64_t>(output_tensor);
for (int batch = 0; batch < batch_size; ++batch) {
int logits_offset = num_classes * batch;
int outputs_offset = num_samples_ * batch;
switch (output_tensor->type) {
case kTfLiteInt64:
GenerateMultinomialNumbers(data->rng, logits + logits_offset,
num_classes, output + outputs_offset,
num_samples_);
break;
default:
TF_LITE_KERNEL_LOG(context,
"Unsupported output datatype for Multinomial op: %s",
TfLiteTypeGetName(output_tensor->type));
return kTfLiteError;
}
}
return kTfLiteOk;
}
} // namespace random
TfLiteRegistration* Register_RANDOM_UNIFORM() {
static TfLiteRegistration r = {random::Init, random::Free, random::Prepare,
random::Eval<random::kRandomUniform>};
return &r;
}
TfLiteRegistration* Register_RANDOM_STANDARD_NORMAL() {
static TfLiteRegistration r = {random::Init, random::Free, random::Prepare,
random::Eval<random::kRandomStandardNormal>};
return &r;
}
TfLiteRegistration* Register_MULTINOMIAL() {
static TfLiteRegistration r = {random::Init, random::Free,
random::PrepareMultinomial,
random::EvalMultinomial};
return &r;
}
} // namespace builtin
} // namespace ops
} // namespace tflite
<|endoftext|> |
<commit_before>/*
* Copyright (C) Sometrik oy 2015
*
*/
#include <string.h>
#include <android/log.h>
#include "Menu.h"
#include <jni.h>
#include <android/asset_manager.h>
#include <android/asset_manager_jni.h>
#include <iostream>
#include <android/bitmap.h>
#include <ContextAndroid.h>
#include <AndroidClient.h>
#include <AndroidPlatform.h>
#include <FWApplication.h>
#include <TouchEvent.h>
#include <CommandEvent.h>
#include <DrawEvent.h>
#include <UpdateEvent.h>
#include <ResizeEvent.h>
#include <android_fopen.h>
using namespace std;
extern FWApplication * applicationMain();
void
AndroidPlatform::onTouchesEvent(jobject * _obj, int mode, int fingerIndex, double time, float x, float y) {
x /= getDisplayScale();
y /= getDisplayScale();
switch (mode) {
case 1:
{
TouchEvent ev(TouchEvent::ACTION_DOWN, x, y, time, fingerIndex);
postEvent(getActiveViewId(), ev);
}
break;
case 2:
{
TouchEvent ev(TouchEvent::ACTION_MOVE, x, y, time, fingerIndex);
postEvent(getActiveViewId(), ev);
}
break;
case 3:
{
TouchEvent ev(TouchEvent::ACTION_UP, x, y, time, fingerIndex);
postEvent(getActiveViewId(), ev);
}
break;
}
}
void
AndroidPlatform::onResize(int width, int height) {
__android_log_print(ANDROID_LOG_ERROR, "Sometrik", "resize: %d %d ", width, height);
ResizeEvent ev(getTime(), width / getDisplayScale(), height / getDisplayScale(), width, height);
postEvent(getActiveViewId(), ev);
}
void
AndroidPlatform::menuPressed() {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "Platform menupressed called");
CommandEvent ce(getTime(), FW_ID_MENU);
postEvent(getActiveViewId(), ce);
// jclass handlerClass = env->GetObjectClass(handler);
// jmethodID emptyMessageMethod = env->GetMethodID(handlerClass, "sendEmptyMessage", "(I)Z");
// env->CallVoidMethod(handler, emptyMessageMethod, 1);
}
void
AndroidPlatform::onUpdate(double timestamp) {
UpdateEvent ev(getTime());
postEvent(getActiveViewId(), ev);
}
void
AndroidPlatform::onDraw() {
DrawEvent ev(getTime());
postEvent(getActiveViewId(), ev);
}
void AndroidPlatform::showCanvas(canvas::ContextAndroid & context) {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "showCanvas called");
auto env = getJNIEnv();
jclass cls = env->GetObjectClass(framework);
jmethodID methodRef = env->GetMethodID(cls, "setNativeCanvas", "(Landroid/graphics/Bitmap;)V");
env->CallVoidMethod(framework, methodRef, dynamic_cast<canvas::AndroidSurface&>(context.getDefaultSurface()).getBitmap());
}
std::string AndroidPlatform::getBundleFilename(const char * filename) {
return filename;
}
std::string AndroidPlatform::getLocalFilename(const char * filename, FileType type) {
auto env = getJNIEnv();
jstring path;
jstring jfilename;
std::string result;
switch (type) {
case DATABASE:
case CACHE_DATABASE:
jfilename = env->NewStringUTF(filename);
path = (jstring) env->CallObjectMethod(framework, env->GetMethodID(env->GetObjectClass(framework), "getDBPath", "(Ljava/lang/String;)Ljava/lang/String;"), jfilename);
result = env->GetStringUTFChars(path, JNI_FALSE);
env->ReleaseStringUTFChars(jfilename, filename);
env->ReleaseStringUTFChars(path, result.c_str());
return result;
case NORMAL:
return "";
}
return "";
}
std::string AndroidPlatform::loadValue(const std::string & key) {
auto env = getJNIEnv();
jstring jkey = env->NewStringUTF(key.c_str());
jstring value = (jstring) env->CallObjectMethod(framework, env->GetMethodID(env->GetObjectClass(framework), "getFromPrefs", "(Ljava/lang/String;)Ljava/lang/String;"), jkey);
std::string result = env->GetStringUTFChars(value, JNI_FALSE);
env->ReleaseStringUTFChars(jkey, key.c_str());
env->ReleaseStringUTFChars(value, result.c_str());
return result;
}
void AndroidPlatform::storeValue(const std::string & key, const std::string & value) {
auto env = getJNIEnv();
jstring jkey = env->NewStringUTF(key.c_str());
jstring jvalue = env->NewStringUTF(value.c_str());
env->CallVoidMethod(framework, env->GetMethodID(env->GetObjectClass(framework), "addToPrefs", "(Ljava/lang/String;Ljava/lang/String;)V"), jkey, jvalue);
env->ReleaseStringUTFChars(jkey, key.c_str());
env->ReleaseStringUTFChars(jvalue, value.c_str());
}
void
AndroidPlatform::sendMessage(const Message & message) {
FWPlatform::sendMessage(message);
auto env = getJNIEnv();
jclass frameworkCls = env->FindClass("com/sometrik/framework/FrameWork");
jclass messageCls = env->FindClass("com/sometrik/framework/NativeMessage");
jmethodID sendMessageMethod = env->GetStaticMethodID(frameworkCls, "sendMessage", "(Lcom/sometrik/framework/FrameWork;Lcom/sometrik/framework/NativeMessage;)V");
jmethodID messageConstructor = env->GetMethodID(messageCls, "<init>", "(IIILjava/lang/String;Ljava/lang/String;)V");
int messageTypeId = int(message.getType());
const char * textValue = message.getTextValue().c_str();
const char * textValue2 = message.getTextValue2().c_str();
jstring jtextValue = env->NewStringUTF(textValue);
jstring jtextValue2 = env->NewStringUTF(textValue2);
jobject jmessage = env->NewObject(messageCls, messageConstructor, messageTypeId, message.getInternalId(), message.getChildInternalId(), jtextValue, jtextValue2);
env->CallStaticVoidMethod(frameworkCls, sendMessageMethod, framework, jmessage);
//Fix these releases
// env->ReleaseStringUTFChars(jtextValue, textValue);
// env->ReleaseStringUTFChars(jtextValue2, textValue2);
}
double
AndroidPlatform::getTime() const {
auto env = getJNIEnv();
jclass systemClass = env->FindClass("Ljava/lang/System");
double currentTime = (double)env->CallStaticLongMethod(systemClass, env->GetStaticMethodID(systemClass, "currentTimeMillis", "()L"));
env->DeleteLocalRef(systemClass);
return currentTime;
}
int
AndroidPlatform::showActionSheet(const FWRect & rect, const FWActionSheet & sheet) {
//Initialize java int and string arrays
auto env = getJNIEnv();
std::vector<FWOption> optionsVector = sheet.getOptions();
jobjectArray stringArray = (jobjectArray) env->NewObjectArray(optionsVector.size(), env->FindClass("java/lang/String"), 0);
jintArray intArray = env->NewIntArray(optionsVector.size());
jint fill[optionsVector.size()];
//Set values to java arrays
for (int i = 0; i < optionsVector.size(); i++) {
const char * text = optionsVector[i].getText().c_str();
jstring jtext = env->NewStringUTF(text);
env->SetObjectArrayElement(stringArray, i, jtext);
fill[i] = optionsVector[i].getId();
env->ReleaseStringUTFChars(jtext, text);
}
env->SetIntArrayRegion(intArray, 0, optionsVector.size(), fill);
//Send values to java to create the action sheet
jclass cls = env->FindClass("com/sometrik/framework/FrameWork");
jmethodID methodRef = env->GetStaticMethodID(cls, "createOptionsFromJNI", "(Lcom/sometrik/framework/FrameWork;I[I[Ljava/lang/String;)V");
env->CallStaticVoidMethod(cls, methodRef, framework, 22, intArray, stringArray);
//Not returning anything
return 0;
}
JNIEnv *
AndroidPlatform::getJNIEnv() const {
if (gJavaVM == NULL) {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "JavaVM is null");
return NULL;
}
JNIEnv * Myenv = NULL;
gJavaVM->GetEnv((void**)&Myenv, JNI_VERSION_1_6);
if (Myenv == NULL) {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "Env is null");
}
return Myenv;
}
std::shared_ptr<AndroidPlatform> platform;
extern "C" {
void Java_com_sometrik_framework_MyGLRenderer_onResize(JNIEnv* env, jobject thiz, float x, float y) {
platform->setDisplayWidth(x);
platform->setDisplayHeight(y);
platform->onResize(x, y);
}
void Java_com_sometrik_framework_FrameWork_menuPressed(JNIEnv* env, jobject thiz) {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "menu pressed: env = %p", env);
platform->menuPressed();
}
void Java_com_sometrik_framework_FrameWork_touchEvent(JNIEnv* env, jobject thiz, int mode, int fingerIndex, long time, float x, float y) {
platform->onTouchesEvent(&thiz, mode, fingerIndex, time, x, y);
}
jboolean Java_com_sometrik_framework_MyGLRenderer_onUpdate(JNIEnv* env, jobject thiz, double timestamp) {
platform->onUpdate(timestamp);
return JNI_TRUE; // FIX ME: check the return value from event
}
static JavaVM * gJavaVM = 0;
void Java_com_sometrik_framework_MyGLRenderer_onInit(JNIEnv* env, jobject thiz, jobject assetManager, jobject surface, float screenWidth, float screenHeight, float displayScale, bool hasEs3) {
if (!platform.get()) {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "Creating Platform");
const char* glslVersion = "#version 100"; // "#version es 300"
AAssetManager* manager = AAssetManager_fromJava(env, assetManager);
android_fopen_set_asset_manager(manager);
platform = std::make_shared<AndroidPlatform>(env, assetManager, surface, displayScale, glslVersion, hasEs3);
}
FWApplication * application = applicationMain();
platform->setApplication(application);
if (gJavaVM) {
gJavaVM->AttachCurrentThread(&env, NULL);
platform->setJavaVM(gJavaVM);
}
application->initialize(platform.get());
platform->setDisplayWidth(screenWidth);
platform->setDisplayHeight(screenHeight);
platform->onResize(screenWidth, screenHeight);
application->initializeContent();
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "Init end");
}
void Java_com_sometrik_framework_NativeLooper_test(JNIEnv* env, jobject thiz) {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "Test");
// platform->onInit();
}
void Java_com_sometrik_framework_MyGLRenderer_nativeOnDraw(JNIEnv* env, jobject thiz) {
platform->onDraw();
}
void Java_com_sometrik_framework_FrameWork_okPressed(JNIEnv* env, jobject thiz, jstring text) {
jclass cls = env->FindClass("com/sometrik/framework/FrameWork");
jmethodID methodRef = env->GetMethodID(cls, "printText", "(Ljava/lang/String;)V");
env->CallVoidMethod(thiz, methodRef, text);
}
jint JNI_OnLoad(JavaVM *vm, void *reserved) {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "JNI_Onload on AndroidPlatform");
gJavaVM = vm;
return JNI_VERSION_1_6;
}
}
<commit_msg>Fix a JNI call causing crash<commit_after>/*
* Copyright (C) Sometrik oy 2015
*
*/
#include <string.h>
#include <android/log.h>
#include "Menu.h"
#include <jni.h>
#include <android/asset_manager.h>
#include <android/asset_manager_jni.h>
#include <iostream>
#include <android/bitmap.h>
#include <ContextAndroid.h>
#include <AndroidClient.h>
#include <AndroidPlatform.h>
#include <FWApplication.h>
#include <TouchEvent.h>
#include <CommandEvent.h>
#include <DrawEvent.h>
#include <UpdateEvent.h>
#include <ResizeEvent.h>
#include <android_fopen.h>
using namespace std;
extern FWApplication * applicationMain();
void
AndroidPlatform::onTouchesEvent(jobject * _obj, int mode, int fingerIndex, double time, float x, float y) {
x /= getDisplayScale();
y /= getDisplayScale();
switch (mode) {
case 1:
{
TouchEvent ev(TouchEvent::ACTION_DOWN, x, y, time, fingerIndex);
postEvent(getActiveViewId(), ev);
}
break;
case 2:
{
TouchEvent ev(TouchEvent::ACTION_MOVE, x, y, time, fingerIndex);
postEvent(getActiveViewId(), ev);
}
break;
case 3:
{
TouchEvent ev(TouchEvent::ACTION_UP, x, y, time, fingerIndex);
postEvent(getActiveViewId(), ev);
}
break;
}
}
void
AndroidPlatform::onResize(int width, int height) {
__android_log_print(ANDROID_LOG_ERROR, "Sometrik", "resize: %d %d ", width, height);
ResizeEvent ev(getTime(), width / getDisplayScale(), height / getDisplayScale(), width, height);
postEvent(getActiveViewId(), ev);
}
void
AndroidPlatform::menuPressed() {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "Platform menupressed called");
CommandEvent ce(getTime(), FW_ID_MENU);
postEvent(getActiveViewId(), ce);
// jclass handlerClass = env->GetObjectClass(handler);
// jmethodID emptyMessageMethod = env->GetMethodID(handlerClass, "sendEmptyMessage", "(I)Z");
// env->CallVoidMethod(handler, emptyMessageMethod, 1);
}
void
AndroidPlatform::onUpdate(double timestamp) {
UpdateEvent ev(getTime());
postEvent(getActiveViewId(), ev);
}
void
AndroidPlatform::onDraw() {
DrawEvent ev(getTime());
postEvent(getActiveViewId(), ev);
}
void AndroidPlatform::showCanvas(canvas::ContextAndroid & context) {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "showCanvas called");
auto env = getJNIEnv();
jclass cls = env->GetObjectClass(framework);
jmethodID methodRef = env->GetMethodID(cls, "setNativeCanvas", "(Landroid/graphics/Bitmap;)V");
env->CallVoidMethod(framework, methodRef, dynamic_cast<canvas::AndroidSurface&>(context.getDefaultSurface()).getBitmap());
}
std::string AndroidPlatform::getBundleFilename(const char * filename) {
return filename;
}
std::string AndroidPlatform::getLocalFilename(const char * filename, FileType type) {
auto env = getJNIEnv();
jstring path;
jstring jfilename;
std::string result;
switch (type) {
case DATABASE:
case CACHE_DATABASE:
jfilename = env->NewStringUTF(filename);
path = (jstring) env->CallObjectMethod(framework, env->GetMethodID(env->GetObjectClass(framework), "getDBPath", "(Ljava/lang/String;)Ljava/lang/String;"), jfilename);
result = env->GetStringUTFChars(path, JNI_FALSE);
env->ReleaseStringUTFChars(jfilename, filename);
env->ReleaseStringUTFChars(path, result.c_str());
return result;
case NORMAL:
return "";
}
return "";
}
std::string AndroidPlatform::loadValue(const std::string & key) {
auto env = getJNIEnv();
jstring jkey = env->NewStringUTF(key.c_str());
jstring value = (jstring) env->CallObjectMethod(framework, env->GetMethodID(env->GetObjectClass(framework), "getFromPrefs", "(Ljava/lang/String;)Ljava/lang/String;"), jkey);
std::string result = env->GetStringUTFChars(value, JNI_FALSE);
env->ReleaseStringUTFChars(jkey, key.c_str());
env->ReleaseStringUTFChars(value, result.c_str());
return result;
}
void AndroidPlatform::storeValue(const std::string & key, const std::string & value) {
auto env = getJNIEnv();
jstring jkey = env->NewStringUTF(key.c_str());
jstring jvalue = env->NewStringUTF(value.c_str());
env->CallVoidMethod(framework, env->GetMethodID(env->GetObjectClass(framework), "addToPrefs", "(Ljava/lang/String;Ljava/lang/String;)V"), jkey, jvalue);
env->ReleaseStringUTFChars(jkey, key.c_str());
env->ReleaseStringUTFChars(jvalue, value.c_str());
}
void
AndroidPlatform::sendMessage(const Message & message) {
FWPlatform::sendMessage(message);
auto env = getJNIEnv();
jclass frameworkCls = env->FindClass("com/sometrik/framework/FrameWork");
jclass messageCls = env->FindClass("com/sometrik/framework/NativeMessage");
jmethodID sendMessageMethod = env->GetStaticMethodID(frameworkCls, "sendMessage", "(Lcom/sometrik/framework/FrameWork;Lcom/sometrik/framework/NativeMessage;)V");
jmethodID messageConstructor = env->GetMethodID(messageCls, "<init>", "(IIILjava/lang/String;Ljava/lang/String;)V");
int messageTypeId = int(message.getType());
const char * textValue = message.getTextValue().c_str();
const char * textValue2 = message.getTextValue2().c_str();
jstring jtextValue = env->NewStringUTF(textValue);
jstring jtextValue2 = env->NewStringUTF(textValue2);
jobject jmessage = env->NewObject(messageCls, messageConstructor, messageTypeId, message.getInternalId(), message.getChildInternalId(), jtextValue, jtextValue2);
env->CallStaticVoidMethod(frameworkCls, sendMessageMethod, framework, jmessage);
//Fix these releases
// env->ReleaseStringUTFChars(jtextValue, textValue);
// env->ReleaseStringUTFChars(jtextValue2, textValue2);
}
double
AndroidPlatform::getTime() const {
auto env = getJNIEnv();
jclass systemClass = env->FindClass("java/lang/System");
double currentTime = (double)env->CallStaticLongMethod(systemClass, env->GetStaticMethodID(systemClass, "currentTimeMillis", "()J"));
env->DeleteLocalRef(systemClass);
return currentTime;
}
int
AndroidPlatform::showActionSheet(const FWRect & rect, const FWActionSheet & sheet) {
//Initialize java int and string arrays
auto env = getJNIEnv();
std::vector<FWOption> optionsVector = sheet.getOptions();
jobjectArray stringArray = (jobjectArray) env->NewObjectArray(optionsVector.size(), env->FindClass("java/lang/String"), 0);
jintArray intArray = env->NewIntArray(optionsVector.size());
jint fill[optionsVector.size()];
//Set values to java arrays
for (int i = 0; i < optionsVector.size(); i++) {
const char * text = optionsVector[i].getText().c_str();
jstring jtext = env->NewStringUTF(text);
env->SetObjectArrayElement(stringArray, i, jtext);
fill[i] = optionsVector[i].getId();
env->ReleaseStringUTFChars(jtext, text);
}
env->SetIntArrayRegion(intArray, 0, optionsVector.size(), fill);
//Send values to java to create the action sheet
jclass cls = env->FindClass("com/sometrik/framework/FrameWork");
jmethodID methodRef = env->GetStaticMethodID(cls, "createOptionsFromJNI", "(Lcom/sometrik/framework/FrameWork;I[I[Ljava/lang/String;)V");
env->CallStaticVoidMethod(cls, methodRef, framework, 22, intArray, stringArray);
//Not returning anything
return 0;
}
JNIEnv *
AndroidPlatform::getJNIEnv() const {
if (gJavaVM == NULL) {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "JavaVM is null");
return NULL;
}
JNIEnv * Myenv = NULL;
gJavaVM->GetEnv((void**)&Myenv, JNI_VERSION_1_6);
if (Myenv == NULL) {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "Env is null");
}
return Myenv;
}
std::shared_ptr<AndroidPlatform> platform;
extern "C" {
void Java_com_sometrik_framework_MyGLRenderer_onResize(JNIEnv* env, jobject thiz, float x, float y) {
platform->setDisplayWidth(x);
platform->setDisplayHeight(y);
platform->onResize(x, y);
}
void Java_com_sometrik_framework_FrameWork_menuPressed(JNIEnv* env, jobject thiz) {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "menu pressed: env = %p", env);
platform->menuPressed();
}
void Java_com_sometrik_framework_FrameWork_touchEvent(JNIEnv* env, jobject thiz, int mode, int fingerIndex, long time, float x, float y) {
platform->onTouchesEvent(&thiz, mode, fingerIndex, time, x, y);
}
jboolean Java_com_sometrik_framework_MyGLRenderer_onUpdate(JNIEnv* env, jobject thiz, double timestamp) {
platform->onUpdate(timestamp);
return JNI_TRUE; // FIX ME: check the return value from event
}
static JavaVM * gJavaVM = 0;
void Java_com_sometrik_framework_MyGLRenderer_onInit(JNIEnv* env, jobject thiz, jobject assetManager, jobject surface, float screenWidth, float screenHeight, float displayScale, bool hasEs3) {
if (!platform.get()) {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "Creating Platform");
const char* glslVersion = "#version 100"; // "#version es 300"
AAssetManager* manager = AAssetManager_fromJava(env, assetManager);
android_fopen_set_asset_manager(manager);
platform = std::make_shared<AndroidPlatform>(env, assetManager, surface, displayScale, glslVersion, hasEs3);
}
FWApplication * application = applicationMain();
platform->setApplication(application);
if (gJavaVM) {
gJavaVM->AttachCurrentThread(&env, NULL);
platform->setJavaVM(gJavaVM);
}
application->initialize(platform.get());
platform->setDisplayWidth(screenWidth);
platform->setDisplayHeight(screenHeight);
platform->onResize(screenWidth, screenHeight);
application->initializeContent();
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "Init end");
}
void Java_com_sometrik_framework_NativeLooper_test(JNIEnv* env, jobject thiz) {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "Test");
// platform->onInit();
}
void Java_com_sometrik_framework_MyGLRenderer_nativeOnDraw(JNIEnv* env, jobject thiz) {
platform->onDraw();
}
void Java_com_sometrik_framework_FrameWork_okPressed(JNIEnv* env, jobject thiz, jstring text) {
jclass cls = env->FindClass("com/sometrik/framework/FrameWork");
jmethodID methodRef = env->GetMethodID(cls, "printText", "(Ljava/lang/String;)V");
env->CallVoidMethod(thiz, methodRef, text);
}
jint JNI_OnLoad(JavaVM *vm, void *reserved) {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "JNI_Onload on AndroidPlatform");
gJavaVM = vm;
return JNI_VERSION_1_6;
}
}
<|endoftext|> |
<commit_before>
/*
* Copyright (c) 2012 Karl N. Redgate
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
/** \file NetworkMonitor.cc
* \brief
*
*/
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <arpa/inet.h>
#include <stdint.h>
#include <stdlib.h>
#include <signal.h>
#include <fcntl.h>
#include <time.h>
#include <string.h>
#include <glob.h>
#include <errno.h>
#include <tcl.h>
#include "tcl_util.h"
#include "logger.h"
#include "util.h"
#include "host_table.h"
#include "NetworkMonitor.h"
#include "Neighbor.h"
#include "Interface.h"
#include "PlatformCompat.h"
namespace { int debug = 0; }
/**
* Used to iterate through the node list and clear the partner
* bit in all entries.
*/
class ClearNodePartner : public Network::NodeIterator {
public:
ClearNodePartner() {}
virtual ~ClearNodePartner() {}
virtual int operator() ( Network::Node * node ) {
if ( node->not_partner() ) return 0;
log_notice( "clear partner [%s]", node->uuid().to_s() );
node->clear_partner();
return 1;
}
};
/** Send a packet to each interface.
*
* The interface code will prune which interfaces are valid to send to
* based on interface specific policy. Currently, this means priv0
* and bizN bridge interfaces.
*
* See Network::Interface::sendto() method (in Interface.cc) for description
* of how this is done.
*/
int
Network::Monitor::sendto( void *message, size_t length, int flags, const struct sockaddr_in6 *address) {
std::map<int, Network::Interface *>::const_iterator iter = interfaces.begin();
while ( iter != interfaces.end() ) {
Network::Interface *interface = iter->second;
if ( interface != NULL ) {
interface->sendto( message, length, flags, address );
}
iter++;
}
return 0;
}
/** Send ICMPv6 neighbor advertisements for each interface.
*
* Iterate through each known priv/biz network and send neighbor
* advertisements out of this interface. This will keep the peer's
* neighbor table up to date for this host.
*
* When looking at the peer's * neighbor table (ip -6 neighbor ls) you
* should see "REACHABLE" for this hosts addresses if this node is up and
* running netmgr.
*
* See the Interface.cc advertise code for how this is done.
*/
int
Network::Monitor::advertise() {
std::map<int, Network::Interface *>::const_iterator iter = interfaces.begin();
while ( iter != interfaces.end() ) {
Network::Interface *interface = iter->second;
if ( interface != NULL ) interface->advertise();
iter++;
}
return 0;
}
/**
*/
void
Network::Monitor::capture( Network::Interface *interface ) {
fprintf( stderr, "UNIMPLEMENTED capture\n" );
abort();
}
/**
*/
void
Network::Monitor::bring_up( Network::Interface *interface ) {
fprintf( stderr, "UNIMPLEMENTED bring_up\n" );
abort();
}
/**
*/
Network::Interface *
Network::Monitor::find_bridge_interface( Network::Interface *interface ) {
fprintf( stderr, "UNIMPLEMENTED find_bridge_interface\n" );
abort();
}
/** Iterate and call a callback for each Network::Interface.
*/
int
Network::Monitor::each_interface( Network::InterfaceIterator& callback ) {
int result = 0;
std::map<int, Network::Interface *>::const_iterator iter = interfaces.begin();
while ( iter != interfaces.end() ) {
Network::Interface *interface = iter->second;
if ( interface != NULL ) result += callback( interface );
iter++;
}
return result;
}
/** Iterate and call a callback for each Node.
*/
int
Network::Monitor::each_node( NodeIterator& callback ) {
int result = 0;
pthread_mutex_lock( &node_table_lock );
for ( int i = 0 ; i < NODE_TABLE_SIZE ; ++i ) {
Network::Node& node = node_table[i];
if ( node.is_invalid() ) continue;
result += callback( &node );
}
pthread_mutex_unlock( &node_table_lock );
return result;
}
/**
*
*/
Network::Node*
Network::Monitor::intern_node( UUID& uuid ) {
int in_use_count = 0;
Network::Node *result = NULL;
Network::Node *available = NULL;
pthread_mutex_lock( &node_table_lock );
int i = 0;
for ( ; i < NODE_TABLE_SIZE ; ++i ) {
Network::Node& node = node_table[i];
if ( node.is_invalid() ) {
available = &node;
continue;
}
in_use_count += 1;
if ( node != uuid ) continue;
result = &node;
break;
}
if ( in_use_count > 256 ) {
if ( table_warning_reported == false ) {
log_warn( "WARNING: node table exceeds 256 entries" );
table_warning_reported = true;
}
}
if ( result == NULL ) {
if ( available == NULL ) { // EDM ??? wasn't this set above ???
for ( ; i < NODE_TABLE_SIZE ; ++i ) {
Network::Node& node = node_table[i];
if ( node.is_valid() ) continue;
available = &node;
break;
}
}
if ( available != NULL ) {
available->uuid( uuid );
result = available;
} else {
if ( table_error_reported == false ) {
log_err( "ERROR: node table is full" );
table_error_reported = true;
}
}
}
pthread_mutex_unlock( &node_table_lock );
return result;
}
/**
*
*/
bool
Network::Monitor::remove_node( UUID *uuid ) {
pthread_mutex_lock( &node_table_lock );
for ( int i = 0 ; i < NODE_TABLE_SIZE ; ++i ) {
Network::Node& node = node_table[i];
if ( node.is_invalid() ) continue;
if ( node != *uuid ) continue;
node.invalidate();
}
pthread_mutex_unlock( &node_table_lock );
return true;
}
/**
*
*/
Network::Node*
Network::Monitor::find_node( UUID *uuid ) {
using namespace Network;
Node *result = NULL;
pthread_mutex_lock( &node_table_lock );
for ( int i = 0 ; i < NODE_TABLE_SIZE ; ++i ) {
Network::Node& node = node_table[i];
if ( node.is_invalid() ) continue;
if ( node != *uuid ) continue;
result = &node;
}
pthread_mutex_unlock( &node_table_lock );
return result;
}
/**
* Save the partner node id for later usage as a cache - in case
* priv0 is down and we cannot discover the node id dynamically.
*/
void
Network::Monitor::save_cache() {
FILE *f = fopen( "partner-cache", "w" );
if ( f == NULL ) {
log_notice( "could not save partner cache" );
return;
}
int partner_count = 0;
pthread_mutex_lock( &node_table_lock );
for ( int i = 0 ; i < NODE_TABLE_SIZE ; ++i ) {
Network::Node& node = node_table[i];
if ( node.is_invalid() ) continue;
if ( node.not_partner() ) continue;
if ( debug ) log_notice( "save partner [%s]", node.uuid().to_s() );
if ( partner_count == 0 ) {
fprintf( f, "%s\n", node.uuid().to_s() );
}
partner_count++;
}
pthread_mutex_unlock( &node_table_lock );
fclose( f );
if ( partner_count > 1 ) {
log_err( "%%BUG multiple partner entries in node table" );
}
}
/**
*/
void
Network::Monitor::clear_partners() {
ClearNodePartner callback;
int partner_count = each_node( callback );
if ( partner_count > 0 ) {
log_notice( "cleared %d partners", partner_count );
}
}
/**
* This is called when netmgr starts. It simply loads the previous saved
* value of the partner node id and creates an entry in the node table
* marked as a partner. This value was written the last time netmgr
* discovered a partner node on priv0.
*/
void
Network::Monitor::load_cache() {
char buffer[80];
FILE *f = fopen( "partner-cache", "r" );
if ( f == NULL ) {
log_notice( "partner cache not present" );
return;
}
fscanf( f, "%s\n", buffer );
fclose( f );
log_notice( "loaded partner as [%s]", buffer );
/*
* This should not be necessary - when netmgr starts it should
* not have any partner node table entries.
*/
ClearNodePartner callback;
int partner_count = each_node( callback );
if ( partner_count > 0 ) {
log_notice( "cleared %d partners", partner_count );
}
UUID uuid(buffer);
Network::Node *node = intern_node( uuid );
node->make_partner();
}
/**
*/
class WriteHostsForNeighbors : public Network::NeighborIterator {
int fd;
public:
WriteHostsForNeighbors( int fd ) : fd(fd) {}
virtual ~WriteHostsForNeighbors() {}
virtual int operator() ( Network::Peer& neighbor ) {
struct host_entry entry;
memset( &entry, 0, sizeof(entry) );
Network::Node *node = neighbor.node();
if ( node == NULL ) {
return 0;
}
if ( node->not_partner() ) {
return 0;
}
entry.flags.valid = 1;
entry.flags.partner = neighbor.is_partner();
entry.node.ordinal = node->ordinal();
entry.interface.ordinal = neighbor.ordinal();
entry.flags.is_private = neighbor.is_private();
neighbor.copy_address( &(entry.primary_address) );
if ( debug > 1 ) log_notice( "write host entry for peer" );
// populate entry for the interface itself
ssize_t bytes = write( fd, &entry, sizeof(entry) );
if ( (size_t)bytes < sizeof(entry) ) {
log_err( "write failed creating hosts entry peer" );
}
return 0;
}
};
/**
*/
class WriteHostsForInterface : public Network::InterfaceIterator {
int fd;
public:
WriteHostsForInterface( int fd ) : fd(fd) {}
virtual ~WriteHostsForInterface() {}
virtual int operator() ( Network::Interface * interface ) {
struct host_entry entry;
memset( &entry, 0, sizeof(entry) );
entry.flags.valid = 1;
entry.flags.partner = 0;
entry.node.ordinal = gethostid();
entry.flags.is_private = 0 /* interface->is_private() */ ;
entry.interface.ordinal = interface->ordinal();
interface->lladdr( &entry.primary_address );
unsigned char *mac = interface->mac();
entry.mac[0] = mac[0];
entry.mac[1] = mac[1];
entry.mac[2] = mac[2];
entry.mac[3] = mac[3];
entry.mac[4] = mac[4];
entry.mac[5] = mac[5];
if ( interface->not_bridge() /* and interface->not_private() */ ) {
return 0;
}
if ( debug > 1 ) log_notice( "write host entry for %s", interface->name() );
// populate entry for the interface itself
ssize_t bytes = write( fd, &entry, sizeof(entry) );
if ( (size_t)bytes < sizeof(entry) ) {
log_err( "write failed creating hosts entry" );
}
// call iterator for each neighbor
WriteHostsForNeighbors callback(fd);
interface->each_neighbor( callback );
return 0;
}
};
/** Update hosts file with partner addresses
*
* For each interface, check each neighbor, if it is a partner
* then add a host file entry for that name/uuid and interface
*
* node0.ip6.ibiz0 fe80::XXXX
*/
void
Network::Monitor::update_hosts() {
if ( mkfile(const_cast<char*>("hosts.tmp"), HOST_TABLE_SIZE) == 0 ) {
log_err( "could not create the tmp hosts table" );
return;
}
int fd = open("hosts.tmp", O_RDWR);
if ( fd < 0 ) {
if ( debug > 0 ) log_err( "could not open the hosts table for writing" );
return;
}
WriteHostsForInterface callback(fd);
each_interface( callback );
fsync( fd );
close( fd );
unlink( "hosts.1" );
link( "hosts", "hosts.1" );
rename( "hosts.tmp", "hosts" );
}
/**
* The network monitor needs to probe the current system for network
* devices and keep a list of devices that are being monitored.
*
* The discover interface bit here -- creates a RouteSocket, send
* a GetLink request, and process each response by calling the monitor
* object's receive callback interface. This callback will popoulate the
* Interface table.
*
* Tcl_Interp arg to the constructor is for handlers that are registered
* for network events. (?? also how to handle ASTs for handlers)
*/
Network::Monitor::Monitor( Tcl_Interp *interp, Network::ListenerInterfaceFactory factory )
: Thread("network.monitor"),
interp(interp),
factory(factory),
table_warning_reported(false),
table_error_reported(false)
{
pthread_mutex_init( &node_table_lock, NULL );
size_t size = sizeof(Node) * NODE_TABLE_SIZE;
node_table = (Node *)mmap( 0, size, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, 0, 0 );
if ( node_table == MAP_FAILED ) {
log_err( "node table alloc failed" );
exit( errno );
}
for ( int i = 0 ; i < NODE_TABLE_SIZE ; i++ ) {
node_table[i].invalidate();
}
if ( debug > 0 ) log_err( "node table is at %p (%zu)", node_table, size );
}
/**
*/
Network::Monitor::~Monitor() {
}
/* vim: set autoindent expandtab sw=4 : */
<commit_msg>add base run method<commit_after>
/*
* Copyright (c) 2012 Karl N. Redgate
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
/** \file NetworkMonitor.cc
* \brief
*
*/
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <arpa/inet.h>
#include <stdint.h>
#include <stdlib.h>
#include <signal.h>
#include <fcntl.h>
#include <time.h>
#include <string.h>
#include <glob.h>
#include <errno.h>
#include <tcl.h>
#include "tcl_util.h"
#include "logger.h"
#include "util.h"
#include "host_table.h"
#include "NetworkMonitor.h"
#include "Neighbor.h"
#include "Interface.h"
#include "PlatformCompat.h"
namespace { int debug = 0; }
/**
* Used to iterate through the node list and clear the partner
* bit in all entries.
*/
class ClearNodePartner : public Network::NodeIterator {
public:
ClearNodePartner() {}
virtual ~ClearNodePartner() {}
virtual int operator() ( Network::Node * node ) {
if ( node->not_partner() ) return 0;
log_notice( "clear partner [%s]", node->uuid().to_s() );
node->clear_partner();
return 1;
}
};
/** Send a packet to each interface.
*
* The interface code will prune which interfaces are valid to send to
* based on interface specific policy. Currently, this means priv0
* and bizN bridge interfaces.
*
* See Network::Interface::sendto() method (in Interface.cc) for description
* of how this is done.
*/
int
Network::Monitor::sendto( void *message, size_t length, int flags, const struct sockaddr_in6 *address) {
std::map<int, Network::Interface *>::const_iterator iter = interfaces.begin();
while ( iter != interfaces.end() ) {
Network::Interface *interface = iter->second;
if ( interface != NULL ) {
interface->sendto( message, length, flags, address );
}
iter++;
}
return 0;
}
/** Send ICMPv6 neighbor advertisements for each interface.
*
* Iterate through each known priv/biz network and send neighbor
* advertisements out of this interface. This will keep the peer's
* neighbor table up to date for this host.
*
* When looking at the peer's * neighbor table (ip -6 neighbor ls) you
* should see "REACHABLE" for this hosts addresses if this node is up and
* running netmgr.
*
* See the Interface.cc advertise code for how this is done.
*/
int
Network::Monitor::advertise() {
std::map<int, Network::Interface *>::const_iterator iter = interfaces.begin();
while ( iter != interfaces.end() ) {
Network::Interface *interface = iter->second;
if ( interface != NULL ) interface->advertise();
iter++;
}
return 0;
}
/**
*/
void
Network::Monitor::capture( Network::Interface *interface ) {
fprintf( stderr, "UNIMPLEMENTED capture\n" );
abort();
}
/**
*/
void
Network::Monitor::bring_up( Network::Interface *interface ) {
fprintf( stderr, "UNIMPLEMENTED bring_up\n" );
abort();
}
/**
*/
Network::Interface *
Network::Monitor::find_bridge_interface( Network::Interface *interface ) {
fprintf( stderr, "UNIMPLEMENTED find_bridge_interface\n" );
abort();
}
/**
*/
void
Network::Monitor::run() {
fprintf( stderr, "UNIMPLEMENTED run\n" );
abort();
}
/** Iterate and call a callback for each Network::Interface.
*/
int
Network::Monitor::each_interface( Network::InterfaceIterator& callback ) {
int result = 0;
std::map<int, Network::Interface *>::const_iterator iter = interfaces.begin();
while ( iter != interfaces.end() ) {
Network::Interface *interface = iter->second;
if ( interface != NULL ) result += callback( interface );
iter++;
}
return result;
}
/** Iterate and call a callback for each Node.
*/
int
Network::Monitor::each_node( NodeIterator& callback ) {
int result = 0;
pthread_mutex_lock( &node_table_lock );
for ( int i = 0 ; i < NODE_TABLE_SIZE ; ++i ) {
Network::Node& node = node_table[i];
if ( node.is_invalid() ) continue;
result += callback( &node );
}
pthread_mutex_unlock( &node_table_lock );
return result;
}
/**
*
*/
Network::Node*
Network::Monitor::intern_node( UUID& uuid ) {
int in_use_count = 0;
Network::Node *result = NULL;
Network::Node *available = NULL;
pthread_mutex_lock( &node_table_lock );
int i = 0;
for ( ; i < NODE_TABLE_SIZE ; ++i ) {
Network::Node& node = node_table[i];
if ( node.is_invalid() ) {
available = &node;
continue;
}
in_use_count += 1;
if ( node != uuid ) continue;
result = &node;
break;
}
if ( in_use_count > 256 ) {
if ( table_warning_reported == false ) {
log_warn( "WARNING: node table exceeds 256 entries" );
table_warning_reported = true;
}
}
if ( result == NULL ) {
if ( available == NULL ) { // EDM ??? wasn't this set above ???
for ( ; i < NODE_TABLE_SIZE ; ++i ) {
Network::Node& node = node_table[i];
if ( node.is_valid() ) continue;
available = &node;
break;
}
}
if ( available != NULL ) {
available->uuid( uuid );
result = available;
} else {
if ( table_error_reported == false ) {
log_err( "ERROR: node table is full" );
table_error_reported = true;
}
}
}
pthread_mutex_unlock( &node_table_lock );
return result;
}
/**
*
*/
bool
Network::Monitor::remove_node( UUID *uuid ) {
pthread_mutex_lock( &node_table_lock );
for ( int i = 0 ; i < NODE_TABLE_SIZE ; ++i ) {
Network::Node& node = node_table[i];
if ( node.is_invalid() ) continue;
if ( node != *uuid ) continue;
node.invalidate();
}
pthread_mutex_unlock( &node_table_lock );
return true;
}
/**
*
*/
Network::Node*
Network::Monitor::find_node( UUID *uuid ) {
using namespace Network;
Node *result = NULL;
pthread_mutex_lock( &node_table_lock );
for ( int i = 0 ; i < NODE_TABLE_SIZE ; ++i ) {
Network::Node& node = node_table[i];
if ( node.is_invalid() ) continue;
if ( node != *uuid ) continue;
result = &node;
}
pthread_mutex_unlock( &node_table_lock );
return result;
}
/**
* Save the partner node id for later usage as a cache - in case
* priv0 is down and we cannot discover the node id dynamically.
*/
void
Network::Monitor::save_cache() {
FILE *f = fopen( "partner-cache", "w" );
if ( f == NULL ) {
log_notice( "could not save partner cache" );
return;
}
int partner_count = 0;
pthread_mutex_lock( &node_table_lock );
for ( int i = 0 ; i < NODE_TABLE_SIZE ; ++i ) {
Network::Node& node = node_table[i];
if ( node.is_invalid() ) continue;
if ( node.not_partner() ) continue;
if ( debug ) log_notice( "save partner [%s]", node.uuid().to_s() );
if ( partner_count == 0 ) {
fprintf( f, "%s\n", node.uuid().to_s() );
}
partner_count++;
}
pthread_mutex_unlock( &node_table_lock );
fclose( f );
if ( partner_count > 1 ) {
log_err( "%%BUG multiple partner entries in node table" );
}
}
/**
*/
void
Network::Monitor::clear_partners() {
ClearNodePartner callback;
int partner_count = each_node( callback );
if ( partner_count > 0 ) {
log_notice( "cleared %d partners", partner_count );
}
}
/**
* This is called when netmgr starts. It simply loads the previous saved
* value of the partner node id and creates an entry in the node table
* marked as a partner. This value was written the last time netmgr
* discovered a partner node on priv0.
*/
void
Network::Monitor::load_cache() {
char buffer[80];
FILE *f = fopen( "partner-cache", "r" );
if ( f == NULL ) {
log_notice( "partner cache not present" );
return;
}
fscanf( f, "%s\n", buffer );
fclose( f );
log_notice( "loaded partner as [%s]", buffer );
/*
* This should not be necessary - when netmgr starts it should
* not have any partner node table entries.
*/
ClearNodePartner callback;
int partner_count = each_node( callback );
if ( partner_count > 0 ) {
log_notice( "cleared %d partners", partner_count );
}
UUID uuid(buffer);
Network::Node *node = intern_node( uuid );
node->make_partner();
}
/**
*/
class WriteHostsForNeighbors : public Network::NeighborIterator {
int fd;
public:
WriteHostsForNeighbors( int fd ) : fd(fd) {}
virtual ~WriteHostsForNeighbors() {}
virtual int operator() ( Network::Peer& neighbor ) {
struct host_entry entry;
memset( &entry, 0, sizeof(entry) );
Network::Node *node = neighbor.node();
if ( node == NULL ) {
return 0;
}
if ( node->not_partner() ) {
return 0;
}
entry.flags.valid = 1;
entry.flags.partner = neighbor.is_partner();
entry.node.ordinal = node->ordinal();
entry.interface.ordinal = neighbor.ordinal();
entry.flags.is_private = neighbor.is_private();
neighbor.copy_address( &(entry.primary_address) );
if ( debug > 1 ) log_notice( "write host entry for peer" );
// populate entry for the interface itself
ssize_t bytes = write( fd, &entry, sizeof(entry) );
if ( (size_t)bytes < sizeof(entry) ) {
log_err( "write failed creating hosts entry peer" );
}
return 0;
}
};
/**
*/
class WriteHostsForInterface : public Network::InterfaceIterator {
int fd;
public:
WriteHostsForInterface( int fd ) : fd(fd) {}
virtual ~WriteHostsForInterface() {}
virtual int operator() ( Network::Interface * interface ) {
struct host_entry entry;
memset( &entry, 0, sizeof(entry) );
entry.flags.valid = 1;
entry.flags.partner = 0;
entry.node.ordinal = gethostid();
entry.flags.is_private = 0 /* interface->is_private() */ ;
entry.interface.ordinal = interface->ordinal();
interface->lladdr( &entry.primary_address );
unsigned char *mac = interface->mac();
entry.mac[0] = mac[0];
entry.mac[1] = mac[1];
entry.mac[2] = mac[2];
entry.mac[3] = mac[3];
entry.mac[4] = mac[4];
entry.mac[5] = mac[5];
if ( interface->not_bridge() /* and interface->not_private() */ ) {
return 0;
}
if ( debug > 1 ) log_notice( "write host entry for %s", interface->name() );
// populate entry for the interface itself
ssize_t bytes = write( fd, &entry, sizeof(entry) );
if ( (size_t)bytes < sizeof(entry) ) {
log_err( "write failed creating hosts entry" );
}
// call iterator for each neighbor
WriteHostsForNeighbors callback(fd);
interface->each_neighbor( callback );
return 0;
}
};
/** Update hosts file with partner addresses
*
* For each interface, check each neighbor, if it is a partner
* then add a host file entry for that name/uuid and interface
*
* node0.ip6.ibiz0 fe80::XXXX
*/
void
Network::Monitor::update_hosts() {
if ( mkfile(const_cast<char*>("hosts.tmp"), HOST_TABLE_SIZE) == 0 ) {
log_err( "could not create the tmp hosts table" );
return;
}
int fd = open("hosts.tmp", O_RDWR);
if ( fd < 0 ) {
if ( debug > 0 ) log_err( "could not open the hosts table for writing" );
return;
}
WriteHostsForInterface callback(fd);
each_interface( callback );
fsync( fd );
close( fd );
unlink( "hosts.1" );
link( "hosts", "hosts.1" );
rename( "hosts.tmp", "hosts" );
}
/**
* The network monitor needs to probe the current system for network
* devices and keep a list of devices that are being monitored.
*
* The discover interface bit here -- creates a RouteSocket, send
* a GetLink request, and process each response by calling the monitor
* object's receive callback interface. This callback will popoulate the
* Interface table.
*
* Tcl_Interp arg to the constructor is for handlers that are registered
* for network events. (?? also how to handle ASTs for handlers)
*/
Network::Monitor::Monitor( Tcl_Interp *interp, Network::ListenerInterfaceFactory factory )
: Thread("network.monitor"),
interp(interp),
factory(factory),
table_warning_reported(false),
table_error_reported(false)
{
pthread_mutex_init( &node_table_lock, NULL );
size_t size = sizeof(Node) * NODE_TABLE_SIZE;
node_table = (Node *)mmap( 0, size, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, 0, 0 );
if ( node_table == MAP_FAILED ) {
log_err( "node table alloc failed" );
exit( errno );
}
for ( int i = 0 ; i < NODE_TABLE_SIZE ; i++ ) {
node_table[i].invalidate();
}
if ( debug > 0 ) log_err( "node table is at %p (%zu)", node_table, size );
}
/**
*/
Network::Monitor::~Monitor() {
}
/* vim: set autoindent expandtab sw=4 : */
<|endoftext|> |
<commit_before>/**********
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the
Free Software Foundation; either version 2.1 of the License, or (at your
option) any later version. (See <http://www.gnu.org/copyleft/lesser.html>.)
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
**********/
// "CSIR"
// Copyright (c) 2014 CSIR. All rights reserved.
#include "LiveMediaExtPch.h"
#include <LiveMediaExt/LiveH264Subsession.h>
#include <LiveMediaExt/LiveDeviceSource.h>
#include <LiveMediaExt/LiveH264VideoDeviceSource.h>
#include <H264VideoRTPSink.hh>
#include "Base64.hh"
#include "H264VideoStreamDiscreteFramer.hh"
namespace lme
{
LiveH264Subsession::LiveH264Subsession( UsageEnvironment& env, LiveRtspServer& rParent,
const unsigned uiChannelId, unsigned uiSourceId,
const std::string& sSessionName,
const std::string& sSps, const std::string& sPps,
IRateAdaptationFactory* pFactory,
IRateController* pGlobalRateControl)
:LiveMediaSubsession(env, rParent, uiChannelId, uiSourceId, sSessionName, true, 1, pFactory, pGlobalRateControl),
m_sSps(sSps),
m_sPps(sPps),
fAuxSDPLine(NULL),
fFmtpSDPLine(NULL)
{
VLOG(2) << "LiveH264Subsession() SPS: " << m_sSps << " PPS: " << m_sPps;
}
LiveH264Subsession::~LiveH264Subsession()
{
delete[] fAuxSDPLine;
delete[] fFmtpSDPLine;
}
FramedSource* LiveH264Subsession::createSubsessionSpecificSource(unsigned clientSessionId,
IMediaSampleBuffer* pMediaSampleBuffer,
IRateAdaptationFactory* pRateAdaptationFactory,
IRateController* pRateControl)
{
FramedSource* pLiveDeviceSource = LiveH264VideoDeviceSource::createNew(envir(), clientSessionId, this, m_sSps, m_sPps,
pMediaSampleBuffer, pRateAdaptationFactory, pRateControl);
// wrap framer around our device source
H264VideoStreamDiscreteFramer* pFramer = H264VideoStreamDiscreteFramer::createNew(envir(), pLiveDeviceSource);
return pFramer;
}
void LiveH264Subsession::setEstimatedBitRate(unsigned& estBitrate)
{
// Set estimated session band width
estBitrate = 1000;
}
RTPSink* LiveH264Subsession::createSubsessionSpecificRTPSink( Groupsock* rtpGroupsock, unsigned char rtpPayloadTypeIfDynamic, FramedSource* inputSource )
{
// HACKERY
std::string sPropParameterSets = m_sSps + "," + m_sPps;
H264VideoRTPSink* pSink = H264VideoRTPSink::createNew(envir(), rtpGroupsock, rtpPayloadTypeIfDynamic, sPropParameterSets.c_str());
pSink->setPacketSizes(1000, 1400);
return pSink;
}
char const* LiveH264Subsession::getAuxSDPLine( RTPSink* rtpSink, FramedSource* inputSource )
{
const char* sps = m_sSps.c_str();
unsigned spsSize = m_sSps.length();
const char* pps = m_sPps.c_str();
unsigned ppsSize = m_sPps.length();
u_int32_t profile_level_id;
if (spsSize < 4) { // sanity check
profile_level_id = 0;
} else {
profile_level_id = (sps[1]<<16)|(sps[2]<<8)|sps[3]; // profile_idc|constraint_setN_flag|level_idc
}
// The parameter sets are base64 encoded already
// Set up the "a=fmtp:" SDP line for this stream:
char const* fmtpFmt =
"a=fmtp:%d packetization-mode=1"
";profile-level-id=%06X"
";sprop-parameter-sets=%s,%s\r\n";
unsigned fmtpFmtSize = strlen(fmtpFmt)
+ 3 /* max char len */
+ 6 /* 3 bytes in hex */
+ spsSize + ppsSize;
char* fmtp = new char[fmtpFmtSize];
sprintf(fmtp, fmtpFmt,
rtpSink->rtpPayloadType(),
profile_level_id,
sps, pps);
delete[] fFmtpSDPLine; fFmtpSDPLine = fmtp;
return fFmtpSDPLine;
}
} // lme
<commit_msg>Reduced est bitrate to 500kbps<commit_after>/**********
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the
Free Software Foundation; either version 2.1 of the License, or (at your
option) any later version. (See <http://www.gnu.org/copyleft/lesser.html>.)
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
**********/
// "CSIR"
// Copyright (c) 2014 CSIR. All rights reserved.
#include "LiveMediaExtPch.h"
#include <LiveMediaExt/LiveH264Subsession.h>
#include <LiveMediaExt/LiveDeviceSource.h>
#include <LiveMediaExt/LiveH264VideoDeviceSource.h>
#include <H264VideoRTPSink.hh>
#include "Base64.hh"
#include "H264VideoStreamDiscreteFramer.hh"
namespace lme
{
LiveH264Subsession::LiveH264Subsession( UsageEnvironment& env, LiveRtspServer& rParent,
const unsigned uiChannelId, unsigned uiSourceId,
const std::string& sSessionName,
const std::string& sSps, const std::string& sPps,
IRateAdaptationFactory* pFactory,
IRateController* pGlobalRateControl)
:LiveMediaSubsession(env, rParent, uiChannelId, uiSourceId, sSessionName, true, 1, pFactory, pGlobalRateControl),
m_sSps(sSps),
m_sPps(sPps),
fAuxSDPLine(NULL),
fFmtpSDPLine(NULL)
{
VLOG(2) << "LiveH264Subsession() SPS: " << m_sSps << " PPS: " << m_sPps;
}
LiveH264Subsession::~LiveH264Subsession()
{
delete[] fAuxSDPLine;
delete[] fFmtpSDPLine;
}
FramedSource* LiveH264Subsession::createSubsessionSpecificSource(unsigned clientSessionId,
IMediaSampleBuffer* pMediaSampleBuffer,
IRateAdaptationFactory* pRateAdaptationFactory,
IRateController* pRateControl)
{
FramedSource* pLiveDeviceSource = LiveH264VideoDeviceSource::createNew(envir(), clientSessionId, this, m_sSps, m_sPps,
pMediaSampleBuffer, pRateAdaptationFactory, pRateControl);
// wrap framer around our device source
H264VideoStreamDiscreteFramer* pFramer = H264VideoStreamDiscreteFramer::createNew(envir(), pLiveDeviceSource);
return pFramer;
}
void LiveH264Subsession::setEstimatedBitRate(unsigned& estBitrate)
{
// Set estimated session band width
estBitrate = 500;
}
RTPSink* LiveH264Subsession::createSubsessionSpecificRTPSink( Groupsock* rtpGroupsock, unsigned char rtpPayloadTypeIfDynamic, FramedSource* inputSource )
{
// HACKERY
std::string sPropParameterSets = m_sSps + "," + m_sPps;
H264VideoRTPSink* pSink = H264VideoRTPSink::createNew(envir(), rtpGroupsock, rtpPayloadTypeIfDynamic, sPropParameterSets.c_str());
pSink->setPacketSizes(1000, 1400);
return pSink;
}
char const* LiveH264Subsession::getAuxSDPLine( RTPSink* rtpSink, FramedSource* inputSource )
{
const char* sps = m_sSps.c_str();
unsigned spsSize = m_sSps.length();
const char* pps = m_sPps.c_str();
unsigned ppsSize = m_sPps.length();
u_int32_t profile_level_id;
if (spsSize < 4) { // sanity check
profile_level_id = 0;
} else {
profile_level_id = (sps[1]<<16)|(sps[2]<<8)|sps[3]; // profile_idc|constraint_setN_flag|level_idc
}
// The parameter sets are base64 encoded already
// Set up the "a=fmtp:" SDP line for this stream:
char const* fmtpFmt =
"a=fmtp:%d packetization-mode=1"
";profile-level-id=%06X"
";sprop-parameter-sets=%s,%s\r\n";
unsigned fmtpFmtSize = strlen(fmtpFmt)
+ 3 /* max char len */
+ 6 /* 3 bytes in hex */
+ spsSize + ppsSize;
char* fmtp = new char[fmtpFmtSize];
sprintf(fmtp, fmtpFmt,
rtpSink->rtpPayloadType(),
profile_level_id,
sps, pps);
delete[] fFmtpSDPLine; fFmtpSDPLine = fmtp;
return fFmtpSDPLine;
}
} // lme
<|endoftext|> |
<commit_before>// Copyright © 2016 by Donald King <[email protected]>
// Available under the MIT License. See LICENSE for details.
#include "base/logging.h"
#include <sys/syscall.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <condition_variable>
#include <cstdint>
#include <cstring>
#include <map>
#include <memory>
#include <mutex>
#include <queue>
#include <thread>
#include <vector>
#include "base/concat.h"
#include "base/debug.h"
#include "base/result.h"
#include "base/util.h"
namespace base {
static pid_t gettid() { return syscall(SYS_gettid); }
namespace {
struct Key {
const char* file;
unsigned int line;
Key(const char* file, unsigned int line) noexcept : file(file), line(line) {}
};
static bool operator==(Key a, Key b) noexcept __attribute__((unused));
static bool operator==(Key a, Key b) noexcept {
return a.line == b.line && ::strcmp(a.file, b.file) == 0;
}
static bool operator<(Key a, Key b) noexcept {
int cmp = ::strcmp(a.file, b.file);
return cmp < 0 || (cmp == 0 && a.line < b.line);
}
} // anonymous namespace
using Map = std::map<Key, std::size_t>;
using Vec = std::vector<LogTarget*>;
using Queue = std::queue<LogEntry>;
static std::mutex g_mu;
static std::mutex g_queue_mu;
static std::condition_variable g_queue_put_cv;
static std::condition_variable g_queue_empty_cv;
static std::once_flag g_once;
static level_t g_stderr = LOG_LEVEL_INFO;
static GetTidFunc g_gtid = nullptr;
static GetTimeOfDayFunc g_gtod = nullptr;
static bool g_single_threaded = false;
static bool g_thread_started = false;
static base::LogTarget* make_stderr();
static Map& map_get(std::unique_lock<std::mutex>& lock) {
static Map& m = *new Map;
return m;
}
static Vec& vec_get(std::unique_lock<std::mutex>& lock) {
static Vec& v = *new Vec;
if (v.empty()) {
v.push_back(make_stderr());
}
return v;
}
static Queue& queue_get(std::unique_lock<std::mutex>& lock) {
static Queue& q = *new Queue;
return q;
}
static void process(base::Lock& lock, LogEntry entry) {
auto& v = vec_get(lock);
for (LogTarget* target : v) {
if (target->want(entry.file, entry.line, entry.level)) {
target->log(entry);
}
}
}
static void thread_body() {
auto lock0 = base::acquire_lock(g_queue_mu);
auto& q = queue_get(lock0);
while (true) {
while (q.empty()) g_queue_put_cv.wait(lock0);
auto entry = std::move(q.front());
q.pop();
auto lock1 = base::acquire_lock(g_mu);
process(lock1, std::move(entry));
if (q.empty()) g_queue_empty_cv.notify_all();
}
}
static bool want(const char* file, unsigned int line, unsigned int n,
level_t level) {
if (level >= LOG_LEVEL_DFATAL) return true;
auto lock = base::acquire_lock(g_mu);
if (n > 1) {
auto& m = map_get(lock);
Key key(file, line);
auto pair = m.insert(std::make_pair(key, 0));
auto& count = pair.first->second;
bool x = (count == 0);
count = (count + 1) % n;
if (!x) return false;
}
auto& v = vec_get(lock);
for (const auto& target : v) {
if (target->want(file, line, level)) return true;
}
return false;
}
static void log(LogEntry entry) {
auto lock = base::acquire_lock(g_mu);
if (g_single_threaded) {
process(lock, std::move(entry));
} else {
g_thread_started = true;
std::call_once(g_once, [] { std::thread(thread_body).detach(); });
auto lock = base::acquire_lock(g_queue_mu);
auto& q = queue_get(lock);
q.push(std::move(entry));
g_queue_put_cv.notify_one();
}
}
namespace {
class LogSTDERR : public LogTarget {
public:
LogSTDERR() noexcept = default;
bool want(const char* file, unsigned int line, level_t level) const noexcept override {
// g_mu held by base::want()
return level >= g_stderr;
}
void log(const LogEntry& entry) noexcept override {
// g_mu held by base::thread_body()
auto str = entry.as_string();
::write(2, str.data(), str.size());
}
};
} // anonymous namespace
static base::LogTarget* make_stderr() {
static base::LogTarget* const ptr = new LogSTDERR;
return ptr;
}
LogEntry::LogEntry(const char* file, unsigned int line, level_t level,
std::string message) noexcept : file(file),
line(line),
level(level),
message(std::move(message)) {
auto lock = acquire_lock(g_mu);
::bzero(&time, sizeof(time));
if (g_gtod) {
(*g_gtod)(&time, nullptr);
} else {
::gettimeofday(&time, nullptr);
}
if (g_gtid) {
tid = (*g_gtid)();
} else {
tid = gettid();
}
}
void LogEntry::append_to(std::string& out) const {
char ch;
if (level >= LOG_LEVEL_DFATAL) {
ch = 'F';
} else if (level >= LOG_LEVEL_ERROR) {
ch = 'E';
} else if (level >= LOG_LEVEL_WARN) {
ch = 'W';
} else if (level >= LOG_LEVEL_INFO) {
ch = 'I';
} else {
ch = 'D';
}
struct tm tm;
::gmtime_r(&time.tv_sec, &tm);
// "[IWEF]<mm><dd> <hh>:<mm>:<ss>.<uuuuuu> <tid> <file>:<line>] <message>"
std::array<char, 24> buf;
::snprintf(buf.data(), buf.size(), "%c%02u%02u %02u:%02u:%02u.%06lu ", ch,
tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec,
time.tv_usec);
concat_to(out, std::string(buf.data()), tid, ' ', file, ':', line, "] ", message, '\n');
}
std::string LogEntry::as_string() const {
std::string out;
append_to(out);
return out;
}
static std::unique_ptr<std::ostringstream> make_ss(const char* file,
unsigned int line,
unsigned int n,
level_t level) {
std::unique_ptr<std::ostringstream> ptr;
if (want(file, line, n, level)) ptr.reset(new std::ostringstream);
return ptr;
}
Logger::Logger(std::nullptr_t)
: file_(nullptr), line_(0), n_(0), level_(0), ss_(nullptr) {}
Logger::Logger(const char* file, unsigned int line, unsigned int every_n,
level_t level)
: file_(file),
line_(line),
n_(every_n),
level_(level),
ss_(make_ss(file, line, every_n, level)) {}
Logger::~Logger() noexcept(false) {
if (ss_) {
log(LogEntry(file_, line_, level_, ss_->str()));
if (level_ >= LOG_LEVEL_DFATAL) {
log_flush();
if (level_ >= LOG_LEVEL_FATAL || debug()) {
std::terminate();
}
}
}
}
void log_set_gettid(GetTidFunc func) {
auto lock = acquire_lock(g_mu);
g_gtid = func;
}
void log_set_gettimeofday(GetTimeOfDayFunc func) {
auto lock = acquire_lock(g_mu);
g_gtod = func;
}
void log_single_threaded() {
auto lock = acquire_lock(g_mu);
if (g_thread_started)
throw std::logic_error("logging thread is already running!");
g_single_threaded = true;
}
void log_flush() {
auto lock = base::acquire_lock(g_queue_mu);
auto& q = queue_get(lock);
while (!q.empty()) g_queue_empty_cv.wait(lock);
}
void log_stderr_set_level(level_t level) {
auto lock = acquire_lock(g_mu);
g_stderr = level;
}
void log_target_add(LogTarget* target) {
auto lock = acquire_lock(g_mu);
auto& v = vec_get(lock);
v.push_back(target);
}
void log_target_remove(LogTarget* target) {
auto lock0 = base::acquire_lock(g_queue_mu);
auto& q = queue_get(lock0);
while (!q.empty()) g_queue_empty_cv.wait(lock0);
auto lock1 = acquire_lock(g_mu);
auto& v = vec_get(lock1);
auto begin = v.begin(), it = v.end();
while (it != begin) {
--it;
if (*it == target) {
v.erase(it);
}
}
}
void log_exception(const char* file, unsigned int line, std::exception_ptr e) {
Logger logger(file, line, 1, LOG_LEVEL_ERROR);
try {
std::rethrow_exception(e);
} catch (const std::system_error& e) {
const auto& ecode = e.code();
logger << "caught std::system_error\n"
<< "\t" << ecode.category().name() << "(" << ecode.value()
<< "): " << e.what();
} catch (const std::exception& e) {
logger << "caught std::exception\n"
<< "\t[" << typeid(e).name() << "]\n"
<< "\t" << e.what();
} catch (...) {
logger << "caught unclassifiable exception!";
}
}
Logger log_check(const char* file, unsigned int line, const char* expr,
bool cond) {
if (cond) return Logger(nullptr);
Logger logger(file, line, 1, LOG_LEVEL_DFATAL);
logger << "CHECK FAILED: " << expr;
return logger;
}
Logger log_check_ok(const char* file, unsigned int line, const char* expr,
const Result& rslt) {
if (rslt) return Logger(nullptr);
Logger logger(file, line, 1, LOG_LEVEL_DFATAL);
logger << "CHECK FAILED: " << expr << ": " << rslt.as_string();
return logger;
}
Logger force_eval(bool) { return Logger(nullptr); }
} // namespace base
<commit_msg>Fix deadlock.<commit_after>// Copyright © 2016 by Donald King <[email protected]>
// Available under the MIT License. See LICENSE for details.
#include "base/logging.h"
#include <sys/syscall.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <condition_variable>
#include <cstdint>
#include <cstring>
#include <map>
#include <memory>
#include <mutex>
#include <queue>
#include <thread>
#include <vector>
#include "base/concat.h"
#include "base/debug.h"
#include "base/result.h"
#include "base/util.h"
namespace base {
static pid_t gettid() { return syscall(SYS_gettid); }
namespace {
struct Key {
const char* file;
unsigned int line;
Key(const char* file, unsigned int line) noexcept : file(file), line(line) {}
};
static bool operator==(Key a, Key b) noexcept __attribute__((unused));
static bool operator==(Key a, Key b) noexcept {
return a.line == b.line && ::strcmp(a.file, b.file) == 0;
}
static bool operator<(Key a, Key b) noexcept {
int cmp = ::strcmp(a.file, b.file);
return cmp < 0 || (cmp == 0 && a.line < b.line);
}
} // anonymous namespace
using Map = std::map<Key, std::size_t>;
using Vec = std::vector<LogTarget*>;
using Queue = std::queue<LogEntry>;
static std::mutex g_mu;
static std::mutex g_queue_mu;
static std::condition_variable g_queue_put_cv;
static std::condition_variable g_queue_empty_cv;
static std::once_flag g_once;
static level_t g_stderr = LOG_LEVEL_INFO;
static GetTidFunc g_gtid = nullptr;
static GetTimeOfDayFunc g_gtod = nullptr;
static bool g_single_threaded = false;
static bool g_thread_started = false;
static base::LogTarget* make_stderr();
static Map& map_get(std::unique_lock<std::mutex>& lock) {
static Map& m = *new Map;
return m;
}
static Vec& vec_get(std::unique_lock<std::mutex>& lock) {
static Vec& v = *new Vec;
if (v.empty()) {
v.push_back(make_stderr());
}
return v;
}
static Queue& queue_get(std::unique_lock<std::mutex>& lock) {
static Queue& q = *new Queue;
return q;
}
static void process(base::Lock& lock, LogEntry entry) {
auto& v = vec_get(lock);
for (LogTarget* target : v) {
if (target->want(entry.file, entry.line, entry.level)) {
target->log(entry);
}
}
}
static void thread_body() {
auto lock0 = base::acquire_lock(g_queue_mu);
auto& q = queue_get(lock0);
while (true) {
while (q.empty()) g_queue_put_cv.wait(lock0);
auto entry = std::move(q.front());
q.pop();
auto lock1 = base::acquire_lock(g_mu);
process(lock1, std::move(entry));
if (q.empty()) g_queue_empty_cv.notify_all();
}
}
static bool want(const char* file, unsigned int line, unsigned int n,
level_t level) {
if (level >= LOG_LEVEL_DFATAL) return true;
auto lock = base::acquire_lock(g_mu);
if (n > 1) {
auto& m = map_get(lock);
Key key(file, line);
auto pair = m.insert(std::make_pair(key, 0));
auto& count = pair.first->second;
bool x = (count == 0);
count = (count + 1) % n;
if (!x) return false;
}
auto& v = vec_get(lock);
for (const auto& target : v) {
if (target->want(file, line, level)) return true;
}
return false;
}
static void log(LogEntry entry) {
auto lock0 = base::acquire_lock(g_mu);
if (g_single_threaded) {
process(lock0, std::move(entry));
} else {
g_thread_started = true;
lock0.unlock();
std::call_once(g_once, [] { std::thread(thread_body).detach(); });
auto lock1 = base::acquire_lock(g_queue_mu);
auto& q = queue_get(lock1);
q.push(std::move(entry));
g_queue_put_cv.notify_one();
}
}
namespace {
class LogSTDERR : public LogTarget {
public:
LogSTDERR() noexcept = default;
bool want(const char* file, unsigned int line, level_t level) const noexcept override {
// g_mu held by base::want()
return level >= g_stderr;
}
void log(const LogEntry& entry) noexcept override {
// g_mu held by base::thread_body()
auto str = entry.as_string();
::write(2, str.data(), str.size());
}
};
} // anonymous namespace
static base::LogTarget* make_stderr() {
static base::LogTarget* const ptr = new LogSTDERR;
return ptr;
}
LogEntry::LogEntry(const char* file, unsigned int line, level_t level,
std::string message) noexcept : file(file),
line(line),
level(level),
message(std::move(message)) {
auto lock = acquire_lock(g_mu);
::bzero(&time, sizeof(time));
if (g_gtod) {
(*g_gtod)(&time, nullptr);
} else {
::gettimeofday(&time, nullptr);
}
if (g_gtid) {
tid = (*g_gtid)();
} else {
tid = gettid();
}
}
void LogEntry::append_to(std::string& out) const {
char ch;
if (level >= LOG_LEVEL_DFATAL) {
ch = 'F';
} else if (level >= LOG_LEVEL_ERROR) {
ch = 'E';
} else if (level >= LOG_LEVEL_WARN) {
ch = 'W';
} else if (level >= LOG_LEVEL_INFO) {
ch = 'I';
} else {
ch = 'D';
}
struct tm tm;
::gmtime_r(&time.tv_sec, &tm);
// "[IWEF]<mm><dd> <hh>:<mm>:<ss>.<uuuuuu> <tid> <file>:<line>] <message>"
std::array<char, 24> buf;
::snprintf(buf.data(), buf.size(), "%c%02u%02u %02u:%02u:%02u.%06lu ", ch,
tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec,
time.tv_usec);
concat_to(out, std::string(buf.data()), tid, ' ', file, ':', line, "] ", message, '\n');
}
std::string LogEntry::as_string() const {
std::string out;
append_to(out);
return out;
}
static std::unique_ptr<std::ostringstream> make_ss(const char* file,
unsigned int line,
unsigned int n,
level_t level) {
std::unique_ptr<std::ostringstream> ptr;
if (want(file, line, n, level)) ptr.reset(new std::ostringstream);
return ptr;
}
Logger::Logger(std::nullptr_t)
: file_(nullptr), line_(0), n_(0), level_(0), ss_(nullptr) {}
Logger::Logger(const char* file, unsigned int line, unsigned int every_n,
level_t level)
: file_(file),
line_(line),
n_(every_n),
level_(level),
ss_(make_ss(file, line, every_n, level)) {}
Logger::~Logger() noexcept(false) {
if (ss_) {
log(LogEntry(file_, line_, level_, ss_->str()));
if (level_ >= LOG_LEVEL_DFATAL) {
log_flush();
if (level_ >= LOG_LEVEL_FATAL || debug()) {
std::terminate();
}
}
}
}
void log_set_gettid(GetTidFunc func) {
auto lock = acquire_lock(g_mu);
g_gtid = func;
}
void log_set_gettimeofday(GetTimeOfDayFunc func) {
auto lock = acquire_lock(g_mu);
g_gtod = func;
}
void log_single_threaded() {
auto lock = acquire_lock(g_mu);
if (g_thread_started)
throw std::logic_error("logging thread is already running!");
g_single_threaded = true;
}
void log_flush() {
auto lock = base::acquire_lock(g_queue_mu);
auto& q = queue_get(lock);
while (!q.empty()) g_queue_empty_cv.wait(lock);
}
void log_stderr_set_level(level_t level) {
auto lock = acquire_lock(g_mu);
g_stderr = level;
}
void log_target_add(LogTarget* target) {
auto lock = acquire_lock(g_mu);
auto& v = vec_get(lock);
v.push_back(target);
}
void log_target_remove(LogTarget* target) {
auto lock0 = base::acquire_lock(g_queue_mu);
auto& q = queue_get(lock0);
while (!q.empty()) g_queue_empty_cv.wait(lock0);
auto lock1 = acquire_lock(g_mu);
auto& v = vec_get(lock1);
auto begin = v.begin(), it = v.end();
while (it != begin) {
--it;
if (*it == target) {
v.erase(it);
}
}
}
void log_exception(const char* file, unsigned int line, std::exception_ptr e) {
Logger logger(file, line, 1, LOG_LEVEL_ERROR);
try {
std::rethrow_exception(e);
} catch (const std::system_error& e) {
const auto& ecode = e.code();
logger << "caught std::system_error\n"
<< "\t" << ecode.category().name() << "(" << ecode.value()
<< "): " << e.what();
} catch (const std::exception& e) {
logger << "caught std::exception\n"
<< "\t[" << typeid(e).name() << "]\n"
<< "\t" << e.what();
} catch (...) {
logger << "caught unclassifiable exception!";
}
}
Logger log_check(const char* file, unsigned int line, const char* expr,
bool cond) {
if (cond) return Logger(nullptr);
Logger logger(file, line, 1, LOG_LEVEL_DFATAL);
logger << "CHECK FAILED: " << expr;
return logger;
}
Logger log_check_ok(const char* file, unsigned int line, const char* expr,
const Result& rslt) {
if (rslt) return Logger(nullptr);
Logger logger(file, line, 1, LOG_LEVEL_DFATAL);
logger << "CHECK FAILED: " << expr << ": " << rslt.as_string();
return logger;
}
Logger force_eval(bool) { return Logger(nullptr); }
} // namespace base
<|endoftext|> |
<commit_before>/*
* Copyright 2016 Krysta M Bouzek
*
* 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 <iostream>
#include <cstdlib>
#include <map>
#include "rabit/c_api.h"
#include "xgboost/c_api.h"
// these links were eminently helpful:
// http://stackoverflow.com/questions/36071672/using-xgboost-in-c
// https://stackoverflow.com/questions/38314092/reading-xgboost-model-in-c
class XGBoostWrapper {
public:
XGBoostWrapper(unsigned int num_trees);
~XGBoostWrapper();
// xgboost expects a flat array
void fit(const float Xs[], const float Ys[], unsigned int rows, unsigned int cols);
void predict(const float Xs[], float* Yhats, unsigned int rows, unsigned int cols);
private:
BoosterHandle _h_booster;
// number of boosting rounds
unsigned int _num_trees;
};
// Create an XGBoost handle
XGBoostWrapper::XGBoostWrapper(unsigned int num_trees) {
_h_booster = new BoosterHandle();
_num_trees = num_trees;
}
// Delete the XGBoost handle
XGBoostWrapper::~XGBoostWrapper() {
if (_h_booster) {
XGBoosterFree(_h_booster);
}
}
void XGBoostWrapper::fit(const float Xs[], const float Ys[], unsigned int rows, unsigned int cols) {
// convert to DMatrix
DMatrixHandle h_train[1];
XGDMatrixCreateFromMat((float *) Xs, rows, cols, -1, &h_train[0]);
// load the labels
XGDMatrixSetFloatInfo(h_train[0], "label", Ys, rows);
// read back the labels, just a sanity check
/*bst_ulong bst_result;
const float *out_floats;
XGDMatrixGetFloatInfo(h_train[0], "label" , &bst_result, &out_floats);
for (unsigned int i=0;i<bst_result;i++)
std::cout << "label[" << i << "]=" << out_floats[i] << std::endl;
*/
// create the booster and load some parameters
XGBoosterCreate(h_train, 1, &_h_booster);
std::map<std::string, std::string> booster_params;
booster_params["booster"] = "gbtree";
booster_params["objective"] = "reg:linear";
booster_params["max_depth"] = "5";
booster_params["eta"] = "0.1";
booster_params["min_child_weight"] = "1";
booster_params["subsample"] = "0.5";
booster_params["colsample_bytree"] = "1";
booster_params["num_parallel_tree"] = "1";
std::map<std::string, std::string>::iterator it;
for (it = booster_params.begin(); it != booster_params.end(); ++it) {
std::cout << it->first << ", " << it->second << '\n';
XGBoosterSetParam(_h_booster, it->first.c_str(), it->second.c_str());
}
for (unsigned int iter = 0; iter < _num_trees; iter++) {
XGBoosterUpdateOneIter(_h_booster, iter, h_train[0]);
}
// free xgboost internal structures
XGDMatrixFree(h_train[0]);
}
void XGBoostWrapper::predict(const float Xs[], float* Yhats, unsigned int rows, unsigned int cols) {
DMatrixHandle h_test;
XGDMatrixCreateFromMat((float *) Xs, rows, cols, -1, &h_test);
bst_ulong out_len;
const float* f;
XGBoosterPredict(_h_booster, h_test, 0, 0, &out_len, &f);
for (unsigned int i = 0;i < rows; i++) {
Yhats[i] = f[i];
std::cout << "prediction[" << i << "]=" << Yhats[i] << std::endl;
}
// free xgboost internal structures
XGDMatrixFree(h_test);
// TODO seems as though the pointer set by XGBoosterPredict gets
// freed during XGDMatrixFree. Is that the case? If not, do
// we need to free() it?
}
extern "C" {
XGBoostWrapper* CreateBooster(unsigned int num_trees) {
return new XGBoostWrapper(num_trees);
}
void DeleteBooster(XGBoostWrapper* pBooster) {
if (pBooster) {
delete pBooster;
}
}
void Fit(
XGBoostWrapper* pBooster,
const float Xs[],
const float Ys[],
unsigned int rows,
unsigned int cols) {
return pBooster->fit(Xs, Ys, rows, cols);
}
void Predict(
XGBoostWrapper* pBooster,
const float Xs[],
float* Yhats,
unsigned int rows,
unsigned int cols) {
return pBooster->predict(Xs, Yhats, rows, cols);
}
}
<commit_msg>Removed unnecessary new<commit_after>/*
* Copyright 2016 Krysta M Bouzek
*
* 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 <iostream>
#include <cstdlib>
#include <map>
#include "rabit/c_api.h"
#include "xgboost/c_api.h"
// these links were eminently helpful:
// http://stackoverflow.com/questions/36071672/using-xgboost-in-c
// https://stackoverflow.com/questions/38314092/reading-xgboost-model-in-c
class XGBoostWrapper {
public:
XGBoostWrapper(unsigned int num_trees);
~XGBoostWrapper();
// xgboost expects a flat array
void fit(const float Xs[], const float Ys[], unsigned int rows, unsigned int cols);
void predict(const float Xs[], float* Yhats, unsigned int rows, unsigned int cols);
private:
BoosterHandle _h_booster;
// number of boosting rounds
unsigned int _num_trees;
};
// Create an XGBoost handle
XGBoostWrapper::XGBoostWrapper(unsigned int num_trees) {
_h_booster = BoosterHandle();
_num_trees = num_trees;
}
// Delete the XGBoost handle
XGBoostWrapper::~XGBoostWrapper() {
if (_h_booster) {
XGBoosterFree(_h_booster);
}
}
void XGBoostWrapper::fit(const float Xs[], const float Ys[], unsigned int rows, unsigned int cols) {
// convert to DMatrix
DMatrixHandle h_train[1];
XGDMatrixCreateFromMat((float *) Xs, rows, cols, -1, &h_train[0]);
// load the labels
XGDMatrixSetFloatInfo(h_train[0], "label", Ys, rows);
// read back the labels, just a sanity check
/*bst_ulong bst_result;
const float *out_floats;
XGDMatrixGetFloatInfo(h_train[0], "label" , &bst_result, &out_floats);
for (unsigned int i=0;i<bst_result;i++)
std::cout << "label[" << i << "]=" << out_floats[i] << std::endl;
*/
// create the booster and load some parameters
XGBoosterCreate(h_train, 1, &_h_booster);
std::map<std::string, std::string> booster_params;
booster_params["booster"] = "gbtree";
booster_params["objective"] = "reg:linear";
booster_params["max_depth"] = "5";
booster_params["eta"] = "0.1";
booster_params["min_child_weight"] = "1";
booster_params["subsample"] = "0.5";
booster_params["colsample_bytree"] = "1";
booster_params["num_parallel_tree"] = "1";
std::map<std::string, std::string>::iterator it;
for (it = booster_params.begin(); it != booster_params.end(); ++it) {
std::cout << it->first << ", " << it->second << '\n';
XGBoosterSetParam(_h_booster, it->first.c_str(), it->second.c_str());
}
for (unsigned int iter = 0; iter < _num_trees; iter++) {
XGBoosterUpdateOneIter(_h_booster, iter, h_train[0]);
}
// free xgboost internal structures
XGDMatrixFree(h_train[0]);
}
void XGBoostWrapper::predict(const float Xs[], float* Yhats, unsigned int rows, unsigned int cols) {
DMatrixHandle h_test;
XGDMatrixCreateFromMat((float *) Xs, rows, cols, -1, &h_test);
bst_ulong out_len;
const float* f;
XGBoosterPredict(_h_booster, h_test, 0, 0, &out_len, &f);
for (unsigned int i = 0;i < rows; i++) {
Yhats[i] = f[i];
std::cout << "prediction[" << i << "]=" << Yhats[i] << std::endl;
}
// free xgboost internal structures
XGDMatrixFree(h_test);
// TODO seems as though the pointer set by XGBoosterPredict gets
// freed during XGDMatrixFree. Is that the case? If not, do
// we need to free() it?
}
extern "C" {
XGBoostWrapper* CreateBooster(unsigned int num_trees) {
return new XGBoostWrapper(num_trees);
}
void DeleteBooster(XGBoostWrapper* pBooster) {
if (pBooster) {
delete pBooster;
}
}
void Fit(
XGBoostWrapper* pBooster,
const float Xs[],
const float Ys[],
unsigned int rows,
unsigned int cols) {
return pBooster->fit(Xs, Ys, rows, cols);
}
void Predict(
XGBoostWrapper* pBooster,
const float Xs[],
float* Yhats,
unsigned int rows,
unsigned int cols) {
return pBooster->predict(Xs, Yhats, rows, cols);
}
}
<|endoftext|> |
<commit_before>/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file Session.cpp
* @author Gav Wood <[email protected]>
* @date 2014
*/
#include "Session.h"
#include <chrono>
#include <libdevcore/Common.h>
#include <libethcore/Exceptions.h>
#include "Host.h"
#include "Capability.h"
using namespace std;
using namespace dev;
using namespace dev::p2p;
#define clogS(X) dev::LogOutputStream<X, true>(false) << "| " << std::setw(2) << m_socket.native_handle() << "] "
Session::Session(Host* _s, bi::tcp::socket _socket, bi::address _peerAddress, unsigned short _peerPort):
m_server(_s),
m_socket(std::move(_socket)),
m_listenPort(_peerPort),
m_rating(0)
{
m_disconnect = std::chrono::steady_clock::time_point::max();
m_connect = std::chrono::steady_clock::now();
m_info = PeerInfo({"?", _peerAddress.to_string(), m_listenPort, std::chrono::steady_clock::duration(0)});
}
Session::~Session()
{
// Read-chain finished for one reason or another.
for (auto& i: m_capabilities)
i.second.reset();
try
{
if (m_socket.is_open())
m_socket.close();
}
catch (...){}
}
bi::tcp::endpoint Session::endpoint() const
{
if (m_socket.is_open())
try
{
return bi::tcp::endpoint(m_socket.remote_endpoint().address(), m_listenPort);
}
catch (...){}
return bi::tcp::endpoint();
}
bool Session::interpret(RLP const& _r)
{
clogS(NetRight) << _r;
switch (_r[0].toInt<unsigned>())
{
case HelloPacket:
{
m_protocolVersion = _r[1].toInt<unsigned>();
auto clientVersion = _r[2].toString();
auto caps = _r[3].toVector<string>();
m_listenPort = _r[4].toInt<unsigned short>();
m_id = _r[5].toHash<h512>();
clogS(NetMessageSummary) << "Hello: " << clientVersion << "V[" << m_protocolVersion << "]" << m_id.abridged() << showbase << hex << caps << dec << m_listenPort;
if (m_server->havePeer(m_id))
{
// Already connected.
cwarn << "Already have peer id" << m_id.abridged();// << "at" << l->endpoint() << "rather than" << endpoint();
disconnect(DuplicatePeer);
return false;
}
if (!m_id)
{
disconnect(InvalidIdentity);
return false;
}
if (m_protocolVersion != m_server->protocolVersion())
{
disconnect(IncompatibleProtocol);
return false;
}
try
{ m_info = PeerInfo({clientVersion, m_socket.remote_endpoint().address().to_string(), m_listenPort, std::chrono::steady_clock::duration()}); }
catch (...)
{
disconnect(BadProtocol);
return false;
}
m_server->registerPeer(shared_from_this(), caps);
break;
}
case DisconnectPacket:
{
string reason = "Unspecified";
if (_r[1].isInt())
reason = reasonOf((DisconnectReason)_r[1].toInt<int>());
clogS(NetMessageSummary) << "Disconnect (reason: " << reason << ")";
if (m_socket.is_open())
clogS(NetNote) << "Closing " << m_socket.remote_endpoint();
else
clogS(NetNote) << "Remote closed.";
m_socket.close();
return false;
}
case PingPacket:
{
clogS(NetTriviaSummary) << "Ping";
RLPStream s;
sealAndSend(prep(s).appendList(1) << PongPacket);
break;
}
case PongPacket:
m_info.lastPing = std::chrono::steady_clock::now() - m_ping;
clogS(NetTriviaSummary) << "Latency: " << chrono::duration_cast<chrono::milliseconds>(m_info.lastPing).count() << " ms";
break;
case GetPeersPacket:
{
clogS(NetTriviaSummary) << "GetPeers";
auto peers = m_server->potentialPeers();
RLPStream s;
prep(s).appendList(peers.size() + 1);
s << PeersPacket;
for (auto i: peers)
{
clogS(NetTriviaDetail) << "Sending peer " << i.first.abridged() << i.second;
s.appendList(3) << bytesConstRef(i.second.address().to_v4().to_bytes().data(), 4) << i.second.port() << i.first;
}
sealAndSend(s);
break;
}
case PeersPacket:
clogS(NetTriviaSummary) << "Peers (" << dec << (_r.itemCount() - 1) << " entries)";
for (unsigned i = 1; i < _r.itemCount(); ++i)
{
bi::address_v4 peerAddress(_r[i][0].toHash<FixedHash<4>>().asArray());
auto ep = bi::tcp::endpoint(peerAddress, _r[i][1].toInt<short>());
h512 id = _r[i][2].toHash<h512>();
clogS(NetAllDetail) << "Checking: " << ep << "(" << id.abridged() << ")";
if (isPrivateAddress(peerAddress) && !m_server->m_netPrefs.localNetworking)
goto CONTINUE;
// check that it's not us or one we already know:
if (id && (m_server->m_id == id || (m_id == id && isPrivateAddress(endpoint().address())) || m_server->m_incomingPeers.count(id)))
goto CONTINUE;
// check that we're not already connected to addr:
if (!ep.port())
goto CONTINUE;
for (auto i: m_server->m_addresses)
if (ep.address() == i && ep.port() == m_server->listenPort())
goto CONTINUE;
for (auto i: m_server->m_incomingPeers)
if (i.second.first == ep)
goto CONTINUE;
m_server->m_incomingPeers[id] = make_pair(ep, 0);
m_server->m_freePeers.push_back(id);
m_server->noteNewPeers();
clogS(NetTriviaDetail) << "New peer: " << ep << "(" << id << ")";
CONTINUE:;
}
break;
default:
for (auto const& i: m_capabilities)
if (i.second->m_enabled && i.second->interpret(_r))
return true;
return false;
}
return true;
}
void Session::ping()
{
RLPStream s;
sealAndSend(prep(s).appendList(1) << PingPacket);
m_ping = std::chrono::steady_clock::now();
}
void Session::getPeers()
{
RLPStream s;
sealAndSend(prep(s).appendList(1) << GetPeersPacket);
}
RLPStream& Session::prep(RLPStream& _s)
{
return _s.appendRaw(bytes(8, 0));
}
void Session::sealAndSend(RLPStream& _s)
{
bytes b;
_s.swapOut(b);
m_server->seal(b);
sendDestroy(b);
}
bool Session::checkPacket(bytesConstRef _msg)
{
if (_msg.size() < 8)
return false;
if (!(_msg[0] == 0x22 && _msg[1] == 0x40 && _msg[2] == 0x08 && _msg[3] == 0x91))
return false;
uint32_t len = ((_msg[4] * 256 + _msg[5]) * 256 + _msg[6]) * 256 + _msg[7];
if (_msg.size() != len + 8)
return false;
RLP r(_msg.cropped(8));
if (r.actualSize() != len)
return false;
return true;
}
void Session::sendDestroy(bytes& _msg)
{
clogS(NetLeft) << RLP(bytesConstRef(&_msg).cropped(8));
if (!checkPacket(bytesConstRef(&_msg)))
{
cwarn << "INVALID PACKET CONSTRUCTED!";
}
bytes buffer = bytes(std::move(_msg));
writeImpl(buffer);
}
void Session::send(bytesConstRef _msg)
{
clogS(NetLeft) << RLP(_msg.cropped(8));
if (!checkPacket(_msg))
{
cwarn << "INVALID PACKET CONSTRUCTED!";
}
bytes buffer = bytes(_msg.toBytes());
writeImpl(buffer);
}
void Session::writeImpl(bytes& _buffer)
{
// cerr << (void*)this << " writeImpl" << endl;
if (!m_socket.is_open())
return;
bool doWrite = false;
{
lock_guard<mutex> l(m_writeLock);
m_writeQueue.push_back(_buffer);
doWrite = (m_writeQueue.size() == 1);
}
if (doWrite)
write();
}
void Session::write()
{
const bytes& bytes = m_writeQueue[0];
auto self(shared_from_this());
ba::async_write(m_socket, ba::buffer(bytes), [this, self](boost::system::error_code ec, std::size_t /*length*/)
{
// cerr << (void*)this << " write.callback" << endl;
// must check queue, as write callback can occur following dropped()
if (ec)
{
cwarn << "Error sending: " << ec.message();
dropped();
return;
}
else
{
lock_guard<mutex> l(m_writeLock);
m_writeQueue.pop_front();
if (m_writeQueue.empty())
return;
}
write();
});
}
void Session::dropped()
{
// cerr << (void*)this << " dropped" << endl;
if (m_socket.is_open())
try
{
clogS(NetConnect) << "Closing " << m_socket.remote_endpoint();
m_socket.close();
}
catch (...) {}
}
void Session::disconnect(int _reason)
{
clogS(NetConnect) << "Disconnecting (reason:" << reasonOf((DisconnectReason)_reason) << ")";
if (m_socket.is_open())
{
if (m_disconnect == chrono::steady_clock::time_point::max())
{
RLPStream s;
prep(s);
s.appendList(2) << DisconnectPacket << _reason;
sealAndSend(s);
m_disconnect = chrono::steady_clock::now();
}
else
dropped();
}
}
void Session::start()
{
RLPStream s;
prep(s);
s.appendList(6) << HelloPacket
<< m_server->protocolVersion()
<< m_server->m_clientVersion
<< m_server->caps()
<< m_server->m_public.port()
<< m_server->m_id;
sealAndSend(s);
ping();
getPeers();
doRead();
}
void Session::doRead()
{
// ignore packets received while waiting to disconnect
if (chrono::steady_clock::now() - m_disconnect > chrono::seconds(0))
return;
auto self(shared_from_this());
m_socket.async_read_some(boost::asio::buffer(m_data), [this,self](boost::system::error_code ec, std::size_t length)
{
// If error is end of file, ignore
if (ec && ec.category() != boost::asio::error::get_misc_category() && ec.value() != boost::asio::error::eof)
{
// got here with length of 1241...
cwarn << "Error reading: " << ec.message();
dropped();
}
else if (ec && length == 0)
{
return;
}
else
{
try
{
m_incoming.resize(m_incoming.size() + length);
memcpy(m_incoming.data() + m_incoming.size() - length, m_data.data(), length);
while (m_incoming.size() > 8)
{
if (m_incoming[0] != 0x22 || m_incoming[1] != 0x40 || m_incoming[2] != 0x08 || m_incoming[3] != 0x91)
{
cwarn << "INVALID SYNCHRONISATION TOKEN; expected = 22400891; received = " << toHex(bytesConstRef(m_incoming.data(), 4));
disconnect(BadProtocol);
return;
}
else
{
uint32_t len = fromBigEndian<uint32_t>(bytesConstRef(m_incoming.data() + 4, 4));
uint32_t tlen = len + 8;
if (m_incoming.size() < tlen)
break;
// enough has come in.
auto data = bytesConstRef(m_incoming.data(), tlen);
if (!checkPacket(data))
{
cerr << "Received " << len << ": " << toHex(bytesConstRef(m_incoming.data() + 8, len)) << endl;
cwarn << "INVALID MESSAGE RECEIVED";
disconnect(BadProtocol);
return;
}
else
{
RLP r(data.cropped(8));
if (!interpret(r))
{
// error
dropped();
return;
}
}
memmove(m_incoming.data(), m_incoming.data() + tlen, m_incoming.size() - tlen);
m_incoming.resize(m_incoming.size() - tlen);
}
}
doRead();
}
catch (Exception const& _e)
{
clogS(NetWarn) << "ERROR: " << _e.description();
dropped();
}
catch (std::exception const& _e)
{
clogS(NetWarn) << "ERROR: " << _e.what();
dropped();
}
}
});
}
<commit_msg>More network debugging.<commit_after>/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file Session.cpp
* @author Gav Wood <[email protected]>
* @date 2014
*/
#include "Session.h"
#include <chrono>
#include <libdevcore/Common.h>
#include <libethcore/Exceptions.h>
#include "Host.h"
#include "Capability.h"
using namespace std;
using namespace dev;
using namespace dev::p2p;
#define clogS(X) dev::LogOutputStream<X, true>(false) << "| " << std::setw(2) << m_socket.native_handle() << "] "
Session::Session(Host* _s, bi::tcp::socket _socket, bi::address _peerAddress, unsigned short _peerPort):
m_server(_s),
m_socket(std::move(_socket)),
m_listenPort(_peerPort),
m_rating(0)
{
m_disconnect = std::chrono::steady_clock::time_point::max();
m_connect = std::chrono::steady_clock::now();
m_info = PeerInfo({"?", _peerAddress.to_string(), m_listenPort, std::chrono::steady_clock::duration(0)});
}
Session::~Session()
{
// Read-chain finished for one reason or another.
for (auto& i: m_capabilities)
i.second.reset();
try
{
if (m_socket.is_open())
m_socket.close();
}
catch (...){}
}
bi::tcp::endpoint Session::endpoint() const
{
if (m_socket.is_open())
try
{
return bi::tcp::endpoint(m_socket.remote_endpoint().address(), m_listenPort);
}
catch (...){}
return bi::tcp::endpoint();
}
bool Session::interpret(RLP const& _r)
{
clogS(NetRight) << _r;
switch (_r[0].toInt<unsigned>())
{
case HelloPacket:
{
m_protocolVersion = _r[1].toInt<unsigned>();
auto clientVersion = _r[2].toString();
auto caps = _r[3].toVector<string>();
m_listenPort = _r[4].toInt<unsigned short>();
m_id = _r[5].toHash<h512>();
clogS(NetMessageSummary) << "Hello: " << clientVersion << "V[" << m_protocolVersion << "]" << m_id.abridged() << showbase << hex << caps << dec << m_listenPort;
if (m_server->havePeer(m_id))
{
// Already connected.
cwarn << "Already have peer id" << m_id.abridged();// << "at" << l->endpoint() << "rather than" << endpoint();
disconnect(DuplicatePeer);
return false;
}
if (!m_id)
{
disconnect(InvalidIdentity);
return false;
}
if (m_protocolVersion != m_server->protocolVersion())
{
disconnect(IncompatibleProtocol);
return false;
}
try
{ m_info = PeerInfo({clientVersion, m_socket.remote_endpoint().address().to_string(), m_listenPort, std::chrono::steady_clock::duration()}); }
catch (...)
{
disconnect(BadProtocol);
return false;
}
m_server->registerPeer(shared_from_this(), caps);
break;
}
case DisconnectPacket:
{
string reason = "Unspecified";
if (_r[1].isInt())
reason = reasonOf((DisconnectReason)_r[1].toInt<int>());
clogS(NetMessageSummary) << "Disconnect (reason: " << reason << ")";
if (m_socket.is_open())
clogS(NetNote) << "Closing " << m_socket.remote_endpoint();
else
clogS(NetNote) << "Remote closed.";
m_socket.close();
return false;
}
case PingPacket:
{
clogS(NetTriviaSummary) << "Ping";
RLPStream s;
sealAndSend(prep(s).appendList(1) << PongPacket);
break;
}
case PongPacket:
m_info.lastPing = std::chrono::steady_clock::now() - m_ping;
clogS(NetTriviaSummary) << "Latency: " << chrono::duration_cast<chrono::milliseconds>(m_info.lastPing).count() << " ms";
break;
case GetPeersPacket:
{
clogS(NetTriviaSummary) << "GetPeers";
auto peers = m_server->potentialPeers();
RLPStream s;
prep(s).appendList(peers.size() + 1);
s << PeersPacket;
for (auto i: peers)
{
clogS(NetTriviaDetail) << "Sending peer " << i.first.abridged() << i.second;
s.appendList(3) << bytesConstRef(i.second.address().to_v4().to_bytes().data(), 4) << i.second.port() << i.first;
}
sealAndSend(s);
break;
}
case PeersPacket:
clogS(NetTriviaSummary) << "Peers (" << dec << (_r.itemCount() - 1) << " entries)";
for (unsigned i = 1; i < _r.itemCount(); ++i)
{
bi::address_v4 peerAddress(_r[i][0].toHash<FixedHash<4>>().asArray());
auto ep = bi::tcp::endpoint(peerAddress, _r[i][1].toInt<short>());
h512 id = _r[i][2].toHash<h512>();
clogS(NetAllDetail) << "Checking: " << ep << "(" << id.abridged() << ")" << isPrivateAddress(peerAddress) << m_id.abridged() << id.abridged() << isPrivateAddress(endpoint().address()) << m_server->m_incomingPeers.count(id) << id << m_server->m_incomingPeers.count(id);
if (isPrivateAddress(peerAddress) && !m_server->m_netPrefs.localNetworking)
goto CONTINUE;
// check that it's not us or one we already know:
if (!(m_id == id && isPrivateAddress(endpoint().address()) && (!m_server->m_incomingPeers.count(id) || isPrivateAddress(m_server->m_incomingPeers.at(id).first.address()))) && (!id || m_server->m_id == id || m_server->m_incomingPeers.count(id)))
goto CONTINUE;
// check that we're not already connected to addr:
if (!ep.port())
goto CONTINUE;
for (auto i: m_server->m_addresses)
if (ep.address() == i && ep.port() == m_server->listenPort())
goto CONTINUE;
for (auto i: m_server->m_incomingPeers)
if (i.second.first == ep)
goto CONTINUE;
m_server->m_incomingPeers[id] = make_pair(ep, 0);
m_server->m_freePeers.push_back(id);
m_server->noteNewPeers();
clogS(NetTriviaDetail) << "New peer: " << ep << "(" << id << ")";
CONTINUE:;
}
break;
default:
for (auto const& i: m_capabilities)
if (i.second->m_enabled && i.second->interpret(_r))
return true;
return false;
}
return true;
}
void Session::ping()
{
RLPStream s;
sealAndSend(prep(s).appendList(1) << PingPacket);
m_ping = std::chrono::steady_clock::now();
}
void Session::getPeers()
{
RLPStream s;
sealAndSend(prep(s).appendList(1) << GetPeersPacket);
}
RLPStream& Session::prep(RLPStream& _s)
{
return _s.appendRaw(bytes(8, 0));
}
void Session::sealAndSend(RLPStream& _s)
{
bytes b;
_s.swapOut(b);
m_server->seal(b);
sendDestroy(b);
}
bool Session::checkPacket(bytesConstRef _msg)
{
if (_msg.size() < 8)
return false;
if (!(_msg[0] == 0x22 && _msg[1] == 0x40 && _msg[2] == 0x08 && _msg[3] == 0x91))
return false;
uint32_t len = ((_msg[4] * 256 + _msg[5]) * 256 + _msg[6]) * 256 + _msg[7];
if (_msg.size() != len + 8)
return false;
RLP r(_msg.cropped(8));
if (r.actualSize() != len)
return false;
return true;
}
void Session::sendDestroy(bytes& _msg)
{
clogS(NetLeft) << RLP(bytesConstRef(&_msg).cropped(8));
if (!checkPacket(bytesConstRef(&_msg)))
{
cwarn << "INVALID PACKET CONSTRUCTED!";
}
bytes buffer = bytes(std::move(_msg));
writeImpl(buffer);
}
void Session::send(bytesConstRef _msg)
{
clogS(NetLeft) << RLP(_msg.cropped(8));
if (!checkPacket(_msg))
{
cwarn << "INVALID PACKET CONSTRUCTED!";
}
bytes buffer = bytes(_msg.toBytes());
writeImpl(buffer);
}
void Session::writeImpl(bytes& _buffer)
{
// cerr << (void*)this << " writeImpl" << endl;
if (!m_socket.is_open())
return;
bool doWrite = false;
{
lock_guard<mutex> l(m_writeLock);
m_writeQueue.push_back(_buffer);
doWrite = (m_writeQueue.size() == 1);
}
if (doWrite)
write();
}
void Session::write()
{
const bytes& bytes = m_writeQueue[0];
auto self(shared_from_this());
ba::async_write(m_socket, ba::buffer(bytes), [this, self](boost::system::error_code ec, std::size_t /*length*/)
{
// cerr << (void*)this << " write.callback" << endl;
// must check queue, as write callback can occur following dropped()
if (ec)
{
cwarn << "Error sending: " << ec.message();
dropped();
return;
}
else
{
lock_guard<mutex> l(m_writeLock);
m_writeQueue.pop_front();
if (m_writeQueue.empty())
return;
}
write();
});
}
void Session::dropped()
{
// cerr << (void*)this << " dropped" << endl;
if (m_socket.is_open())
try
{
clogS(NetConnect) << "Closing " << m_socket.remote_endpoint();
m_socket.close();
}
catch (...) {}
}
void Session::disconnect(int _reason)
{
clogS(NetConnect) << "Disconnecting (reason:" << reasonOf((DisconnectReason)_reason) << ")";
if (m_socket.is_open())
{
if (m_disconnect == chrono::steady_clock::time_point::max())
{
RLPStream s;
prep(s);
s.appendList(2) << DisconnectPacket << _reason;
sealAndSend(s);
m_disconnect = chrono::steady_clock::now();
}
else
dropped();
}
}
void Session::start()
{
RLPStream s;
prep(s);
s.appendList(6) << HelloPacket
<< m_server->protocolVersion()
<< m_server->m_clientVersion
<< m_server->caps()
<< m_server->m_public.port()
<< m_server->m_id;
sealAndSend(s);
ping();
getPeers();
doRead();
}
void Session::doRead()
{
// ignore packets received while waiting to disconnect
if (chrono::steady_clock::now() - m_disconnect > chrono::seconds(0))
return;
auto self(shared_from_this());
m_socket.async_read_some(boost::asio::buffer(m_data), [this,self](boost::system::error_code ec, std::size_t length)
{
// If error is end of file, ignore
if (ec && ec.category() != boost::asio::error::get_misc_category() && ec.value() != boost::asio::error::eof)
{
// got here with length of 1241...
cwarn << "Error reading: " << ec.message();
dropped();
}
else if (ec && length == 0)
{
return;
}
else
{
try
{
m_incoming.resize(m_incoming.size() + length);
memcpy(m_incoming.data() + m_incoming.size() - length, m_data.data(), length);
while (m_incoming.size() > 8)
{
if (m_incoming[0] != 0x22 || m_incoming[1] != 0x40 || m_incoming[2] != 0x08 || m_incoming[3] != 0x91)
{
cwarn << "INVALID SYNCHRONISATION TOKEN; expected = 22400891; received = " << toHex(bytesConstRef(m_incoming.data(), 4));
disconnect(BadProtocol);
return;
}
else
{
uint32_t len = fromBigEndian<uint32_t>(bytesConstRef(m_incoming.data() + 4, 4));
uint32_t tlen = len + 8;
if (m_incoming.size() < tlen)
break;
// enough has come in.
auto data = bytesConstRef(m_incoming.data(), tlen);
if (!checkPacket(data))
{
cerr << "Received " << len << ": " << toHex(bytesConstRef(m_incoming.data() + 8, len)) << endl;
cwarn << "INVALID MESSAGE RECEIVED";
disconnect(BadProtocol);
return;
}
else
{
RLP r(data.cropped(8));
if (!interpret(r))
{
// error
dropped();
return;
}
}
memmove(m_incoming.data(), m_incoming.data() + tlen, m_incoming.size() - tlen);
m_incoming.resize(m_incoming.size() - tlen);
}
}
doRead();
}
catch (Exception const& _e)
{
clogS(NetWarn) << "ERROR: " << _e.description();
dropped();
}
catch (std::exception const& _e)
{
clogS(NetWarn) << "ERROR: " << _e.what();
dropped();
}
}
});
}
<|endoftext|> |
<commit_before>///
/// @file cmdoptions.hpp
///
/// Copyright (C) 2013 Kim Walisch, <[email protected]>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#ifndef PRIMESIEVE_CMDOPTIONS_HPP
#define PRIMESIEVE_CMDOPTIONS_HPP
#include <deque>
#include <stdint.h>
struct PrimeSieveOptions
{
std::deque<uint64_t> n;
int flags;
int sieveSize;
int threads;
bool quiet;
bool nthPrime;
PrimeSieveOptions() :
flags(0),
sieveSize(0),
threads(0),
quiet(false),
nthPrime(false)
{ }
};
PrimeSieveOptions parseOptions(int, char**);
#endif
<commit_msg>Refactoring<commit_after>///
/// @file cmdoptions.hpp
///
/// Copyright (C) 2013 Kim Walisch, <[email protected]>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#ifndef CMDOPTIONS_HPP
#define CMDOPTIONS_HPP
#include <deque>
#include <stdint.h>
struct PrimeSieveOptions
{
std::deque<uint64_t> n;
int flags;
int sieveSize;
int threads;
bool quiet;
bool nthPrime;
PrimeSieveOptions() :
flags(0),
sieveSize(0),
threads(0),
quiet(false),
nthPrime(false)
{ }
};
PrimeSieveOptions parseOptions(int, char**);
#endif
<|endoftext|> |
<commit_before>/**
* This file is part of the "libfnord" project
* Copyright (c) 2015 Paul Asmuth
*
* FnordMetric is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License v3.0. You should have received a
* copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <stdlib.h>
#include <unistd.h>
#include "fnord-base/application.h"
#include "fnord-base/io/filerepository.h"
#include "fnord-base/io/fileutil.h"
#include "fnord-base/thread/eventloop.h"
#include "fnord-base/thread/threadpool.h"
#include "fnord-base/random.h"
#include "fnord-base/wallclock.h"
#include "fnord-base/cli/flagparser.h"
#include "fnord-http/httprouter.h"
#include "fnord-http/httpserver.h"
#include "fnord-http/httpconnectionpool.h"
#include "fnord-tsdb/TSDBClient.h"
#include "fnord-msg/msg.h"
#include <sensord/SensorSampleFeed.h>
#include <sensord/SensorPushServlet.h>
using namespace fnord;
int main(int argc, const char** argv) {
Application::init();
Application::logToStderr();
cli::FlagParser flags;
flags.defineFlag(
"http",
cli::FlagParser::T_INTEGER,
false,
NULL,
"8000",
"Start the http server on this port",
"<port>");
flags.defineFlag(
"tsdb",
cli::FlagParser::T_STRING,
false,
NULL,
NULL,
"tsdb addr",
"<host:port>");
flags.defineFlag(
"loglevel",
cli::FlagParser::T_STRING,
false,
NULL,
"INFO",
"loglevel",
"<level>");
flags.parseArgv(argc, argv);
Logger::get()->setMinimumLogLevel(
strToLogLevel(flags.getString("loglevel")));
thread::EventLoop evloop;
thread::ThreadPool tp(
std::unique_ptr<ExceptionHandler>(
new CatchAndLogExceptionHandler("metricd")));
http::HTTPConnectionPool http(&evloop);
tsdb::TSDBClient tsdb(
StringUtil::format("http://$0/tsdb", flags.getString("tsdb")),
&http);
/* set up http server */
http::HTTPRouter http_router;
http::HTTPServer http_server(&http_router, &evloop);
http_server.listen(flags.getInt("http"));
http_server.stats()->exportStats("/metricd/http");
sensord::SensorSampleFeed sensor_feed;
sensor_feed.subscribe(&tp, [&tsdb] (const sensord::SampleEnvelope& smpl) {
if (smpl.sample_namespace().empty()) {
fnord::logWarning("metricd", "discarding sample without namespace");
}
auto stream_key = StringUtil::format(
"metricd.sensors.$0.$1",
smpl.sample_namespace(),
smpl.sensor_key());
tsdb.insertRecord(
stream_key,
WallClock::unixMicros(),
tsdb.mkMessageID(),
*msg::encode(smpl));
});
metricdb::SensorPushServlet sensor_servlet(&sensor_feed);
http_router.addRouteByPrefixMatch("/sensors", &sensor_servlet);
//stats::StatsHTTPServlet stats_servlet;
//http_router.addRouteByPrefixMatch("/stats", &stats_servlet);
evloop.run();
return 0;
}
<commit_msg>insert actual sample data instead of envelope<commit_after>/**
* This file is part of the "libfnord" project
* Copyright (c) 2015 Paul Asmuth
*
* FnordMetric is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License v3.0. You should have received a
* copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <stdlib.h>
#include <unistd.h>
#include "fnord-base/application.h"
#include "fnord-base/io/filerepository.h"
#include "fnord-base/io/fileutil.h"
#include "fnord-base/thread/eventloop.h"
#include "fnord-base/thread/threadpool.h"
#include "fnord-base/random.h"
#include "fnord-base/wallclock.h"
#include "fnord-base/cli/flagparser.h"
#include "fnord-http/httprouter.h"
#include "fnord-http/httpserver.h"
#include "fnord-http/httpconnectionpool.h"
#include "fnord-tsdb/TSDBClient.h"
#include "fnord-msg/msg.h"
#include <sensord/SensorSampleFeed.h>
#include <sensord/SensorPushServlet.h>
using namespace fnord;
int main(int argc, const char** argv) {
Application::init();
Application::logToStderr();
cli::FlagParser flags;
flags.defineFlag(
"http",
cli::FlagParser::T_INTEGER,
false,
NULL,
"8000",
"Start the http server on this port",
"<port>");
flags.defineFlag(
"tsdb",
cli::FlagParser::T_STRING,
false,
NULL,
NULL,
"tsdb addr",
"<host:port>");
flags.defineFlag(
"loglevel",
cli::FlagParser::T_STRING,
false,
NULL,
"INFO",
"loglevel",
"<level>");
flags.parseArgv(argc, argv);
Logger::get()->setMinimumLogLevel(
strToLogLevel(flags.getString("loglevel")));
thread::EventLoop evloop;
thread::ThreadPool tp(
std::unique_ptr<ExceptionHandler>(
new CatchAndLogExceptionHandler("metricd")));
http::HTTPConnectionPool http(&evloop);
tsdb::TSDBClient tsdb(
StringUtil::format("http://$0/tsdb", flags.getString("tsdb")),
&http);
/* set up http server */
http::HTTPRouter http_router;
http::HTTPServer http_server(&http_router, &evloop);
http_server.listen(flags.getInt("http"));
http_server.stats()->exportStats("/metricd/http");
sensord::SensorSampleFeed sensor_feed;
sensor_feed.subscribe(&tp, [&tsdb] (const sensord::SampleEnvelope& smpl) {
if (smpl.sample_namespace().empty()) {
fnord::logWarning("metricd", "discarding sample without namespace");
}
auto stream_key = StringUtil::format(
"metricd.sensors.$0.$1",
smpl.sample_namespace(),
smpl.sensor_key());
auto sample_data = smpl.data();
auto sample_time = WallClock::unixMicros();
tsdb.insertRecord(
stream_key,
sample_time,
tsdb.mkMessageID(),
Buffer(sample_data.data(), sample_data.size()));
});
metricdb::SensorPushServlet sensor_servlet(&sensor_feed);
http_router.addRouteByPrefixMatch("/sensors", &sensor_servlet);
//stats::StatsHTTPServlet stats_servlet;
//http_router.addRouteByPrefixMatch("/stats", &stats_servlet);
evloop.run();
return 0;
}
<|endoftext|> |
<commit_before>// __BEGIN_LICENSE__
// Copyright (c) 2009-2013, United States Government as represented by the
// Administrator of the National Aeronautics and Space Administration. All
// rights reserved.
//
// The NGT platform is 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.
// __END_LICENSE__
/// \file disparitydebug.cc
///
#ifdef _MSC_VER
#pragma warning(disable:4244)
#pragma warning(disable:4267)
#pragma warning(disable:4996)
#endif
#ifdef NDEBUG
#undef NDEBUG
#endif
#include <vw/Cartography/GeoReferenceUtils.h>
#include <vw/Stereo/DisparityMap.h>
#include <vw/Image/Filter.h>
#include <asp/Core/Macros.h>
#include <asp/Core/Common.h>
using namespace vw;
using namespace vw::stereo;
namespace po = boost::program_options;
namespace fs = boost::filesystem;
// Disparity norm
double disparity_norm(PixelMask<Vector2f> const& pix) {
if (!is_valid(pix))
return 0.0;
return norm_2(pix.child());
}
// To Find the disparity norm of an image, use per_pixel_filter(image,
// DisparityNorm()).
class DisparityNorm: public ReturnFixedType<double> {
public:
double operator()(PixelMask<Vector2f> const& pix) const {
return disparity_norm(pix);
}
};
// Find the maximum of the norms of differences between a disparity
// at a pixel and its four left, right, top, and bottom neighbors.
// For the disparity to result in a nice transform from left to
// right image the norms better be less than 1.
class DispNormDiff: public ImageViewBase<DispNormDiff> {
ImageViewRef<PixelMask<Vector2f>> m_img;
public:
DispNormDiff(ImageViewRef<PixelMask<Vector2f>> const& img):
m_img(img) {}
typedef float result_type;
typedef result_type pixel_type;
typedef ProceduralPixelAccessor<DispNormDiff> pixel_accessor;
inline int32 cols() const { return m_img.cols(); }
inline int32 rows() const { return m_img.rows(); }
inline int32 planes() const { return 1; }
inline pixel_accessor origin() const { return pixel_accessor(*this, 0, 0); }
inline result_type operator()( double/*i*/, double/*j*/, int32/*p*/ = 0 ) const {
vw_throw(NoImplErr() << "DispNormDiff::operator()(...) is not implemented");
return result_type(0.0);
}
typedef CropView<ImageView<result_type>> prerasterize_type;
inline prerasterize_type prerasterize(BBox2i const& bbox) const {
ImageView<result_type> tile(bbox.width(), bbox.height());
// Need to see each pixel's neighbors
int extra = 1;
BBox2i biased_box = bbox;
biased_box.expand(extra);
biased_box.crop(bounding_box(m_img));
// Bring fully in memory a crop of the input for this tile
ImageView<PixelMask<Vector2f>> cropped_img = crop(m_img, biased_box);
for (int col = bbox.min().x(); col < bbox.max().x(); col++) {
for (int row = bbox.min().y(); row < bbox.max().y(); row++) {
// Find the disparity value at the current pixel and the neighbors.
// Need to be careful to account for the bias and for indices
// going out of range.
// Coordinates of a pixel and its neighbors.
std::vector<Vector2i> coords = {Vector2i(0, 0), Vector2i(1, 0), Vector2i(0, 1),
Vector2i(-1, 0), Vector2i(0, -1)};
std::vector<PixelMask<Vector2f>> vals(5);
for (int it = 0; it < 5; it++) {
Vector2i coord = Vector2i(col, row) + coords[it]; // pixel in uncropped image
if (biased_box.contains(coord)) {
// Take into account the bounds and the crop
vals[it] = cropped_img(coord.x() - biased_box.min().x(),
coord.y() - biased_box.min().y());
} else {
// Out of range
vals[it].child() = Vector2f(0, 0);
vals[it].invalidate();
}
}
double max_norm_diff = 0.0;
if (is_valid(vals[0])) {
// Need to have the center pixel valid
for (int it = 1; it < 5; it++) {
if (!is_valid(vals[it]))
continue;
max_norm_diff = std::max(max_norm_diff, norm_2(vals[it].child() - vals[0].child()));
}
}
tile(col - bbox.min().x(), row - bbox.min().y()) = max_norm_diff;
}
}
return prerasterize_type(tile, -bbox.min().x(), -bbox.min().y(),
cols(), rows());
}
template <class DestT>
inline void rasterize(DestT const& dest, BBox2i bbox) const {
vw::rasterize(prerasterize(bbox), dest, bbox);
}
};
struct Options : vw::cartography::GdalWriteOptions {
// Input
std::string input_file_name;
BBox2 normalization_range;
BBox2 roi; ///< Only generate output images in this region
bool save_norm, save_norm_diff;
// Output
std::string output_prefix, output_file_type;
Options(): save_norm(false), save_norm_diff(false) {}
};
void handle_arguments(int argc, char *argv[], Options& opt) {
po::options_description general_options("");
general_options.add_options()
("normalization", po::value(&opt.normalization_range)->default_value(BBox2(0, 0, 0, 0), "auto"),
"Normalization range. Specify in format: hmin vmin hmax vmax.")
("roi", po::value(&opt.roi)->default_value(BBox2(0,0,0,0), "auto"),
"Region of interest. Specify in format: xmin ymin xmax ymax.")
("save-norm", po::bool_switch(&opt.save_norm)->default_value(false),
"Save the norm of the disparity instead of its two bands.")
("save-norm-diff", po::bool_switch(&opt.save_norm_diff)->default_value(false),
"Save the maximum of norms of differences between a disparity and its four neighbors.")
("output-prefix, o", po::value(&opt.output_prefix), "Specify the output prefix.")
("output-filetype, t", po::value(&opt.output_file_type)->default_value("tif"),
"Specify the output file type.");
general_options.add(vw::cartography::GdalWriteOptionsDescription(opt));
po::options_description positional("");
positional.add_options()
("input-file", po::value(&opt.input_file_name), "Input disparity map.");
po::positional_options_description positional_desc;
positional_desc.add("input-file", 1);
std::string usage("[options] <input disparity map>");
bool allow_unregistered = false;
std::vector<std::string> unregistered;
po::variables_map vm =
asp::check_command_line(argc, argv, opt, general_options, general_options,
positional, positional_desc, usage,
allow_unregistered, unregistered);
if (opt.input_file_name.empty())
vw_throw(ArgumentErr() << "Missing input file!\n"
<< usage << general_options);
if (opt.output_prefix.empty())
opt.output_prefix = vw::prefix_from_filename(opt.input_file_name);
if (opt.save_norm && opt.save_norm_diff)
vw_throw(ArgumentErr() << "Cannot save both the norm and norm of differences at the same "
<< "time.\n" << usage << general_options);
}
template <class PixelT>
void process_disparity(Options& opt) {
cartography::GeoReference georef;
bool has_georef = read_georeference(georef, opt.input_file_name);
bool has_nodata = false;
float output_nodata = -32768.0;
if (opt.save_norm) {
DiskImageView<PixelMask<Vector2f>> disk_disparity_map(opt.input_file_name);
std::string norm_file = opt.output_prefix + "-norm." + opt.output_file_type;
vw_out() << "\t--> Writing disparity norm: " << norm_file << "\n";
block_write_gdal_image(norm_file,
per_pixel_filter(disk_disparity_map, DisparityNorm()),
has_georef, georef,
has_nodata, output_nodata,
opt, TerminalProgressCallback("asp","\t norm: "));
return;
}
if (opt.save_norm_diff) {
DiskImageView<PixelMask<Vector2f>> disk_disparity_map(opt.input_file_name);
std::string norm_file = opt.output_prefix + "-norm-diff." + opt.output_file_type;
vw_out() << "\t--> Writing disparity norm: " << norm_file << "\n";
block_write_gdal_image(norm_file,
DispNormDiff(disk_disparity_map),
has_georef, georef,
has_nodata, output_nodata,
opt, TerminalProgressCallback("asp","\t norm: "));
return;
}
DiskImageView<PixelT> disk_disparity_map(opt.input_file_name);
// If no ROI passed in, use the full image
BBox2 roiToUse(opt.roi);
if (opt.roi == BBox2(0,0,0,0))
roiToUse = BBox2(0,0,disk_disparity_map.cols(),disk_disparity_map.rows());
if (has_georef)
georef = crop(georef, roiToUse);
// Compute intensity display range if not passed in. For this purpose
// subsample the image.
vw_out() << "\t--> Computing disparity range.\n";
if (opt.normalization_range == BBox2(0,0,0,0)) {
float subsample_amt =
float(roiToUse.height())*float(roiToUse.width()) / (1000.f * 1000.f);
subsample_amt = std::max(subsample_amt, 1.0f);
opt.normalization_range
= get_disparity_range(subsample(crop(disk_disparity_map, roiToUse), subsample_amt));
}
vw_out() << "\t Horizontal: [" << opt.normalization_range.min().x()
<< " " << opt.normalization_range.max().x() << "] Vertical: ["
<< opt.normalization_range.min().y() << " "
<< opt.normalization_range.max().y() << "]\n";
// Generate value-normalized copies of the H and V channels
typedef typename PixelChannelType<PixelT>::type ChannelT;
ImageViewRef<ChannelT> horizontal =
apply_mask(copy_mask(clamp(normalize(crop(select_channel(disk_disparity_map, 0),
roiToUse),
opt.normalization_range.min().x(),
opt.normalization_range.max().x(),
ChannelRange<ChannelT>::min(),
ChannelRange<ChannelT>::max()
)),
crop(disk_disparity_map, roiToUse)));
ImageViewRef<ChannelT> vertical =
apply_mask(copy_mask(clamp(normalize(crop(select_channel(disk_disparity_map, 1),
roiToUse),
opt.normalization_range.min().y(),
opt.normalization_range.max().y(),
ChannelRange<ChannelT>::min(),
ChannelRange<ChannelT>::max()
)),
crop(disk_disparity_map, roiToUse)));
// Write both images to disk, casting as UINT8
std::string h_file = opt.output_prefix + "-H." + opt.output_file_type;
vw_out() << "\t--> Writing horizontal disparity debug image: " << h_file << "\n";
block_write_gdal_image(h_file,
channel_cast_rescale<uint8>(horizontal),
has_georef, georef,
has_nodata, output_nodata,
opt, TerminalProgressCallback("asp","\t H : "));
std::string v_file = opt.output_prefix + "-V." + opt.output_file_type;
vw_out() << "\t--> Writing vertical disparity debug image: " << v_file << "\n";
block_write_gdal_image(v_file,
channel_cast_rescale<uint8>(vertical),
has_georef, georef,
has_nodata, output_nodata,
opt, TerminalProgressCallback("asp","\t V : "));
}
int main(int argc, char *argv[]) {
Options opt;
try {
handle_arguments(argc, argv, opt);
vw_out() << "Opening " << opt.input_file_name << "\n";
ImageFormat fmt = vw::image_format(opt.input_file_name);
switch(fmt.pixel_format) {
case VW_PIXEL_GENERIC_2_CHANNEL:
switch (fmt.channel_type) {
case VW_CHANNEL_INT32:
process_disparity<Vector2i>(opt); break;
default:
process_disparity<Vector2f>(opt); break;
} break;
case VW_PIXEL_RGB:
case VW_PIXEL_GENERIC_3_CHANNEL:
switch (fmt.channel_type) {
case VW_CHANNEL_INT32:
process_disparity<PixelMask<Vector2i>>(opt); break;
default:
process_disparity<PixelMask<Vector2f>>(opt); break;
} break;
case VW_PIXEL_SCALAR:
// OpenEXR stores everything as planar, so this allows us to
// still read that data.
if (fmt.planes == 2) {
switch (fmt.channel_type) {
case VW_CHANNEL_INT32:
process_disparity<Vector2i>(opt); break;
default:
process_disparity<Vector2f>(opt); break;
} break;
} else if (fmt.planes == 3) {
switch (fmt.channel_type) {
case VW_CHANNEL_INT32:
process_disparity<PixelMask<Vector2i>>(opt); break;
default:
process_disparity<PixelMask<Vector2f>>(opt); break;
} break;
}
default:
vw_throw(ArgumentErr() << "Unsupported pixel format. Expected 2 or 3 channel image. "
<< "Instead got [" << pixel_format_name(fmt.pixel_format) << "].");
}
} ASP_STANDARD_CATCHES;
return 0;
}
<commit_msg>disparitydebug: Minor wording<commit_after>// __BEGIN_LICENSE__
// Copyright (c) 2009-2013, United States Government as represented by the
// Administrator of the National Aeronautics and Space Administration. All
// rights reserved.
//
// The NGT platform is 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.
// __END_LICENSE__
/// \file disparitydebug.cc
///
#ifdef _MSC_VER
#pragma warning(disable:4244)
#pragma warning(disable:4267)
#pragma warning(disable:4996)
#endif
#ifdef NDEBUG
#undef NDEBUG
#endif
#include <vw/Cartography/GeoReferenceUtils.h>
#include <vw/Stereo/DisparityMap.h>
#include <vw/Image/Filter.h>
#include <asp/Core/Macros.h>
#include <asp/Core/Common.h>
using namespace vw;
using namespace vw::stereo;
namespace po = boost::program_options;
namespace fs = boost::filesystem;
// Disparity norm
double disparity_norm(PixelMask<Vector2f> const& pix) {
if (!is_valid(pix))
return 0.0;
return norm_2(pix.child());
}
// To find the disparity norm of an image, use
// per_pixel_filter(image, DisparityNorm()).
class DisparityNorm: public ReturnFixedType<double> {
public:
double operator()(PixelMask<Vector2f> const& pix) const {
return disparity_norm(pix);
}
};
// Find the maximum of the norms of differences between a disparity
// at a pixel and its four left, right, top, and bottom neighbors.
// For the disparity to result in a nice transform from left to
// right image the norms better be less than 1.
class DispNormDiff: public ImageViewBase<DispNormDiff> {
ImageViewRef<PixelMask<Vector2f>> m_img;
public:
DispNormDiff(ImageViewRef<PixelMask<Vector2f>> const& img):
m_img(img) {}
typedef float result_type;
typedef result_type pixel_type;
typedef ProceduralPixelAccessor<DispNormDiff> pixel_accessor;
inline int32 cols() const { return m_img.cols(); }
inline int32 rows() const { return m_img.rows(); }
inline int32 planes() const { return 1; }
inline pixel_accessor origin() const { return pixel_accessor(*this, 0, 0); }
inline result_type operator()( double/*i*/, double/*j*/, int32/*p*/ = 0 ) const {
vw_throw(NoImplErr() << "DispNormDiff::operator()(...) is not implemented");
return result_type(0.0);
}
typedef CropView<ImageView<result_type>> prerasterize_type;
inline prerasterize_type prerasterize(BBox2i const& bbox) const {
ImageView<result_type> tile(bbox.width(), bbox.height());
// Need to see each pixel's neighbors
int extra = 1;
BBox2i biased_box = bbox;
biased_box.expand(extra);
biased_box.crop(bounding_box(m_img));
// Bring fully in memory a crop of the input for this tile
ImageView<PixelMask<Vector2f>> cropped_img = crop(m_img, biased_box);
for (int col = bbox.min().x(); col < bbox.max().x(); col++) {
for (int row = bbox.min().y(); row < bbox.max().y(); row++) {
// Find the disparity value at the current pixel and the neighbors.
// Need to be careful to account for the bias and for indices
// going out of range.
// Coordinates of a pixel and its neighbors.
std::vector<Vector2i> coords = {Vector2i(0, 0), Vector2i(1, 0), Vector2i(0, 1),
Vector2i(-1, 0), Vector2i(0, -1)};
std::vector<PixelMask<Vector2f>> vals(5);
for (int it = 0; it < 5; it++) {
Vector2i coord = Vector2i(col, row) + coords[it]; // pixel in uncropped image
if (biased_box.contains(coord)) {
// Take into account the bounds and the crop
vals[it] = cropped_img(coord.x() - biased_box.min().x(),
coord.y() - biased_box.min().y());
} else {
// Out of range
vals[it].child() = Vector2f(0, 0);
vals[it].invalidate();
}
}
double max_norm_diff = 0.0;
if (is_valid(vals[0])) {
// Need to have the center pixel valid
for (int it = 1; it < 5; it++) {
if (!is_valid(vals[it]))
continue;
max_norm_diff = std::max(max_norm_diff, norm_2(vals[it].child() - vals[0].child()));
}
}
tile(col - bbox.min().x(), row - bbox.min().y()) = max_norm_diff;
}
}
return prerasterize_type(tile, -bbox.min().x(), -bbox.min().y(),
cols(), rows());
}
template <class DestT>
inline void rasterize(DestT const& dest, BBox2i bbox) const {
vw::rasterize(prerasterize(bbox), dest, bbox);
}
};
struct Options : vw::cartography::GdalWriteOptions {
// Input
std::string input_file_name;
BBox2 normalization_range;
BBox2 roi; ///< Only generate output images in this region
bool save_norm, save_norm_diff;
// Output
std::string output_prefix, output_file_type;
Options(): save_norm(false), save_norm_diff(false) {}
};
void handle_arguments(int argc, char *argv[], Options& opt) {
po::options_description general_options("");
general_options.add_options()
("normalization", po::value(&opt.normalization_range)->default_value(BBox2(0, 0, 0, 0), "auto"),
"Normalization range. Specify in format: hmin vmin hmax vmax.")
("roi", po::value(&opt.roi)->default_value(BBox2(0,0,0,0), "auto"),
"Region of interest. Specify in format: xmin ymin xmax ymax.")
("save-norm", po::bool_switch(&opt.save_norm)->default_value(false),
"Save the norm of the disparity instead of its two bands.")
("save-norm-diff", po::bool_switch(&opt.save_norm_diff)->default_value(false),
"Save the maximum of norms of differences between a disparity and its four neighbors.")
("output-prefix, o", po::value(&opt.output_prefix), "Specify the output prefix.")
("output-filetype, t", po::value(&opt.output_file_type)->default_value("tif"),
"Specify the output file type.");
general_options.add(vw::cartography::GdalWriteOptionsDescription(opt));
po::options_description positional("");
positional.add_options()
("input-file", po::value(&opt.input_file_name), "Input disparity map.");
po::positional_options_description positional_desc;
positional_desc.add("input-file", 1);
std::string usage("[options] <input disparity map>");
bool allow_unregistered = false;
std::vector<std::string> unregistered;
po::variables_map vm =
asp::check_command_line(argc, argv, opt, general_options, general_options,
positional, positional_desc, usage,
allow_unregistered, unregistered);
if (opt.input_file_name.empty())
vw_throw(ArgumentErr() << "Missing input file!\n"
<< usage << general_options);
if (opt.output_prefix.empty())
opt.output_prefix = vw::prefix_from_filename(opt.input_file_name);
if (opt.save_norm && opt.save_norm_diff)
vw_throw(ArgumentErr() << "Cannot save both the norm and norm of differences at the same "
<< "time.\n" << usage << general_options);
}
template <class PixelT>
void process_disparity(Options& opt) {
cartography::GeoReference georef;
bool has_georef = read_georeference(georef, opt.input_file_name);
bool has_nodata = false;
float output_nodata = -32768.0;
if (opt.save_norm) {
DiskImageView<PixelMask<Vector2f>> disk_disparity_map(opt.input_file_name);
std::string norm_file = opt.output_prefix + "-norm." + opt.output_file_type;
vw_out() << "\t--> Writing disparity norm: " << norm_file << "\n";
block_write_gdal_image(norm_file,
per_pixel_filter(disk_disparity_map, DisparityNorm()),
has_georef, georef,
has_nodata, output_nodata,
opt, TerminalProgressCallback("asp","\t norm: "));
return;
}
if (opt.save_norm_diff) {
DiskImageView<PixelMask<Vector2f>> disk_disparity_map(opt.input_file_name);
std::string norm_file = opt.output_prefix + "-norm-diff." + opt.output_file_type;
vw_out() << "\t--> Writing norm of disparity diff: " << norm_file << "\n";
block_write_gdal_image(norm_file,
DispNormDiff(disk_disparity_map),
has_georef, georef,
has_nodata, output_nodata,
opt, TerminalProgressCallback("asp","\t norm: "));
return;
}
DiskImageView<PixelT> disk_disparity_map(opt.input_file_name);
// If no ROI passed in, use the full image
BBox2 roiToUse(opt.roi);
if (opt.roi == BBox2(0,0,0,0))
roiToUse = BBox2(0,0,disk_disparity_map.cols(),disk_disparity_map.rows());
if (has_georef)
georef = crop(georef, roiToUse);
// Compute intensity display range if not passed in. For this purpose
// subsample the image.
vw_out() << "\t--> Computing disparity range.\n";
if (opt.normalization_range == BBox2(0,0,0,0)) {
float subsample_amt =
float(roiToUse.height())*float(roiToUse.width()) / (1000.f * 1000.f);
subsample_amt = std::max(subsample_amt, 1.0f);
opt.normalization_range
= get_disparity_range(subsample(crop(disk_disparity_map, roiToUse), subsample_amt));
}
vw_out() << "\t Horizontal: [" << opt.normalization_range.min().x()
<< " " << opt.normalization_range.max().x() << "] Vertical: ["
<< opt.normalization_range.min().y() << " "
<< opt.normalization_range.max().y() << "]\n";
// Generate value-normalized copies of the H and V channels
typedef typename PixelChannelType<PixelT>::type ChannelT;
ImageViewRef<ChannelT> horizontal =
apply_mask(copy_mask(clamp(normalize(crop(select_channel(disk_disparity_map, 0),
roiToUse),
opt.normalization_range.min().x(),
opt.normalization_range.max().x(),
ChannelRange<ChannelT>::min(),
ChannelRange<ChannelT>::max()
)),
crop(disk_disparity_map, roiToUse)));
ImageViewRef<ChannelT> vertical =
apply_mask(copy_mask(clamp(normalize(crop(select_channel(disk_disparity_map, 1),
roiToUse),
opt.normalization_range.min().y(),
opt.normalization_range.max().y(),
ChannelRange<ChannelT>::min(),
ChannelRange<ChannelT>::max()
)),
crop(disk_disparity_map, roiToUse)));
// Write both images to disk, casting as UINT8
std::string h_file = opt.output_prefix + "-H." + opt.output_file_type;
vw_out() << "\t--> Writing horizontal disparity debug image: " << h_file << "\n";
block_write_gdal_image(h_file,
channel_cast_rescale<uint8>(horizontal),
has_georef, georef,
has_nodata, output_nodata,
opt, TerminalProgressCallback("asp","\t H : "));
std::string v_file = opt.output_prefix + "-V." + opt.output_file_type;
vw_out() << "\t--> Writing vertical disparity debug image: " << v_file << "\n";
block_write_gdal_image(v_file,
channel_cast_rescale<uint8>(vertical),
has_georef, georef,
has_nodata, output_nodata,
opt, TerminalProgressCallback("asp","\t V : "));
}
int main(int argc, char *argv[]) {
Options opt;
try {
handle_arguments(argc, argv, opt);
vw_out() << "Opening " << opt.input_file_name << "\n";
ImageFormat fmt = vw::image_format(opt.input_file_name);
switch(fmt.pixel_format) {
case VW_PIXEL_GENERIC_2_CHANNEL:
switch (fmt.channel_type) {
case VW_CHANNEL_INT32:
process_disparity<Vector2i>(opt); break;
default:
process_disparity<Vector2f>(opt); break;
} break;
case VW_PIXEL_RGB:
case VW_PIXEL_GENERIC_3_CHANNEL:
switch (fmt.channel_type) {
case VW_CHANNEL_INT32:
process_disparity<PixelMask<Vector2i>>(opt); break;
default:
process_disparity<PixelMask<Vector2f>>(opt); break;
} break;
case VW_PIXEL_SCALAR:
// OpenEXR stores everything as planar, so this allows us to
// still read that data.
if (fmt.planes == 2) {
switch (fmt.channel_type) {
case VW_CHANNEL_INT32:
process_disparity<Vector2i>(opt); break;
default:
process_disparity<Vector2f>(opt); break;
} break;
} else if (fmt.planes == 3) {
switch (fmt.channel_type) {
case VW_CHANNEL_INT32:
process_disparity<PixelMask<Vector2i>>(opt); break;
default:
process_disparity<PixelMask<Vector2f>>(opt); break;
} break;
}
default:
vw_throw(ArgumentErr() << "Unsupported pixel format. Expected 2 or 3 channel image. "
<< "Instead got [" << pixel_format_name(fmt.pixel_format) << "].");
}
} ASP_STANDARD_CATCHES;
return 0;
}
<|endoftext|> |
<commit_before>#include "PipeThrottler.h"
#include "Server.h"
#include "Interface/Mutex.h"
#include "stringtools.h"
#define DLOG(x) x
PipeThrottler::PipeThrottler(size_t bps)
: throttle_bps(bps), curr_bytes(0), lastresettime(0)
{
mutex=Server->createMutex();
}
PipeThrottler::~PipeThrottler(void)
{
Server->destroy(mutex);
}
bool PipeThrottler::addBytes(size_t new_bytes, bool wait)
{
IScopedLock lock(mutex);
if(throttle_bps==0) return true;
int64 ctime=Server->getTimeMS();
if(ctime-lastresettime>1000)
{
lastresettime=ctime;
curr_bytes=0;
}
curr_bytes+=new_bytes;
int64 passed_time=ctime-lastresettime;
size_t maxRateTime=(size_t)(((_i64)curr_bytes*1000)/throttle_bps);
if(passed_time>0)
{
size_t bps=(size_t)(((_i64)curr_bytes*1000)/passed_time);
if(bps>throttle_bps)
{
unsigned int sleepTime=(unsigned int)(maxRateTime-passed_time);
if(sleepTime>0)
{
if(wait)
{
DLOG(Server->Log("Throttler: Sleeping for " + nconvert(sleepTime)+ "ms", LL_DEBUG));
Server->wait(sleepTime);
if(Server->getTimeMS()-lastresettime>1000)
{
curr_bytes=0;
lastresettime=Server->getTimeMS();
}
}
return false;
}
}
}
else if(curr_bytes>=throttle_bps)
{
if(wait)
{
DLOG(Server->Log("Throttler: Sleeping for " + nconvert(maxRateTime)+ "ms", LL_DEBUG));
Server->wait(static_cast<unsigned int>(maxRateTime));
}
curr_bytes=0;
lastresettime=Server->getTimeMS();
return false;
}
return true;
}
void PipeThrottler::changeThrottleLimit(size_t bps)
{
IScopedLock lock(mutex);
throttle_bps=bps;
}<commit_msg>Disabled throttler debug messages<commit_after>#include "PipeThrottler.h"
#include "Server.h"
#include "Interface/Mutex.h"
#include "stringtools.h"
#define DLOG(x) //x
PipeThrottler::PipeThrottler(size_t bps)
: throttle_bps(bps), curr_bytes(0), lastresettime(0)
{
mutex=Server->createMutex();
}
PipeThrottler::~PipeThrottler(void)
{
Server->destroy(mutex);
}
bool PipeThrottler::addBytes(size_t new_bytes, bool wait)
{
IScopedLock lock(mutex);
if(throttle_bps==0) return true;
int64 ctime=Server->getTimeMS();
if(ctime-lastresettime>1000)
{
lastresettime=ctime;
curr_bytes=0;
}
curr_bytes+=new_bytes;
int64 passed_time=ctime-lastresettime;
size_t maxRateTime=(size_t)(((_i64)curr_bytes*1000)/throttle_bps);
if(passed_time>0)
{
size_t bps=(size_t)(((_i64)curr_bytes*1000)/passed_time);
if(bps>throttle_bps)
{
unsigned int sleepTime=(unsigned int)(maxRateTime-passed_time);
if(sleepTime>0)
{
if(wait)
{
DLOG(Server->Log("Throttler: Sleeping for " + nconvert(sleepTime)+ "ms", LL_DEBUG));
Server->wait(sleepTime);
if(Server->getTimeMS()-lastresettime>1000)
{
curr_bytes=0;
lastresettime=Server->getTimeMS();
}
}
return false;
}
}
}
else if(curr_bytes>=throttle_bps)
{
if(wait)
{
DLOG(Server->Log("Throttler: Sleeping for " + nconvert(maxRateTime)+ "ms", LL_DEBUG));
Server->wait(static_cast<unsigned int>(maxRateTime));
}
curr_bytes=0;
lastresettime=Server->getTimeMS();
return false;
}
return true;
}
void PipeThrottler::changeThrottleLimit(size_t bps)
{
IScopedLock lock(mutex);
throttle_bps=bps;
}<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: controllerframe.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: kz $ $Date: 2008-03-06 17:55:44 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef DBACCESS_CONTROLLERFRAME_HXX
#define DBACCESS_CONTROLLERFRAME_HXX
/** === begin UNO includes === **/
#include <com/sun/star/frame/XFrame.hpp>
#include <com/sun/star/frame/FrameAction.hpp>
/** === end UNO includes === **/
#include <memory>
//........................................................................
namespace dbaui
{
//........................................................................
class IController;
//====================================================================
//= ControllerFrame
//====================================================================
struct ControllerFrame_Data;
/** helper class to ancapsulate the frame which a controller is plugged into,
doing some common actions on it.
*/
class ControllerFrame
{
public:
ControllerFrame( IController& _rController );
~ControllerFrame();
/// attaches a new frame
const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >&
attachFrame(
const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& _rxFrame
);
// retrieves the current frame
const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >&
getFrame() const;
/** determines whether the frame is currently active
*/
bool isActive() const;
/** notifies the instance that a certain frame action happened with our frame
*/
void frameAction( ::com::sun::star::frame::FrameAction _eAction );
private:
::std::auto_ptr< ControllerFrame_Data > m_pData;
};
//........................................................................
} // namespace dbaui
//........................................................................
#endif // DBACCESS_CONTROLLERFRAME_HXX
<commit_msg>INTEGRATION: CWS changefileheader (1.2.12); FILE MERGED 2008/03/31 13:26:39 rt 1.2.12.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: controllerframe.hxx,v $
* $Revision: 1.3 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef DBACCESS_CONTROLLERFRAME_HXX
#define DBACCESS_CONTROLLERFRAME_HXX
/** === begin UNO includes === **/
#include <com/sun/star/frame/XFrame.hpp>
#include <com/sun/star/frame/FrameAction.hpp>
/** === end UNO includes === **/
#include <memory>
//........................................................................
namespace dbaui
{
//........................................................................
class IController;
//====================================================================
//= ControllerFrame
//====================================================================
struct ControllerFrame_Data;
/** helper class to ancapsulate the frame which a controller is plugged into,
doing some common actions on it.
*/
class ControllerFrame
{
public:
ControllerFrame( IController& _rController );
~ControllerFrame();
/// attaches a new frame
const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >&
attachFrame(
const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& _rxFrame
);
// retrieves the current frame
const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >&
getFrame() const;
/** determines whether the frame is currently active
*/
bool isActive() const;
/** notifies the instance that a certain frame action happened with our frame
*/
void frameAction( ::com::sun::star::frame::FrameAction _eAction );
private:
::std::auto_ptr< ControllerFrame_Data > m_pData;
};
//........................................................................
} // namespace dbaui
//........................................................................
#endif // DBACCESS_CONTROLLERFRAME_HXX
<|endoftext|> |
<commit_before>/**
* @file game.cpp
* @brief Purpose: Contains methods that create and specify a hitbox.
*
* MIT License
* Copyright (c) 2017 MindScape
*
* https://github.com/TecProg2017-2/mindscape/blob/master/LICENSE.md
*/
#include "game.hpp"
#include <unistd.h>
#include "log.hpp"
using namespace engine;
Game* Game::instance = NULL; /**< initialization of the game instance singleton */
/**
* @brief shows which function has an error and exits.
*
* @params function that has an error.
* @return void.
*/
void throw_error(const char* function) {
WARN(("Something's wrong in %s\n", function));
exit(-1);
}
/**
* @brief Checks if an instance was created.
*
* In cases when dont have an instance created, it is alerted to create one and exits.
*
* @return Returns the instance.
*/
Game& Game::get_instance() {
DEBUG("Getting instance of game");
if (!instance) {
/* if the instance is null */
WARN("Instance is null. Exiting.");
exit(1);
}
else {
/*Do nothing*/
}
return *instance;
}
/**
* @brief Initializes an instance if one does not exist.
*
* @params p_name name of the game.
* @params p_dimensions dimensions of the window.
* @return Returns an instance created.
*/
Game& Game::initialize(std::string p_name, std::pair<int, int> p_dimensions) {
if (!instance) {
/* if the instance is null */
instance = new Game();
instance->set_information(p_name, p_dimensions);
instance->init();
}
else {
/*Do nothing*/
}
return *instance;
}
/**
* @brief Initializes the game.
*
* initializes all that need in background,
* video, audio before the start the window. And treats the erros.
*
* @return void.
*/
void Game::init() {
int img_flags = IMG_INIT_PNG; /**< flags for sdl image lib */
if (SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO) < 0) {
/* if the initialization of the video and audio doesn't work properly */
WARN("Audio and video not initialized properly");
throw_error("SDL_Init");
}
else {
/*Do nothing*/
}
img_flags = IMG_INIT_PNG;
if (!(IMG_Init(IMG_INIT_PNG) & img_flags)) {
/* if the initialization of sdl img is not working properly */
WARN("SDL IMG not initialized properly");
throw_error("IMG_Init");
}
else {
/*Do nothing*/
}
if (Mix_OpenAudio( 44100, MIX_DEFAULT_FORMAT, 2, 512 ) < 0 ) {
/* if the mix audio sdl lib is not working properly */
WARN(("SDL_mixer could not initialize! SDL_mixer Error: %s\n", Mix_GetError()));
}
else {
/*Do nothing*/
}
if (TTF_Init() == -1) {
/* if the ttf sdl lib is not working properly */
WARN("TTF SDL lib not initialized properly");
throw_error("TTF_Init");
}
else {
/*Do nothing*/
}
window = SDL_CreateWindow(name.c_str(),SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,window_dimensions.first,
window_dimensions.second,SDL_WINDOW_SHOWN);
if (!window) {
/* if the window is null it means it didnt work well */
WARN("Window not created");
throw_error("SDL_CreateWindow");
}
else {
/*Do nothing*/
}
renderer = SDL_CreateRenderer(window,-1,SDL_RENDERER_ACCELERATED
| SDL_RENDERER_PRESENTVSYNC);
if (!renderer) {
/* if renderer is null then it was not instantiated correctly */
WARN("Renderer is null");
throw_error("SDL_CreateRenderer");
}
else {
/*Do nothing*/
}
}
/**
* @brief Load the media based its scene.
*
* @return void.
*/
void Game::load_media() {
actual_scene->load();
loaded_media = true;
}
/**
* @brief This method is a test to know if media is loaded.
*
* @return Returns the situation of media.
*/
bool Game::is_media_loaded() {
return loaded_media;
}
/**
* @brief Closes the game.
*
* Closes the game, destroying its renderer, window, functions of the game and medias.
*
* @return void.
*/
void Game::close() {
DEBUG("Attempting to close game");
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
renderer = NULL;
window = NULL;
IMG_Quit();
SDL_Quit();
}
void Game::run() {
state = RUNNING;
DEBUG("Game is running");
if (is_media_loaded()) {
DEBUG("Game media is loaded");
/* if the media is already loaded */
SDL_Event e;
EventHandler event_handler = EventHandler();
Time::init();
while (state != QUIT) {
/* while the state is not quit */
unsigned now = Time::time_elapsed();
event_handler.dispatch_pending_events(now);
if (state != PAUSED) {
/* if the state is different from pause state */
actual_scene->update();
}
else {
/*Do nothing*/
}
SDL_SetRenderDrawColor(renderer, 0xE2, 0xAC, 0xF3, 0x00);
SDL_RenderClear(renderer);
actual_scene->draw();
SDL_RenderPresent(renderer);
}
}
else {
/* print if the medias were not yet loaded */
WARN("Medias could not be loaded\n");
}
close();
}
/**
* @brief Sets the name and the dimensions of the window.
*
* @params p_name the name of the game.
* @params p_dimensions this params refers to a dimension os the window.
* @return void.
*/
void Game::set_information(std::string p_name,std::pair<int,int> p_dimensions) {
set_name(p_name);
set_window_dimensions(p_dimensions);
}
/**
* @brief Changes the scene.
*
* Changes the scene based in its level and in its actual scene.
* Loads the media based in this.
*
* @params level pointer to know which scene will be loaded.
* @return void.
*/
void Game::change_scene(Scene *level) {
DEBUG("Changing scene");
if (actual_scene) {
/* if actual scene is not null */
actual_scene->deactivate();
actual_scene->free();
delete actual_scene;
}
else {
/*Do nothing*/
}
level->activate();
actual_scene = level;
load_media();
}
/**
* @brief This method get the current scene of the game.
*
* It is important to load the media of the game
*
*
*/
Scene* Game::get_actual_scene() {
return actual_scene;
}
/**
* @brief This routine validates an RGBA color.
*
* It is important to use RGBA to change the opacity of the background.
* R (red) G (green) B (blue) is the regular colors and the A is the opacity nivel.
*
* @param integer containing the quantity of the red color.
* @param integer containing the quantity of the green color.
* @param integer containing the quantity of the blue color.
* @param integer containing the quantity of the Alpha (A) opacity.
* @return void.
*/
bool RGBA_color_is_valid(int R, int G, int B, int A) {
bool color_is_valid = true;
if (R < 0 || R > 255) {
/*Given value for red channel is out of limits, therefore, invalid*/
color_is_valid = false;
}
else if (G < 0 || G > 255) {
/*Given value for green channel is out of limits, therefore, invalid*/
color_is_valid = false;
}
else if (B < 0 || B > 255) {
/*Given value for blue channel is out of limits, therefore, invalid*/
color_is_valid = false;
}
else if (A < 0 || A > 255) {
/*Given value for alpha channel is out of limits, therefore, invalid*/
color_is_valid = false;
}
else {
/*All values are valid*/
}
return color_is_valid;
}
/**
* @brief This Routine set the game background color.
*
* It is important to use RGBA to change the opacity of the background.
* R (red) G (green) B (blue) is the regular colors and the A is the opacity nivel.
*
* @param integer containing the quantity of the red color to be set to the background.
* @param integer containing the quantity of the green color to be set to the background.
* @param integer containing the quantity of the blue color to be set to the background.
* @param integer containing the quantity of the Alpha (A) opacity to be set to the background.
* @return void.
*/
void Game::set_game_background_color(int R, int G, int B, int A) {
if (RGBA_color_is_valid(R, G, B, A)) {
/*Ensures that the color values given are valid*/
game_background_color = Color(R, G, B, A);
}
}
/**
* @brief This Routine set the name of the game.
*
* @param string containing the game name to be set.
* @return void.
*/
void Game::set_name(std::string p_name) {
name = p_name;
}
/**
* @brief This method get the current game name.
*
* @return string that contains the game name.
*/
std::string Game::get_name() {
return name;
}
/**
* @brief This method set the window dimensions.
*
* it is important to scale the window on the player screen and no errors happen.
*
* @param map that contains two integer that will set the width and the height.
* @return void.
*/
void Game::set_window_dimensions(std::pair<int, int> p_window_dimensions) {
window_dimensions = p_window_dimensions;
}
/**
* @brief This method get the window dimensions.
*
* It is important to resize the window dimensions accordingly the dimensions that need to run the game without bugs.
* @return map that contains the window dimensions.
*/
std::pair<int, int> Game::get_window_dimensions() {
return window_dimensions;
}
/**
* @brief This method set the current game state.
*
* @param state that contains the game state.
* @return void.
*/
void Game::set_state(State p_state) {
state = p_state;
}
/**
* @brief This method get the current game state.
*
* It is important to know what the game state to run the game.
*
* @return state of the game.
*/
Game::State Game::get_state() {
return state;
}
/**
* @brief This method get the renderer of the game.
*
* it is most important because it's the contact of the software with the user.
* It is one the principals parts to load and close the game.
*
* @return renderer of the game.
*/
SDL_Renderer * Game::get_renderer() {
return renderer;
}
<commit_msg>[DECOMPOSITION IN ATOMIC FUNCTIONS] Apply technique 2 in game.cpp<commit_after>/**
* @file game.cpp
* @brief Purpose: Contains methods that create and specify a hitbox.
*
* MIT License
* Copyright (c) 2017 MindScape
*
* https://github.com/TecProg2017-2/mindscape/blob/master/LICENSE.md
*/
#include "game.hpp"
#include <unistd.h>
#include "log.hpp"
using namespace engine;
Game* Game::instance = NULL; /**< initialization of the game instance singleton */
/**
* @brief shows which function has an error and exits.
*
* @params function that has an error.
* @return void.
*/
void throw_error(const char* function) {
WARN(("Something's wrong in %s\n", function));
exit(-1);
}
/**
* @brief Checks if an instance was created.
*
* In cases when dont have an instance created, it is alerted to create one and exits.
*
* @return Returns the instance.
*/
Game& Game::get_instance() {
DEBUG("Getting instance of game");
if (!instance) {
/* if the instance is null */
WARN("Instance is null. Exiting.");
exit(1);
}
else {
/*Do nothing*/
}
return *instance;
}
/**
* @brief Initializes an instance if one does not exist.
*
* @params p_name name of the game.
* @params p_dimensions dimensions of the window.
* @return Returns an instance created.
*/
Game& Game::initialize(std::string p_name, std::pair<int, int> p_dimensions) {
if (!instance) {
/* if the instance is null */
instance = new Game();
instance->set_information(p_name, p_dimensions);
instance->init();
}
else {
/*Do nothing*/
}
return *instance;
}
/**
* @brief Initializes the game.
*
* initializes all that need in background,
* video, audio before the start the window. And treats the erros.
*
* @return void.
*/
void Game::init() {
int img_flags = IMG_INIT_PNG; /**< flags for sdl image lib */
if (SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO) < 0) {
/* if the initialization of the video and audio doesn't work properly */
WARN("Audio and video not initialized properly");
throw_error("SDL_Init");
}
else {
/*Do nothing*/
}
img_flags = IMG_INIT_PNG;
if (!(IMG_Init(IMG_INIT_PNG) & img_flags)) {
/* if the initialization of sdl img is not working properly */
WARN("SDL IMG not initialized properly");
throw_error("IMG_Init");
}
else {
/*Do nothing*/
}
if (Mix_OpenAudio( 44100, MIX_DEFAULT_FORMAT, 2, 512 ) < 0 ) {
/* if the mix audio sdl lib is not working properly */
WARN(("SDL_mixer could not initialize! SDL_mixer Error: %s\n", Mix_GetError()));
}
else {
/*Do nothing*/
}
if (TTF_Init() == -1) {
/* if the ttf sdl lib is not working properly */
WARN("TTF SDL lib not initialized properly");
throw_error("TTF_Init");
}
else {
/*Do nothing*/
}
window = SDL_CreateWindow(name.c_str(),SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,window_dimensions.first,
window_dimensions.second,SDL_WINDOW_SHOWN);
if (!window) {
/* if the window is null it means it didnt work well */
WARN("Window not created");
throw_error("SDL_CreateWindow");
}
else {
/*Do nothing*/
}
renderer = SDL_CreateRenderer(window,-1,SDL_RENDERER_ACCELERATED
| SDL_RENDERER_PRESENTVSYNC);
if (!renderer) {
/* if renderer is null then it was not instantiated correctly */
WARN("Renderer is null");
throw_error("SDL_CreateRenderer");
}
else {
/*Do nothing*/
}
}
/**
* @brief Load the media based its scene.
*
* @return void.
*/
void Game::load_media() {
actual_scene->load();
loaded_media = true;
}
/**
* @brief This method is a test to know if media is loaded.
*
* @return Returns the situation of media.
*/
bool Game::is_media_loaded() {
return loaded_media;
}
/**
* @brief Closes the game.
*
* Closes the game, destroying its renderer, window, functions of the game and medias.
*
* @return void.
*/
void Game::close() {
DEBUG("Attempting to close game");
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
renderer = NULL;
window = NULL;
IMG_Quit();
SDL_Quit();
}
/**
* @brief Renders a given scene.
*
* Given a scene, it replaces the previous with the given.
*
* @params SDL_Renderer* renderer that will render the new scene.
* @params Scene* actual_scene that is the scene that will be updated.
*
* @return void.
*/
void renderScreen(SDL_Renderer* renderer, Scene* actual_scene) {
SDL_SetRenderDrawColor(renderer, 0xE2, 0xAC, 0xF3, 0x00);
SDL_RenderClear(renderer);
actual_scene->draw();
SDL_RenderPresent(renderer);
}
/**
* @brief Runs the game.
*
* Runs the game updating the scenes and verifying the states.
*
* @return void.
*/
void Game::run() {
state = RUNNING;
DEBUG("Game is running");
if (is_media_loaded()) {
DEBUG("Game media is loaded");
/* if the media is already loaded */
SDL_Event e;
EventHandler event_handler = EventHandler();
Time::init();
while (state != QUIT) {
/* while the state is not quit */
unsigned now = Time::time_elapsed();
event_handler.dispatch_pending_events(now);
if (state != PAUSED) {
/* if the state is different from pause state */
actual_scene->update();
}
else {
/*Do nothing*/
}
renderScreen(renderer, actual_scene);
}
}
else {
/* print if the medias were not yet loaded */
WARN("Medias could not be loaded\n");
}
close();
}
/**
* @brief Sets the name and the dimensions of the window.
*
* @params p_name the name of the game.
* @params p_dimensions this params refers to a dimension os the window.
* @return void.
*/
void Game::set_information(std::string p_name,std::pair<int,int> p_dimensions) {
set_name(p_name);
set_window_dimensions(p_dimensions);
}
/**
* @brief Changes the scene.
*
* Changes the scene based in its level and in its actual scene.
* Loads the media based in this.
*
* @params level pointer to know which scene will be loaded.
* @return void.
*/
void Game::change_scene(Scene *level) {
DEBUG("Changing scene");
if (actual_scene) {
/* if actual scene is not null */
actual_scene->deactivate();
actual_scene->free();
delete actual_scene;
}
else {
/*Do nothing*/
}
level->activate();
actual_scene = level;
load_media();
}
/**
* @brief This method get the current scene of the game.
*
* It is important to load the media of the game
*
*
*/
Scene* Game::get_actual_scene() {
return actual_scene;
}
/**
* @brief This routine validates an RGBA color.
*
* It is important to use RGBA to change the opacity of the background.
* R (red) G (green) B (blue) is the regular colors and the A is the opacity nivel.
*
* @param integer containing the quantity of the red color.
* @param integer containing the quantity of the green color.
* @param integer containing the quantity of the blue color.
* @param integer containing the quantity of the Alpha (A) opacity.
* @return void.
*/
bool RGBA_color_is_valid(int R, int G, int B, int A) {
bool color_is_valid = true;
if (R < 0 || R > 255) {
/*Given value for red channel is out of limits, therefore, invalid*/
color_is_valid = false;
}
else if (G < 0 || G > 255) {
/*Given value for green channel is out of limits, therefore, invalid*/
color_is_valid = false;
}
else if (B < 0 || B > 255) {
/*Given value for blue channel is out of limits, therefore, invalid*/
color_is_valid = false;
}
else if (A < 0 || A > 255) {
/*Given value for alpha channel is out of limits, therefore, invalid*/
color_is_valid = false;
}
else {
/*All values are valid*/
}
return color_is_valid;
}
/**
* @brief This Routine set the game background color.
*
* It is important to use RGBA to change the opacity of the background.
* R (red) G (green) B (blue) is the regular colors and the A is the opacity nivel.
*
* @param integer containing the quantity of the red color to be set to the background.
* @param integer containing the quantity of the green color to be set to the background.
* @param integer containing the quantity of the blue color to be set to the background.
* @param integer containing the quantity of the Alpha (A) opacity to be set to the background.
* @return void.
*/
void Game::set_game_background_color(int R, int G, int B, int A) {
if (RGBA_color_is_valid(R, G, B, A)) {
/*Ensures that the color values given are valid*/
game_background_color = Color(R, G, B, A);
}
}
/**
* @brief This Routine set the name of the game.
*
* @param string containing the game name to be set.
* @return void.
*/
void Game::set_name(std::string p_name) {
name = p_name;
}
/**
* @brief This method get the current game name.
*
* @return string that contains the game name.
*/
std::string Game::get_name() {
return name;
}
/**
* @brief This method set the window dimensions.
*
* it is important to scale the window on the player screen and no errors happen.
*
* @param map that contains two integer that will set the width and the height.
* @return void.
*/
void Game::set_window_dimensions(std::pair<int, int> p_window_dimensions) {
window_dimensions = p_window_dimensions;
}
/**
* @brief This method get the window dimensions.
*
* It is important to resize the window dimensions accordingly the dimensions that need to run the game without bugs.
* @return map that contains the window dimensions.
*/
std::pair<int, int> Game::get_window_dimensions() {
return window_dimensions;
}
/**
* @brief This method set the current game state.
*
* @param state that contains the game state.
* @return void.
*/
void Game::set_state(State p_state) {
state = p_state;
}
/**
* @brief This method get the current game state.
*
* It is important to know what the game state to run the game.
*
* @return state of the game.
*/
Game::State Game::get_state() {
return state;
}
/**
* @brief This method get the renderer of the game.
*
* it is most important because it's the contact of the software with the user.
* It is one the principals parts to load and close the game.
*
* @return renderer of the game.
*/
SDL_Renderer * Game::get_renderer() {
return renderer;
}
<|endoftext|> |
<commit_before>/**
* Non-metric Space Library
*
* Authors: Bilegsaikhan Naidan (https://github.com/bileg), Leonid Boytsov (http://boytsov.info).
* With contributions from Lawrence Cayton (http://lcayton.com/) and others.
*
* For the complete list of contributors and further details see:
* https://github.com/searchivarius/NonMetricSpaceLib
*
* Copyright (c) 2014
*
* This code is released under the
* Apache License Version 2.0 http://www.apache.org/licenses/.
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <cmath>
#include <limits>
#include <string>
#include <sstream>
#include <vector>
#include <fstream>
#include <map>
#include "init.h"
#include "global.h"
#include "utils.h"
#include "memory.h"
#include "ztimer.h"
#include "experiments.h"
#include "experimentconf.h"
#include "space.h"
#include "spacefactory.h"
#include "logging.h"
#include "report.h"
#include "methodfactory.h"
#include "meta_analysis.h"
#include "params.h"
using namespace similarity;
using std::multimap;
using std::vector;
using std::string;
using std::stringstream;
void OutData(bool DoAppend, const string& FilePrefix,
const string& Print, const string& Header, const string& Data) {
string FileNameData = FilePrefix + ".dat";
string FileNameRep = FilePrefix + ".rep";
LOG(LIB_INFO) << "DoAppend? " << DoAppend;
std::ofstream OutFileData(FileNameData.c_str(),
(DoAppend ? std::ios::app : (std::ios::trunc | std::ios::out)));
if (!OutFileData) {
LOG(LIB_FATAL) << "Cannot create output file: '" << FileNameData << "'";
}
OutFileData.exceptions(std::ios::badbit);
std::ofstream OutFileRep(FileNameRep.c_str(),
(DoAppend ? std::ios::app : (std::ios::trunc | std::ios::out)));
if (!OutFileRep) {
LOG(LIB_FATAL) << "Cannot create output file: '" << FileNameRep << "'";
}
OutFileRep.exceptions(std::ios::badbit);
if (!DoAppend) {
OutFileData << Header;
}
OutFileData<< Data;
OutFileRep<< Print;
OutFileRep.close();
OutFileData.close();
}
template <typename dist_t>
void ProcessResults(const ExperimentConfig<dist_t>& config,
MetaAnalysis& ExpRes,
const string& MethDescStr,
const string& MethParamStr,
string& PrintStr, // For display
string& HeaderStr,
string& DataStr /* to be processed by a script */) {
std::stringstream Print, Data, Header;
ExpRes.ComputeAll();
Header << "MethodName\tRecall\tPrecisionOfApprox\tRelPosError\tNumCloser\tClassAccuracy\tQueryTime\tDistComp\tImprEfficiency\tImprDistComp\tMem\tMethodParams" << std::endl;
Data << "\"" << MethDescStr << "\"\t";
Data << ExpRes.GetRecallAvg() << "\t";
Data << ExpRes.GetPrecisionOfApproxAvg() << "\t";
Data << ExpRes.GetRelPosErrorAvg() << "\t";
Data << ExpRes.GetNumCloserAvg() << "\t";
Data << ExpRes.GetClassAccuracyAvg() << "\t";
Data << ExpRes.GetQueryTimeAvg() << "\t";
Data << ExpRes.GetDistCompAvg() << "\t";
Data << ExpRes.GetImprEfficiencyAvg() << "\t";
Data << ExpRes.GetImprDistCompAvg() << "\t";
Data << size_t(ExpRes.GetMemAvg()) << "\t";
Data << "\"" << MethParamStr << "\"";
Data << std::endl;
PrintStr = produceHumanReadableReport(config, ExpRes, MethDescStr, MethParamStr);
DataStr = Data.str();
HeaderStr = Header.str();
};
template <typename dist_t>
void RunExper(const vector<shared_ptr<MethodWithParams>>& MethodsDesc,
const string SpaceType,
const shared_ptr<AnyParams>& SpaceParams,
unsigned dimension,
unsigned ThreadTestQty,
bool DoAppend,
const string& ResFilePrefix,
unsigned TestSetQty,
const string& DataFile,
const string& QueryFile,
unsigned MaxNumData,
unsigned MaxNumQuery,
const vector<unsigned>& knn,
const float eps,
const string& RangeArg
)
{
LOG(LIB_INFO) << "### Append? : " << DoAppend;
LOG(LIB_INFO) << "### OutFilePrefix : " << ResFilePrefix;
vector<dist_t> range;
bool bFail = false;
if (!RangeArg.empty()) {
if (!SplitStr(RangeArg, range, ',')) {
LOG(LIB_FATAL) << "Wrong format of the range argument: '" << RangeArg << "' Should be a list of coma-separated values.";
}
}
// Note that space will be deleted by the destructor of ExperimentConfig
ExperimentConfig<dist_t> config(SpaceFactoryRegistry<dist_t>::
Instance().CreateSpace(SpaceType, *SpaceParams),
DataFile, QueryFile, TestSetQty,
MaxNumData, MaxNumQuery,
dimension, knn, eps, range);
config.ReadDataset();
MemUsage mem_usage_measure;
std::vector<std::string> MethDescStr;
std::vector<std::string> MethParams;
vector<double> MemUsage;
vector<vector<MetaAnalysis*>> ExpResRange(config.GetRange().size(),
vector<MetaAnalysis*>(MethodsDesc.size()));
vector<vector<MetaAnalysis*>> ExpResKNN(config.GetKNN().size(),
vector<MetaAnalysis*>(MethodsDesc.size()));
size_t MethNum = 0;
for (auto it = MethodsDesc.begin(); it != MethodsDesc.end(); ++it, ++MethNum) {
for (size_t i = 0; i < config.GetRange().size(); ++i) {
ExpResRange[i][MethNum] = new MetaAnalysis(config.GetTestSetQty());
}
for (size_t i = 0; i < config.GetKNN().size(); ++i) {
ExpResKNN[i][MethNum] = new MetaAnalysis(config.GetTestSetQty());
}
}
for (int TestSetId = 0; TestSetId < config.GetTestSetQty(); ++TestSetId) {
config.SelectTestSet(TestSetId);
LOG(LIB_INFO) << ">>>> Test set id: " << TestSetId << " (set qty: " << config.GetTestSetQty() << ")";
ReportIntrinsicDimensionality("Main data set" , *config.GetSpace(), config.GetDataObjects());
vector<shared_ptr<Index<dist_t>>> IndexPtrs;
try {
for (const auto& methElem: MethodsDesc) {
MethNum = &methElem - &MethodsDesc[0];
const string& MethodName = methElem->methName_;
const AnyParams& MethPars = methElem->methPars_;
const string& MethParStr = MethPars.ToString();
LOG(LIB_INFO) << ">>>> Index type : " << MethodName;
LOG(LIB_INFO) << ">>>> Parameters: " << MethParStr;
const double vmsize_before = mem_usage_measure.get_vmsize();
WallClockTimer wtm;
wtm.reset();
bool bCreateNew = true;
if (MethNum && MethodName == MethodsDesc[MethNum-1]->methName_) {
vector<string> exceptList = IndexPtrs.back()->GetQueryTimeParamNames();
if (MethodsDesc[MethNum-1]->methPars_.equalsIgnoreInList(MethPars, exceptList)) {
bCreateNew = false;
}
}
LOG(LIB_INFO) << (bCreateNew ? "Creating a new index":"Using a previosuly created index");
IndexPtrs.push_back(
bCreateNew ?
shared_ptr<Index<dist_t>>(
MethodFactoryRegistry<dist_t>::Instance().
CreateMethod(true /* print progress */,
MethodName,
SpaceType, config.GetSpace(),
config.GetDataObjects(), MethPars)
)
:IndexPtrs.back());
LOG(LIB_INFO) << "==============================================";
const double vmsize_after = mem_usage_measure.get_vmsize();
const double data_size = DataSpaceUsed(config.GetDataObjects()) / 1024.0 / 1024.0;
const double TotalMemByMethod = vmsize_after - vmsize_before + data_size;
wtm.split();
LOG(LIB_INFO) << ">>>> Process memory usage: " << vmsize_after << " MBs";
LOG(LIB_INFO) << ">>>> Virtual memory usage: " << TotalMemByMethod << " MBs";
LOG(LIB_INFO) << ">>>> Data size: " << data_size << " MBs";
LOG(LIB_INFO) << ">>>> Time elapsed: " << (wtm.elapsed()/double(1e6)) << " sec";
for (size_t i = 0; i < config.GetRange().size(); ++i) {
MetaAnalysis* res = ExpResRange[i][MethNum];
res->SetMem(TestSetId, TotalMemByMethod);
}
for (size_t i = 0; i < config.GetKNN().size(); ++i) {
MetaAnalysis* res = ExpResKNN[i][MethNum];
res->SetMem(TestSetId, TotalMemByMethod);
}
if (!TestSetId) {
MethDescStr.push_back(IndexPtrs.back()->ToString());
MethParams.push_back(MethParStr);
}
}
Experiments<dist_t>::RunAll(true /* print info */,
ThreadTestQty,
TestSetId,
ExpResRange, ExpResKNN,
config,
IndexPtrs, MethodsDesc);
} catch (const std::exception& e) {
LOG(LIB_ERROR) << "Exception: " << e.what();
bFail = true;
} catch (...) {
LOG(LIB_ERROR) << "Unknown exception";
bFail = true;
}
if (bFail) {
LOG(LIB_FATAL) << "Failure due to an exception!";
}
}
for (auto it = MethDescStr.begin(); it != MethDescStr.end(); ++it) {
size_t MethNum = it - MethDescStr.begin();
// Don't overwrite file after we output data at least for one method!
bool DoAppendHere = DoAppend || MethNum;
string Print, Data, Header;
for (size_t i = 0; i < config.GetRange().size(); ++i) {
MetaAnalysis* res = ExpResRange[i][MethNum];
ProcessResults(config, *res, MethDescStr[MethNum], MethParams[MethNum], Print, Header, Data);
LOG(LIB_INFO) << "Range: " << config.GetRange()[i];
LOG(LIB_INFO) << Print;
LOG(LIB_INFO) << "Data: " << Header << Data;
if (!ResFilePrefix.empty()) {
stringstream str;
str << ResFilePrefix << "_r=" << config.GetRange()[i];
OutData(DoAppendHere, str.str(), Print, Header, Data);
}
delete res;
}
for (size_t i = 0; i < config.GetKNN().size(); ++i) {
MetaAnalysis* res = ExpResKNN[i][MethNum];
ProcessResults(config, *res, MethDescStr[MethNum], MethParams[MethNum], Print, Header, Data);
LOG(LIB_INFO) << "KNN: " << config.GetKNN()[i];
LOG(LIB_INFO) << Print;
LOG(LIB_INFO) << "Data: " << Header << Data;
if (!ResFilePrefix.empty()) {
stringstream str;
str << ResFilePrefix << "_K=" << config.GetKNN()[i];
OutData(DoAppendHere, str.str(), Print, Header, Data);
}
delete res;
}
}
}
int main(int ac, char* av[]) {
// This should be the first function called before
WallClockTimer timer;
timer.reset();
string LogFile;
string DistType;
string SpaceType;
shared_ptr<AnyParams> SpaceParams;
bool DoAppend;
string ResFilePrefix;
unsigned TestSetQty;
string DataFile;
string QueryFile;
unsigned MaxNumData;
unsigned MaxNumQuery;
vector<unsigned> knn;
string RangeArg;
unsigned dimension;
float eps = 0.0;
unsigned ThreadTestQty;
vector<shared_ptr<MethodWithParams>> MethodsDesc;
ParseCommandLine(ac, av, LogFile,
DistType,
SpaceType,
SpaceParams,
dimension,
ThreadTestQty,
DoAppend,
ResFilePrefix,
TestSetQty,
DataFile,
QueryFile,
MaxNumData,
MaxNumQuery,
knn,
eps,
RangeArg,
MethodsDesc);
initLibrary(LogFile.empty() ? LIB_LOGSTDERR:LIB_LOGFILE, LogFile.c_str());
LOG(LIB_INFO) << "Program arguments are processed";
ToLower(DistType);
if ("int" == DistType) {
RunExper<int>(MethodsDesc,
SpaceType,
SpaceParams,
dimension,
ThreadTestQty,
DoAppend,
ResFilePrefix,
TestSetQty,
DataFile,
QueryFile,
MaxNumData,
MaxNumQuery,
knn,
eps,
RangeArg
);
} else if ("float" == DistType) {
RunExper<float>(MethodsDesc,
SpaceType,
SpaceParams,
dimension,
ThreadTestQty,
DoAppend,
ResFilePrefix,
TestSetQty,
DataFile,
QueryFile,
MaxNumData,
MaxNumQuery,
knn,
eps,
RangeArg
);
} else if ("double" == DistType) {
RunExper<double>(MethodsDesc,
SpaceType,
SpaceParams,
dimension,
ThreadTestQty,
DoAppend,
ResFilePrefix,
TestSetQty,
DataFile,
QueryFile,
MaxNumData,
MaxNumQuery,
knn,
eps,
RangeArg
);
} else {
LOG(LIB_FATAL) << "Unknown distance value type: " << DistType;
}
timer.split();
LOG(LIB_INFO) << "Time elapsed = " << timer.elapsed() / 1e6;
LOG(LIB_INFO) << "Finished at " << LibGetCurrentTime();
return 0;
}
<commit_msg>adding fields to the output file.<commit_after>/**
* Non-metric Space Library
*
* Authors: Bilegsaikhan Naidan (https://github.com/bileg), Leonid Boytsov (http://boytsov.info).
* With contributions from Lawrence Cayton (http://lcayton.com/) and others.
*
* For the complete list of contributors and further details see:
* https://github.com/searchivarius/NonMetricSpaceLib
*
* Copyright (c) 2014
*
* This code is released under the
* Apache License Version 2.0 http://www.apache.org/licenses/.
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <cmath>
#include <limits>
#include <string>
#include <sstream>
#include <vector>
#include <fstream>
#include <map>
#include "init.h"
#include "global.h"
#include "utils.h"
#include "memory.h"
#include "ztimer.h"
#include "experiments.h"
#include "experimentconf.h"
#include "space.h"
#include "spacefactory.h"
#include "logging.h"
#include "report.h"
#include "methodfactory.h"
#include "meta_analysis.h"
#include "params.h"
using namespace similarity;
using std::multimap;
using std::vector;
using std::string;
using std::stringstream;
void OutData(bool DoAppend, const string& FilePrefix,
const string& Print, const string& Header, const string& Data) {
string FileNameData = FilePrefix + ".dat";
string FileNameRep = FilePrefix + ".rep";
LOG(LIB_INFO) << "DoAppend? " << DoAppend;
std::ofstream OutFileData(FileNameData.c_str(),
(DoAppend ? std::ios::app : (std::ios::trunc | std::ios::out)));
if (!OutFileData) {
LOG(LIB_FATAL) << "Cannot create output file: '" << FileNameData << "'";
}
OutFileData.exceptions(std::ios::badbit);
std::ofstream OutFileRep(FileNameRep.c_str(),
(DoAppend ? std::ios::app : (std::ios::trunc | std::ios::out)));
if (!OutFileRep) {
LOG(LIB_FATAL) << "Cannot create output file: '" << FileNameRep << "'";
}
OutFileRep.exceptions(std::ios::badbit);
if (!DoAppend) {
OutFileData << Header;
}
OutFileData<< Data;
OutFileRep<< Print;
OutFileRep.close();
OutFileData.close();
}
template <typename dist_t>
void ProcessResults(const ExperimentConfig<dist_t>& config,
MetaAnalysis& ExpRes,
const string& MethDescStr,
const string& MethParamStr,
string& PrintStr, // For display
string& HeaderStr,
string& DataStr /* to be processed by a script */) {
std::stringstream Print, Data, Header;
ExpRes.ComputeAll();
Header << "MethodName\tRecall\tPrecisionOfApprox\tRelPosError\tNumCloser\tClassAccuracy\tQueryTime\tDistComp\tImprEfficiency\tImprDistComp\tMem\tMethodParams\tNumData" << std::endl;
Data << "\"" << MethDescStr << "\"\t";
Data << ExpRes.GetRecallAvg() << "\t";
Data << ExpRes.GetPrecisionOfApproxAvg() << "\t";
Data << ExpRes.GetRelPosErrorAvg() << "\t";
Data << ExpRes.GetNumCloserAvg() << "\t";
Data << ExpRes.GetClassAccuracyAvg() << "\t";
Data << ExpRes.GetQueryTimeAvg() << "\t";
Data << ExpRes.GetDistCompAvg() << "\t";
Data << ExpRes.GetImprEfficiencyAvg() << "\t";
Data << ExpRes.GetImprDistCompAvg() << "\t";
Data << size_t(ExpRes.GetMemAvg()) << "\t";
Data << "\"" << MethParamStr << "\"" << "\t";
Data << config.GetDataObjects().size() << "\t";
Data << std::endl;
PrintStr = produceHumanReadableReport(config, ExpRes, MethDescStr, MethParamStr);
DataStr = Data.str();
HeaderStr = Header.str();
};
template <typename dist_t>
void RunExper(const vector<shared_ptr<MethodWithParams>>& MethodsDesc,
const string SpaceType,
const shared_ptr<AnyParams>& SpaceParams,
unsigned dimension,
unsigned ThreadTestQty,
bool DoAppend,
const string& ResFilePrefix,
unsigned TestSetQty,
const string& DataFile,
const string& QueryFile,
unsigned MaxNumData,
unsigned MaxNumQuery,
const vector<unsigned>& knn,
const float eps,
const string& RangeArg
)
{
LOG(LIB_INFO) << "### Append? : " << DoAppend;
LOG(LIB_INFO) << "### OutFilePrefix : " << ResFilePrefix;
vector<dist_t> range;
bool bFail = false;
if (!RangeArg.empty()) {
if (!SplitStr(RangeArg, range, ',')) {
LOG(LIB_FATAL) << "Wrong format of the range argument: '" << RangeArg << "' Should be a list of coma-separated values.";
}
}
// Note that space will be deleted by the destructor of ExperimentConfig
ExperimentConfig<dist_t> config(SpaceFactoryRegistry<dist_t>::
Instance().CreateSpace(SpaceType, *SpaceParams),
DataFile, QueryFile, TestSetQty,
MaxNumData, MaxNumQuery,
dimension, knn, eps, range);
config.ReadDataset();
MemUsage mem_usage_measure;
std::vector<std::string> MethDescStr;
std::vector<std::string> MethParams;
vector<double> MemUsage;
vector<vector<MetaAnalysis*>> ExpResRange(config.GetRange().size(),
vector<MetaAnalysis*>(MethodsDesc.size()));
vector<vector<MetaAnalysis*>> ExpResKNN(config.GetKNN().size(),
vector<MetaAnalysis*>(MethodsDesc.size()));
size_t MethNum = 0;
for (auto it = MethodsDesc.begin(); it != MethodsDesc.end(); ++it, ++MethNum) {
for (size_t i = 0; i < config.GetRange().size(); ++i) {
ExpResRange[i][MethNum] = new MetaAnalysis(config.GetTestSetQty());
}
for (size_t i = 0; i < config.GetKNN().size(); ++i) {
ExpResKNN[i][MethNum] = new MetaAnalysis(config.GetTestSetQty());
}
}
for (int TestSetId = 0; TestSetId < config.GetTestSetQty(); ++TestSetId) {
config.SelectTestSet(TestSetId);
LOG(LIB_INFO) << ">>>> Test set id: " << TestSetId << " (set qty: " << config.GetTestSetQty() << ")";
ReportIntrinsicDimensionality("Main data set" , *config.GetSpace(), config.GetDataObjects());
vector<shared_ptr<Index<dist_t>>> IndexPtrs;
try {
for (const auto& methElem: MethodsDesc) {
MethNum = &methElem - &MethodsDesc[0];
const string& MethodName = methElem->methName_;
const AnyParams& MethPars = methElem->methPars_;
const string& MethParStr = MethPars.ToString();
LOG(LIB_INFO) << ">>>> Index type : " << MethodName;
LOG(LIB_INFO) << ">>>> Parameters: " << MethParStr;
const double vmsize_before = mem_usage_measure.get_vmsize();
WallClockTimer wtm;
wtm.reset();
bool bCreateNew = true;
if (MethNum && MethodName == MethodsDesc[MethNum-1]->methName_) {
vector<string> exceptList = IndexPtrs.back()->GetQueryTimeParamNames();
if (MethodsDesc[MethNum-1]->methPars_.equalsIgnoreInList(MethPars, exceptList)) {
bCreateNew = false;
}
}
LOG(LIB_INFO) << (bCreateNew ? "Creating a new index":"Using a previosuly created index");
IndexPtrs.push_back(
bCreateNew ?
shared_ptr<Index<dist_t>>(
MethodFactoryRegistry<dist_t>::Instance().
CreateMethod(true /* print progress */,
MethodName,
SpaceType, config.GetSpace(),
config.GetDataObjects(), MethPars)
)
:IndexPtrs.back());
LOG(LIB_INFO) << "==============================================";
const double vmsize_after = mem_usage_measure.get_vmsize();
const double data_size = DataSpaceUsed(config.GetDataObjects()) / 1024.0 / 1024.0;
const double TotalMemByMethod = vmsize_after - vmsize_before + data_size;
wtm.split();
LOG(LIB_INFO) << ">>>> Process memory usage: " << vmsize_after << " MBs";
LOG(LIB_INFO) << ">>>> Virtual memory usage: " << TotalMemByMethod << " MBs";
LOG(LIB_INFO) << ">>>> Data size: " << data_size << " MBs";
LOG(LIB_INFO) << ">>>> Time elapsed: " << (wtm.elapsed()/double(1e6)) << " sec";
for (size_t i = 0; i < config.GetRange().size(); ++i) {
MetaAnalysis* res = ExpResRange[i][MethNum];
res->SetMem(TestSetId, TotalMemByMethod);
}
for (size_t i = 0; i < config.GetKNN().size(); ++i) {
MetaAnalysis* res = ExpResKNN[i][MethNum];
res->SetMem(TestSetId, TotalMemByMethod);
}
if (!TestSetId) {
MethDescStr.push_back(IndexPtrs.back()->ToString());
MethParams.push_back(MethParStr);
}
}
Experiments<dist_t>::RunAll(true /* print info */,
ThreadTestQty,
TestSetId,
ExpResRange, ExpResKNN,
config,
IndexPtrs, MethodsDesc);
} catch (const std::exception& e) {
LOG(LIB_ERROR) << "Exception: " << e.what();
bFail = true;
} catch (...) {
LOG(LIB_ERROR) << "Unknown exception";
bFail = true;
}
if (bFail) {
LOG(LIB_FATAL) << "Failure due to an exception!";
}
}
for (auto it = MethDescStr.begin(); it != MethDescStr.end(); ++it) {
size_t MethNum = it - MethDescStr.begin();
// Don't overwrite file after we output data at least for one method!
bool DoAppendHere = DoAppend || MethNum;
string Print, Data, Header;
for (size_t i = 0; i < config.GetRange().size(); ++i) {
MetaAnalysis* res = ExpResRange[i][MethNum];
ProcessResults(config, *res, MethDescStr[MethNum], MethParams[MethNum], Print, Header, Data);
LOG(LIB_INFO) << "Range: " << config.GetRange()[i];
LOG(LIB_INFO) << Print;
LOG(LIB_INFO) << "Data: " << Header << Data;
if (!ResFilePrefix.empty()) {
stringstream str;
str << ResFilePrefix << "_r=" << config.GetRange()[i];
OutData(DoAppendHere, str.str(), Print, Header, Data);
}
delete res;
}
for (size_t i = 0; i < config.GetKNN().size(); ++i) {
MetaAnalysis* res = ExpResKNN[i][MethNum];
ProcessResults(config, *res, MethDescStr[MethNum], MethParams[MethNum], Print, Header, Data);
LOG(LIB_INFO) << "KNN: " << config.GetKNN()[i];
LOG(LIB_INFO) << Print;
LOG(LIB_INFO) << "Data: " << Header << Data;
if (!ResFilePrefix.empty()) {
stringstream str;
str << ResFilePrefix << "_K=" << config.GetKNN()[i];
OutData(DoAppendHere, str.str(), Print, Header, Data);
}
delete res;
}
}
}
int main(int ac, char* av[]) {
// This should be the first function called before
WallClockTimer timer;
timer.reset();
string LogFile;
string DistType;
string SpaceType;
shared_ptr<AnyParams> SpaceParams;
bool DoAppend;
string ResFilePrefix;
unsigned TestSetQty;
string DataFile;
string QueryFile;
unsigned MaxNumData;
unsigned MaxNumQuery;
vector<unsigned> knn;
string RangeArg;
unsigned dimension;
float eps = 0.0;
unsigned ThreadTestQty;
vector<shared_ptr<MethodWithParams>> MethodsDesc;
ParseCommandLine(ac, av, LogFile,
DistType,
SpaceType,
SpaceParams,
dimension,
ThreadTestQty,
DoAppend,
ResFilePrefix,
TestSetQty,
DataFile,
QueryFile,
MaxNumData,
MaxNumQuery,
knn,
eps,
RangeArg,
MethodsDesc);
initLibrary(LogFile.empty() ? LIB_LOGSTDERR:LIB_LOGFILE, LogFile.c_str());
LOG(LIB_INFO) << "Program arguments are processed";
ToLower(DistType);
if ("int" == DistType) {
RunExper<int>(MethodsDesc,
SpaceType,
SpaceParams,
dimension,
ThreadTestQty,
DoAppend,
ResFilePrefix,
TestSetQty,
DataFile,
QueryFile,
MaxNumData,
MaxNumQuery,
knn,
eps,
RangeArg
);
} else if ("float" == DistType) {
RunExper<float>(MethodsDesc,
SpaceType,
SpaceParams,
dimension,
ThreadTestQty,
DoAppend,
ResFilePrefix,
TestSetQty,
DataFile,
QueryFile,
MaxNumData,
MaxNumQuery,
knn,
eps,
RangeArg
);
} else if ("double" == DistType) {
RunExper<double>(MethodsDesc,
SpaceType,
SpaceParams,
dimension,
ThreadTestQty,
DoAppend,
ResFilePrefix,
TestSetQty,
DataFile,
QueryFile,
MaxNumData,
MaxNumQuery,
knn,
eps,
RangeArg
);
} else {
LOG(LIB_FATAL) << "Unknown distance value type: " << DistType;
}
timer.split();
LOG(LIB_INFO) << "Time elapsed = " << timer.elapsed() / 1e6;
LOG(LIB_INFO) << "Finished at " << LibGetCurrentTime();
return 0;
}
<|endoftext|> |
<commit_before>/* Copyright 2016 Carnegie Mellon University, NVIDIA Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "lightscan/storage/storage_config.h"
#include "lightscan/storage/storage_backend.h"
#include "lightscan/util/common.h"
#include "lightscan/util/video.h"
#include "lightscan/util/caffe.h"
#include <opencv2/opencv.hpp>
#include <mpi.h>
#include <pthread.h>
#include <cstdlib>
#include <string>
#include <libgen.h>
#include <atomic>
extern "C" {
#include "libavformat/avformat.h"
#include <libavutil/imgutils.h>
#include <libswscale/swscale.h>
}
using namespace lightscan;
const std::string DB_PATH = "/Users/abpoms/kcam";
const std::string IFRAME_PATH_POSTFIX = "_iframes";
const std::string METADATA_PATH_POSTFIX = "_metadata";
const std::string PROCESSED_VIDEO_POSTFIX = "_processed";
const int NUM_GPUS = 1;
const int BATCH_SIZE = 8;
#define THREAD_RETURN_SUCCESS() \
do { \
void* val = malloc(sizeof(int)); \
*((int*)val) = EXIT_SUCCESS; \
pthread_exit(val); \
} while (0);
///////////////////////////////////////////////////////////////////////////////
/// Path utils
std::string dirname_s(const std::string& path) {
char* path_copy = strdup(path.c_str());
char* dir = dirname(path_copy);
return std::string(dir);
}
std::string basename_s(const std::string& path) {
char* path_copy = strdup(path.c_str());
char* base = basename(path_copy);
return std::string(base);
}
std::string processed_video_path(const std::string& video_path) {
return dirname_s(video_path) + "/" +
basename_s(video_path) + PROCESSED_VIDEO_POSTFIX + ".mp4";
}
std::string metadata_path(const std::string& video_path) {
return dirname_s(video_path) + "/" +
basename_s(video_path) + METADATA_PATH_POSTFIX + ".bin";
}
std::string iframe_path(const std::string& video_path) {
return dirname_s(video_path) + "/" +
basename_s(video_path) + IFRAME_PATH_POSTFIX + ".bin";
}
///////////////////////////////////////////////////////////////////////////////
/// MPI utils
inline bool is_master(int rank) {
return rank == 0;
}
///////////////////////////////////////////////////////////////////////////////
///
void startup(int argc, char** argv) {
MPI_Init(&argc, &argv);
av_register_all();
FLAGS_minloglevel = 2;
}
///////////////////////////////////////////////////////////////////////////////
/// Thread to asynchronously load video
void convert_av_frame_to_rgb(
SwsContext*& sws_context,
AVFrame* frame,
char* buffer)
{
size_t buffer_size =
av_image_get_buffer_size(AV_PIX_FMT_RGB24, frame->width, frame->height, 1);
// Convert image to RGB
sws_context = sws_getCachedContext(
sws_context,
frame->width, frame->height,
static_cast<AVPixelFormat>(frame->format),
frame->width, frame->height, AV_PIX_FMT_RGB24,
SWS_BICUBIC, 0, 0, 0);
if (sws_context == nullptr) {
fprintf(stderr, "Error trying to get sws context\n");
assert(false);
}
AVFrame rgb_format;
int alloc_fail = av_image_alloc(rgb_format.data,
rgb_format.linesize,
frame->width,
frame->height,
AV_PIX_FMT_RGB24,
1);
if (alloc_fail < 0) {
fprintf(stderr, "Error while allocating avpicture for conversion\n");
assert(false);
}
sws_scale(sws_context,
frame->data /* input data */,
frame->linesize /* input layout */,
0 /* x start location */,
frame->height /* height of input image */,
rgb_format.data /* output data */,
rgb_format.linesize /* output layout */);
av_image_copy_to_buffer(reinterpret_cast<uint8_t*>(buffer),
buffer_size,
rgb_format.data,
rgb_format.linesize,
AV_PIX_FMT_RGB24,
frame->width,
frame->height,
1);
av_freep(&rgb_format.data[0]);
}
struct LoadVideoArgs {
// Input arguments
StorageConfig* storage_config;
std::string video_path;
std::string iframe_path;
int frame_start;
int frame_end;
VideoMetadata metadata;
// Output arguments
size_t frames_buffer_size;
char* decoded_frames_buffer; // Should have space for start - end frames
std::atomic<int>* frames_written;
};
void* load_video_thread(void* arg) {
// Setup connection to load video
LoadVideoArgs& args = *reinterpret_cast<LoadVideoArgs*>(arg);
// Setup a distinct storage backend for each IO thread
StorageBackend* storage =
StorageBackend::make_from_config(args.storage_config);
// Open the iframe file to setup keyframe data
std::vector<int> keyframe_positions;
std::vector<int64_t> keyframe_timestamps;
{
RandomReadFile* iframe_file;
storage->make_random_read_file(args.iframe_path, iframe_file);
(void)read_keyframe_info(
iframe_file, 0, keyframe_positions, keyframe_timestamps);
delete iframe_file;
}
// Open the video file for reading
RandomReadFile* file;
storage->make_random_read_file(args.video_path, file);
VideoDecoder decoder(file, keyframe_positions, keyframe_timestamps);
decoder.seek(args.frame_start);
size_t frame_size =
av_image_get_buffer_size(AV_PIX_FMT_RGB24,
args.metadata.width,
args.metadata.height,
1);
SwsContext* sws_context;
int current_frame = args.frame_start;
while (current_frame < args.frame_end) {
AVFrame* frame = decoder.decode();
assert(frame != nullptr);
size_t frames_buffer_offset =
frame_size * (current_frame - args.frame_start);
assert(frames_buffer_offset < args.frames_buffer_size);
char* current_frame_buffer_pos =
args.decoded_frames_buffer + frames_buffer_offset;
convert_av_frame_to_rgb(sws_context, frame, current_frame_buffer_pos);
*args.frames_written += 1;
current_frame += 1;
}
// Cleanup
delete file;
delete storage;
THREAD_RETURN_SUCCESS();
}
///////////////////////////////////////////////////////////////////////////////
/// Thread to asynchronously save out results
struct SaveVideoArgs {
};
void* save_video_thread(void* arg) {
// Setup connection to save video
THREAD_RETURN_SUCCESS();
}
///////////////////////////////////////////////////////////////////////////////
/// Main processing thread that runs the read, evaluate net, write loop
struct ProcessArgs {
int gpu_device_id;
StorageConfig* storage_config;
std::string video_path;
std::string iframe_path;
int frame_start;
int frame_end;
VideoMetadata metadata;
};
void* process_thread(void* arg) {
ProcessArgs& args = *reinterpret_cast<ProcessArgs*>(arg);
size_t frame_size =
av_image_get_buffer_size(AV_PIX_FMT_RGB24,
args.metadata.width,
args.metadata.height,
1);
size_t frame_buffer_size = frame_size * (args.frame_end - args.frame_start);
char* frame_buffer = new char[frame_buffer_size];
std::atomic<int> frames_written{0};
// Create IO threads for reading and writing
LoadVideoArgs load_args;
load_args.storage_config = args.storage_config;
load_args.video_path = args.video_path;
load_args.iframe_path = args.iframe_path;
load_args.frame_start = args.frame_start;
load_args.frame_end = args.frame_end;
load_args.metadata = args.metadata;
load_args.frames_buffer_size = frame_buffer_size;
load_args.decoded_frames_buffer = frame_buffer;
load_args.frames_written = &frames_written;
pthread_t load_thread;
pthread_create(&load_thread, NULL, load_video_thread, &load_args);
// pthread_t* save_thread;
// pthread_create(save_thread, NULL, save_video_thread, NULL);
// Setup caffe net
NetInfo net_info = load_neural_net(NetType::ALEX_NET, args.gpu_device_id);
caffe::Net<float>* net = net_info.net;
// Resize net input blob for batch size
const boost::shared_ptr<caffe::Blob<float>> data_blob{
net->blob_by_name("data")};
if (data_blob->shape(0) != BATCH_SIZE) {
data_blob->Reshape({
BATCH_SIZE, 3, net_info.input_size, net_info.input_size});
}
int dim = net_info.input_size;
cv::Mat unsized_mean_mat(
net_info.mean_width, net_info.mean_height, CV_32FC3, net_info.mean_image);
cv::Mat mean_mat;
cv::resize(unsized_mean_mat, mean_mat, cv::Size(dim, dim));
int current_frame = args.frame_start;
while (current_frame + BATCH_SIZE < args.frame_end) {
// Read batch of frames
if ((current_frame + BATCH_SIZE - args.frame_start) >= frames_written)
continue;
// Decompress batch of frame
printf("processing frame %d\n", current_frame);
// Process batch of frames
caffe::Blob<float> net_input{BATCH_SIZE, 3, dim, dim};
float* net_input_buffer = net_input.mutable_cpu_data();
for (int i = 0; i < BATCH_SIZE; ++i) {
char* buffer = frame_buffer + frame_size * (i + current_frame);
cv::Mat input_mat(
args.metadata.height, args.metadata.width, CV_8UC3, buffer);
cv::cvtColor(input_mat, input_mat, CV_RGB2BGR);
cv::Mat conv_input;
cv::resize(input_mat, conv_input, cv::Size(dim, dim));
cv::Mat float_conv_input;
conv_input.convertTo(float_conv_input, CV_32FC3);
cv::Mat normed_input = float_conv_input - mean_mat;
//to_conv_input(&std::get<0>(in_vec[i]), &conv_input, &mean);
memcpy(net_input_buffer + i * (dim * dim * 3),
normed_input.data,
dim * dim * 3 * sizeof(float));
}
net->Forward({&net_input});
// Save batch of frames
current_frame += BATCH_SIZE;
}
// Epilogue for processing less than a batch of frames
// Cleanup
delete[] frame_buffer;
delete net;
THREAD_RETURN_SUCCESS();
}
void shutdown() {
MPI_Finalize();
}
int main(int argc, char **argv) {
startup(argc, argv);
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
std::string video_path =
"kcam-videos-20140910_195012_247.mp4";
// Setup storage config
StorageConfig* config =
StorageConfig::make_disk_config(DB_PATH);
StorageBackend* storage = StorageBackend::make_from_config(config);
// Check if we have already preprocessed the video
FileInfo video_info;
StoreResult result =
storage->get_file_info(processed_video_path(video_path), video_info);
if (result == StoreResult::FileDoesNotExist) {
// Preprocess video and then exit
if (is_master(rank)) {
log_ls.print("Video not processed yet. Processing now...\n");
//video_path = "../../../tmp/lightscan3n1YnH";
//video_path = "../../../tmp/lightscanLNaRk3";
preprocess_video(storage,
video_path,
processed_video_path(video_path),
metadata_path(video_path),
iframe_path(video_path));
}
} else {
// Get video metadata to pass to all workers and determine work distribution
// from frame count
VideoMetadata metadata;
{
std::unique_ptr<RandomReadFile> metadata_file;
exit_on_error(
make_unique_random_read_file(storage,
metadata_path(video_path),
metadata_file));
(void) read_video_metadata(metadata_file.get(), 0, metadata);
}
// Parse args to determine video offset
// Create processing threads for each gpu
ProcessArgs processing_thread_args[NUM_GPUS];
pthread_t processing_threads[NUM_GPUS];
int total_frames = 2000;
int frames_allocated = 0;
for (int i = 0; i < NUM_GPUS; ++i) {
int frames =
std::ceil((total_frames - frames_allocated) * 1.0 / (NUM_GPUS - i));
int frame_start = frames_allocated;
int frame_end = frame_start + frames;
frames_allocated += frames;
ProcessArgs& args = processing_thread_args[i];
args.gpu_device_id = i;
args.storage_config = config;
args.video_path = video_path;
args.iframe_path = iframe_path(video_path);
args.frame_start = frame_start;
args.frame_end = frame_end;
args.metadata = metadata;
pthread_create(&processing_threads[i],
NULL,
process_thread,
&processing_thread_args[i]);
}
// Wait till done
for (int i = 0; i < NUM_GPUS; ++i) {
void* result;
int err = pthread_join(processing_threads[i], &result);
if (err != 0) {
fprintf(stderr, "error in pthread_join\n");
exit(EXIT_FAILURE);
}
printf("Joined with thread %d; returned value was %d\n",
i, *((int *)result));
free(result); /* Free memory allocated by thread */
}
}
// Cleanup
delete storage;
delete config;
shutdown();
return EXIT_SUCCESS;
}
<commit_msg>Set frame relative to start instead of absolutely<commit_after>/* Copyright 2016 Carnegie Mellon University, NVIDIA Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "lightscan/storage/storage_config.h"
#include "lightscan/storage/storage_backend.h"
#include "lightscan/util/common.h"
#include "lightscan/util/video.h"
#include "lightscan/util/caffe.h"
#include <opencv2/opencv.hpp>
#include <mpi.h>
#include <pthread.h>
#include <cstdlib>
#include <string>
#include <libgen.h>
#include <atomic>
extern "C" {
#include "libavformat/avformat.h"
#include <libavutil/imgutils.h>
#include <libswscale/swscale.h>
}
using namespace lightscan;
const std::string DB_PATH = "/Users/abpoms/kcam";
const std::string IFRAME_PATH_POSTFIX = "_iframes";
const std::string METADATA_PATH_POSTFIX = "_metadata";
const std::string PROCESSED_VIDEO_POSTFIX = "_processed";
const int NUM_GPUS = 1;
const int BATCH_SIZE = 8;
#define THREAD_RETURN_SUCCESS() \
do { \
void* val = malloc(sizeof(int)); \
*((int*)val) = EXIT_SUCCESS; \
pthread_exit(val); \
} while (0);
///////////////////////////////////////////////////////////////////////////////
/// Path utils
std::string dirname_s(const std::string& path) {
char* path_copy = strdup(path.c_str());
char* dir = dirname(path_copy);
return std::string(dir);
}
std::string basename_s(const std::string& path) {
char* path_copy = strdup(path.c_str());
char* base = basename(path_copy);
return std::string(base);
}
std::string processed_video_path(const std::string& video_path) {
return dirname_s(video_path) + "/" +
basename_s(video_path) + PROCESSED_VIDEO_POSTFIX + ".mp4";
}
std::string metadata_path(const std::string& video_path) {
return dirname_s(video_path) + "/" +
basename_s(video_path) + METADATA_PATH_POSTFIX + ".bin";
}
std::string iframe_path(const std::string& video_path) {
return dirname_s(video_path) + "/" +
basename_s(video_path) + IFRAME_PATH_POSTFIX + ".bin";
}
///////////////////////////////////////////////////////////////////////////////
/// MPI utils
inline bool is_master(int rank) {
return rank == 0;
}
///////////////////////////////////////////////////////////////////////////////
///
void startup(int argc, char** argv) {
MPI_Init(&argc, &argv);
av_register_all();
FLAGS_minloglevel = 2;
}
///////////////////////////////////////////////////////////////////////////////
/// Thread to asynchronously load video
void convert_av_frame_to_rgb(
SwsContext*& sws_context,
AVFrame* frame,
char* buffer)
{
size_t buffer_size =
av_image_get_buffer_size(AV_PIX_FMT_RGB24, frame->width, frame->height, 1);
// Convert image to RGB
sws_context = sws_getCachedContext(
sws_context,
frame->width, frame->height,
static_cast<AVPixelFormat>(frame->format),
frame->width, frame->height, AV_PIX_FMT_RGB24,
SWS_BICUBIC, 0, 0, 0);
if (sws_context == nullptr) {
fprintf(stderr, "Error trying to get sws context\n");
assert(false);
}
AVFrame rgb_format;
int alloc_fail = av_image_alloc(rgb_format.data,
rgb_format.linesize,
frame->width,
frame->height,
AV_PIX_FMT_RGB24,
1);
if (alloc_fail < 0) {
fprintf(stderr, "Error while allocating avpicture for conversion\n");
assert(false);
}
sws_scale(sws_context,
frame->data /* input data */,
frame->linesize /* input layout */,
0 /* x start location */,
frame->height /* height of input image */,
rgb_format.data /* output data */,
rgb_format.linesize /* output layout */);
av_image_copy_to_buffer(reinterpret_cast<uint8_t*>(buffer),
buffer_size,
rgb_format.data,
rgb_format.linesize,
AV_PIX_FMT_RGB24,
frame->width,
frame->height,
1);
av_freep(&rgb_format.data[0]);
}
struct LoadVideoArgs {
// Input arguments
StorageConfig* storage_config;
std::string video_path;
std::string iframe_path;
int frame_start;
int frame_end;
VideoMetadata metadata;
// Output arguments
size_t frames_buffer_size;
char* decoded_frames_buffer; // Should have space for start - end frames
std::atomic<int>* frames_written;
};
void* load_video_thread(void* arg) {
// Setup connection to load video
LoadVideoArgs& args = *reinterpret_cast<LoadVideoArgs*>(arg);
// Setup a distinct storage backend for each IO thread
StorageBackend* storage =
StorageBackend::make_from_config(args.storage_config);
// Open the iframe file to setup keyframe data
std::vector<int> keyframe_positions;
std::vector<int64_t> keyframe_timestamps;
{
RandomReadFile* iframe_file;
storage->make_random_read_file(args.iframe_path, iframe_file);
(void)read_keyframe_info(
iframe_file, 0, keyframe_positions, keyframe_timestamps);
delete iframe_file;
}
// Open the video file for reading
RandomReadFile* file;
storage->make_random_read_file(args.video_path, file);
VideoDecoder decoder(file, keyframe_positions, keyframe_timestamps);
decoder.seek(args.frame_start);
size_t frame_size =
av_image_get_buffer_size(AV_PIX_FMT_RGB24,
args.metadata.width,
args.metadata.height,
1);
SwsContext* sws_context;
int current_frame = args.frame_start;
while (current_frame < args.frame_end) {
AVFrame* frame = decoder.decode();
assert(frame != nullptr);
size_t frames_buffer_offset =
frame_size * (current_frame - args.frame_start);
assert(frames_buffer_offset < args.frames_buffer_size);
char* current_frame_buffer_pos =
args.decoded_frames_buffer + frames_buffer_offset;
convert_av_frame_to_rgb(sws_context, frame, current_frame_buffer_pos);
*args.frames_written += 1;
current_frame += 1;
}
// Cleanup
delete file;
delete storage;
THREAD_RETURN_SUCCESS();
}
///////////////////////////////////////////////////////////////////////////////
/// Thread to asynchronously save out results
struct SaveVideoArgs {
};
void* save_video_thread(void* arg) {
// Setup connection to save video
THREAD_RETURN_SUCCESS();
}
///////////////////////////////////////////////////////////////////////////////
/// Main processing thread that runs the read, evaluate net, write loop
struct ProcessArgs {
int gpu_device_id;
StorageConfig* storage_config;
std::string video_path;
std::string iframe_path;
int frame_start;
int frame_end;
VideoMetadata metadata;
};
void* process_thread(void* arg) {
ProcessArgs& args = *reinterpret_cast<ProcessArgs*>(arg);
size_t frame_size =
av_image_get_buffer_size(AV_PIX_FMT_RGB24,
args.metadata.width,
args.metadata.height,
1);
size_t frame_buffer_size = frame_size * (args.frame_end - args.frame_start);
char* frame_buffer = new char[frame_buffer_size];
std::atomic<int> frames_written{0};
// Create IO threads for reading and writing
LoadVideoArgs load_args;
load_args.storage_config = args.storage_config;
load_args.video_path = args.video_path;
load_args.iframe_path = args.iframe_path;
load_args.frame_start = args.frame_start;
load_args.frame_end = args.frame_end;
load_args.metadata = args.metadata;
load_args.frames_buffer_size = frame_buffer_size;
load_args.decoded_frames_buffer = frame_buffer;
load_args.frames_written = &frames_written;
pthread_t load_thread;
pthread_create(&load_thread, NULL, load_video_thread, &load_args);
// pthread_t* save_thread;
// pthread_create(save_thread, NULL, save_video_thread, NULL);
// Setup caffe net
NetInfo net_info = load_neural_net(NetType::ALEX_NET, args.gpu_device_id);
caffe::Net<float>* net = net_info.net;
// Resize net input blob for batch size
const boost::shared_ptr<caffe::Blob<float>> data_blob{
net->blob_by_name("data")};
if (data_blob->shape(0) != BATCH_SIZE) {
data_blob->Reshape({
BATCH_SIZE, 3, net_info.input_size, net_info.input_size});
}
int dim = net_info.input_size;
cv::Mat unsized_mean_mat(
net_info.mean_width, net_info.mean_height, CV_32FC3, net_info.mean_image);
cv::Mat mean_mat;
cv::resize(unsized_mean_mat, mean_mat, cv::Size(dim, dim));
int current_frame = args.frame_start;
while (current_frame + BATCH_SIZE < args.frame_end) {
// Read batch of frames
if ((current_frame + BATCH_SIZE - args.frame_start) >= frames_written)
continue;
int frame_offset = current_frame - args.frame_start;
// Decompress batch of frame
printf("processing frame %d\n", current_frame);
// Process batch of frames
caffe::Blob<float> net_input{BATCH_SIZE, 3, dim, dim};
float* net_input_buffer = net_input.mutable_cpu_data();
for (int i = 0; i < BATCH_SIZE; ++i) {
char* buffer = frame_buffer + frame_size * (i + frame_offset);
cv::Mat input_mat(
args.metadata.height, args.metadata.width, CV_8UC3, buffer);
cv::cvtColor(input_mat, input_mat, CV_RGB2BGR);
cv::Mat conv_input;
cv::resize(input_mat, conv_input, cv::Size(dim, dim));
cv::Mat float_conv_input;
conv_input.convertTo(float_conv_input, CV_32FC3);
cv::Mat normed_input = float_conv_input - mean_mat;
//to_conv_input(&std::get<0>(in_vec[i]), &conv_input, &mean);
memcpy(net_input_buffer + i * (dim * dim * 3),
normed_input.data,
dim * dim * 3 * sizeof(float));
}
net->Forward({&net_input});
// Save batch of frames
current_frame += BATCH_SIZE;
}
// Epilogue for processing less than a batch of frames
// Cleanup
delete[] frame_buffer;
delete net;
THREAD_RETURN_SUCCESS();
}
void shutdown() {
MPI_Finalize();
}
int main(int argc, char **argv) {
startup(argc, argv);
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
std::string video_path =
"kcam-videos-20140910_195012_247.mp4";
// Setup storage config
StorageConfig* config =
StorageConfig::make_disk_config(DB_PATH);
StorageBackend* storage = StorageBackend::make_from_config(config);
// Check if we have already preprocessed the video
FileInfo video_info;
StoreResult result =
storage->get_file_info(processed_video_path(video_path), video_info);
if (result == StoreResult::FileDoesNotExist) {
// Preprocess video and then exit
if (is_master(rank)) {
log_ls.print("Video not processed yet. Processing now...\n");
//video_path = "../../../tmp/lightscan3n1YnH";
//video_path = "../../../tmp/lightscanLNaRk3";
preprocess_video(storage,
video_path,
processed_video_path(video_path),
metadata_path(video_path),
iframe_path(video_path));
}
} else {
// Get video metadata to pass to all workers and determine work distribution
// from frame count
VideoMetadata metadata;
{
std::unique_ptr<RandomReadFile> metadata_file;
exit_on_error(
make_unique_random_read_file(storage,
metadata_path(video_path),
metadata_file));
(void) read_video_metadata(metadata_file.get(), 0, metadata);
}
// Parse args to determine video offset
// Create processing threads for each gpu
ProcessArgs processing_thread_args[NUM_GPUS];
pthread_t processing_threads[NUM_GPUS];
int total_frames = 2000;
int frames_allocated = 0;
for (int i = 0; i < NUM_GPUS; ++i) {
int frames =
std::ceil((total_frames - frames_allocated) * 1.0 / (NUM_GPUS - i));
int frame_start = frames_allocated;
int frame_end = frame_start + frames;
frames_allocated += frames;
ProcessArgs& args = processing_thread_args[i];
args.gpu_device_id = i;
args.storage_config = config;
args.video_path = video_path;
args.iframe_path = iframe_path(video_path);
args.frame_start = frame_start;
args.frame_end = frame_end;
args.metadata = metadata;
pthread_create(&processing_threads[i],
NULL,
process_thread,
&processing_thread_args[i]);
}
// Wait till done
for (int i = 0; i < NUM_GPUS; ++i) {
void* result;
int err = pthread_join(processing_threads[i], &result);
if (err != 0) {
fprintf(stderr, "error in pthread_join\n");
exit(EXIT_FAILURE);
}
printf("Joined with thread %d; returned value was %d\n",
i, *((int *)result));
free(result); /* Free memory allocated by thread */
}
}
// Cleanup
delete storage;
delete config;
shutdown();
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/* bzflag
* Copyright (c) 1993 - 2003 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named LICENSE that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include "CommandsStandard.h"
#include "CommandManager.h"
#include "StateDatabase.h"
#include <stdio.h>
#include <ctype.h>
static bool quitFlag = false;
//
// command handlers
//
static std::string cmdQuit(const std::string&,
const CommandManager::ArgList&)
{
CommandsStandard::quit();
return std::string();
}
static void onHelpCB(const std::string& name,
void* userData)
{
std::string& result = *reinterpret_cast<std::string*>(userData);
result += name;
result += "\n";
}
static std::string cmdHelp(const std::string&,
const CommandManager::ArgList& args)
{
switch (args.size()) {
case 0: {
std::string result;
CMDMGR->iterate(&onHelpCB, &result);
return result;
}
case 1:
return CMDMGR->getHelp(args[0]);
default:
return "usage: help [<command-name>]";
}
}
static std::string cmdPrint(const std::string&,
const CommandManager::ArgList& args)
{
// merge all arguments into one string
std::string arg;
const unsigned int n = args.size();
if (n > 0)
arg = args[0];
for (unsigned int i = 1; i < n; ++i) {
arg += " ";
arg += args[i];
}
// interpolate variables
std::string result;
const char* scan = arg.c_str();
while (*scan != '\0') {
if (*scan != '$') {
result.append(scan, 1);
++scan;
} else {
// could be a variable
++scan;
if (*scan == '$') {
// no, it's just $$ which maps to $
result += "$";
++scan;
} else if (*scan != '{') {
// parse variable name
const char* name = scan;
while (*scan != '\0' && !isspace(*scan))
++scan;
// look up variable
result += BZDB->get(std::string(name, scan - name));
} else {
// parse "quoted" variable name
const char* name = ++scan;
while (*scan != '\0' && *scan != '}')
++scan;
if (*scan != '\0') {
// look up variable
result += BZDB->get(std::string(name, scan - name));
// skip }
++scan;
}
}
}
}
return result;
}
static void onSetCB(const std::string& name,
void* userData)
{
// don't show names starting with _
std::string& result = *reinterpret_cast<std::string*>(userData);
if (!name.empty() && name.c_str()[0] != '_') {
result += name;
result += " = ";
result += BZDB->get(name);
result += "\n";
}
}
static std::string cmdSet(const std::string&,
const CommandManager::ArgList& args)
{
switch (args.size()) {
case 0: {
std::string result;
BZDB->iterate(&onSetCB, &result);
return result;
}
case 2:
BZDB->set(args[0], args[1], StateDatabase::User);
return std::string();
default:
return "usage: set <name> <value>";
}
}
static std::string cmdUnset(const std::string&,
const CommandManager::ArgList& args)
{
if (args.size() != 1)
return "usage: unset <name>";
BZDB->unset(args[0], StateDatabase::User);
return std::string();
}
static std::string cmdToggle(const std::string&,
const CommandManager::ArgList& args)
{
if (args.size() != 1)
return "usage: toggle <name>";
const std::string& name = args[0];
if (BZDB->isTrue(name))
BZDB->set(name, "0", StateDatabase::User);
else
BZDB->set(name, "1", StateDatabase::User);
return std::string();
}
//
// command name to function mapping
//
struct CommandListItem {
public:
const char* name;
CommandManager::CommandFunction func;
const char* help;
};
static const CommandListItem commandList[] = {
{ "quit", &cmdQuit, "quit: quit the program" },
{ "help", &cmdHelp, "help [<command-name>]: get help on a command or a list of commands" },
{ "print", &cmdPrint, "print ...: print arguments; $name is replaced by value of variable \"name\"" },
{ "set", &cmdSet, "set [<name> <value>]: set a variable or print all set variables" },
{ "unset", &cmdUnset, "unset <name>: unset a variable" },
{ "toggle", &cmdToggle, "toggle <name>: toggle truth value of a variable" },
};
// FIXME -- may want a cmd to cycle through a list
//
// CommandsStandard
//
void CommandsStandard::add()
{
unsigned int i;
for (i = 0; i < countof(commandList); ++i)
CMDMGR->add(commandList[i].name, commandList[i].func, commandList[i].help);
}
void CommandsStandard::remove()
{
unsigned int i;
for (i = 0; i < countof(commandList); ++i)
CMDMGR->remove(commandList[i].name);
}
void CommandsStandard::quit()
{
quitFlag = true;
}
bool CommandsStandard::isQuit()
{
return quitFlag;
}
// ex: shiftwidth=2 tabstop=8
<commit_msg>add bind/unbind commands<commit_after>/* bzflag
* Copyright (c) 1993 - 2003 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named LICENSE that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include "CommandsStandard.h"
#include "CommandManager.h"
#include "StateDatabase.h"
#include "KeyManager.h"
#include <stdio.h>
#include <ctype.h>
static bool quitFlag = false;
//
// command handlers
//
static std::string cmdQuit(const std::string&,
const CommandManager::ArgList&)
{
CommandsStandard::quit();
return std::string();
}
static void onHelpCB(const std::string& name,
void* userData)
{
std::string& result = *reinterpret_cast<std::string*>(userData);
result += name;
result += "\n";
}
static std::string cmdHelp(const std::string&,
const CommandManager::ArgList& args)
{
switch (args.size()) {
case 0: {
std::string result;
CMDMGR->iterate(&onHelpCB, &result);
return result;
}
case 1:
return CMDMGR->getHelp(args[0]);
default:
return "usage: help [<command-name>]";
}
}
static std::string cmdPrint(const std::string&,
const CommandManager::ArgList& args)
{
// merge all arguments into one string
std::string arg;
const unsigned int n = args.size();
if (n > 0)
arg = args[0];
for (unsigned int i = 1; i < n; ++i) {
arg += " ";
arg += args[i];
}
// interpolate variables
std::string result;
const char* scan = arg.c_str();
while (*scan != '\0') {
if (*scan != '$') {
result.append(scan, 1);
++scan;
} else {
// could be a variable
++scan;
if (*scan == '$') {
// no, it's just $$ which maps to $
result += "$";
++scan;
} else if (*scan != '{') {
// parse variable name
const char* name = scan;
while (*scan != '\0' && !isspace(*scan))
++scan;
// look up variable
result += BZDB->get(std::string(name, scan - name));
} else {
// parse "quoted" variable name
const char* name = ++scan;
while (*scan != '\0' && *scan != '}')
++scan;
if (*scan != '\0') {
// look up variable
result += BZDB->get(std::string(name, scan - name));
// skip }
++scan;
}
}
}
}
return result;
}
static void onSetCB(const std::string& name,
void* userData)
{
// don't show names starting with _
std::string& result = *reinterpret_cast<std::string*>(userData);
if (!name.empty() && name.c_str()[0] != '_') {
result += name;
result += " = ";
result += BZDB->get(name);
result += "\n";
}
}
static std::string cmdSet(const std::string&,
const CommandManager::ArgList& args)
{
switch (args.size()) {
case 0: {
std::string result;
BZDB->iterate(&onSetCB, &result);
return result;
}
case 2:
BZDB->set(args[0], args[1], StateDatabase::User);
return std::string();
default:
return "usage: set <name> <value>";
}
}
static std::string cmdUnset(const std::string&,
const CommandManager::ArgList& args)
{
if (args.size() != 1)
return "usage: unset <name>";
BZDB->unset(args[0], StateDatabase::User);
return std::string();
}
static void onBindCB(const std::string& name, bool press,
const std::string& cmd, void* userData)
{
std::string& result = *reinterpret_cast<std::string*>(userData);
result += name;
result += (press ? " down " : " up ");
result += cmd;
result += "\n";
}
static std::string cmdBind(const std::string&,
const CommandManager::ArgList& args)
{
if (args.size() == 0) {
std::string result;
KEYMGR->iterate(&onBindCB, &result);
return result;
} else if (args.size() < 3) {
return "usage: bind <button-name> {up|down} <command> <args>...";
}
BzfKeyEvent key;
if (!KEYMGR->stringToKeyEvent(args[0], key))
return std::string("bind error: unknown button name \"") + args[0] + "\"";
bool down;
if (args[1] == "up")
down = false;
else if (args[1] == "down")
down = true;
else
return std::string("bind error: illegal state \"") + args[1] + "\"";
std::string cmd = args[2];
for (unsigned int i = 3; i < args.size(); ++i) {
cmd += " ";
cmd += args[i];
}
// ignore attempts to modify Esc. we reserve that for the menu
if (key.ascii != 27)
KEYMGR->bind(key, down, cmd);
return std::string();
}
static std::string cmdUnbind(const std::string&,
const CommandManager::ArgList& args)
{
if (args.size() != 2)
return "usage: unbind <button-name> {up|down}";
BzfKeyEvent key;
if (!KEYMGR->stringToKeyEvent(args[0], key))
return std::string("bind error: unknown button name \"") + args[0] + "\"";
bool down;
if (args[1] == "up")
down = false;
else if (args[1] == "down")
down = true;
else
return std::string("bind error: illegal state \"") + args[1] + "\"";
if (key.ascii != 27)
KEYMGR->unbind(key, down);
return std::string();
}
static std::string cmdToggle(const std::string&,
const CommandManager::ArgList& args)
{
if (args.size() != 1)
return "usage: toggle <name>";
const std::string& name = args[0];
if (BZDB->isTrue(name))
BZDB->set(name, "0", StateDatabase::User);
else
BZDB->set(name, "1", StateDatabase::User);
return std::string();
}
//
// command name to function mapping
//
struct CommandListItem {
public:
const char* name;
CommandManager::CommandFunction func;
const char* help;
};
static const CommandListItem commandList[] = {
{ "quit", &cmdQuit, "quit: quit the program" },
{ "help", &cmdHelp, "help [<command-name>]: get help on a command or a list of commands" },
{ "print", &cmdPrint, "print ...: print arguments; $name is replaced by value of variable \"name\"" },
{ "set", &cmdSet, "set [<name> <value>]: set a variable or print all set variables" },
{ "unset", &cmdUnset, "unset <name>: unset a variable" },
{ "bind", &cmdBind, "bind <button-name> {up|down} <command> <args>...: bind a key" },
{ "unbind", &cmdUnbind, "unbind <button-name> {up|down}: unbind a key" },
{ "toggle", &cmdToggle, "toggle <name>: toggle truth value of a variable" }
};
// FIXME -- may want a cmd to cycle through a list
//
// CommandsStandard
//
void CommandsStandard::add()
{
unsigned int i;
for (i = 0; i < countof(commandList); ++i)
CMDMGR->add(commandList[i].name, commandList[i].func, commandList[i].help);
}
void CommandsStandard::remove()
{
unsigned int i;
for (i = 0; i < countof(commandList); ++i)
CMDMGR->remove(commandList[i].name);
}
void CommandsStandard::quit()
{
quitFlag = true;
}
bool CommandsStandard::isQuit()
{
return quitFlag;
}
// ex: shiftwidth=2 tabstop=8
<|endoftext|> |
<commit_before>#include "x11api.h"
#ifdef __LINUX__
#include <X11/X.h>
#include <X11/Xlib.h>
#include <X11/Xatom.h>
#include <X11/Xos.h>
#include <X11/keysymdef.h>
#include <X11/Xutil.h>
//#include <GL/glx.h> //FIXME
#include <Tempest/Event>
#include <Tempest/TextCodec>
#include <Tempest/Window>
#include <atomic>
#include <stdexcept>
#include <cstring>
#include <thread>
#include <unordered_map>
struct HWND final {
::Window wnd;
HWND()=default;
HWND(::Window w):wnd(w) {
}
HWND(Tempest::SystemApi::Window* p) {
std::memcpy(&wnd,&p,sizeof(wnd));
}
HWND& operator = (::Window w) { wnd = w; return *this; }
operator ::Window() { return wnd; }
Tempest::SystemApi::Window* ptr() {
static_assert (sizeof(::Window)<=sizeof(void*),"cannot map X11 window handle to pointer");
Tempest::SystemApi::Window* ret=nullptr;
std::memcpy(&ret,&wnd,sizeof(wnd));
return ret;
}
};
using namespace Tempest;
static const char* wndClassName="Tempest.Window";
static Display* dpy = nullptr;
static ::Window root = {};
static std::atomic_bool isExit{0};
static std::unordered_map<SystemApi::Window*,Tempest::Window*> windows;
static Atom& wmDeleteMessage(){
static Atom w = XInternAtom( dpy, "WM_DELETE_WINDOW", 0);
return w;
}
static Atom& _NET_WM_STATE(){
static Atom w = XInternAtom( dpy, "_NET_WM_STATE", 0);
return w;
}
static Atom& _NET_WM_STATE_MAXIMIZED_HORZ(){
static Atom w = XInternAtom( dpy, "_NET_WM_STATE_MAXIMIZED_HORZ", 0);
return w;
}
static Atom& _NET_WM_STATE_MAXIMIZED_VERT(){
static Atom w = XInternAtom( dpy, "_NET_WM_STATE_MAXIMIZED_VERT", 0);
return w;
}
static Atom& _NET_WM_STATE_FULLSCREEN(){
static Atom w = XInternAtom( dpy, "_NET_WM_STATE_FULLSCREEN", 0);
return w;
}
static Event::MouseButton toButton( XButtonEvent& msg ){
if( msg.button==Button1 )
return Event::ButtonLeft;
if( msg.button==Button3 )
return Event::ButtonRight;
if( msg.button==Button2 )
return Event::ButtonMid;
return Event::ButtonNone;
}
static void maximizeWindow(HWND& w) {
Atom a[2];
a[0] = _NET_WM_STATE_MAXIMIZED_HORZ();
a[1] = _NET_WM_STATE_MAXIMIZED_VERT();
XChangeProperty ( dpy, w, _NET_WM_STATE(),
XA_ATOM, 32, PropModeReplace, (unsigned char*)a, 2);
XSync(dpy,False);
}
X11Api::X11Api() {
dpy = XOpenDisplay(nullptr);
if(dpy == nullptr)
throw std::runtime_error("cannot connect to X server!");
root = DefaultRootWindow(dpy);
static const TranslateKeyPair k[] = {
{ XK_KP_Left, Event::K_Left },
{ XK_KP_Right, Event::K_Right },
{ XK_KP_Up, Event::K_Up },
{ XK_KP_Down, Event::K_Down },
{ XK_Shift_L, Event::K_LShift },
{ XK_Shift_R, Event::K_RShift },
{ XK_Control_L, Event::K_LControl },
{ XK_Control_R, Event::K_RControl },
{ XK_Escape, Event::K_ESCAPE },
{ XK_Tab, Event::K_Tab },
{ XK_BackSpace, Event::K_Back },
{ XK_Delete, Event::K_Delete },
{ XK_Insert, Event::K_Insert },
{ XK_Home, Event::K_Home },
{ XK_End, Event::K_End },
{ XK_Pause, Event::K_Pause },
{ XK_Return, Event::K_Return },
{ XK_F1, Event::K_F1 },
{ 48, Event::K_0 },
{ 97, Event::K_A },
{ 0, Event::K_NoKey }
};
setupKeyTranslate(k,24);
}
void *X11Api::display() {
return dpy;
}
void X11Api::alignGeometry(SystemApi::Window *w, Tempest::Window& owner) {
XWindowAttributes xwa={};
if(XGetWindowAttributes(dpy, HWND(w), &xwa)){
Tempest::SizeEvent e(xwa.width, xwa.height);
SystemApi::dispatchResize(owner,e);
}
}
SystemApi::Window *X11Api::implCreateWindow(Tempest::Window *owner, uint32_t w, uint32_t h) {
//GLint att[] = { GLX_RGBA, GLX_DEPTH_SIZE, 24, GLX_DOUBLEBUFFER, None };
//XVisualInfo * vi = glXChooseVisual(dpy, 0, att);
long visualMask = VisualScreenMask;
int numberOfVisuals;
XVisualInfo vInfoTemplate = {};
vInfoTemplate.screen = DefaultScreen(dpy);
XVisualInfo * vi = XGetVisualInfo(dpy, visualMask, &vInfoTemplate, &numberOfVisuals);
Colormap cmap;
cmap = XCreateColormap(dpy, root, vi->visual, AllocNone);
XSetWindowAttributes swa={};
swa.colormap = cmap;
swa.event_mask = PointerMotionMask | ExposureMask |
ButtonPressMask | ButtonReleaseMask |
KeyPressMask | KeyReleaseMask;
HWND win = XCreateWindow( dpy, root, 0, 0, w, h,
0, vi->depth, InputOutput, vi->visual,
CWColormap | CWEventMask, &swa );
XSetWMProtocols(dpy, win, &wmDeleteMessage(), 1);
XStoreName(dpy, win, wndClassName);
XFreeColormap( dpy, cmap );
XFree(vi);
auto ret = reinterpret_cast<SystemApi::Window*>(win.ptr());
windows[ret] = owner;
//maximizeWindow(win);
setAsFullscreen(ret, true); // This had to be added for the setAsFullscreen function to be called for me
XMapWindow(dpy, win);
XSync(dpy,False);
if(owner!=nullptr)
alignGeometry(win.ptr(),*owner);
return ret;
}
SystemApi::Window *X11Api::implCreateWindow(Tempest::Window *owner, SystemApi::ShowMode sm) {
Screen* s = DefaultScreenOfDisplay(dpy);
int width = s->width;
int height = s->height;
SystemApi::Window* hwnd = nullptr;
if(sm==Normal)
hwnd = implCreateWindow(owner,800, 600);
else
hwnd = implCreateWindow(owner,width, height);
if(sm==FullScreen)
setAsFullscreen(hwnd,true);
return hwnd;
}
void X11Api::implDestroyWindow(SystemApi::Window *w) {
windows.erase(w); //NOTE: X11 can send events to ded window
XDestroyWindow(dpy, HWND(w));
}
bool X11Api::implSetAsFullscreen(SystemApi::Window *w, bool fullScreen) {
Atom a[1];
a[0] = _NET_WM_STATE_FULLSCREEN();
// In case this is needed, this can be used to resize a window after it has been created
// XResizeWindow(dpy, HWND(w), width, height);
if(fullScreen) {
XChangeProperty ( dpy, HWND(w), _NET_WM_STATE(),
XA_ATOM, 32, PropModeReplace, (unsigned char*)a, 1);
} else {
XChangeProperty ( dpy, HWND(w), _NET_WM_STATE(),
XA_ATOM, 32, PropModeReplace, (unsigned char*)a, 0);
}
XSync(dpy,False);
}
bool X11Api::implIsFullscreen(SystemApi::Window *w) {
Atom actualType;
int actualFormat;
unsigned long i, numItems, bytesAfter;
unsigned char *propertyValue = NULL;
long maxLength = 1024;
if (XGetWindowProperty(dpy, HWND(w), _NET_WM_STATE(),
0l, maxLength, False, XA_ATOM, &actualType,
&actualFormat, &numItems, &bytesAfter,
&propertyValue) == Success) {
int fullscreen = 0;
Atom *atoms = (Atom *) propertyValue;
for (i = 0; i < numItems; ++i) {
if (atoms[i] == _NET_WM_STATE_FULLSCREEN()) {
fullscreen = 1;
}
}
if(fullscreen) {
return true;
}
}
return false;
}
void X11Api::implSetCursorPosition(int x, int y) {
// If I turn this code on, it causes no input to work. I'm guessing it may have to do with either the function itself (need to look further at what the windows version does) or the events coming from this.
//XSelectInput(dpy, HWND(windows.begin()->first), KeyReleaseMask);
//XWarpPointer(dpy, None, HWND(windows.begin()->first), 0, 0, 0, 0, x, y);
//XFlush(dpy);
}
void X11Api::implShowCursor(bool show) {
if(show) {
XUndefineCursor(dpy, HWND(windows.begin()->first));
} else {
Cursor invisibleCursor;
Pixmap bitmapNoData;
XColor black;
static char noData[] = { 0,0,0,0,0,0,0,0 };
black.red = black.green = black.blue = 0;
bitmapNoData = XCreateBitmapFromData(dpy, HWND(windows.begin()->first), noData, 8, 8);
invisibleCursor = XCreatePixmapCursor(dpy, bitmapNoData, bitmapNoData,
&black, &black, 0, 0);
XDefineCursor(dpy, HWND(windows.begin()->first), invisibleCursor);
XFreeCursor(dpy, invisibleCursor);
XFreePixmap(dpy, bitmapNoData);
}
XSync(dpy, False);
}
Rect X11Api::implWindowClientRect(SystemApi::Window *w) {
XWindowAttributes xwa;
XGetWindowAttributes(dpy, HWND(w), &xwa);
return Rect( xwa.x, xwa.y, xwa.width, xwa.height );
}
void X11Api::implExit() {
isExit.store(true);
}
bool X11Api::implIsRunning() {
return !isExit.load();
}
int X11Api::implExec(SystemApi::AppCallBack &cb) {
// main message loop
while (!isExit.load()) {
implProcessEvents(cb);
}
return 0;
}
void X11Api::implProcessEvents(SystemApi::AppCallBack &cb) {
// main message loop
if(XPending(dpy)>0) {
XEvent xev={};
XNextEvent(dpy, &xev);
HWND hWnd = xev.xclient.window;
auto it = windows.find(hWnd.ptr());
if(it==windows.end() || it->second==nullptr)
return;
Tempest::Window& cb = *it->second; //TODO: validation
switch( xev.type ) {
case ClientMessage: {
if( xev.xclient.data.l[0] == long(wmDeleteMessage()) ){
SystemApi::exit();
}
break;
}
case ButtonPress:
case ButtonRelease: {
bool isWheel = false;
if( xev.type==ButtonPress && XPending(dpy) &&
(xev.xbutton.button == Button4 || xev.xbutton.button == Button5) ){
XEvent ev;
XNextEvent(dpy, &ev);
isWheel = (ev.type==ButtonRelease);
}
if( isWheel ){
int ticks = 0;
if( xev.xbutton.button == Button4 ) {
ticks = 100;
}
else if ( xev.xbutton.button == Button5 ) {
ticks = -100;
}
Tempest::MouseEvent e( xev.xbutton.x,
xev.xbutton.y,
Tempest::Event::ButtonNone,
ticks,
0,
Event::MouseWheel );
SystemApi::dispatchMouseWheel(cb, e);
} else {
MouseEvent e( xev.xbutton.x,
xev.xbutton.y,
toButton( xev.xbutton ),
0,
0,
xev.type==ButtonPress ? Event::MouseDown : Event::MouseUp );
if(xev.type==ButtonPress)
SystemApi::dispatchMouseDown(cb, e); else
SystemApi::dispatchMouseUp(cb, e);
}
break;
}
case MotionNotify: {
MouseEvent e( xev.xmotion.x,
xev.xmotion.y,
Event::ButtonNone,
0,
0,
Event::MouseMove );
SystemApi::dispatchMouseMove(cb, e);
break;
}
case KeyPress:
case KeyRelease: {
int keysyms_per_keycode_return = 0;
KeySym *ksym = XGetKeyboardMapping( dpy, KeyCode(xev.xkey.keycode),
1,
&keysyms_per_keycode_return );
char txt[10]={};
XLookupString(&xev.xkey, txt, sizeof(txt)-1, ksym, nullptr );
auto u16 = TextCodec::toUtf16(txt); // TODO: remove dynamic allocation
auto key = SystemApi::translateKey(*ksym);
uint32_t scan = xev.xkey.keycode;
Tempest::KeyEvent e(Event::KeyType(key),uint32_t(u16.size()>0 ? u16[0] : 0),Event::M_NoModifier,(xev.type==KeyPress) ? Event::KeyDown : Event::KeyUp);
if(xev.type==KeyPress)
SystemApi::dispatchKeyDown(cb,e,scan); else
SystemApi::dispatchKeyUp (cb,e,scan);
break;
}
}
std::this_thread::yield();
} else {
if(cb.onTimer()==0)
std::this_thread::yield();
for(auto& i:windows) {
if(i.second==nullptr)
continue;
// artificial move/resize event
alignGeometry(i.first,*i.second);
SystemApi::dispatchRender(*i.second);
}
}
}
#endif
<commit_msg>Fixes mouse cursor movement, code cleanup<commit_after>#include "x11api.h"
#ifdef __LINUX__
#include <X11/X.h>
#include <X11/Xlib.h>
#include <X11/Xatom.h>
#include <X11/Xos.h>
#include <X11/keysymdef.h>
#include <X11/Xutil.h>
//#include <GL/glx.h> //FIXME
#include <Tempest/Event>
#include <Tempest/TextCodec>
#include <Tempest/Window>
#include <Tempest/Log>
#include <atomic>
#include <stdexcept>
#include <cstring>
#include <thread>
#include <unordered_map>
struct HWND final {
::Window wnd;
HWND()=default;
HWND(::Window w):wnd(w) {
}
HWND(Tempest::SystemApi::Window* p) {
std::memcpy(&wnd,&p,sizeof(wnd));
}
HWND& operator = (::Window w) { wnd = w; return *this; }
operator ::Window() { return wnd; }
Tempest::SystemApi::Window* ptr() {
static_assert (sizeof(::Window)<=sizeof(void*),"cannot map X11 window handle to pointer");
Tempest::SystemApi::Window* ret=nullptr;
std::memcpy(&ret,&wnd,sizeof(wnd));
return ret;
}
};
using namespace Tempest;
static const char* wndClassName="Tempest.Window";
static Display* dpy = nullptr;
static ::Window root = {};
static std::atomic_bool isExit{0};
static int activeCursorChange = 0;
static std::unordered_map<SystemApi::Window*,Tempest::Window*> windows;
static Atom& wmDeleteMessage(){
static Atom w = XInternAtom( dpy, "WM_DELETE_WINDOW", 0);
return w;
}
static Atom& _NET_WM_STATE(){
static Atom w = XInternAtom( dpy, "_NET_WM_STATE", 0);
return w;
}
static Atom& _NET_WM_STATE_MAXIMIZED_HORZ(){
static Atom w = XInternAtom( dpy, "_NET_WM_STATE_MAXIMIZED_HORZ", 0);
return w;
}
static Atom& _NET_WM_STATE_MAXIMIZED_VERT(){
static Atom w = XInternAtom( dpy, "_NET_WM_STATE_MAXIMIZED_VERT", 0);
return w;
}
static Atom& _NET_WM_STATE_FULLSCREEN(){
static Atom w = XInternAtom( dpy, "_NET_WM_STATE_FULLSCREEN", 0);
return w;
}
static Event::MouseButton toButton( XButtonEvent& msg ){
if( msg.button==Button1 )
return Event::ButtonLeft;
if( msg.button==Button3 )
return Event::ButtonRight;
if( msg.button==Button2 )
return Event::ButtonMid;
return Event::ButtonNone;
}
static void maximizeWindow(HWND& w) {
Atom a[2];
a[0] = _NET_WM_STATE_MAXIMIZED_HORZ();
a[1] = _NET_WM_STATE_MAXIMIZED_VERT();
XChangeProperty ( dpy, w, _NET_WM_STATE(),
XA_ATOM, 32, PropModeReplace, (unsigned char*)a, 2);
XSync(dpy,False);
}
X11Api::X11Api() {
dpy = XOpenDisplay(nullptr);
if(dpy == nullptr)
throw std::runtime_error("cannot connect to X server!");
root = DefaultRootWindow(dpy);
static const TranslateKeyPair k[] = {
{ XK_KP_Left, Event::K_Left },
{ XK_KP_Right, Event::K_Right },
{ XK_KP_Up, Event::K_Up },
{ XK_KP_Down, Event::K_Down },
{ XK_Shift_L, Event::K_LShift },
{ XK_Shift_R, Event::K_RShift },
{ XK_Control_L, Event::K_LControl },
{ XK_Control_R, Event::K_RControl },
{ XK_Escape, Event::K_ESCAPE },
{ XK_Tab, Event::K_Tab },
{ XK_BackSpace, Event::K_Back },
{ XK_Delete, Event::K_Delete },
{ XK_Insert, Event::K_Insert },
{ XK_Home, Event::K_Home },
{ XK_End, Event::K_End },
{ XK_Pause, Event::K_Pause },
{ XK_Return, Event::K_Return },
{ XK_F1, Event::K_F1 },
{ 48, Event::K_0 },
{ 97, Event::K_A },
{ 0, Event::K_NoKey }
};
setupKeyTranslate(k,24);
}
void *X11Api::display() {
return dpy;
}
void X11Api::alignGeometry(SystemApi::Window *w, Tempest::Window& owner) {
XWindowAttributes xwa={};
if(XGetWindowAttributes(dpy, HWND(w), &xwa)){
Tempest::SizeEvent e(xwa.width, xwa.height);
SystemApi::dispatchResize(owner,e);
}
}
SystemApi::Window *X11Api::implCreateWindow(Tempest::Window *owner, uint32_t w, uint32_t h) {
//GLint att[] = { GLX_RGBA, GLX_DEPTH_SIZE, 24, GLX_DOUBLEBUFFER, None };
//XVisualInfo * vi = glXChooseVisual(dpy, 0, att);
long visualMask = VisualScreenMask;
int numberOfVisuals;
XVisualInfo vInfoTemplate = {};
vInfoTemplate.screen = DefaultScreen(dpy);
XVisualInfo * vi = XGetVisualInfo(dpy, visualMask, &vInfoTemplate, &numberOfVisuals);
Colormap cmap;
cmap = XCreateColormap(dpy, root, vi->visual, AllocNone);
XSetWindowAttributes swa={};
swa.colormap = cmap;
swa.event_mask = PointerMotionMask | ExposureMask |
ButtonPressMask | ButtonReleaseMask |
KeyPressMask | KeyReleaseMask;
HWND win = XCreateWindow( dpy, root, 0, 0, w, h,
0, vi->depth, InputOutput, vi->visual,
CWColormap | CWEventMask, &swa );
XSetWMProtocols(dpy, win, &wmDeleteMessage(), 1);
XStoreName(dpy, win, wndClassName);
XFreeColormap( dpy, cmap );
XFree(vi);
auto ret = reinterpret_cast<SystemApi::Window*>(win.ptr());
windows[ret] = owner;
//maximizeWindow(win);
setAsFullscreen(ret, true); // This had to be added for the setAsFullscreen function to be called for me
XMapWindow(dpy, win);
XSync(dpy,False);
if(owner!=nullptr)
alignGeometry(win.ptr(),*owner);
return ret;
}
SystemApi::Window *X11Api::implCreateWindow(Tempest::Window *owner, SystemApi::ShowMode sm) {
Screen* s = DefaultScreenOfDisplay(dpy);
int width = s->width;
int height = s->height;
SystemApi::Window* hwnd = nullptr;
switch(sm) {
case Hidden:
hwnd = implCreateWindow(owner,1, 1);
// TODO: make window invisible
break;
case Normal:
hwnd = implCreateWindow(owner,800, 600);
break;
case Minimized:
case Maximized
// TODO
hwnd = implCreateWindow(owner,width, height);
break;
case FullScreen:
hwnd = implCreateWindow(owner,width, height);
implSetAsFullscreen(hwnd,true);
break;
}
return hwnd;
}
void X11Api::implDestroyWindow(SystemApi::Window *w) {
windows.erase(w); //NOTE: X11 can send events to ded window
XDestroyWindow(dpy, HWND(w));
}
bool X11Api::implSetAsFullscreen(SystemApi::Window *w, bool fullScreen) {
Atom a[1];
a[0] = _NET_WM_STATE_FULLSCREEN();
if(fullScreen) {
XChangeProperty ( dpy, HWND(w), _NET_WM_STATE(),
XA_ATOM, 32, PropModeReplace, (unsigned char*)a, 1);
} else {
XChangeProperty ( dpy, HWND(w), _NET_WM_STATE(),
XA_ATOM, 32, PropModeReplace, (unsigned char*)a, 0);
}
XSync(dpy,False);
}
bool X11Api::implIsFullscreen(SystemApi::Window *w) {
Atom actualType;
int actualFormat;
unsigned long i, numItems, bytesAfter;
unsigned char *propertyValue = NULL;
long maxLength = 1024;
if (XGetWindowProperty(dpy, HWND(w), _NET_WM_STATE(),
0l, maxLength, False, XA_ATOM, &actualType,
&actualFormat, &numItems, &bytesAfter,
&propertyValue) == Success) {
int fullscreen = 0;
Atom *atoms = (Atom *) propertyValue;
for (i = 0; i < numItems; ++i) {
if (atoms[i] == _NET_WM_STATE_FULLSCREEN()) {
fullscreen = 1;
}
}
if(fullscreen) {
return true;
}
}
return false;
}
void X11Api::implSetCursorPosition(int x, int y) {
activeCursorChange = 1;
XWarpPointer(dpy, None, HWND(windows.begin()->first), 0, 0, 0, 0, x, y);
XFlush(dpy);
}
void X11Api::implShowCursor(bool show) {
if(show) {
XUndefineCursor(dpy, HWND(windows.begin()->first));
} else {
Cursor invisibleCursor;
Pixmap bitmapNoData;
XColor black;
static char noData[] = { 0,0,0,0,0,0,0,0 };
black.red = black.green = black.blue = 0;
bitmapNoData = XCreateBitmapFromData(dpy, HWND(windows.begin()->first), noData, 8, 8);
invisibleCursor = XCreatePixmapCursor(dpy, bitmapNoData, bitmapNoData,
&black, &black, 0, 0);
XDefineCursor(dpy, HWND(windows.begin()->first), invisibleCursor);
XFreeCursor(dpy, invisibleCursor);
XFreePixmap(dpy, bitmapNoData);
}
XSync(dpy, False);
}
Rect X11Api::implWindowClientRect(SystemApi::Window *w) {
XWindowAttributes xwa;
XGetWindowAttributes(dpy, HWND(w), &xwa);
return Rect( xwa.x, xwa.y, xwa.width, xwa.height );
}
void X11Api::implExit() {
isExit.store(true);
}
bool X11Api::implIsRunning() {
return !isExit.load();
}
int X11Api::implExec(SystemApi::AppCallBack &cb) {
// main message loop
while (!isExit.load()) {
implProcessEvents(cb);
}
return 0;
}
void X11Api::implProcessEvents(SystemApi::AppCallBack &cb) {
// main message loop
if(XPending(dpy)>0) {
XEvent xev={};
XNextEvent(dpy, &xev);
HWND hWnd = xev.xclient.window;
auto it = windows.find(hWnd.ptr());
if(it==windows.end() || it->second==nullptr)
return;
Tempest::Window& cb = *it->second; //TODO: validation
switch( xev.type ) {
case ClientMessage: {
if( xev.xclient.data.l[0] == long(wmDeleteMessage()) ){
SystemApi::exit();
}
break;
}
case ButtonPress:
case ButtonRelease: {
bool isWheel = false;
if( xev.type==ButtonPress && XPending(dpy) &&
(xev.xbutton.button == Button4 || xev.xbutton.button == Button5) ){
XEvent ev;
XNextEvent(dpy, &ev);
isWheel = (ev.type==ButtonRelease);
}
if( isWheel ){
int ticks = 0;
if( xev.xbutton.button == Button4 ) {
ticks = 100;
}
else if ( xev.xbutton.button == Button5 ) {
ticks = -100;
}
Tempest::MouseEvent e( xev.xbutton.x,
xev.xbutton.y,
Tempest::Event::ButtonNone,
ticks,
0,
Event::MouseWheel );
SystemApi::dispatchMouseWheel(cb, e);
} else {
MouseEvent e( xev.xbutton.x,
xev.xbutton.y,
toButton( xev.xbutton ),
0,
0,
xev.type==ButtonPress ? Event::MouseDown : Event::MouseUp );
if(xev.type==ButtonPress)
SystemApi::dispatchMouseDown(cb, e); else
SystemApi::dispatchMouseUp(cb, e);
}
break;
}
case MotionNotify: {
if(activeCursorChange == 1) {
activeCursorChange = 0;
break;
}
MouseEvent e( xev.xmotion.x,
xev.xmotion.y,
Event::ButtonNone,
0,
0,
Event::MouseMove );
SystemApi::dispatchMouseMove(cb, e);
break;
}
case KeyPress:
case KeyRelease: {
int keysyms_per_keycode_return = 0;
KeySym *ksym = XGetKeyboardMapping( dpy, KeyCode(xev.xkey.keycode),
1,
&keysyms_per_keycode_return );
char txt[10]={};
XLookupString(&xev.xkey, txt, sizeof(txt)-1, ksym, nullptr );
auto u16 = TextCodec::toUtf16(txt); // TODO: remove dynamic allocation
auto key = SystemApi::translateKey(*ksym);
uint32_t scan = xev.xkey.keycode;
Tempest::KeyEvent e(Event::KeyType(key),uint32_t(u16.size()>0 ? u16[0] : 0),Event::M_NoModifier,(xev.type==KeyPress) ? Event::KeyDown : Event::KeyUp);
if(xev.type==KeyPress)
SystemApi::dispatchKeyDown(cb,e,scan); else
SystemApi::dispatchKeyUp (cb,e,scan);
break;
}
}
std::this_thread::yield();
} else {
if(cb.onTimer()==0)
std::this_thread::yield();
for(auto& i:windows) {
if(i.second==nullptr)
continue;
// artificial move/resize event
alignGeometry(i.first,*i.second);
SystemApi::dispatchRender(*i.second);
}
}
}
#endif
<|endoftext|> |
<commit_before>#include <pcl/simulation/sum_reduce.h>
using namespace pcl::simulation;
pcl::simulation::SumReduce::SumReduce (int width, int height, int levels) : levels_ (levels),
width_ (width),
height_ (height)
{
std::cout << "SumReduce: levels: " << levels_ << std::endl;
// Load shader
sum_program_ = gllib::Program::Ptr (new gllib::Program ());
// TODO: to remove file dependency include the shader source in the binary
if (!sum_program_->addShaderFile ("sum_score.vert", gllib::VERTEX))
{
std::cout << "Failed loading vertex shader" << std::endl;
exit (-1);
}
// TODO: to remove file dependency include the shader source in the binary
if (!sum_program_->addShaderFile ("sum_score.frag", gllib::FRAGMENT))
{
std::cout << "Failed loading fragment shader" << std::endl;
exit (-1);
}
sum_program_->link ();
// Setup the framebuffer object for rendering
glGenFramebuffers (1, &fbo_);
arrays_ = new GLuint[levels_];
glGenTextures (levels_, arrays_);
int level_width = width_;
int level_height = height_;
for (int i = 0; i < levels_; ++i)
{
level_width = level_width / 2;
level_height = level_height / 2;
glBindTexture (GL_TEXTURE_2D, arrays_[i]);
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_MIN_FILTER, GL_NEAREST);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_NONE);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL);
glTexImage2D (GL_TEXTURE_2D, 0, GL_R32F, level_width, level_height, 0, GL_RED, GL_FLOAT, NULL);
glBindTexture (GL_TEXTURE_2D, 0);
}
}
pcl::simulation::SumReduce::~SumReduce ()
{
glDeleteTextures (levels_, arrays_);
glDeleteFramebuffers (1, &fbo_);
}
void
pcl::simulation::SumReduce::sum (GLuint input_array, float* output_array)
{
if (gllib::getGLError () != GL_NO_ERROR)
{
std::cout << "SumReduce::sum enter" << std::endl;
}
glDisable (GL_DEPTH_TEST);
glBindFramebuffer (GL_FRAMEBUFFER, fbo_);
int width = width_;
int height = height_;
glActiveTexture (GL_TEXTURE0);
glBindTexture (GL_TEXTURE_2D, input_array);
// use program
sum_program_->use ();
glUniform1i (sum_program_->getUniformLocation ("ArraySampler"), 0);
if (gllib::getGLError () != GL_NO_ERROR)
{
std::cout << "SumReduce::sum set sampler" << std::endl;
}
for (int i=0; i < levels_; ++i)
{
glFramebufferTexture2D (GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, arrays_[i], 0);
glDrawBuffer (GL_COLOR_ATTACHMENT0);
glViewport (0, 0, width/2, height/2);
float step_x = 1.0f / width;
float step_y = 1.0f / height;
sum_program_->setUniform ("step_x", step_x);
sum_program_->setUniform ("step_y", step_y);
//float step_x = 1.0f / static_cast<float> (width);
//float step_y = 1.0f / static_cast<float> (height);
quad_.render ();
if (gllib::getGLError () != GL_NO_ERROR)
{
std::cout << "SumReduce::sum render" << std::endl;
}
width = width / 2;
height = height / 2;
glActiveTexture (GL_TEXTURE0);
glBindTexture (GL_TEXTURE_2D, arrays_[i]);
}
glBindFramebuffer (GL_FRAMEBUFFER, 0);
glActiveTexture (GL_TEXTURE0);
glBindTexture (GL_TEXTURE_2D, 0);
glUseProgram (0);
// Final results is in arrays_[levels_-1]
glActiveTexture (GL_TEXTURE0);
glBindTexture (GL_TEXTURE_2D, arrays_[levels_-1]);
glGetTexImage (GL_TEXTURE_2D, 0, GL_RED, GL_FLOAT, output_array);
glBindTexture (GL_TEXTURE_2D, 0);
if (gllib::getGLError () != GL_NO_ERROR)
{
std::cout << "Error: SumReduce exit" << std::endl;
}
}
<commit_msg>fixed compiler warnings<commit_after>#include <pcl/simulation/sum_reduce.h>
using namespace pcl::simulation;
pcl::simulation::SumReduce::SumReduce (int width, int height, int levels) : levels_ (levels),
width_ (width),
height_ (height)
{
std::cout << "SumReduce: levels: " << levels_ << std::endl;
// Load shader
sum_program_ = gllib::Program::Ptr (new gllib::Program ());
// TODO: to remove file dependency include the shader source in the binary
if (!sum_program_->addShaderFile ("sum_score.vert", gllib::VERTEX))
{
std::cout << "Failed loading vertex shader" << std::endl;
exit (-1);
}
// TODO: to remove file dependency include the shader source in the binary
if (!sum_program_->addShaderFile ("sum_score.frag", gllib::FRAGMENT))
{
std::cout << "Failed loading fragment shader" << std::endl;
exit (-1);
}
sum_program_->link ();
// Setup the framebuffer object for rendering
glGenFramebuffers (1, &fbo_);
arrays_ = new GLuint[levels_];
glGenTextures (levels_, arrays_);
int level_width = width_;
int level_height = height_;
for (int i = 0; i < levels_; ++i)
{
level_width = level_width / 2;
level_height = level_height / 2;
glBindTexture (GL_TEXTURE_2D, arrays_[i]);
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_MIN_FILTER, GL_NEAREST);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_NONE);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL);
glTexImage2D (GL_TEXTURE_2D, 0, GL_R32F, level_width, level_height, 0, GL_RED, GL_FLOAT, NULL);
glBindTexture (GL_TEXTURE_2D, 0);
}
}
pcl::simulation::SumReduce::~SumReduce ()
{
glDeleteTextures (levels_, arrays_);
glDeleteFramebuffers (1, &fbo_);
}
void
pcl::simulation::SumReduce::sum (GLuint input_array, float* output_array)
{
if (gllib::getGLError () != GL_NO_ERROR)
{
std::cout << "SumReduce::sum enter" << std::endl;
}
glDisable (GL_DEPTH_TEST);
glBindFramebuffer (GL_FRAMEBUFFER, fbo_);
int width = width_;
int height = height_;
glActiveTexture (GL_TEXTURE0);
glBindTexture (GL_TEXTURE_2D, input_array);
// use program
sum_program_->use ();
glUniform1i (sum_program_->getUniformLocation ("ArraySampler"), 0);
if (gllib::getGLError () != GL_NO_ERROR)
{
std::cout << "SumReduce::sum set sampler" << std::endl;
}
for (int i=0; i < levels_; ++i)
{
glFramebufferTexture2D (GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, arrays_[i], 0);
glDrawBuffer (GL_COLOR_ATTACHMENT0);
glViewport (0, 0, width/2, height/2);
float step_x = 1.0f / float (width);
float step_y = 1.0f / float (height);
sum_program_->setUniform ("step_x", step_x);
sum_program_->setUniform ("step_y", step_y);
//float step_x = 1.0f / static_cast<float> (width);
//float step_y = 1.0f / static_cast<float> (height);
quad_.render ();
if (gllib::getGLError () != GL_NO_ERROR)
{
std::cout << "SumReduce::sum render" << std::endl;
}
width = width / 2;
height = height / 2;
glActiveTexture (GL_TEXTURE0);
glBindTexture (GL_TEXTURE_2D, arrays_[i]);
}
glBindFramebuffer (GL_FRAMEBUFFER, 0);
glActiveTexture (GL_TEXTURE0);
glBindTexture (GL_TEXTURE_2D, 0);
glUseProgram (0);
// Final results is in arrays_[levels_-1]
glActiveTexture (GL_TEXTURE0);
glBindTexture (GL_TEXTURE_2D, arrays_[levels_-1]);
glGetTexImage (GL_TEXTURE_2D, 0, GL_RED, GL_FLOAT, output_array);
glBindTexture (GL_TEXTURE_2D, 0);
if (gllib::getGLError () != GL_NO_ERROR)
{
std::cout << "Error: SumReduce exit" << std::endl;
}
}
<|endoftext|> |
<commit_before>#include<cstdio>
#include<cstring>
#include<iostream>
#include<queue>
#include<utility>
using namespace std;
const int maxn = 100000;
struct node {
int v, c;
node *next;
} edges[maxn * 2 + 10];
node *adj[maxn + 10];
node *end_edge = edges;
inline void addedge(const int &u, const int &v, const int &c) {
node *p = ++end_edge;
p->v = v;
p->c = c;
p->next = adj[u];
adj[u] = p;
}
int d[maxn + 10], path[maxn + 10];
bool vis[maxn + 10];
queue<int> q;
void calculate_distance(int s) {
memset(d, 0, sizeof(d));
d[s] = 1;
q.push(s);
while (!q.empty()) {
int u = q.front();
q.pop();
for (node *p = adj[u]; p != NULL; p = p->next) {
int v = p->v;
if (!d[v]) {
d[v] = d[u] + 1;
q.push(v);
}
}
}
}
queue<pair<int, int> > q2;
void shortest_path(int s) {
memset(path, 0x3f, sizeof(path));
memset(vis, 0, sizeof(vis));
q2.push(make_pair(s, 0));
path[0] = 0;
while (!q2.empty()) {
int u = q2.front().first;
int cy = q2.front().second;
q2.pop();
if (path[d[1] - d[u]] != cy || vis[u]) { continue; }
vis[u] = true;
for (node *p = adj[u]; p != NULL; p = p->next) {
int v = p->v;
int c = p->c;
if (d[u] != d[v] + 1 || path[d[1] - d[v]] <= c) { continue; }
path[d[1] - d[v]] = c;
}
for (node *p = adj[u]; p != NULL; p = p->next) {
int v = p->v;
int c = p->c;
if (d[u] != d[v] + 1 || path[d[1] - d[v]] != c) { continue; }
q2.push(make_pair(v, c));
}
}
d[1] -= 1;
int i;
printf("%d\n", d[1]);
for (int i = 1; i <= d[i]; i ++) {
printf("%d%c", path[i], i == d[1] ? '\n' : ' ');
}
}
int main() {
int u, v, c;
int n, m;
while (scanf("%d%d", &n, &m) == 2) {
memset(adj, 0, sizeof(adj));
end_edge = edges;
for (int i = 1; i <= m; i ++) {
scanf("%d%d%d", &u, &v, &c);
addedge(u, v, c);
addedge(v, u, c);
}
calculate_distance(n);
shortest_path(1);
}
return 0;
}<commit_msg>fixed a bug<commit_after>#include<cstdio>
#include<cstring>
#include<iostream>
#include<queue>
#include<utility>
using namespace std;
const int maxn = 100000;
struct node {
int v, c;
node *next;
} edges[maxn * 4 + 10];
node *adj[maxn + 10];
node *end_edge = edges;
inline void addedge(const int &u, const int &v, const int &c) {
node *p = ++end_edge;
p->v = v;
p->c = c;
p->next = adj[u];
adj[u] = p;
}
int d[maxn + 10], path[maxn + 10];
bool vis[maxn + 10];
queue<int> q;
void calculate_distance(int s) {
memset(d, 0, sizeof(d));
d[s] = 1;
q.push(s);
while (!q.empty()) {
int u = q.front();
q.pop();
for (node *p = adj[u]; p != NULL; p = p->next) {
int v = p->v;
if (!d[v]) {
d[v] = d[u] + 1;
q.push(v);
}
}
}
}
queue<pair<int, int> > q2;
void shortest_path(int s) {
memset(path, 0x3f, sizeof(path));
memset(vis, 0, sizeof(vis));
q2.push(make_pair(s, 0));
path[0] = 0;
while (!q2.empty()) {
int u = q2.front().first;
int cy = q2.front().second;
q2.pop();
if (path[d[1] - d[u]] != cy || vis[u]) { continue; }
vis[u] = true;
for (node *p = adj[u]; p != NULL; p = p->next) {
int v = p->v;
int c = p->c;
if (d[u] != d[v] + 1 || path[d[1] - d[v]] <= c) { continue; }
path[d[1] - d[v]] = c;
}
for (node *p = adj[u]; p != NULL; p = p->next) {
int v = p->v;
int c = p->c;
if (d[u] != d[v] + 1 || path[d[1] - d[v]] != c) { continue; }
q2.push(make_pair(v, c));
}
}
d[1] -= 1;
int i;
printf("%d\n", d[1]);
for (int i = 1; i <= d[1]; i ++) {
printf("%d%c", path[i], i == d[1] ? '\n' : ' ');
}
}
int main() {
int u, v, c;
int n, m;
while (scanf("%d%d", &n, &m) == 2) {
memset(adj, 0, sizeof(adj));
end_edge = edges;
for (int i = 1; i <= m; i ++) {
scanf("%d%d%d", &u, &v, &c);
addedge(u, v, c);
addedge(v, u, c);
}
calculate_distance(n);
shortest_path(1);
}
return 0;
}<|endoftext|> |
<commit_before>/**************************************************************************
* This file is property of and copyright by the ALICE HLT Project *
* ALICE Experiment at CERN, All rights reserved. *
* *
* Primary Author: Mikolaj Krzewicki, [email protected] *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
#include "AliHLTZMQsink.h"
#include "AliHLTErrorGuard.h"
#include "TDatime.h"
#include "TRandom3.h"
#include <TObject.h>
#include <TPRegexp.h>
#include "zmq.h"
#include "AliZMQhelpers.h"
using namespace std;
ClassImp(AliHLTZMQsink)
//______________________________________________________________________________
AliHLTZMQsink::AliHLTZMQsink() :
AliHLTComponent()
, fZMQcontext(NULL)
, fZMQout(NULL)
, fZMQsocketType(-1)
, fZMQoutConfig("PUB")
, fZMQpollIn(kFALSE)
, fPushbackDelayPeriod(-1)
, fIncludePrivateBlocks(kFALSE)
, fZMQneverBlock(kTRUE)
, fSendRunNumber(kTRUE)
, fNskippedErrorMessages(0)
, fZMQerrorMsgSkip(100)
, fSendECSparamString(kFALSE)
, fECSparamString()
{
//ctor
}
//______________________________________________________________________________
AliHLTZMQsink::~AliHLTZMQsink()
{
//dtor
zmq_close(fZMQout);
zmq_ctx_destroy(fZMQcontext);
}
//______________________________________________________________________________
const Char_t* AliHLTZMQsink::GetComponentID()
{
//id
return "ZMQsink";
}
//______________________________________________________________________________
AliHLTComponentDataType AliHLTZMQsink::GetOutputDataType()
{
// default method as sink components do not produce output
AliHLTComponentDataType dt =
{sizeof(AliHLTComponentDataType),
kAliHLTVoidDataTypeID,
kAliHLTVoidDataOrigin};
return dt;
}
//______________________________________________________________________________
void AliHLTZMQsink::GetInputDataTypes( vector<AliHLTComponentDataType>& list)
{
//what data types do we accept
list.clear();
list.push_back(kAliHLTAllDataTypes);
}
//______________________________________________________________________________
void AliHLTZMQsink::GetOutputDataSize( unsigned long& constBase, double& inputMultiplier )
{
// default method as sink components do not produce output
constBase=0;
inputMultiplier=0;
}
//______________________________________________________________________________
AliHLTComponent* AliHLTZMQsink::Spawn()
{
//Spawn a new instance
return new AliHLTZMQsink();
}
//______________________________________________________________________________
Int_t AliHLTZMQsink::DoInit( Int_t /*argc*/, const Char_t** /*argv*/ )
{
// see header file for class documentation
Int_t retCode=0;
//process arguments
if (ProcessOptionString(GetComponentArgs())<0)
{
HLTFatal("wrong config string! %s", GetComponentArgs().c_str());
return -1;
}
int rc = 0;
//init ZMQ context
fZMQcontext = alizmq_context();
HLTMessage(Form("ctx create ptr %p %s",fZMQcontext,(rc<0)?zmq_strerror(errno):""));
if (!fZMQcontext) return -1;
//init ZMQ socket
rc = alizmq_socket_init(fZMQout, fZMQcontext, fZMQoutConfig.Data(), 0, 10 );
if (!fZMQout || rc<0)
{
HLTError("cannot initialize ZMQ socket %s, %s",fZMQoutConfig.Data(),zmq_strerror(errno));
return -1;
}
HLTMessage(Form("socket create ptr %p %s",fZMQout,(rc<0)?zmq_strerror(errno):""));
HLTImportant(Form("ZMQ connected to: %s (%s(id %i)) rc %i %s",fZMQoutConfig.Data(),alizmq_socket_name(fZMQsocketType),fZMQsocketType,rc,(rc<0)?zmq_strerror(errno):""));
return retCode;
}
//______________________________________________________________________________
Int_t AliHLTZMQsink::DoDeinit()
{
// see header file for class documentation
return 0;
}
//______________________________________________________________________________
int AliHLTZMQsink::DoProcessing( const AliHLTComponentEventData& evtData,
const AliHLTComponentBlockData* blocks,
AliHLTComponentTriggerData& /*trigData*/,
AliHLTUInt8_t* /*outputPtr*/,
AliHLTUInt32_t& /*size*/,
AliHLTComponentBlockDataList& outputBlocks,
AliHLTComponentEventDoneData*& /*edd*/ )
{
// see header file for class documentation
Int_t retCode=0;
//create a default selection of any data:
int requestTopicSize=-1;
char requestTopic[kAliHLTComponentDataTypeTopicSize];
memset(requestTopic, '*', kAliHLTComponentDataTypeTopicSize);
int requestSize=-1;
char request[kAliHLTComponentDataTypeTopicSize];
memset(request, '*', kAliHLTComponentDataTypeTopicSize);
int rc = 0;
Bool_t doSend = kTRUE;
Bool_t doSendECSparamString = kFALSE;
//cache an ECS param topic
char ecsParamTopic[kAliHLTComponentDataTypeTopicSize];
DataType2Topic(kAliHLTDataTypeECSParam, ecsParamTopic);
//in case we reply to requests instead of just pushing/publishing
//we poll for requests
if (fZMQpollIn)
{
zmq_pollitem_t items[] = { { fZMQout, 0, ZMQ_POLLIN, 0 } };
zmq_poll(items, 1, 0);
if (items[0].revents & ZMQ_POLLIN)
{
int64_t more=0;
size_t moreSize=sizeof(more);
do //request could be multipart, get all parts
{
requestTopicSize = zmq_recv (fZMQout, requestTopic, kAliHLTComponentDataTypeTopicSize, 0);
zmq_getsockopt(fZMQout, ZMQ_RCVMORE, &more, &moreSize);
if (more) {
requestSize = zmq_recv(fZMQout, request, kAliHLTComponentDataTypeTopicSize, 0);
zmq_getsockopt(fZMQout, ZMQ_RCVMORE, &more, &moreSize);
}
//if request is for ECS params, set the flag
if (*reinterpret_cast<const AliHLTUInt64_t*>(requestTopic) ==
*reinterpret_cast<const AliHLTUInt64_t*>(kAliHLTDataTypeECSParam.fID))
{
doSendECSparamString = kTRUE;
}
} while (more==1);
}
else { doSend = kFALSE; }
}
//if enabled (option -pushback-period), send at most so often
if (fPushbackDelayPeriod>0)
{
TDatime time;
if ((Int_t)time.Get()-fLastPushbackDelayTime<fPushbackDelayPeriod)
{
doSend=kFALSE;
}
}
//caching the ECS param string has to happen for non data event
if (!IsDataEvent())
{
const AliHLTComponentBlockData* inputBlock = NULL;
for (int iBlock = 0;
iBlock < evtData.fBlockCnt;
iBlock++)
{
inputBlock = &blocks[iBlock];
//cache the ECS param string
if (*reinterpret_cast<const AliHLTUInt64_t*>(inputBlock->fDataType.fID) ==
*reinterpret_cast<const AliHLTUInt64_t*>(kAliHLTDataTypeECSParam.fID))
{
const char* ecsparamstr = reinterpret_cast<const char*>(inputBlock->fPtr);
int ecsparamsize = inputBlock->fSize;
if (ecsparamstr[ecsparamsize-1]!=0)
{
fECSparamString.Insert(0, ecsparamstr, ecsparamsize);
fECSparamString += "";
}
else
{
fECSparamString = ecsparamstr;
}
break;
}
}
}
if (doSend)
{
//set the time of current push
if (fPushbackDelayPeriod>0)
{
TDatime time;
fLastPushbackDelayTime=time.Get();
}
//first make a map of selected blocks, and identify the last one
//so we can properly mark the last block for multipart ZMQ sending later
const AliHLTComponentBlockData* inputBlock = NULL;
std::vector<int> selectedBlockIdx;
for (int iBlock = 0;
iBlock < evtData.fBlockCnt;
iBlock++)
{
inputBlock = &blocks[iBlock];
//don't include provate data unless explicitly asked to
if (!fIncludePrivateBlocks &&
*reinterpret_cast<const AliHLTUInt32_t*>(inputBlock->fDataType.fOrigin) ==
*reinterpret_cast<const AliHLTUInt32_t*>(kAliHLTDataOriginPrivate))
{
continue;
}
//check if the data type matches the request
char blockTopic[kAliHLTComponentDataTypeTopicSize];
DataType2Topic(inputBlock->fDataType, blockTopic);
if (Topicncmp(requestTopic, blockTopic, requestTopicSize))
{
selectedBlockIdx.push_back(iBlock);
}
}
int nSelectedBlocks = selectedBlockIdx.size();
int nSentBlocks = 0;
//only send the INFO block if there is something to send
if (fSendRunNumber && nSelectedBlocks>0)
{
string runNumberString = "run=";
char tmp[34];
snprintf(tmp,34,"%i",GetRunNo());
runNumberString+=tmp;
rc = zmq_send(fZMQout, "INFO", 4, ZMQ_SNDMORE);
rc = zmq_send(fZMQout, runNumberString.data(), runNumberString.size(), ZMQ_SNDMORE);
if (rc>=0) nSentBlocks++;
}
//maybe send the ECS param string
//once if requested or always if so configured
if (fSendECSparamString || doSendECSparamString)
{
AliHLTDataTopic topic = kAliHLTDataTypeECSParam;
rc = zmq_send(fZMQout, &topic, sizeof(topic), ZMQ_SNDMORE);
int flags = (nSelectedBlocks==0)?0:ZMQ_SNDMORE;
rc = zmq_send(fZMQout, fECSparamString.Data(), fECSparamString.Length(), flags);
if (rc>=0) nSentBlocks++;
HLTMessage("sent ECS params, as per request, rc=%i",rc);
doSendECSparamString = kFALSE;
}
//send the selected blocks
for (int iSelectedBlock = 0;
iSelectedBlock < selectedBlockIdx.size();
iSelectedBlock++)
{
inputBlock = &blocks[selectedBlockIdx[iSelectedBlock]];
AliHLTDataTopic blockTopic = *inputBlock;
//send:
// first part : AliHLTComponentDataType in string format
// second part: Payload
rc = zmq_send(fZMQout, &blockTopic, sizeof(blockTopic), ZMQ_SNDMORE);
HLTMessage(Form("send topic rc %i %s",rc,(rc<0)?zmq_strerror(errno):""));
int flags = 0;
if (fZMQneverBlock) flags = ZMQ_DONTWAIT;
if (iSelectedBlock < (selectedBlockIdx.size()-1)) flags = ZMQ_SNDMORE;
rc = zmq_send(fZMQout, inputBlock->fPtr, inputBlock->fSize, flags);
if (rc<0 && (fNskippedErrorMessages++ >= fZMQerrorMsgSkip))
{
fNskippedErrorMessages=0;
HLTWarning("error sending data frame %s, %s",
blockTopic.Description().c_str(),
zmq_strerror(errno));
}
else
{
nSentBlocks++;
}
HLTMessage(Form("send data rc %i %s",rc,(rc<0)?zmq_strerror(errno):""));
}
//send an empty message if we really need a reply (ZMQ_REP mode)
//only in case no blocks were sent
if (nSentBlocks == 0 && fZMQsocketType==ZMQ_REP)
{
rc = zmq_send(fZMQout, 0, 0, ZMQ_SNDMORE);
HLTMessage(Form("send endframe rc %i %s",rc,(rc<0)?zmq_strerror(errno):""));
if (rc<0) HLTWarning("error sending dummy REP topic");
rc = zmq_send(fZMQout, 0, 0, 0);
HLTMessage(Form("send endframe rc %i %s",rc,(rc<0)?zmq_strerror(errno):""));
if (rc<0) HLTWarning("error sending dummy REP data");
}
}
outputBlocks.clear();
return retCode;
}
//______________________________________________________________________________
int AliHLTZMQsink::ProcessOption(TString option, TString value)
{
//process option
//to be implemented by the user
if (option.EqualTo("out"))
{
fZMQoutConfig = value;
fZMQsocketType = alizmq_socket_type(value.Data());
switch (fZMQsocketType)
{
case ZMQ_REP:
fZMQpollIn=kTRUE;
break;
case ZMQ_PUSH:
fZMQpollIn=kFALSE;
break;
case ZMQ_PUB:
fZMQpollIn=kFALSE;
break;
default:
HLTFatal("use of socket type %s for a sink is currently unsupported! (config: %s)", alizmq_socket_name(fZMQsocketType), fZMQoutConfig.Data());
return -EINVAL;
}
}
else if (option.EqualTo("SendRunNumber"))
{
fSendRunNumber=(value.EqualTo("0") || value.EqualTo("no") || value.EqualTo("false"))?kFALSE:kTRUE;
}
else if (option.EqualTo("SendECSparamString"))
{
fSendECSparamString=(value.EqualTo("0") || value.EqualTo("no") || value.EqualTo("false"))?kFALSE:kTRUE;
}
else if (option.EqualTo("pushback-period"))
{
HLTMessage(Form("Setting pushback delay to %i", atoi(value.Data())));
fPushbackDelayPeriod = atoi(value.Data());
}
else if (option.EqualTo("IncludePrivateBlocks"))
{
fIncludePrivateBlocks=kTRUE;
}
else if (option.EqualTo("ZMQneverBlock"))
{
if (value.EqualTo("0") || value.EqualTo("no") || value.Contains("false",TString::kIgnoreCase))
fZMQneverBlock = kFALSE;
else if (value.EqualTo("1") || value.EqualTo("yes") || value.Contains("true",TString::kIgnoreCase) )
fZMQneverBlock = kTRUE;
}
else if (option.EqualTo("ZMQerrorMsgSkip"))
{
fZMQerrorMsgSkip = value.Atoi();
}
return 1;
}
<commit_msg>throw error on unrecognized option<commit_after>/**************************************************************************
* This file is property of and copyright by the ALICE HLT Project *
* ALICE Experiment at CERN, All rights reserved. *
* *
* Primary Author: Mikolaj Krzewicki, [email protected] *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
#include "AliHLTZMQsink.h"
#include "AliHLTErrorGuard.h"
#include "TDatime.h"
#include "TRandom3.h"
#include <TObject.h>
#include <TPRegexp.h>
#include "zmq.h"
#include "AliZMQhelpers.h"
using namespace std;
ClassImp(AliHLTZMQsink)
//______________________________________________________________________________
AliHLTZMQsink::AliHLTZMQsink() :
AliHLTComponent()
, fZMQcontext(NULL)
, fZMQout(NULL)
, fZMQsocketType(-1)
, fZMQoutConfig("PUB")
, fZMQpollIn(kFALSE)
, fPushbackDelayPeriod(-1)
, fIncludePrivateBlocks(kFALSE)
, fZMQneverBlock(kTRUE)
, fSendRunNumber(kTRUE)
, fNskippedErrorMessages(0)
, fZMQerrorMsgSkip(100)
, fSendECSparamString(kFALSE)
, fECSparamString()
{
//ctor
}
//______________________________________________________________________________
AliHLTZMQsink::~AliHLTZMQsink()
{
//dtor
zmq_close(fZMQout);
zmq_ctx_destroy(fZMQcontext);
}
//______________________________________________________________________________
const Char_t* AliHLTZMQsink::GetComponentID()
{
//id
return "ZMQsink";
}
//______________________________________________________________________________
AliHLTComponentDataType AliHLTZMQsink::GetOutputDataType()
{
// default method as sink components do not produce output
AliHLTComponentDataType dt =
{sizeof(AliHLTComponentDataType),
kAliHLTVoidDataTypeID,
kAliHLTVoidDataOrigin};
return dt;
}
//______________________________________________________________________________
void AliHLTZMQsink::GetInputDataTypes( vector<AliHLTComponentDataType>& list)
{
//what data types do we accept
list.clear();
list.push_back(kAliHLTAllDataTypes);
}
//______________________________________________________________________________
void AliHLTZMQsink::GetOutputDataSize( unsigned long& constBase, double& inputMultiplier )
{
// default method as sink components do not produce output
constBase=0;
inputMultiplier=0;
}
//______________________________________________________________________________
AliHLTComponent* AliHLTZMQsink::Spawn()
{
//Spawn a new instance
return new AliHLTZMQsink();
}
//______________________________________________________________________________
Int_t AliHLTZMQsink::DoInit( Int_t /*argc*/, const Char_t** /*argv*/ )
{
// see header file for class documentation
Int_t retCode=0;
//process arguments
if (ProcessOptionString(GetComponentArgs())<0)
{
HLTFatal("wrong config string! %s", GetComponentArgs().c_str());
return -1;
}
int rc = 0;
//init ZMQ context
fZMQcontext = alizmq_context();
HLTMessage(Form("ctx create ptr %p %s",fZMQcontext,(rc<0)?zmq_strerror(errno):""));
if (!fZMQcontext) return -1;
//init ZMQ socket
rc = alizmq_socket_init(fZMQout, fZMQcontext, fZMQoutConfig.Data(), 0, 10 );
if (!fZMQout || rc<0)
{
HLTError("cannot initialize ZMQ socket %s, %s",fZMQoutConfig.Data(),zmq_strerror(errno));
return -1;
}
HLTMessage(Form("socket create ptr %p %s",fZMQout,(rc<0)?zmq_strerror(errno):""));
HLTImportant(Form("ZMQ connected to: %s (%s(id %i)) rc %i %s",fZMQoutConfig.Data(),alizmq_socket_name(fZMQsocketType),fZMQsocketType,rc,(rc<0)?zmq_strerror(errno):""));
return retCode;
}
//______________________________________________________________________________
Int_t AliHLTZMQsink::DoDeinit()
{
// see header file for class documentation
return 0;
}
//______________________________________________________________________________
int AliHLTZMQsink::DoProcessing( const AliHLTComponentEventData& evtData,
const AliHLTComponentBlockData* blocks,
AliHLTComponentTriggerData& /*trigData*/,
AliHLTUInt8_t* /*outputPtr*/,
AliHLTUInt32_t& /*size*/,
AliHLTComponentBlockDataList& outputBlocks,
AliHLTComponentEventDoneData*& /*edd*/ )
{
// see header file for class documentation
Int_t retCode=0;
//create a default selection of any data:
int requestTopicSize=-1;
char requestTopic[kAliHLTComponentDataTypeTopicSize];
memset(requestTopic, '*', kAliHLTComponentDataTypeTopicSize);
int requestSize=-1;
char request[kAliHLTComponentDataTypeTopicSize];
memset(request, '*', kAliHLTComponentDataTypeTopicSize);
int rc = 0;
Bool_t doSend = kTRUE;
Bool_t doSendECSparamString = kFALSE;
//cache an ECS param topic
char ecsParamTopic[kAliHLTComponentDataTypeTopicSize];
DataType2Topic(kAliHLTDataTypeECSParam, ecsParamTopic);
//in case we reply to requests instead of just pushing/publishing
//we poll for requests
if (fZMQpollIn)
{
zmq_pollitem_t items[] = { { fZMQout, 0, ZMQ_POLLIN, 0 } };
zmq_poll(items, 1, 0);
if (items[0].revents & ZMQ_POLLIN)
{
int64_t more=0;
size_t moreSize=sizeof(more);
do //request could be multipart, get all parts
{
requestTopicSize = zmq_recv (fZMQout, requestTopic, kAliHLTComponentDataTypeTopicSize, 0);
zmq_getsockopt(fZMQout, ZMQ_RCVMORE, &more, &moreSize);
if (more) {
requestSize = zmq_recv(fZMQout, request, kAliHLTComponentDataTypeTopicSize, 0);
zmq_getsockopt(fZMQout, ZMQ_RCVMORE, &more, &moreSize);
}
//if request is for ECS params, set the flag
if (*reinterpret_cast<const AliHLTUInt64_t*>(requestTopic) ==
*reinterpret_cast<const AliHLTUInt64_t*>(kAliHLTDataTypeECSParam.fID))
{
doSendECSparamString = kTRUE;
}
} while (more==1);
}
else { doSend = kFALSE; }
}
//if enabled (option -pushback-period), send at most so often
if (fPushbackDelayPeriod>0)
{
TDatime time;
if ((Int_t)time.Get()-fLastPushbackDelayTime<fPushbackDelayPeriod)
{
doSend=kFALSE;
}
}
//caching the ECS param string has to happen for non data event
if (!IsDataEvent())
{
const AliHLTComponentBlockData* inputBlock = NULL;
for (int iBlock = 0;
iBlock < evtData.fBlockCnt;
iBlock++)
{
inputBlock = &blocks[iBlock];
//cache the ECS param string
if (*reinterpret_cast<const AliHLTUInt64_t*>(inputBlock->fDataType.fID) ==
*reinterpret_cast<const AliHLTUInt64_t*>(kAliHLTDataTypeECSParam.fID))
{
const char* ecsparamstr = reinterpret_cast<const char*>(inputBlock->fPtr);
int ecsparamsize = inputBlock->fSize;
if (ecsparamstr[ecsparamsize-1]!=0)
{
fECSparamString.Insert(0, ecsparamstr, ecsparamsize);
fECSparamString += "";
}
else
{
fECSparamString = ecsparamstr;
}
break;
}
}
}
if (doSend)
{
//set the time of current push
if (fPushbackDelayPeriod>0)
{
TDatime time;
fLastPushbackDelayTime=time.Get();
}
//first make a map of selected blocks, and identify the last one
//so we can properly mark the last block for multipart ZMQ sending later
const AliHLTComponentBlockData* inputBlock = NULL;
std::vector<int> selectedBlockIdx;
for (int iBlock = 0;
iBlock < evtData.fBlockCnt;
iBlock++)
{
inputBlock = &blocks[iBlock];
//don't include provate data unless explicitly asked to
if (!fIncludePrivateBlocks &&
*reinterpret_cast<const AliHLTUInt32_t*>(inputBlock->fDataType.fOrigin) ==
*reinterpret_cast<const AliHLTUInt32_t*>(kAliHLTDataOriginPrivate))
{
continue;
}
//check if the data type matches the request
char blockTopic[kAliHLTComponentDataTypeTopicSize];
DataType2Topic(inputBlock->fDataType, blockTopic);
if (Topicncmp(requestTopic, blockTopic, requestTopicSize))
{
selectedBlockIdx.push_back(iBlock);
}
}
int nSelectedBlocks = selectedBlockIdx.size();
int nSentBlocks = 0;
//only send the INFO block if there is something to send
if (fSendRunNumber && nSelectedBlocks>0)
{
string runNumberString = "run=";
char tmp[34];
snprintf(tmp,34,"%i",GetRunNo());
runNumberString+=tmp;
rc = zmq_send(fZMQout, "INFO", 4, ZMQ_SNDMORE);
rc = zmq_send(fZMQout, runNumberString.data(), runNumberString.size(), ZMQ_SNDMORE);
if (rc>=0) nSentBlocks++;
}
//maybe send the ECS param string
//once if requested or always if so configured
if (fSendECSparamString || doSendECSparamString)
{
AliHLTDataTopic topic = kAliHLTDataTypeECSParam;
rc = zmq_send(fZMQout, &topic, sizeof(topic), ZMQ_SNDMORE);
int flags = (nSelectedBlocks==0)?0:ZMQ_SNDMORE;
rc = zmq_send(fZMQout, fECSparamString.Data(), fECSparamString.Length(), flags);
if (rc>=0) nSentBlocks++;
HLTMessage("sent ECS params, as per request, rc=%i",rc);
doSendECSparamString = kFALSE;
}
//send the selected blocks
for (int iSelectedBlock = 0;
iSelectedBlock < selectedBlockIdx.size();
iSelectedBlock++)
{
inputBlock = &blocks[selectedBlockIdx[iSelectedBlock]];
AliHLTDataTopic blockTopic = *inputBlock;
//send:
// first part : AliHLTComponentDataType in string format
// second part: Payload
rc = zmq_send(fZMQout, &blockTopic, sizeof(blockTopic), ZMQ_SNDMORE);
HLTMessage(Form("send topic rc %i %s",rc,(rc<0)?zmq_strerror(errno):""));
int flags = 0;
if (fZMQneverBlock) flags = ZMQ_DONTWAIT;
if (iSelectedBlock < (selectedBlockIdx.size()-1)) flags = ZMQ_SNDMORE;
rc = zmq_send(fZMQout, inputBlock->fPtr, inputBlock->fSize, flags);
if (rc<0 && (fNskippedErrorMessages++ >= fZMQerrorMsgSkip))
{
fNskippedErrorMessages=0;
HLTWarning("error sending data frame %s, %s",
blockTopic.Description().c_str(),
zmq_strerror(errno));
}
else
{
nSentBlocks++;
}
HLTMessage(Form("send data rc %i %s",rc,(rc<0)?zmq_strerror(errno):""));
}
//send an empty message if we really need a reply (ZMQ_REP mode)
//only in case no blocks were sent
if (nSentBlocks == 0 && fZMQsocketType==ZMQ_REP)
{
rc = zmq_send(fZMQout, 0, 0, ZMQ_SNDMORE);
HLTMessage(Form("send endframe rc %i %s",rc,(rc<0)?zmq_strerror(errno):""));
if (rc<0) HLTWarning("error sending dummy REP topic");
rc = zmq_send(fZMQout, 0, 0, 0);
HLTMessage(Form("send endframe rc %i %s",rc,(rc<0)?zmq_strerror(errno):""));
if (rc<0) HLTWarning("error sending dummy REP data");
}
}
outputBlocks.clear();
return retCode;
}
//______________________________________________________________________________
int AliHLTZMQsink::ProcessOption(TString option, TString value)
{
//process option
//to be implemented by the user
if (option.EqualTo("out"))
{
fZMQoutConfig = value;
fZMQsocketType = alizmq_socket_type(value.Data());
switch (fZMQsocketType)
{
case ZMQ_REP:
fZMQpollIn=kTRUE;
break;
case ZMQ_PUSH:
fZMQpollIn=kFALSE;
break;
case ZMQ_PUB:
fZMQpollIn=kFALSE;
break;
default:
HLTFatal("use of socket type %s for a sink is currently unsupported! (config: %s)", alizmq_socket_name(fZMQsocketType), fZMQoutConfig.Data());
return -EINVAL;
}
}
else if (option.EqualTo("SendRunNumber"))
{
fSendRunNumber=(value.EqualTo("0") || value.EqualTo("no") || value.EqualTo("false"))?kFALSE:kTRUE;
}
else if (option.EqualTo("SendECSparamString"))
{
fSendECSparamString=(value.EqualTo("0") || value.EqualTo("no") || value.EqualTo("false"))?kFALSE:kTRUE;
}
else if (option.EqualTo("pushback-period"))
{
HLTMessage(Form("Setting pushback delay to %i", atoi(value.Data())));
fPushbackDelayPeriod = atoi(value.Data());
}
else if (option.EqualTo("IncludePrivateBlocks"))
{
fIncludePrivateBlocks=kTRUE;
}
else if (option.EqualTo("ZMQneverBlock"))
{
if (value.EqualTo("0") || value.EqualTo("no") || value.Contains("false",TString::kIgnoreCase))
fZMQneverBlock = kFALSE;
else if (value.EqualTo("1") || value.EqualTo("yes") || value.Contains("true",TString::kIgnoreCase) )
fZMQneverBlock = kTRUE;
}
else if (option.EqualTo("ZMQerrorMsgSkip"))
{
fZMQerrorMsgSkip = value.Atoi();
}
else
{
HLTError("unrecognized option %s", option.Data());
return -1;
}
return 1;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include "Box.h"
using namespace std;
int main() {
const unsigned DIM {3};
MatVec<lengthT,DIM> abmessung{2*m,2*m,2*m};
Kugel<DIM> kugel1{1*kg, .1*m};
Box<DIM> box{abmessung, 10, kugel1};
if(! box.initiate()) return 1;
cout << "after Init\n" << box << '\n';
}
<commit_msg>Kontrolle der Geschwindigkeitsinitiierung<commit_after>#include <iostream>
#include "Box.h"
using namespace std;
int main() {
const unsigned DIM {3};
MatVec<lengthT,DIM> abmessung{2*m,2*m,2*m};
Kugel<DIM> kugel1{1*kg, .1*m};
Box<DIM> box{abmessung, 10, kugel1};
if(! box.initiate()) return 1;
cout << "after Init\n" << box << '\n';
MatVec<velocityT,DIM> vel_com {};
energyT ekin {};
box.unitary([&](const Kugel<DIM>& k){vel_com += k.velocity(); ekin += k.ekin();});
cout << "com Vel: " << vel_com << "\nekin: " << ekin << '\n';
}
<|endoftext|> |
<commit_before>RICHdetect (Int_t evNumber1=0,Int_t evNumber2=0) {
// Dynamically link some shared libs
if (gClassTable->GetID("AliRun") < 0) {
gROOT->LoadMacro("loadlibs.C");
loadlibs();
}
else {
delete gAlice;
gAlice = 0;
}
galice=0;
// Connect the Root Galice file containing Geometry, Kine and Hits
TFile *file = (TFile*)gROOT->GetListOfFiles()->FindObject("galice.root");
if (file) file->Close();
file = new TFile("galice.root","UPDATE");
file->ls();
//printf ("I'm after Map \n");
// Get AliRun object from file or create it if not on file
if (!gAlice) {
gAlice = (AliRun*)file->Get("gAlice");
if (gAlice) printf("AliRun object found on file\n");
if (!gAlice) gAlice = new AliRun("gAlice","RICH reconstruction program");
} else {
delete gAlice;
gAlice = (AliRun*)file->Get("gAlice");
if (gAlice) printf("AliRun object found on file\n");
if (!gAlice) gAlice = new AliRun("gAlice","Alice test program");
}
//printf ("I'm after gAlice \n");
AliRICH *RICH = (AliRICH*) gAlice->GetDetector("RICH");
// Create Recontruction algorithm object
AliRICHDetect *detect = new AliRICHDetect("RICH reconstruction algorithm","Reconstruction");
// Reconstruct
// Event Loop
//
for (int nev=0; nev<= evNumber2; nev++) {
Int_t nparticles = gAlice->GetEvent(nev);
printf("\nProcessing event: %d\n",nev);
printf("\nParticles : %d\n",nparticles);
if (nev < evNumber1) continue;
if (nparticles <= 0) return;
if (RICH) detect->Detect();
char hname[30];
sprintf(hname,"TreeR%d",nev);
gAlice->TreeR()->Write(hname);
gAlice->TreeR()->Reset();
} // event loop
//delete gAlice;
printf("\nEnd of Macro *************************************\n");
}
<commit_msg>New call to reconstuction algorithm.<commit_after>RICHdetect (Int_t evNumber1=0,Int_t evNumber2=0) {
// Dynamically link some shared libs
if (gClassTable->GetID("AliRun") < 0) {
gROOT->LoadMacro("loadlibs.C");
loadlibs();
}
else {
//delete gAlice;
gAlice = 0;
}
// Connect the Root Galice file containing Geometry, Kine and Hits
TFile *file = (TFile*)gROOT->GetListOfFiles()->FindObject("galice.root");
if (file) file->Close();
file = new TFile("galice.root","UPDATE");
file->ls();
//printf ("I'm after Map \n");
// Get AliRun object from file or create it if not on file
if (!gAlice) {
gAlice = (AliRun*)file->Get("gAlice");
if (gAlice) printf("AliRun object found on file\n");
if (!gAlice) gAlice = new AliRun("gAlice","RICH reconstruction program");
} else {
delete gAlice;
gAlice = (AliRun*)file->Get("gAlice");
if (gAlice) printf("AliRun object found on file\n");
if (!gAlice) gAlice = new AliRun("gAlice","Alice test program");
}
//printf ("I'm after gAlice \n");
AliRICH *RICH = (AliRICH*) gAlice->GetDetector("RICH");
// Create Recontruction algorithm object
AliRICHDetect *detect = new AliRICHDetect("RICH reconstruction algorithm","Reconstruction");
// Reconstruct
// Event Loop
//
for (int nev=0; nev<= evNumber2; nev++) {
Int_t nparticles = gAlice->GetEvent(nev);
printf("\nProcessing event: %d\n",nev);
printf("\nParticles : %d\n",nparticles);
if (nev < evNumber1) continue;
if (nparticles <= 0) return;
if (RICH) detect->Detect(nev);
char hname[30];
sprintf(hname,"TreeR%d",nev);
gAlice->TreeR()->Write(hname);
gAlice->TreeR()->Reset();
} // event loop
//delete gAlice;
printf("\nEnd of Macro *************************************\n");
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkImageMaskBits.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkImageMaskBits.h"
#include "vtkObjectFactory.h"
#include <math.h>
vtkCxxRevisionMacro(vtkImageMaskBits, "1.12");
vtkStandardNewMacro(vtkImageMaskBits);
vtkImageMaskBits::vtkImageMaskBits()
{
this->Operation = VTK_AND;
this->Masks[0] = 0xffffffff;
this->Masks[1] = 0xffffffff;
this->Masks[2] = 0xffffffff;
this->Masks[3] = 0xffffffff;
}
//----------------------------------------------------------------------------
// This execute method handles boundaries.
// it handles boundaries. Pixels are just replicated to get values
// out of extent.
template <class T>
static void vtkImageMaskBitsExecute(vtkImageMaskBits *self,
vtkImageData *inData, T *inPtr,
vtkImageData *outData, T *outPtr,
int outExt[6], int id)
{
int idxX, idxY, idxZ, idxC;
int maxX, maxY, maxZ, maxC;
int inIncX, inIncY, inIncZ;
int outIncX, outIncY, outIncZ;
unsigned long count = 0;
unsigned long target;
unsigned int *masks;
int operation;
// find the region to loop over
maxC = inData->GetNumberOfScalarComponents();
maxX = outExt[1] - outExt[0];
maxY = outExt[3] - outExt[2];
maxZ = outExt[5] - outExt[4];
target = (unsigned long)((maxZ+1)*(maxY+1)/50.0);
target++;
// Get increments to march through data
inData->GetContinuousIncrements(outExt, inIncX, inIncY, inIncZ);
outData->GetContinuousIncrements(outExt, outIncX, outIncY, outIncZ);
masks = self->GetMasks();
operation = self->GetOperation();
// Loop through ouput pixels
for (idxZ = 0; idxZ <= maxZ; idxZ++)
{
for (idxY = 0; !self->AbortExecute && idxY <= maxY; idxY++)
{
if (!id)
{
if (!(count%target))
{
self->UpdateProgress(count/(50.0*target));
}
count++;
}
switch (operation)
{
case VTK_AND:
for (idxX = 0; idxX <= maxX; idxX++)
{
for (idxC = 0; idxC < maxC; idxC++)
{
// Pixel operation
*outPtr++ = *inPtr++ & (T) masks[idxC];
}
}
break;
case VTK_OR:
for (idxX = 0; idxX <= maxX; idxX++)
{
for (idxC = 0; idxC < maxC; idxC++)
{
// Pixel operation
*outPtr++ = *inPtr++ | (T) masks[idxC];
}
}
break;
case VTK_XOR:
for (idxX = 0; idxX <= maxX; idxX++)
{
for (idxC = 0; idxC < maxC; idxC++)
{
// Pixel operation
*outPtr++ = *inPtr++ ^ (T) masks[idxC];
}
}
break;
case VTK_NAND:
for (idxX = 0; idxX <= maxX; idxX++)
{
for (idxC = 0; idxC < maxC; idxC++)
{
// Pixel operation
*outPtr++ = ~(*inPtr++ & (T) masks[idxC]);
}
}
break;
case VTK_NOR:
for (idxX = 0; idxX <= maxX; idxX++)
{
for (idxC = 0; idxC < maxC; idxC++)
{
// Pixel operation
*outPtr++ = ~(*inPtr++ | (T) masks[idxC]);
}
}
break;
}
outPtr += outIncY;
inPtr += inIncY;
}
outPtr += outIncZ;
inPtr += inIncZ;
}
}
//----------------------------------------------------------------------------
// This method contains a switch statement that calls the correct
// templated function for the input data type. The output data
// must match input type. This method does handle boundary conditions.
void vtkImageMaskBits::ThreadedExecute(vtkImageData *inData,
vtkImageData *outData,
int outExt[6], int id)
{
void *inPtr = inData->GetScalarPointerForExtent(outExt);
void *outPtr = outData->GetScalarPointerForExtent(outExt);
vtkDebugMacro(<< "Execute: inData = " << inData
<< ", outData = " << outData);
// this filter expects that input is the same type as output.
if (inData->GetScalarType() != outData->GetScalarType())
{
vtkErrorMacro(<< "Execute: input ScalarType, " << inData->GetScalarType()
<< ", must match out ScalarType " << outData->GetScalarType());
return;
}
switch (inData->GetScalarType())
{
case VTK_INT:
vtkImageMaskBitsExecute(this,
inData, (int *)(inPtr),
outData, (int *)(outPtr), outExt, id);
break;
case VTK_UNSIGNED_INT:
vtkImageMaskBitsExecute(this,
inData, (unsigned int *)(inPtr),
outData, (unsigned int *)(outPtr), outExt, id);
break;
case VTK_LONG:
vtkImageMaskBitsExecute(this,
inData, (long *)(inPtr),
outData, (long *)(outPtr), outExt, id);
break;
case VTK_UNSIGNED_LONG:
vtkImageMaskBitsExecute(this,
inData, (unsigned long *)(inPtr),
outData, (unsigned long *)(outPtr), outExt, id);
break;
case VTK_SHORT:
vtkImageMaskBitsExecute(this,
inData, (short *)(inPtr),
outData, (short *)(outPtr), outExt, id);
break;
case VTK_UNSIGNED_SHORT:
vtkImageMaskBitsExecute(this,
inData, (unsigned short *)(inPtr),
outData, (unsigned short *)(outPtr),
outExt, id);
break;
case VTK_CHAR:
vtkImageMaskBitsExecute(this,
inData, (char *)(inPtr),
outData, (char *)(outPtr), outExt, id);
break;
case VTK_UNSIGNED_CHAR:
vtkImageMaskBitsExecute(this,
inData, (unsigned char *)(inPtr),
outData, (unsigned char *)(outPtr), outExt, id);
break;
default:
vtkErrorMacro(<< "Execute: ScalarType can only be [unsigned] char, [unsigned] short, "
<< "[unsigned] int, or [unsigned] long.");
return;
}
}
void vtkImageMaskBits::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "Operation: " << this->Operation << "\n";
os << indent << "Masks: (" << this->Masks[0] << ", " << this->Masks[1] << ", "
<< this->Masks[2] << ", " << this->Masks[3] << ")" << endl;
}
<commit_msg>converted to iterator<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkImageMaskBits.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkImageMaskBits.h"
#include "vtkObjectFactory.h"
#include "vtkImageProgressIterator.h"
#include <math.h>
vtkCxxRevisionMacro(vtkImageMaskBits, "1.13");
vtkStandardNewMacro(vtkImageMaskBits);
vtkImageMaskBits::vtkImageMaskBits()
{
this->Operation = VTK_AND;
this->Masks[0] = 0xffffffff;
this->Masks[1] = 0xffffffff;
this->Masks[2] = 0xffffffff;
this->Masks[3] = 0xffffffff;
}
//----------------------------------------------------------------------------
// This execute method handles boundaries.
// it handles boundaries. Pixels are just replicated to get values
// out of extent.
template <class T>
static void vtkImageMaskBitsExecute(vtkImageMaskBits *self,
vtkImageData *inData,
vtkImageData *outData,
int outExt[6], int id, T *)
{
vtkImageIterator<T> inIt(inData, outExt);
vtkImageProgressIterator<T> outIt(outData, outExt, self, id);
int idxC, maxC;
unsigned int *masks;
int operation;
// find the region to loop over
maxC = inData->GetNumberOfScalarComponents();
masks = self->GetMasks();
operation = self->GetOperation();
// Loop through ouput pixels
while (!outIt.IsAtEnd())
{
T* inSI = inIt.BeginSpan();
T* outSI = outIt.BeginSpan();
T* outSIEnd = outIt.EndSpan();
switch (operation)
{
case VTK_AND:
while (outSI != outSIEnd)
{
for (idxC = 0; idxC < maxC; idxC++)
{
// Pixel operation
*outSI++ = *inSI++ & (T) masks[idxC];
}
}
break;
case VTK_OR:
while (outSI != outSIEnd)
{
for (idxC = 0; idxC < maxC; idxC++)
{
// Pixel operation
*outSI++ = *inSI++ | (T) masks[idxC];
}
}
break;
case VTK_XOR:
while (outSI != outSIEnd)
{
for (idxC = 0; idxC < maxC; idxC++)
{
// Pixel operation
*outSI++ = *inSI++ ^ (T) masks[idxC];
}
}
break;
case VTK_NAND:
while (outSI != outSIEnd)
{
for (idxC = 0; idxC < maxC; idxC++)
{
// Pixel operation
*outSI++ = ~(*inSI++ & (T) masks[idxC]);
}
}
break;
case VTK_NOR:
while (outSI != outSIEnd)
{
for (idxC = 0; idxC < maxC; idxC++)
{
// Pixel operation
*outSI++ = ~(*inSI++ | (T) masks[idxC]);
}
}
break;
}
inIt.NextSpan();
outIt.NextSpan();
}
}
//----------------------------------------------------------------------------
// This method contains a switch statement that calls the correct
// templated function for the input data type. The output data
// must match input type. This method does handle boundary conditions.
void vtkImageMaskBits::ThreadedExecute(vtkImageData *inData,
vtkImageData *outData,
int outExt[6], int id)
{
vtkDebugMacro(<< "Execute: inData = " << inData
<< ", outData = " << outData);
// this filter expects that input is the same type as output.
if (inData->GetScalarType() != outData->GetScalarType())
{
vtkErrorMacro(<< "Execute: input ScalarType, " << inData->GetScalarType()
<< ", must match out ScalarType " << outData->GetScalarType());
return;
}
switch (inData->GetScalarType())
{
case VTK_INT:
vtkImageMaskBitsExecute(this, inData, outData, outExt, id,
static_cast<int *>(0));
break;
case VTK_UNSIGNED_INT:
vtkImageMaskBitsExecute(this, inData, outData, outExt, id,
static_cast<unsigned int *>(0));
break;
case VTK_LONG:
vtkImageMaskBitsExecute(this, inData, outData, outExt, id,
static_cast<long *>(0));
break;
case VTK_UNSIGNED_LONG:
vtkImageMaskBitsExecute(this, inData, outData, outExt, id,
static_cast<unsigned long *>(0));
break;
case VTK_SHORT:
vtkImageMaskBitsExecute(this, inData, outData, outExt, id,
static_cast<short *>(0));
break;
case VTK_UNSIGNED_SHORT:
vtkImageMaskBitsExecute(this, inData, outData, outExt, id,
static_cast<unsigned short *>(0));
break;
case VTK_CHAR:
vtkImageMaskBitsExecute(this, inData, outData, outExt, id,
static_cast<char *>(0));
break;
case VTK_UNSIGNED_CHAR:
vtkImageMaskBitsExecute(this, inData, outData, outExt, id,
static_cast<unsigned char *>(0));
break;
default:
vtkErrorMacro(<< "Execute: ScalarType can only be [unsigned] char, [unsigned] short, "
<< "[unsigned] int, or [unsigned] long.");
return;
}
}
void vtkImageMaskBits::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "Operation: " << this->Operation << "\n";
os << indent << "Masks: (" << this->Masks[0] << ", " << this->Masks[1] << ", "
<< this->Masks[2] << ", " << this->Masks[3] << ")" << endl;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2014 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#if SK_SUPPORT_GPU
#include "GrLayerHoister.h"
#include "GrRecordReplaceDraw.h"
#endif
#include "SkCanvas.h"
#include "SkMultiPictureDraw.h"
#include "SkPicture.h"
#include "SkTaskGroup.h"
void SkMultiPictureDraw::DrawData::draw() {
fCanvas->drawPicture(fPicture, &fMatrix, fPaint);
}
void SkMultiPictureDraw::DrawData::init(SkCanvas* canvas, const SkPicture* picture,
const SkMatrix* matrix, const SkPaint* paint) {
fPicture = SkRef(picture);
fCanvas = SkRef(canvas);
if (matrix) {
fMatrix = *matrix;
} else {
fMatrix.setIdentity();
}
if (paint) {
fPaint = SkNEW_ARGS(SkPaint, (*paint));
} else {
fPaint = NULL;
}
}
void SkMultiPictureDraw::DrawData::Reset(SkTDArray<DrawData>& data) {
for (int i = 0; i < data.count(); ++i) {
data[i].fPicture->unref();
data[i].fCanvas->unref();
SkDELETE(data[i].fPaint);
}
data.rewind();
}
//////////////////////////////////////////////////////////////////////////////////////
SkMultiPictureDraw::SkMultiPictureDraw(int reserve) {
if (reserve > 0) {
fGPUDrawData.setReserve(reserve);
fThreadSafeDrawData.setReserve(reserve);
}
}
void SkMultiPictureDraw::reset() {
DrawData::Reset(fGPUDrawData);
DrawData::Reset(fThreadSafeDrawData);
}
void SkMultiPictureDraw::add(SkCanvas* canvas,
const SkPicture* picture,
const SkMatrix* matrix,
const SkPaint* paint) {
if (NULL == canvas || NULL == picture) {
SkDEBUGFAIL("parameters to SkMultiPictureDraw::add should be non-NULL");
return;
}
SkTDArray<DrawData>& array = canvas->getGrContext() ? fGPUDrawData : fThreadSafeDrawData;
array.append()->init(canvas, picture, matrix, paint);
}
class AutoMPDReset : SkNoncopyable {
SkMultiPictureDraw* fMPD;
public:
AutoMPDReset(SkMultiPictureDraw* mpd) : fMPD(mpd) {}
~AutoMPDReset() { fMPD->reset(); }
};
void SkMultiPictureDraw::draw() {
AutoMPDReset mpdreset(this);
// we place the taskgroup after the MPDReset, to ensure that we don't delete the DrawData
// objects until after we're finished the tasks (which have pointers to the data).
SkTaskGroup group;
group.batch(DrawData::Draw, fThreadSafeDrawData.begin(), fThreadSafeDrawData.count());
// we deliberately don't call wait() here, since the destructor will do that, this allows us
// to continue processing gpu-data without having to wait on the cpu tasks.
const int count = fGPUDrawData.count();
if (0 == count) {
return;
}
#if !defined(SK_IGNORE_GPU_LAYER_HOISTING) && SK_SUPPORT_GPU
GrContext* context = fGPUDrawData[0].fCanvas->getGrContext();
SkASSERT(context);
// Start by collecting all the layers that are going to be atlased and render
// them (if necessary). Hoisting the free floating layers is deferred until
// drawing the canvas that requires them.
SkTDArray<GrHoistedLayer> atlasedNeedRendering, atlasedRecycled;
for (int i = 0; i < count; ++i) {
const DrawData& data = fGPUDrawData[i];
// we only expect 1 context for all the canvases
SkASSERT(data.fCanvas->getGrContext() == context);
if (!data.fPaint && data.fMatrix.isIdentity()) {
// TODO: this path always tries to optimize pictures. Should we
// switch to this API approach (vs. SkCanvas::EXPERIMENTAL_optimize)?
data.fCanvas->EXPERIMENTAL_optimize(data.fPicture);
SkRect clipBounds;
if (!data.fCanvas->getClipBounds(&clipBounds)) {
continue;
}
// TODO: sorting the cacheable layers from smallest to largest
// would improve the packing and reduce the number of swaps
// TODO: another optimization would be to make a first pass to
// lock any required layer that is already in the atlas
GrLayerHoister::FindLayersToAtlas(context, data.fPicture,
clipBounds,
&atlasedNeedRendering, &atlasedRecycled);
}
}
GrLayerHoister::DrawLayersToAtlas(context, atlasedNeedRendering);
SkTDArray<GrHoistedLayer> needRendering, recycled;
#endif
for (int i = 0; i < count; ++i) {
const DrawData& data = fGPUDrawData[i];
SkCanvas* canvas = data.fCanvas;
const SkPicture* picture = data.fPicture;
#if !defined(SK_IGNORE_GPU_LAYER_HOISTING) && SK_SUPPORT_GPU
if (!data.fPaint && data.fMatrix.isIdentity()) {
SkRect clipBounds;
if (!canvas->getClipBounds(&clipBounds)) {
continue;
}
// Find the layers required by this canvas. It will return atlased
// layers in the 'recycled' list since they have already been drawn.
GrLayerHoister::FindLayersToHoist(context, picture,
clipBounds, &needRendering, &recycled);
GrLayerHoister::DrawLayers(context, needRendering);
GrReplacements replacements;
GrLayerHoister::ConvertLayersToReplacements(needRendering, &replacements);
GrLayerHoister::ConvertLayersToReplacements(recycled, &replacements);
const SkMatrix initialMatrix = canvas->getTotalMatrix();
// Render the entire picture using new layers
GrRecordReplaceDraw(picture, canvas, &replacements, initialMatrix, NULL);
GrLayerHoister::UnlockLayers(context, needRendering);
GrLayerHoister::UnlockLayers(context, recycled);
needRendering.rewind();
recycled.rewind();
} else
#endif
{
canvas->drawPicture(picture, &data.fMatrix, data.fPaint);
}
}
#if !defined(SK_IGNORE_GPU_LAYER_HOISTING) && SK_SUPPORT_GPU
GrLayerHoister::UnlockLayers(context, atlasedNeedRendering);
GrLayerHoister::UnlockLayers(context, atlasedRecycled);
#if !GR_CACHE_HOISTED_LAYERS
GrLayerHoister::PurgeCache(context);
#endif
#endif
}
<commit_msg>Include SkTypes so that SK_SUPPORT_GPU is meaningful.<commit_after>/*
* Copyright 2014 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
// Need to include something before #if SK_SUPPORT_GPU so that the Android
// framework build, which gets its defines from SkTypes rather than a makefile,
// has the definition before checking it.
#include "SkCanvas.h"
#include "SkMultiPictureDraw.h"
#include "SkPicture.h"
#include "SkTaskGroup.h"
#if SK_SUPPORT_GPU
#include "GrLayerHoister.h"
#include "GrRecordReplaceDraw.h"
#endif
void SkMultiPictureDraw::DrawData::draw() {
fCanvas->drawPicture(fPicture, &fMatrix, fPaint);
}
void SkMultiPictureDraw::DrawData::init(SkCanvas* canvas, const SkPicture* picture,
const SkMatrix* matrix, const SkPaint* paint) {
fPicture = SkRef(picture);
fCanvas = SkRef(canvas);
if (matrix) {
fMatrix = *matrix;
} else {
fMatrix.setIdentity();
}
if (paint) {
fPaint = SkNEW_ARGS(SkPaint, (*paint));
} else {
fPaint = NULL;
}
}
void SkMultiPictureDraw::DrawData::Reset(SkTDArray<DrawData>& data) {
for (int i = 0; i < data.count(); ++i) {
data[i].fPicture->unref();
data[i].fCanvas->unref();
SkDELETE(data[i].fPaint);
}
data.rewind();
}
//////////////////////////////////////////////////////////////////////////////////////
SkMultiPictureDraw::SkMultiPictureDraw(int reserve) {
if (reserve > 0) {
fGPUDrawData.setReserve(reserve);
fThreadSafeDrawData.setReserve(reserve);
}
}
void SkMultiPictureDraw::reset() {
DrawData::Reset(fGPUDrawData);
DrawData::Reset(fThreadSafeDrawData);
}
void SkMultiPictureDraw::add(SkCanvas* canvas,
const SkPicture* picture,
const SkMatrix* matrix,
const SkPaint* paint) {
if (NULL == canvas || NULL == picture) {
SkDEBUGFAIL("parameters to SkMultiPictureDraw::add should be non-NULL");
return;
}
SkTDArray<DrawData>& array = canvas->getGrContext() ? fGPUDrawData : fThreadSafeDrawData;
array.append()->init(canvas, picture, matrix, paint);
}
class AutoMPDReset : SkNoncopyable {
SkMultiPictureDraw* fMPD;
public:
AutoMPDReset(SkMultiPictureDraw* mpd) : fMPD(mpd) {}
~AutoMPDReset() { fMPD->reset(); }
};
void SkMultiPictureDraw::draw() {
AutoMPDReset mpdreset(this);
// we place the taskgroup after the MPDReset, to ensure that we don't delete the DrawData
// objects until after we're finished the tasks (which have pointers to the data).
SkTaskGroup group;
group.batch(DrawData::Draw, fThreadSafeDrawData.begin(), fThreadSafeDrawData.count());
// we deliberately don't call wait() here, since the destructor will do that, this allows us
// to continue processing gpu-data without having to wait on the cpu tasks.
const int count = fGPUDrawData.count();
if (0 == count) {
return;
}
#if !defined(SK_IGNORE_GPU_LAYER_HOISTING) && SK_SUPPORT_GPU
GrContext* context = fGPUDrawData[0].fCanvas->getGrContext();
SkASSERT(context);
// Start by collecting all the layers that are going to be atlased and render
// them (if necessary). Hoisting the free floating layers is deferred until
// drawing the canvas that requires them.
SkTDArray<GrHoistedLayer> atlasedNeedRendering, atlasedRecycled;
for (int i = 0; i < count; ++i) {
const DrawData& data = fGPUDrawData[i];
// we only expect 1 context for all the canvases
SkASSERT(data.fCanvas->getGrContext() == context);
if (!data.fPaint && data.fMatrix.isIdentity()) {
// TODO: this path always tries to optimize pictures. Should we
// switch to this API approach (vs. SkCanvas::EXPERIMENTAL_optimize)?
data.fCanvas->EXPERIMENTAL_optimize(data.fPicture);
SkRect clipBounds;
if (!data.fCanvas->getClipBounds(&clipBounds)) {
continue;
}
// TODO: sorting the cacheable layers from smallest to largest
// would improve the packing and reduce the number of swaps
// TODO: another optimization would be to make a first pass to
// lock any required layer that is already in the atlas
GrLayerHoister::FindLayersToAtlas(context, data.fPicture,
clipBounds,
&atlasedNeedRendering, &atlasedRecycled);
}
}
GrLayerHoister::DrawLayersToAtlas(context, atlasedNeedRendering);
SkTDArray<GrHoistedLayer> needRendering, recycled;
#endif
for (int i = 0; i < count; ++i) {
const DrawData& data = fGPUDrawData[i];
SkCanvas* canvas = data.fCanvas;
const SkPicture* picture = data.fPicture;
#if !defined(SK_IGNORE_GPU_LAYER_HOISTING) && SK_SUPPORT_GPU
if (!data.fPaint && data.fMatrix.isIdentity()) {
SkRect clipBounds;
if (!canvas->getClipBounds(&clipBounds)) {
continue;
}
// Find the layers required by this canvas. It will return atlased
// layers in the 'recycled' list since they have already been drawn.
GrLayerHoister::FindLayersToHoist(context, picture,
clipBounds, &needRendering, &recycled);
GrLayerHoister::DrawLayers(context, needRendering);
GrReplacements replacements;
GrLayerHoister::ConvertLayersToReplacements(needRendering, &replacements);
GrLayerHoister::ConvertLayersToReplacements(recycled, &replacements);
const SkMatrix initialMatrix = canvas->getTotalMatrix();
// Render the entire picture using new layers
GrRecordReplaceDraw(picture, canvas, &replacements, initialMatrix, NULL);
GrLayerHoister::UnlockLayers(context, needRendering);
GrLayerHoister::UnlockLayers(context, recycled);
needRendering.rewind();
recycled.rewind();
} else
#endif
{
canvas->drawPicture(picture, &data.fMatrix, data.fPaint);
}
}
#if !defined(SK_IGNORE_GPU_LAYER_HOISTING) && SK_SUPPORT_GPU
GrLayerHoister::UnlockLayers(context, atlasedNeedRendering);
GrLayerHoister::UnlockLayers(context, atlasedRecycled);
#if !GR_CACHE_HOISTED_LAYERS
GrLayerHoister::PurgeCache(context);
#endif
#endif
}
<|endoftext|> |
<commit_before>/*
* ProgramOptions.cpp
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include <core/ProgramOptions.hpp>
#include <string>
#include <iostream>
#include <boost/foreach.hpp>
#include <core/Error.hpp>
#include <core/Log.hpp>
#include <core/FilePath.hpp>
#include <core/ProgramStatus.hpp>
#include <core/system/System.hpp>
using namespace boost::program_options ;
namespace core {
namespace program_options {
namespace {
bool validateOptionsProvided(const variables_map& vm,
const options_description& optionsDescription,
const std::string& configFile = std::string())
{
BOOST_FOREACH( const boost::shared_ptr<option_description>& pOptionsDesc,
optionsDescription.options() )
{
std::string optionName = pOptionsDesc->long_name();
if ( !(vm.count(optionName)) )
{
std::string msg = "Required option " + optionName + " not specified";
if (!configFile.empty())
msg += " in config file " + configFile;
reportError(msg, ERROR_LOCATION);
return false ;
}
}
// all options validated
return true;
}
}
void reportError(const std::string& errorMessage, const ErrorLocation& location)
{
if (core::system::stderrIsTerminal())
std::cerr << errorMessage << std::endl;
else
core::log::logErrorMessage(errorMessage, location);
}
ProgramStatus read(const OptionsDescription& optionsDescription,
int argc,
char * const argv[],
bool* pHelp)
{
std::string configFile;
try
{
// general options
options_description general("general") ;
general.add_options()
("help",
value<bool>(pHelp)->default_value(false),
"print help message")
("test-config", "test to ensure the config file is valid")
("config-file",
value<std::string>(&configFile)->default_value(
optionsDescription.defaultConfigFilePath),
std::string("configuration file").c_str());
// make copy of command line options so we can add general to them
options_description commandLineOptions(optionsDescription.commandLine);
commandLineOptions.add(general);
// parse the command line
variables_map vm ;
command_line_parser parser(argc, const_cast<char**>(argv));
store(parser.options(commandLineOptions).
positional(optionsDescription.positionalOptions).run(), vm);
notify(vm) ;
// "none" is a special sentinel value for the config-file which
// explicitly prevents us from reading the defautl config file above
// now that we are past that we can reset it to empty
if (configFile == "none")
configFile = "";
// open the config file
if (!configFile.empty())
{
boost::shared_ptr<std::istream> pIfs;
Error error = FilePath(configFile).open_r(&pIfs);
if (error)
{
reportError("Unable to open config file: " + configFile,
ERROR_LOCATION);
return ProgramStatus::exitFailure() ;
}
try
{
// parse config file
store(parse_config_file(*pIfs, optionsDescription.configFile), vm) ;
notify(vm) ;
}
catch(const std::exception& e)
{
reportError(
"IO error reading " + configFile + ": " + std::string(e.what()),
ERROR_LOCATION);
return ProgramStatus::exitFailure();
}
}
// show help if requested
if (vm.count("help"))
{
std::cout << commandLineOptions ;
return ProgramStatus::exitSuccess() ;
}
// validate all options are provided
else
{
if (!validateOptionsProvided(vm, optionsDescription.commandLine))
return ProgramStatus::exitFailure();
if (!configFile.empty())
{
if (!validateOptionsProvided(vm,
optionsDescription.configFile,
configFile))
return ProgramStatus::exitFailure();
}
}
// if this was a config-test then return exitSuccess, otherwise run
if (vm.count("test-config"))
{
return ProgramStatus::exitSuccess();
}
else
{
return ProgramStatus::run() ;
}
}
catch(const boost::program_options::error& e)
{
std::string msg(e.what());
if (!configFile.empty())
msg += " in config file " + configFile;
reportError(msg, ERROR_LOCATION);
return ProgramStatus::exitFailure();
}
CATCH_UNEXPECTED_EXCEPTION
// keep compiler happy
return ProgramStatus::exitFailure();
}
} // namespace program_options
} // namespace core
<commit_msg>nicer error message for config file error<commit_after>/*
* ProgramOptions.cpp
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include <core/ProgramOptions.hpp>
#include <string>
#include <iostream>
#include <boost/foreach.hpp>
#include <core/Error.hpp>
#include <core/Log.hpp>
#include <core/FilePath.hpp>
#include <core/ProgramStatus.hpp>
#include <core/system/System.hpp>
using namespace boost::program_options ;
namespace core {
namespace program_options {
namespace {
bool validateOptionsProvided(const variables_map& vm,
const options_description& optionsDescription,
const std::string& configFile = std::string())
{
BOOST_FOREACH( const boost::shared_ptr<option_description>& pOptionsDesc,
optionsDescription.options() )
{
std::string optionName = pOptionsDesc->long_name();
if ( !(vm.count(optionName)) )
{
std::string msg = "Required option " + optionName + " not specified";
if (!configFile.empty())
msg += " in config file " + configFile;
reportError(msg, ERROR_LOCATION);
return false ;
}
}
// all options validated
return true;
}
}
void reportError(const std::string& errorMessage, const ErrorLocation& location)
{
if (core::system::stderrIsTerminal())
std::cerr << errorMessage << std::endl;
else
core::log::logErrorMessage(errorMessage, location);
}
ProgramStatus read(const OptionsDescription& optionsDescription,
int argc,
char * const argv[],
bool* pHelp)
{
std::string configFile;
try
{
// general options
options_description general("general") ;
general.add_options()
("help",
value<bool>(pHelp)->default_value(false),
"print help message")
("test-config", "test to ensure the config file is valid")
("config-file",
value<std::string>(&configFile)->default_value(
optionsDescription.defaultConfigFilePath),
std::string("configuration file").c_str());
// make copy of command line options so we can add general to them
options_description commandLineOptions(optionsDescription.commandLine);
commandLineOptions.add(general);
// parse the command line
variables_map vm ;
command_line_parser parser(argc, const_cast<char**>(argv));
store(parser.options(commandLineOptions).
positional(optionsDescription.positionalOptions).run(), vm);
notify(vm) ;
// "none" is a special sentinel value for the config-file which
// explicitly prevents us from reading the defautl config file above
// now that we are past that we can reset it to empty
if (configFile == "none")
configFile = "";
// open the config file
if (!configFile.empty())
{
boost::shared_ptr<std::istream> pIfs;
Error error = FilePath(configFile).open_r(&pIfs);
if (error)
{
reportError("Unable to open config file: " + configFile,
ERROR_LOCATION);
return ProgramStatus::exitFailure() ;
}
try
{
// parse config file
store(parse_config_file(*pIfs, optionsDescription.configFile), vm) ;
notify(vm) ;
}
catch(const std::exception& e)
{
reportError(
"Error reading " + configFile + ": " + std::string(e.what()),
ERROR_LOCATION);
return ProgramStatus::exitFailure();
}
}
// show help if requested
if (vm.count("help"))
{
std::cout << commandLineOptions ;
return ProgramStatus::exitSuccess() ;
}
// validate all options are provided
else
{
if (!validateOptionsProvided(vm, optionsDescription.commandLine))
return ProgramStatus::exitFailure();
if (!configFile.empty())
{
if (!validateOptionsProvided(vm,
optionsDescription.configFile,
configFile))
return ProgramStatus::exitFailure();
}
}
// if this was a config-test then return exitSuccess, otherwise run
if (vm.count("test-config"))
{
return ProgramStatus::exitSuccess();
}
else
{
return ProgramStatus::run() ;
}
}
catch(const boost::program_options::error& e)
{
std::string msg(e.what());
if (!configFile.empty())
msg += " in config file " + configFile;
reportError(msg, ERROR_LOCATION);
return ProgramStatus::exitFailure();
}
CATCH_UNEXPECTED_EXCEPTION
// keep compiler happy
return ProgramStatus::exitFailure();
}
} // namespace program_options
} // namespace core
<|endoftext|> |
<commit_before>#include<ros/ros.h>
#include "reuleaux/WorkSpace.h"
#include<octomap/octomap.h>
#include<octomap/MapCollection.h>
#include <octomap/math/Utils.h>
#include <reuleaux/sphere_discretization.h>
#include <tf2/LinearMath/Quaternion.h>
#include "geometry_msgs/PoseArray.h"
#include<map>
#include<reuleaux/kinematics.h>
using namespace octomap;
using namespace std;
using namespace octomath;
using namespace sphere_discretization;
using namespace kinematics;
int main(int argc, char **argv)
{
ros::init(argc, argv, "workspace");
ros::NodeHandle n;
ros::Publisher workspace_pub = n.advertise<reuleaux::WorkSpace>("workspace", 1000);
//ros::Rate loop_rate(10);
ros::Rate poll_rate(100);
while(workspace_pub.getNumSubscribers() == 0)
poll_rate.sleep();
int count = 0;
while (ros::ok())
{
float HI=-1.5, LO=1.5;
unsigned char maxDepth = 16;
unsigned char minDepth = 0;
SphereDiscretization sd;
float r=1;
float resolution =0.05;
point3d origin=point3d(0,0,0);
OcTree* tree=sd.generateBoxTree(origin, r, resolution);
cout<<"Leaf"<<endl;
std::vector<point3d> newData;
for (OcTree::leaf_iterator it=tree->begin_leafs(maxDepth), end=tree->end_leafs();it !=end;++it){
newData.push_back(it.getCoordinate());
}
//cout<<"The # of leaf nodes in first tree: "<<tree->getNumLeafNodes()<<endl;
cout<<"Total no of spheres now: "<<newData.size()<<endl;
//cout<<"Hello"<<endl;
float radius=resolution;
vector<geometry_msgs::PoseArray> pose_Col;
multimap<vector<double>, vector<double> > PoseCol;
for (int i=0;i<newData.size();i++){
vector<geometry_msgs::Pose> pose;
vector<double> sphere_coord;
sd.convertPointToVector(newData[i],sphere_coord);
pose=sd.make_sphere_poses(newData[i],radius);
for(int j=0;j<pose.size();j++){
vector<double> point_on_sphere;
sd.convertPoseToVector(pose[j],point_on_sphere);
//cout<<"Data from vector"<<point_on_sphere[0]<<" "<<point_on_sphere[1]<<" "<<point_on_sphere[2]<<" "<<point_on_sphere[3]<<" "<<point_on_sphere[4]<<" "<<point_on_sphere[5]<<" "<<point_on_sphere[6]<<endl;
PoseCol.insert(pair<vector<double>, vector<double> >(point_on_sphere,sphere_coord));
}
}
Kinematics k;
multimap<vector<double>, vector<double> > PoseColFilter;
for (multimap<vector<double>, vector<double> >::iterator it = PoseCol.begin();it != PoseCol.end();++it){
//std::cout << it->first[0] <<" "<< it->first[1]<<" "<<it->first[2]<<" "<< it->first[3]<<" "<< it->first[4]<<" "<< it->first[5]<<" "<< it->first[6]<<endl;
//cout<<k.isIKSuccess(it->first)<<endl;
if (k.isIKSuccess(it->first)){
PoseColFilter.insert(pair<vector<double>, vector<double> >(it->second,it->first));
}
}
cout<<"Total # of poses: "<<PoseCol.size()<<endl;
cout<<"Total # of filtered poses: "<<PoseColFilter.size()<<endl;
reuleaux::WorkSpace ws;
ws.header.stamp=ros::Time::now();
ws.header.frame_id="/base_link";
for (multimap<vector<double>, vector<double> >::iterator it = PoseColFilter.begin();it != PoseColFilter.end();++it){
geometry_msgs::Pose p;
p.position.x=it->second[0];
p.position.y=it->second[1];
p.position.z=it->second[2];
p.orientation.x=it->second[3];
p.orientation.y=it->second[4];
p.orientation.z=it->second[5];
p.orientation.w=it->second[6];
ws.poses.push_back(p);
}
map<vector<double>, int> sphereColor;
for (multimap<vector<double>, vector<double> >::iterator it = PoseColFilter.begin();it != PoseColFilter.end();++it){
sphereColor.insert(pair<vector<double>, int >(it->first,2));
}
cout<<"No of spheres reachable: "<<sphereColor.size()<<endl;
for (map<vector<double>, int> ::iterator it = sphereColor.begin();it != sphereColor.end();++it){
geometry_msgs::Point32 p;
p.x=it->first[0];
p.y=it->first[1];
p.z=it->first[2];
ws.points.push_back(p);
}
workspace_pub.publish(ws);
ros::spinOnce();
sleep(10000);
//loop_rate.sleep();
++count;
}
return 0;
}
<commit_msg>Update create_sphere_and_arrow.cpp<commit_after>#include<ros/ros.h>
#include "reuleaux/WorkSpace.h"
#include<octomap/octomap.h>
#include<octomap/MapCollection.h>
#include <octomap/math/Utils.h>
#include <reuleaux/sphere_discretization.h>
#include <tf2/LinearMath/Quaternion.h>
#include "geometry_msgs/PoseArray.h"
#include<map>
#include<reuleaux/kinematics.h>
using namespace octomap;
using namespace std;
using namespace octomath;
using namespace sphere_discretization;
using namespace kinematics;
int main(int argc, char **argv)
{
ros::init(argc, argv, "workspace");
ros::NodeHandle n;
ros::Publisher workspace_pub = n.advertise<reuleaux::WorkSpace>("workspace", 1000);
//ros::Rate loop_rate(10);
ros::Rate poll_rate(100);
while(workspace_pub.getNumSubscribers() == 0)
poll_rate.sleep();
int count = 0;
while (ros::ok())
{
float HI=-1.5, LO=1.5;
unsigned char maxDepth = 16;
unsigned char minDepth = 0;
SphereDiscretization sd;
float r=1;
float resolution =0.05;
point3d origin=point3d(0,0,0);
OcTree* tree=sd.generateBoxTree(origin, r, resolution);
std::vector<point3d> newData;
for (OcTree::leaf_iterator it=tree->begin_leafs(maxDepth), end=tree->end_leafs();it !=end;++it){
newData.push_back(it.getCoordinate());
}
float radius=resolution;
vector<geometry_msgs::PoseArray> pose_Col;
multimap<vector<double>, vector<double> > PoseCol;
for (int i=0;i<newData.size();i++){
vector<geometry_msgs::Pose> pose;
vector<double> sphere_coord;
sd.convertPointToVector(newData[i],sphere_coord);
pose=sd.make_sphere_poses(newData[i],radius);
for(int j=0;j<pose.size();j++){
vector<double> point_on_sphere;
sd.convertPoseToVector(pose[j],point_on_sphere);
PoseCol.insert(pair<vector<double>, vector<double> >(point_on_sphere,sphere_coord));
}
}
Kinematics k;
multimap<vector<double>, vector<double> > PoseColFilter;
for (multimap<vector<double>, vector<double> >::iterator it = PoseCol.begin();it != PoseCol.end();++it){
if (k.isIKSuccess(it->first)){
PoseColFilter.insert(pair<vector<double>, vector<double> >(it->second,it->first));
}
}
ROS_INFO("Total # of poses: [%zd]",PoseCol.size());
ROS_INFO("Total # of filtered poses: [%zd]",PoseColFilter.size());
reuleaux::WorkSpace ws;
ws.header.stamp=ros::Time::now();
ws.header.frame_id="/base_link";
for (multimap<vector<double>, vector<double> >::iterator it = PoseColFilter.begin();it != PoseColFilter.end();++it){
geometry_msgs::Pose p;
p.position.x=it->second[0];
p.position.y=it->second[1];
p.position.z=it->second[2];
p.orientation.x=it->second[3];
p.orientation.y=it->second[4];
p.orientation.z=it->second[5];
p.orientation.w=it->second[6];
ws.poses.push_back(p);
}
map<vector<double>, int> sphereColor;
for (multimap<vector<double>, vector<double> >::iterator it = PoseColFilter.begin();it != PoseColFilter.end();++it){
sphereColor.insert(pair<vector<double>, int >(it->first,2));
}
for (map<vector<double>, int> ::iterator it = sphereColor.begin();it != sphereColor.end();++it){
geometry_msgs::Point32 p;
p.x=it->first[0];
p.y=it->first[1];
p.z=it->first[2];
ws.points.push_back(p);
}
workspace_pub.publish(ws);
ros::spinOnce();
sleep(10000);
//loop_rate.sleep();
++count;
}
return 0;
}
<|endoftext|> |
<commit_before>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
// $Id$
#include "AliMUONCalibParamNF.h"
#include "AliLog.h"
#include "Riostream.h"
#include "TMath.h"
#include "TString.h"
#include <limits.h>
//-----------------------------------------------------------------------------
/// \class AliMUONCalibParamNF
///
/// Handle the case of N floating point parameters per channel.
///
/// \author Laurent Aphecetche
//-----------------------------------------------------------------------------
/// \cond CLASSIMP
ClassImp(AliMUONCalibParamNF)
/// \endcond
//_____________________________________________________________________________
AliMUONCalibParamNF::AliMUONCalibParamNF()
: AliMUONVCalibParam(),
fDimension(0),
fSize(0),
fN(0),
fValues(0x0)
{
/// Default constructor.
}
//_____________________________________________________________________________
AliMUONCalibParamNF::AliMUONCalibParamNF(Int_t dimension, Int_t theSize,
Int_t id0, Int_t id1,
Float_t fillWithValue)
: AliMUONVCalibParam(id0,id1),
fDimension(dimension),
fSize(theSize),
fN(fSize*fDimension),
fValues(0x0)
{
/// Normal constructor, where theSize specifies the number of channels handled
/// by this object, and fillWithValue the default value assigned to each
/// channel.
if ( fN > 0 )
{
fValues = new Float_t[fN];
for ( Int_t i = 0; i < fN; ++i )
{
fValues[i] = fillWithValue;
}
}
}
//_____________________________________________________________________________
AliMUONCalibParamNF::AliMUONCalibParamNF(const AliMUONCalibParamNF& other)
: AliMUONVCalibParam(),
fDimension(0),
fSize(0),
fN(0),
fValues(0x0)
{
/// Copy constructor.
other.CopyTo(*this);
}
//_____________________________________________________________________________
AliMUONCalibParamNF&
AliMUONCalibParamNF::operator=(const AliMUONCalibParamNF& other)
{
/// Assignment operator
other.CopyTo(*this);
return *this;
}
//_____________________________________________________________________________
AliMUONCalibParamNF::~AliMUONCalibParamNF()
{
/// Destructor
delete[] fValues;
}
//_____________________________________________________________________________
void
AliMUONCalibParamNF::CopyTo(AliMUONCalibParamNF& destination) const
{
/// Copy *this to destination
const TObject& o = static_cast<const TObject&>(*this);
o.Copy(destination);
delete[] destination.fValues;
destination.fN = fN;
destination.fSize = fSize;
destination.fDimension = fDimension;
if ( fN > 0 )
{
destination.fValues = new Float_t[fN];
for ( Int_t i = 0; i < fN; ++i )
{
destination.fValues[i] = fValues[i];
}
}
}
//_____________________________________________________________________________
Int_t
AliMUONCalibParamNF::Index(Int_t i, Int_t j) const
{
/// Compute the 1D index of the internal storage from the pair (i,j)
/// Returns -1 if the (i,j) pair is invalid
if ( i >= 0 && i < Size() && j >= 0 && j < Dimension() )
{
return IndexFast(i,j);
}
return -1;
}
//_____________________________________________________________________________
Int_t
AliMUONCalibParamNF::IndexFast(Int_t i, Int_t j) const
{
/// Compute the 1D index of the internal storage from the pair (i,j)
return i + Size()*j;
}
//_____________________________________________________________________________
void
AliMUONCalibParamNF::Print(Option_t* opt) const
{
/// Output this object to stdout.
/// If opt=="full", then all channels are printed,
/// if opt=="mean#", only the mean and sigma value are printed for j-th dimension
/// otherwise only the general characteristics are printed.
TString sopt(opt);
sopt.ToUpper();
cout << Form("AliMUONCalibParamNF Id=(%d,%d) Size=%d Dimension=%d",ID0(),
ID1(),Size(),Dimension()) << endl;
if ( sopt.Contains("FULL") )
{
for ( Int_t i = 0; i < Size(); ++i )
{
cout << Form("CH %3d",i);
for ( Int_t j = 0; j < Dimension(); ++j )
{
cout << Form(" %e",ValueAsFloat(i,j));
}
cout << endl;
}
}
if ( sopt.Contains("MEAN") )
{
Int_t j(0);
sscanf(sopt.Data(),"MEAN%d",&j);
Float_t mean(0);
Float_t v2(0);
Int_t n = Size();
for ( Int_t i = 0; i < Size(); ++i )
{
Float_t v = ValueAsFloat(i,j);
mean += v;
v2 += v*v;
}
mean /= n;
float sigma = 0;
if ( n > 1 ) sigma = TMath::Sqrt( (v2-n*mean*mean)/(n-1) );
cout << Form(" Mean(j=%d)=%e Sigma(j=%d)=%e",j,mean,j,sigma) << endl;
}
}
//_____________________________________________________________________________
void
AliMUONCalibParamNF::SetValueAsFloat(Int_t i, Int_t j, Float_t value)
{
/// Set one value as a float, after checking that the indices are correct.
Int_t ix = Index(i,j);
if ( ix < 0 )
{
AliError(Form("Invalid (i,j)=(%d,%d) max allowed is (%d,%d)",
i,j,Size()-1,Dimension()-1));
}
else
{
fValues[ix]=value;
}
}
//_____________________________________________________________________________
void
AliMUONCalibParamNF::SetValueAsFloatFast(Int_t i, Int_t j, Float_t value)
{
/// Set one value as a float, w/o checking that the indices are correct.
fValues[IndexFast(i,j)] = value;
}
//_____________________________________________________________________________
void
AliMUONCalibParamNF::SetValueAsInt(Int_t i, Int_t j, Int_t value)
{
/// Set one value as an int.
SetValueAsFloat(i,j,static_cast<Float_t>(value));
}
//_____________________________________________________________________________
void
AliMUONCalibParamNF::SetValueAsIntFast(Int_t i, Int_t j, Int_t value)
{
/// Set one value as an int.
SetValueAsFloatFast(i,j,static_cast<Float_t>(value));
}
//_____________________________________________________________________________
Float_t
AliMUONCalibParamNF::ValueAsFloat(Int_t i, Int_t j) const
{
/// Return the value as a float (which it is), after checking indices.
Int_t ix = Index(i,j);
if ( ix < 0 )
{
AliError(Form("Invalid (i,j)=(%d,%d) max allowed is (%d,%d)",
i,j,Size()-1,Dimension()-1));
return 0.0;
}
else
{
return fValues[ix];
}
}
//_____________________________________________________________________________
Float_t
AliMUONCalibParamNF::ValueAsFloatFast(Int_t i, Int_t j) const
{
/// Return the value as a float (which it is), after checking indices.
return fValues[IndexFast(i,j)];
}
//_____________________________________________________________________________
Int_t
AliMUONCalibParamNF::ValueAsInt(Int_t i, Int_t j) const
{
/// Return the value as an int, by rounding the internal float value.
Float_t v = ValueAsFloat(i,j);
if ( v >= Float_t(INT_MAX) ) {
AliErrorStream()
<< "Cannot convert value " << v << " to Int_t." << endl;
return 0;
}
return TMath::Nint(v);
}
//_____________________________________________________________________________
Int_t
AliMUONCalibParamNF::ValueAsIntFast(Int_t i, Int_t j) const
{
/// Return the value as an int, by rounding the internal float value.
Float_t v = ValueAsFloatFast(i,j);
return TMath::Nint(v);
}
<commit_msg>Remove uneeded line<commit_after>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
// $Id$
#include "AliMUONCalibParamNF.h"
#include "AliLog.h"
#include "Riostream.h"
#include "TMath.h"
#include "TString.h"
#include <limits.h>
//-----------------------------------------------------------------------------
/// \class AliMUONCalibParamNF
///
/// Handle the case of N floating point parameters per channel.
///
/// \author Laurent Aphecetche
//-----------------------------------------------------------------------------
/// \cond CLASSIMP
ClassImp(AliMUONCalibParamNF)
/// \endcond
//_____________________________________________________________________________
AliMUONCalibParamNF::AliMUONCalibParamNF()
: AliMUONVCalibParam(),
fDimension(0),
fSize(0),
fN(0),
fValues(0x0)
{
/// Default constructor.
}
//_____________________________________________________________________________
AliMUONCalibParamNF::AliMUONCalibParamNF(Int_t dimension, Int_t theSize,
Int_t id0, Int_t id1,
Float_t fillWithValue)
: AliMUONVCalibParam(id0,id1),
fDimension(dimension),
fSize(theSize),
fN(fSize*fDimension),
fValues(0x0)
{
/// Normal constructor, where theSize specifies the number of channels handled
/// by this object, and fillWithValue the default value assigned to each
/// channel.
if ( fN > 0 )
{
fValues = new Float_t[fN];
for ( Int_t i = 0; i < fN; ++i )
{
fValues[i] = fillWithValue;
}
}
}
//_____________________________________________________________________________
AliMUONCalibParamNF::AliMUONCalibParamNF(const AliMUONCalibParamNF& other)
: AliMUONVCalibParam(),
fDimension(0),
fSize(0),
fN(0),
fValues(0x0)
{
/// Copy constructor.
other.CopyTo(*this);
}
//_____________________________________________________________________________
AliMUONCalibParamNF&
AliMUONCalibParamNF::operator=(const AliMUONCalibParamNF& other)
{
/// Assignment operator
other.CopyTo(*this);
return *this;
}
//_____________________________________________________________________________
AliMUONCalibParamNF::~AliMUONCalibParamNF()
{
/// Destructor
delete[] fValues;
}
//_____________________________________________________________________________
void
AliMUONCalibParamNF::CopyTo(AliMUONCalibParamNF& destination) const
{
/// Copy *this to destination
TObject::Copy(destination);
delete[] destination.fValues;
destination.fN = fN;
destination.fSize = fSize;
destination.fDimension = fDimension;
if ( fN > 0 )
{
destination.fValues = new Float_t[fN];
for ( Int_t i = 0; i < fN; ++i )
{
destination.fValues[i] = fValues[i];
}
}
}
//_____________________________________________________________________________
Int_t
AliMUONCalibParamNF::Index(Int_t i, Int_t j) const
{
/// Compute the 1D index of the internal storage from the pair (i,j)
/// Returns -1 if the (i,j) pair is invalid
if ( i >= 0 && i < Size() && j >= 0 && j < Dimension() )
{
return IndexFast(i,j);
}
return -1;
}
//_____________________________________________________________________________
Int_t
AliMUONCalibParamNF::IndexFast(Int_t i, Int_t j) const
{
/// Compute the 1D index of the internal storage from the pair (i,j)
return i + Size()*j;
}
//_____________________________________________________________________________
void
AliMUONCalibParamNF::Print(Option_t* opt) const
{
/// Output this object to stdout.
/// If opt=="full", then all channels are printed,
/// if opt=="mean#", only the mean and sigma value are printed for j-th dimension
/// otherwise only the general characteristics are printed.
TString sopt(opt);
sopt.ToUpper();
cout << Form("AliMUONCalibParamNF Id=(%d,%d) Size=%d Dimension=%d",ID0(),
ID1(),Size(),Dimension()) << endl;
if ( sopt.Contains("FULL") )
{
for ( Int_t i = 0; i < Size(); ++i )
{
cout << Form("CH %3d",i);
for ( Int_t j = 0; j < Dimension(); ++j )
{
cout << Form(" %e",ValueAsFloat(i,j));
}
cout << endl;
}
}
if ( sopt.Contains("MEAN") )
{
Int_t j(0);
sscanf(sopt.Data(),"MEAN%d",&j);
Float_t mean(0);
Float_t v2(0);
Int_t n = Size();
for ( Int_t i = 0; i < Size(); ++i )
{
Float_t v = ValueAsFloat(i,j);
mean += v;
v2 += v*v;
}
mean /= n;
float sigma = 0;
if ( n > 1 ) sigma = TMath::Sqrt( (v2-n*mean*mean)/(n-1) );
cout << Form(" Mean(j=%d)=%e Sigma(j=%d)=%e",j,mean,j,sigma) << endl;
}
}
//_____________________________________________________________________________
void
AliMUONCalibParamNF::SetValueAsFloat(Int_t i, Int_t j, Float_t value)
{
/// Set one value as a float, after checking that the indices are correct.
Int_t ix = Index(i,j);
if ( ix < 0 )
{
AliError(Form("Invalid (i,j)=(%d,%d) max allowed is (%d,%d)",
i,j,Size()-1,Dimension()-1));
}
else
{
fValues[ix]=value;
}
}
//_____________________________________________________________________________
void
AliMUONCalibParamNF::SetValueAsFloatFast(Int_t i, Int_t j, Float_t value)
{
/// Set one value as a float, w/o checking that the indices are correct.
fValues[IndexFast(i,j)] = value;
}
//_____________________________________________________________________________
void
AliMUONCalibParamNF::SetValueAsInt(Int_t i, Int_t j, Int_t value)
{
/// Set one value as an int.
SetValueAsFloat(i,j,static_cast<Float_t>(value));
}
//_____________________________________________________________________________
void
AliMUONCalibParamNF::SetValueAsIntFast(Int_t i, Int_t j, Int_t value)
{
/// Set one value as an int.
SetValueAsFloatFast(i,j,static_cast<Float_t>(value));
}
//_____________________________________________________________________________
Float_t
AliMUONCalibParamNF::ValueAsFloat(Int_t i, Int_t j) const
{
/// Return the value as a float (which it is), after checking indices.
Int_t ix = Index(i,j);
if ( ix < 0 )
{
AliError(Form("Invalid (i,j)=(%d,%d) max allowed is (%d,%d)",
i,j,Size()-1,Dimension()-1));
return 0.0;
}
else
{
return fValues[ix];
}
}
//_____________________________________________________________________________
Float_t
AliMUONCalibParamNF::ValueAsFloatFast(Int_t i, Int_t j) const
{
/// Return the value as a float (which it is), after checking indices.
return fValues[IndexFast(i,j)];
}
//_____________________________________________________________________________
Int_t
AliMUONCalibParamNF::ValueAsInt(Int_t i, Int_t j) const
{
/// Return the value as an int, by rounding the internal float value.
Float_t v = ValueAsFloat(i,j);
if ( v >= Float_t(INT_MAX) ) {
AliErrorStream()
<< "Cannot convert value " << v << " to Int_t." << endl;
return 0;
}
return TMath::Nint(v);
}
//_____________________________________________________________________________
Int_t
AliMUONCalibParamNF::ValueAsIntFast(Int_t i, Int_t j) const
{
/// Return the value as an int, by rounding the internal float value.
Float_t v = ValueAsFloatFast(i,j);
return TMath::Nint(v);
}
<|endoftext|> |
<commit_before>#include "solverdialog.h"
#include "ui_solverdialog.h"
#include <QDebug>
#include <QMessageBox>
SolverDialog::SolverDialog(QVector<Solver>& solvers0, QWidget *parent) :
QDialog(parent),
ui(new Ui::SolverDialog),
solvers(solvers0)
{
ui->setupUi(this);
for (int i=solvers.size(); i--;) {
ui->solvers_combo->insertItem(0,solvers[i].name,i);
}
ui->solvers_combo->setCurrentIndex(0);
}
SolverDialog::~SolverDialog()
{
delete ui;
}
void SolverDialog::on_solvers_combo_currentIndexChanged(int index)
{
if (index<solvers.size()) {
qDebug() << "switch to " << index;
ui->name->setText(solvers[index].name);
ui->executable->setText(solvers[index].executable);
ui->mznpath->setText(solvers[index].mznlib);
ui->backend->setText(solvers[index].backend);
ui->updateButton->setText("Update");
ui->deleteButton->setEnabled(true);
ui->solverFrame->setEnabled(!solvers[index].builtin);
} else {
qDebug() << "switch to add";
ui->name->setText("");
ui->executable->setText("");
ui->mznpath->setText("");
ui->backend->setText("");
ui->solverFrame->setEnabled(true);
ui->updateButton->setText("Add");
ui->deleteButton->setEnabled(false);
}
}
void SolverDialog::on_updateButton_clicked()
{
int index = ui->solvers_combo->currentIndex();
if (index==solvers.size()) {
Solver s;
solvers.append(s);
}
solvers[index].backend = ui->backend->text();
solvers[index].executable = ui->executable->text();
solvers[index].mznlib = ui->mznpath->text();
solvers[index].name = ui->name->text();
solvers[index].builtin = false;
if (index==solvers.size()-1) {
ui->solvers_combo->insertItem(index,ui->name->text(),index);
}
ui->solvers_combo->setCurrentIndex(index);
}
void SolverDialog::on_deleteButton_clicked()
{
int index = ui->solvers_combo->currentIndex();
if (QMessageBox::warning(this,"MiniZinc IDE","Delete solver "+solvers[index].name+"?",QMessageBox::Ok | QMessageBox::Cancel)
== QMessageBox::Ok) {
solvers.removeAt(index);
ui->solvers_combo->removeItem(index);
}
}
<commit_msg>Remove debug output<commit_after>#include "solverdialog.h"
#include "ui_solverdialog.h"
#include <QDebug>
#include <QMessageBox>
SolverDialog::SolverDialog(QVector<Solver>& solvers0, QWidget *parent) :
QDialog(parent),
ui(new Ui::SolverDialog),
solvers(solvers0)
{
ui->setupUi(this);
for (int i=solvers.size(); i--;) {
ui->solvers_combo->insertItem(0,solvers[i].name,i);
}
ui->solvers_combo->setCurrentIndex(0);
}
SolverDialog::~SolverDialog()
{
delete ui;
}
void SolverDialog::on_solvers_combo_currentIndexChanged(int index)
{
if (index<solvers.size()) {
ui->name->setText(solvers[index].name);
ui->executable->setText(solvers[index].executable);
ui->mznpath->setText(solvers[index].mznlib);
ui->backend->setText(solvers[index].backend);
ui->updateButton->setText("Update");
ui->deleteButton->setEnabled(true);
ui->solverFrame->setEnabled(!solvers[index].builtin);
} else {
ui->name->setText("");
ui->executable->setText("");
ui->mznpath->setText("");
ui->backend->setText("");
ui->solverFrame->setEnabled(true);
ui->updateButton->setText("Add");
ui->deleteButton->setEnabled(false);
}
}
void SolverDialog::on_updateButton_clicked()
{
int index = ui->solvers_combo->currentIndex();
if (index==solvers.size()) {
Solver s;
solvers.append(s);
}
solvers[index].backend = ui->backend->text();
solvers[index].executable = ui->executable->text();
solvers[index].mznlib = ui->mznpath->text();
solvers[index].name = ui->name->text();
solvers[index].builtin = false;
if (index==solvers.size()-1) {
ui->solvers_combo->insertItem(index,ui->name->text(),index);
}
ui->solvers_combo->setCurrentIndex(index);
}
void SolverDialog::on_deleteButton_clicked()
{
int index = ui->solvers_combo->currentIndex();
if (QMessageBox::warning(this,"MiniZinc IDE","Delete solver "+solvers[index].name+"?",QMessageBox::Ok | QMessageBox::Cancel)
== QMessageBox::Ok) {
solvers.removeAt(index);
ui->solvers_combo->removeItem(index);
}
}
<|endoftext|> |
<commit_before>#include <fstream>
#include <cryptopp/dh.h>
#include <cryptopp/dsa.h>
#include "CryptoConst.h"
#include "RouterContext.h"
#include "util.h"
namespace i2p
{
RouterContext context;
RouterContext::RouterContext ()
{
if (!Load ())
CreateNewRouter ();
Save ();
// we generate LeaseSet at every start-up
CryptoPP::DH dh (i2p::crypto::elgp, i2p::crypto::elgg);
dh.GenerateKeyPair(m_Rnd, m_LeaseSetPrivateKey, m_LeaseSetPublicKey);
}
void RouterContext::CreateNewRouter ()
{
m_Keys = i2p::data::CreateRandomKeys ();
m_SigningPrivateKey.Initialize (i2p::crypto::dsap, i2p::crypto::dsaq, i2p::crypto::dsag,
CryptoPP::Integer (m_Keys.signingPrivateKey, 20));
i2p::data::Identity ident;
ident = m_Keys;
m_RouterInfo.SetRouterIdentity (ident);
m_RouterInfo.AddNTCPAddress ("127.0.0.1", 17007); // TODO:
m_RouterInfo.SetProperty ("caps", "LR");
m_RouterInfo.SetProperty ("coreVersion", "0.9.8.1");
m_RouterInfo.SetProperty ("netId", "2");
m_RouterInfo.SetProperty ("router.version", "0.9.8.1");
m_RouterInfo.SetProperty ("start_uptime", "90m");
m_RouterInfo.CreateBuffer ();
}
void RouterContext::OverrideNTCPAddress (const char * host, int port)
{
m_RouterInfo.CreateBuffer ();
auto address = const_cast<i2p::data::RouterInfo::Address *>(m_RouterInfo.GetNTCPAddress ());
if (address)
{
address->host = boost::asio::ip::address::from_string (host);
address->port = port;
}
m_RouterInfo.CreateBuffer ();
}
void RouterContext::UpdateAddress (const char * host)
{
for (auto& address : m_RouterInfo.GetAddresses ())
address.host = boost::asio::ip::address::from_string (host);
m_RouterInfo.CreateBuffer ();
}
void RouterContext::Sign (uint8_t * buf, int len, uint8_t * signature)
{
CryptoPP::DSA::Signer signer (m_SigningPrivateKey);
signer.SignMessage (m_Rnd, buf, len, signature);
}
bool RouterContext::Load ()
{
std::ifstream fk (ROUTER_KEYS, std::ifstream::binary | std::ofstream::in);
if (!fk.is_open ()) return false;
fk.read ((char *)&m_Keys, sizeof (m_Keys));
m_SigningPrivateKey.Initialize (i2p::crypto::dsap, i2p::crypto::dsaq, i2p::crypto::dsag,
CryptoPP::Integer (m_Keys.signingPrivateKey, 20));
m_RouterInfo = i2p::data::RouterInfo (ROUTER_INFO); // TODO
return true;
}
void RouterContext::Save ()
{
std::ofstream fk (ROUTER_KEYS, std::ofstream::binary | std::ofstream::out);
fk.write ((char *)&m_Keys, sizeof (m_Keys));
std::ofstream fi (ROUTER_INFO, std::ofstream::binary | std::ofstream::out);
fi.write ((char *)m_RouterInfo.GetBuffer (), m_RouterInfo.GetBufferLen ());
}
}
<commit_msg>Save/Load router.info/router.key from data directory<commit_after>#include <fstream>
#include <cryptopp/dh.h>
#include <cryptopp/dsa.h>
#include "CryptoConst.h"
#include "RouterContext.h"
#include "util.h"
namespace i2p
{
RouterContext context;
RouterContext::RouterContext ()
{
if (!Load ())
CreateNewRouter ();
Save ();
// we generate LeaseSet at every start-up
CryptoPP::DH dh (i2p::crypto::elgp, i2p::crypto::elgg);
dh.GenerateKeyPair(m_Rnd, m_LeaseSetPrivateKey, m_LeaseSetPublicKey);
}
void RouterContext::CreateNewRouter ()
{
m_Keys = i2p::data::CreateRandomKeys ();
m_SigningPrivateKey.Initialize (i2p::crypto::dsap, i2p::crypto::dsaq, i2p::crypto::dsag,
CryptoPP::Integer (m_Keys.signingPrivateKey, 20));
i2p::data::Identity ident;
ident = m_Keys;
m_RouterInfo.SetRouterIdentity (ident);
m_RouterInfo.AddNTCPAddress ("127.0.0.1", 17007); // TODO:
m_RouterInfo.SetProperty ("caps", "LR");
m_RouterInfo.SetProperty ("coreVersion", "0.9.8.1");
m_RouterInfo.SetProperty ("netId", "2");
m_RouterInfo.SetProperty ("router.version", "0.9.8.1");
m_RouterInfo.SetProperty ("start_uptime", "90m");
m_RouterInfo.CreateBuffer ();
}
void RouterContext::OverrideNTCPAddress (const char * host, int port)
{
m_RouterInfo.CreateBuffer ();
auto address = const_cast<i2p::data::RouterInfo::Address *>(m_RouterInfo.GetNTCPAddress ());
if (address)
{
address->host = boost::asio::ip::address::from_string (host);
address->port = port;
}
m_RouterInfo.CreateBuffer ();
}
void RouterContext::UpdateAddress (const char * host)
{
for (auto& address : m_RouterInfo.GetAddresses ())
address.host = boost::asio::ip::address::from_string (host);
m_RouterInfo.CreateBuffer ();
}
void RouterContext::Sign (uint8_t * buf, int len, uint8_t * signature)
{
CryptoPP::DSA::Signer signer (m_SigningPrivateKey);
signer.SignMessage (m_Rnd, buf, len, signature);
}
bool RouterContext::Load ()
{
std::string dataDir = i2p::util::filesystem::GetDataDir ().string ();
#ifndef _WIN32
dataDir.append ("/");
#else
dataDir.append ("\\");
#endif
std::string router_keys = dataDir;
router_keys.append (ROUTER_KEYS);
std::string router_info = dataDir;
router_info.append (ROUTER_INFO);
std::ifstream fk (router_keys.c_str (), std::ifstream::binary | std::ofstream::in);
if (!fk.is_open ()) return false;
fk.read ((char *)&m_Keys, sizeof (m_Keys));
m_SigningPrivateKey.Initialize (i2p::crypto::dsap, i2p::crypto::dsaq, i2p::crypto::dsag,
CryptoPP::Integer (m_Keys.signingPrivateKey, 20));
m_RouterInfo = i2p::data::RouterInfo (router_info.c_str ()); // TODO
return true;
}
void RouterContext::Save ()
{
std::string dataDir = i2p::util::filesystem::GetDataDir ().string ();
#ifndef _WIN32
dataDir.append ("/");
#else
dataDir.append ("\\");
#endif
std::string router_keys = dataDir;
router_keys.append (ROUTER_KEYS);
std::string router_info = dataDir;
router_info.append (ROUTER_INFO);
std::ofstream fk (router_keys.c_str (), std::ofstream::binary | std::ofstream::out);
fk.write ((char *)&m_Keys, sizeof (m_Keys));
std::ofstream fi (router_info.c_str (), std::ofstream::binary | std::ofstream::out);
fi.write ((char *)m_RouterInfo.GetBuffer (), m_RouterInfo.GetBufferLen ());
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "after_initialization_fixture.h"
#include "test/testsupport/fileutils.h"
namespace {
const int kSampleRateHz = 16000;
const int kTestDurationMs = 1000;
const int16_t kInputValue = 15000;
const int16_t kSilenceValue = 0;
} // namespace
class FileBeforeStreamingTest : public AfterInitializationFixture {
protected:
FileBeforeStreamingTest()
: input_filename_(webrtc::test::OutputPath() + "file_test_input.pcm"),
output_filename_(webrtc::test::OutputPath() + "file_test_output.pcm") {
}
void SetUp() {
channel_ = voe_base_->CreateChannel();
}
void TearDown() {
voe_base_->DeleteChannel(channel_);
}
// TODO(andrew): consolidate below methods in a shared place?
// Generate input file with constant values as |kInputValue|. The file
// will be one second longer than the duration of the test.
void GenerateInputFile() {
FILE* input_file = fopen(input_filename_.c_str(), "wb");
ASSERT_TRUE(input_file != NULL);
for (int i = 0; i < kSampleRateHz / 1000 * (kTestDurationMs + 1000); i++) {
ASSERT_EQ(1u, fwrite(&kInputValue, sizeof(kInputValue), 1, input_file));
}
ASSERT_EQ(0, fclose(input_file));
}
void RecordOutput() {
// Start recording the mixed output for |kTestDurationMs| long.
EXPECT_EQ(0, voe_file_->StartRecordingPlayout(-1,
output_filename_.c_str()));
Sleep(kTestDurationMs);
EXPECT_EQ(0, voe_file_->StopRecordingPlayout(-1));
}
void VerifyOutput(int16_t target_value) {
FILE* output_file = fopen(output_filename_.c_str(), "rb");
ASSERT_TRUE(output_file != NULL);
int16_t output_value = 0;
int samples_read = 0;
while (fread(&output_value, sizeof(output_value), 1, output_file) == 1) {
samples_read++;
EXPECT_EQ(output_value, target_value);
}
// Ensure the recording length is close to the duration of the test.
ASSERT_GE((samples_read * 1000.0) / kSampleRateHz, 0.9 * kTestDurationMs);
// Ensure we read the entire file.
ASSERT_NE(0, feof(output_file));
ASSERT_EQ(0, fclose(output_file));
}
void VerifyEmptyOutput() {
FILE* output_file = fopen(output_filename_.c_str(), "rb");
ASSERT_TRUE(output_file != NULL);
ASSERT_EQ(0, fseek(output_file, 0, SEEK_END));
EXPECT_EQ(0, ftell(output_file));
ASSERT_EQ(0, fclose(output_file));
}
int channel_;
const std::string input_filename_;
const std::string output_filename_;
};
// This test case is to ensure that StartPlayingFileLocally() and
// StartPlayout() can be called in any order.
// A DC signal is used as input. And the output of mixer is supposed to be:
// 1. the same DC signal if file is played out,
// 2. total silence if file is not played out,
// 3. no output if playout is not started.
TEST_F(FileBeforeStreamingTest,
DISABLED_TestStartPlayingFileLocallyWithStartPlayout) {
GenerateInputFile();
TEST_LOG("Playout is not started. File will not be played out.\n");
EXPECT_EQ(0, voe_file_->StartPlayingFileLocally(
channel_, input_filename_.c_str(), true));
EXPECT_EQ(1, voe_file_->IsPlayingFileLocally(channel_));
RecordOutput();
VerifyEmptyOutput();
TEST_LOG("Playout is now started. File will be played out.\n");
EXPECT_EQ(0, voe_base_->StartPlayout(channel_));
RecordOutput();
VerifyOutput(kInputValue);
TEST_LOG("Stop playing file. Only silence will be played out.\n");
EXPECT_EQ(0, voe_file_->StopPlayingFileLocally(channel_));
EXPECT_EQ(0, voe_file_->IsPlayingFileLocally(channel_));
RecordOutput();
VerifyOutput(kSilenceValue);
TEST_LOG("Start playing file again. File will be played out.\n");
EXPECT_EQ(0, voe_file_->StartPlayingFileLocally(
channel_, input_filename_.c_str(), true));
EXPECT_EQ(1, voe_file_->IsPlayingFileLocally(channel_));
RecordOutput();
VerifyOutput(kInputValue);
EXPECT_EQ(0, voe_base_->StopPlayout(channel_));
EXPECT_EQ(0, voe_file_->StopPlayingFileLocally(channel_));
}
<commit_msg>Fix the flakiness in FileBeforeStreamingTest<commit_after>/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "after_initialization_fixture.h"
#include "test/testsupport/fileutils.h"
namespace {
const int kSampleRateHz = 16000;
const int kTestDurationMs = 1000;
const int kSkipOutputMs = 50;
const int16_t kInputValue = 15000;
const int16_t kSilenceValue = 0;
} // namespace
class FileBeforeStreamingTest : public AfterInitializationFixture {
protected:
FileBeforeStreamingTest()
: input_filename_(webrtc::test::OutputPath() + "file_test_input.pcm"),
output_filename_(webrtc::test::OutputPath() + "file_test_output.pcm") {
}
void SetUp() {
channel_ = voe_base_->CreateChannel();
}
void TearDown() {
voe_base_->DeleteChannel(channel_);
}
// TODO(andrew): consolidate below methods in a shared place?
// Generate input file with constant values as |kInputValue|. The file
// will be one second longer than the duration of the test.
void GenerateInputFile() {
FILE* input_file = fopen(input_filename_.c_str(), "wb");
ASSERT_TRUE(input_file != NULL);
for (int i = 0; i < kSampleRateHz / 1000 * (kTestDurationMs + 1000); i++) {
ASSERT_EQ(1u, fwrite(&kInputValue, sizeof(kInputValue), 1, input_file));
}
ASSERT_EQ(0, fclose(input_file));
}
void RecordOutput() {
// Start recording the mixed output for |kTestDurationMs| long.
EXPECT_EQ(0, voe_file_->StartRecordingPlayout(-1,
output_filename_.c_str()));
Sleep(kTestDurationMs);
EXPECT_EQ(0, voe_file_->StopRecordingPlayout(-1));
}
void VerifyOutput(int16_t target_value) {
FILE* output_file = fopen(output_filename_.c_str(), "rb");
ASSERT_TRUE(output_file != NULL);
int16_t output_value = 0;
int samples_read = 0;
// Skip the first segment to avoid initialization and ramping-in effects.
EXPECT_EQ(0, fseek(output_file, sizeof(output_value) *
kSampleRateHz / 1000 * kSkipOutputMs, SEEK_SET));
while (fread(&output_value, sizeof(output_value), 1, output_file) == 1) {
samples_read++;
EXPECT_EQ(output_value, target_value);
}
// Ensure the recording length is close to the duration of the test.
ASSERT_GE((samples_read * 1000.0) / kSampleRateHz, 0.9 * kTestDurationMs);
// Ensure we read the entire file.
ASSERT_NE(0, feof(output_file));
ASSERT_EQ(0, fclose(output_file));
}
void VerifyEmptyOutput() {
FILE* output_file = fopen(output_filename_.c_str(), "rb");
ASSERT_TRUE(output_file != NULL);
ASSERT_EQ(0, fseek(output_file, 0, SEEK_END));
EXPECT_EQ(0, ftell(output_file));
ASSERT_EQ(0, fclose(output_file));
}
int channel_;
const std::string input_filename_;
const std::string output_filename_;
};
// This test case is to ensure that StartPlayingFileLocally() and
// StartPlayout() can be called in any order.
// A DC signal is used as input. And the output of mixer is supposed to be:
// 1. the same DC signal if file is played out,
// 2. total silence if file is not played out,
// 3. no output if playout is not started.
TEST_F(FileBeforeStreamingTest, TestStartPlayingFileLocallyWithStartPlayout) {
GenerateInputFile();
TEST_LOG("Playout is not started. File will not be played out.\n");
EXPECT_EQ(0, voe_file_->StartPlayingFileLocally(
channel_, input_filename_.c_str(), true));
EXPECT_EQ(1, voe_file_->IsPlayingFileLocally(channel_));
RecordOutput();
VerifyEmptyOutput();
TEST_LOG("Playout is now started. File will be played out.\n");
EXPECT_EQ(0, voe_base_->StartPlayout(channel_));
RecordOutput();
VerifyOutput(kInputValue);
TEST_LOG("Stop playing file. Only silence will be played out.\n");
EXPECT_EQ(0, voe_file_->StopPlayingFileLocally(channel_));
EXPECT_EQ(0, voe_file_->IsPlayingFileLocally(channel_));
RecordOutput();
VerifyOutput(kSilenceValue);
TEST_LOG("Start playing file again. File will be played out.\n");
EXPECT_EQ(0, voe_file_->StartPlayingFileLocally(
channel_, input_filename_.c_str(), true));
EXPECT_EQ(1, voe_file_->IsPlayingFileLocally(channel_));
RecordOutput();
VerifyOutput(kInputValue);
EXPECT_EQ(0, voe_base_->StopPlayout(channel_));
EXPECT_EQ(0, voe_file_->StopPlayingFileLocally(channel_));
}
<|endoftext|> |
<commit_before>/*! \file TestInstructionThroughput.cpp
\date Saturday November 14, 2009
\author Sudnya Padalikar <[email protected]>
\brief A test for instruction throughput.
*/
#ifndef TEST_INSTRUCTION_THROUGHPUT_CPP_INCLUDED
#define TEST_INSTRUCTION_THROUGHPUT_CPP_INCLUDED
#include <tests/TestInstructionThroughput/TestInstructionThroughput.h>
#include <hydrazine/implementation/ArgumentParser.h>
#include <cuda_runtime_api.h>
#include <ocelot/api/interface/ocelot.h>
namespace test
{
bool TestInstructionThroughput::testu64InstructionThroughput()
{
unsigned int* input;
unsigned int k=5;
cudaMalloc( ( void** ) &input, sizeof( unsigned int ) );
cudaMemcpy( input, &k, sizeof( unsigned int ), cudaMemcpyHostToDevice );
cudaConfigureCall( dim3( ctas, 1, 1 ), dim3( threads, 1, 1 ), 0, 0 );
cudaSetupArgument( &input, sizeof( long long unsigned int ), 0 );
std::stringstream program;
program << ".version 1.4\n";
program << ".target sm_10, map_f64_to_f32\n\n";
program << ".entry testInstructionThroughput( .param .u64 input )\n";
program << "{\n";
program << " .reg .u64 %r<7>;\n";
program << " .reg .pred %p0;\n";
program << " Entry:\n";
program << " ld.param.u64 %r0, [input];\n";
program << " ld.global.u32 %r1, [%r0];\n";
program << " mov.u64 %r2, " << iterations <<";\n";
program << " mov.u64 %r3, 0; \n";
program << " mov.u64 %r6, 0; \n";
program << " setp.eq.u64 %p0, %r3, %r2;\n";
program << " @%p0 bra Exit;\n";
program << " Begin_iter:\n";
for(int i=0; i<unroll; ++i )
{
program << " add.u64 %r6, %r6, %r1;\n";
}
program << " add.u64 %r3, %r3, 1; \n";
program << " setp.lt.u64 %p0, %r3, %r2;\n";
program << " @%p0 bra Begin_iter;\n";
program << " End_loop:";
program << " st.global.u32 [%r0], %r6;\n";
program << " Exit:\n";
program << " exit;";
program << "}\n";
ocelot::registerPTXModule( program, "throughput" );
const char* kernelPointer = ocelot::getKernelPointer(
"testInstructionThroughput", "throughput" );
hydrazine::Timer timer;
timer.start();
cudaLaunch( kernelPointer );
cudaThreadSynchronize();
timer.stop();
status << "Operations/sec "
<< ( (threads * ctas * iterations * unroll) / timer.seconds() )
<< " seconds. \n";
unsigned int result;
cudaMemcpy( &result, input, sizeof( unsigned int ),
cudaMemcpyDeviceToHost );
bool pass = true;
if( result != k * iterations * unroll )
{
status << "Program generated incorrect output " << result
<< ", expecting " << (k * iterations * unroll ) << "\n";
pass = false;
}
cudaFree( input );
return pass;
}
bool TestInstructionThroughput::testu32InstructionThroughput()
{
unsigned int* input;
unsigned int k=5;
cudaMalloc( ( void** ) &input, sizeof( unsigned int ) );
cudaMemcpy( input, &k, sizeof( unsigned int ), cudaMemcpyHostToDevice );
cudaConfigureCall( dim3( ctas, 1, 1 ), dim3( threads, 1, 1 ), 0, 0 );
cudaSetupArgument( &input, sizeof( long long unsigned int ), 0 );
std::stringstream program;
program << ".version 1.4\n";
program << ".target sm_10, map_f64_to_f32\n\n";
program << ".entry testu32InstructionThroughput( .param .u64 input )\n";
program << "{\n";
program << " .reg .u64 %r<7>;\n";
program << " .reg .u32 %sum;\n";
program << " .reg .u32 %initial;\n";
program << " .reg .pred %p0;\n";
program << " Entry:\n";
program << " ld.param.u64 %r0, [input];\n";
program << " ld.global.u32 %initial, [%r0];\n";
program << " mov.u64 %r2, " << iterations <<";\n";
program << " mov.u64 %r3, 0; \n";
program << " mov.u32 %sum, 0; \n";
program << " setp.eq.u64 %p0, %r3, %r2;\n";
program << " @%p0 bra Exit;\n";
program << " Begin_iter:\n";
for(int i=0; i<unroll; ++i )
{
program << " add.u32 %sum, %sum, %initial;\n";
}
program << " add.u64 %r3, %r3, 1; \n";
program << " setp.lt.u64 %p0, %r3, %r2;\n";
program << " @%p0 bra Begin_iter;\n";
program << " End_loop:";
program << " st.global.u32 [%r0], %sum;\n";
program << " Exit:\n";
program << " exit;";
program << "}\n";
ocelot::registerPTXModule( program, "u32throughput" );
const char* kernelPointer = ocelot::getKernelPointer(
"testu32InstructionThroughput", "u32throughput" );
hydrazine::Timer timer;
timer.start();
cudaLaunch( kernelPointer );
cudaThreadSynchronize();
timer.stop();
status << "Operations/sec "
<< ( (threads * ctas * iterations * unroll) / timer.seconds() )
<< " seconds. \n";
unsigned int result;
cudaMemcpy( &result, input, sizeof( unsigned int ),
cudaMemcpyDeviceToHost );
bool pass = true;
if( result != k * iterations * unroll )
{
status << "Program generated incorrect output " << result
<< ", expecting " << (k * iterations * unroll ) << "\n";
pass = false;
}
cudaFree( input );
return pass;
}
bool TestInstructionThroughput::testf32InstructionThroughput()
{
unsigned int* input;
float k=5;
cudaMalloc( ( void** ) &input, sizeof( unsigned int ) );
cudaMemcpy( input, &k, sizeof( unsigned int ), cudaMemcpyHostToDevice );
cudaConfigureCall( dim3( ctas, 1, 1 ), dim3( threads, 1, 1 ), 0, 0 );
cudaSetupArgument( &input, sizeof( long long unsigned int ), 0 );
std::stringstream program;
program << ".version 1.4\n";
program << ".target sm_10, map_f64_to_f32\n\n";
program << ".entry testf32InstructionThroughput( .param .u64 input )\n";
program << "{\n";
program << " .reg .u64 %r<7>;\n";
program << " .reg .f32 %sum;\n";
program << " .reg .f32 %initial;\n";
program << " .reg .pred %p0;\n";
program << " Entry:\n";
program << " ld.param.u64 %r0, [input];\n";
program << " ld.global.f32 %initial, [%r0];\n";
program << " mov.u64 %r2, " << iterations <<";\n";
program << " mov.u64 %r3, 0; \n";
program << " mov.f32 %sum, 0; \n";
program << " setp.eq.u64 %p0, %r3, %r2;\n";
program << " @%p0 bra Exit;\n";
program << " Begin_iter:\n";
for(int i=0; i<unroll; ++i )
{
program << " mad.f32 %sum, 0f3f800000, %initial, %sum;\n";
}
program << " add.u64 %r3, %r3, 1; \n";
program << " setp.lt.u64 %p0, %r3, %r2;\n";
program << " @%p0 bra Begin_iter;\n";
program << " End_loop:";
program << " st.global.f32 [%r0], %sum;\n";
program << " Exit:\n";
program << " exit;";
program << "}\n";
ocelot::registerPTXModule( program, "f32throughput" );
const char* kernelPointer = ocelot::getKernelPointer(
"testf32InstructionThroughput", "f32throughput" );
hydrazine::Timer timer;
timer.start();
cudaLaunch( kernelPointer );
cudaThreadSynchronize();
timer.stop();
status << "Operations/sec "
<< ( (threads * ctas * iterations * unroll * 2) / timer.seconds() )
<< " seconds. \n";
float result;
cudaMemcpy( &result, input, sizeof( float ),
cudaMemcpyDeviceToHost );
bool pass = true;
if( result != k * iterations * unroll )
{
status << "Program generated incorrect output " << result
<< ", expecting " << (k * iterations * unroll ) << "\n";
pass = false;
}
cudaFree( input );
return pass;
}
bool TestInstructionThroughput::doTest()
{
return testu64InstructionThroughput() && testu32InstructionThroughput()
&& testf32InstructionThroughput();
}
TestInstructionThroughput::TestInstructionThroughput()
{
name = "TestInstructionThroughput";
description = "A benchmark for PTX Instruction Throughput.";
}
}
int main(int argc, char** argv)
{
hydrazine::ArgumentParser parser( argc, argv );
test::TestInstructionThroughput test;
parser.description( test.testDescription() );
//threads, ctas, unroll, iter
parser.parse( "-t", "--threads", test.threads, 8,
"The number of threads." );
parser.parse( "-c", "--ctas", test.ctas, 1, "The number of CTAs." );
parser.parse("-u", "--unroll", test.unroll, 10, "The unrolled times");
parser.parse( "-i", "--iterations", test.iterations, 10000,
"The number of times to run through the barrier region." );
parser.parse( "-s", "--seed", test.seed, 0,
"Set the random seed, 0 implies seed with time." );
parser.parse( "-v", "--verbose", test.verbose, false,
"Print out info after the test." );
parser.parse();
test.test();
return test.passed();
}
#endif
<commit_msg>BUG: Fixed test for instruction throughput to only compare the result when using one thread<commit_after>/*! \file TestInstructionThroughput.cpp
\date Saturday November 14, 2009
\author Sudnya Padalikar <[email protected]>
\brief A test for instruction throughput.
*/
#ifndef TEST_INSTRUCTION_THROUGHPUT_CPP_INCLUDED
#define TEST_INSTRUCTION_THROUGHPUT_CPP_INCLUDED
#include <tests/TestInstructionThroughput/TestInstructionThroughput.h>
#include <hydrazine/implementation/ArgumentParser.h>
#include <cuda_runtime_api.h>
#include <ocelot/api/interface/ocelot.h>
namespace test
{
bool TestInstructionThroughput::testu64InstructionThroughput()
{
unsigned int* input;
unsigned int k=5;
cudaMalloc( ( void** ) &input, sizeof( unsigned int ) );
cudaMemcpy( input, &k, sizeof( unsigned int ), cudaMemcpyHostToDevice );
cudaConfigureCall( dim3( ctas, 1, 1 ), dim3( threads, 1, 1 ), 0, 0 );
cudaSetupArgument( &input, sizeof( long long unsigned int ), 0 );
std::stringstream program;
program << ".version 1.4\n";
program << ".target sm_10, map_f64_to_f32\n\n";
program << ".entry testInstructionThroughput( .param .u64 input )\n";
program << "{\n";
program << " .reg .u64 %r<7>;\n";
program << " .reg .pred %p0;\n";
program << " Entry:\n";
program << " ld.param.u64 %r0, [input];\n";
program << " ld.global.u32 %r1, [%r0];\n";
program << " mov.u64 %r2, " << iterations <<";\n";
program << " mov.u64 %r3, 0; \n";
program << " mov.u64 %r6, 0; \n";
program << " setp.eq.u64 %p0, %r3, %r2;\n";
program << " @%p0 bra Exit;\n";
program << " Begin_iter:\n";
for(int i=0; i<unroll; ++i )
{
program << " add.u64 %r6, %r6, %r1;\n";
}
program << " add.u64 %r3, %r3, 1; \n";
program << " setp.lt.u64 %p0, %r3, %r2;\n";
program << " @%p0 bra Begin_iter;\n";
program << " End_loop:";
program << " st.global.u32 [%r0], %r6;\n";
program << " Exit:\n";
program << " exit;";
program << "}\n";
ocelot::registerPTXModule( program, "throughput" );
const char* kernelPointer = ocelot::getKernelPointer(
"testInstructionThroughput", "throughput" );
hydrazine::Timer timer;
timer.start();
cudaLaunch( kernelPointer );
cudaThreadSynchronize();
timer.stop();
status << "Operations/sec "
<< ( (threads * ctas * iterations * unroll) / timer.seconds() )
<< " seconds. \n";
unsigned int result;
cudaMemcpy( &result, input, sizeof( unsigned int ),
cudaMemcpyDeviceToHost );
bool pass = true;
if( result != k * iterations * unroll && threads == 1 && ctas == 1 )
{
status << "Program generated incorrect output " << result
<< ", expecting " << (k * iterations * unroll ) << "\n";
pass = false;
}
cudaFree( input );
return pass;
}
bool TestInstructionThroughput::testu32InstructionThroughput()
{
unsigned int* input;
unsigned int k=5;
cudaMalloc( ( void** ) &input, sizeof( unsigned int ) );
cudaMemcpy( input, &k, sizeof( unsigned int ), cudaMemcpyHostToDevice );
cudaConfigureCall( dim3( ctas, 1, 1 ), dim3( threads, 1, 1 ), 0, 0 );
cudaSetupArgument( &input, sizeof( long long unsigned int ), 0 );
std::stringstream program;
program << ".version 1.4\n";
program << ".target sm_10, map_f64_to_f32\n\n";
program << ".entry testu32InstructionThroughput( .param .u64 input )\n";
program << "{\n";
program << " .reg .u64 %r<7>;\n";
program << " .reg .u32 %sum;\n";
program << " .reg .u32 %initial;\n";
program << " .reg .pred %p0;\n";
program << " Entry:\n";
program << " ld.param.u64 %r0, [input];\n";
program << " ld.global.u32 %initial, [%r0];\n";
program << " mov.u64 %r2, " << iterations <<";\n";
program << " mov.u64 %r3, 0; \n";
program << " mov.u32 %sum, 0; \n";
program << " setp.eq.u64 %p0, %r3, %r2;\n";
program << " @%p0 bra Exit;\n";
program << " Begin_iter:\n";
for(int i=0; i<unroll; ++i )
{
program << " add.u32 %sum, %sum, %initial;\n";
}
program << " add.u64 %r3, %r3, 1; \n";
program << " setp.lt.u64 %p0, %r3, %r2;\n";
program << " @%p0 bra Begin_iter;\n";
program << " End_loop:";
program << " st.global.u32 [%r0], %sum;\n";
program << " Exit:\n";
program << " exit;";
program << "}\n";
ocelot::registerPTXModule( program, "u32throughput" );
const char* kernelPointer = ocelot::getKernelPointer(
"testu32InstructionThroughput", "u32throughput" );
hydrazine::Timer timer;
timer.start();
cudaLaunch( kernelPointer );
cudaThreadSynchronize();
timer.stop();
status << "Operations/sec "
<< ( (threads * ctas * iterations * unroll) / timer.seconds() )
<< " seconds. \n";
unsigned int result;
cudaMemcpy( &result, input, sizeof( unsigned int ),
cudaMemcpyDeviceToHost );
bool pass = true;
if( result != k * iterations * unroll && threads == 1 && ctas == 1 )
{
status << "Program generated incorrect output " << result
<< ", expecting " << (k * iterations * unroll ) << "\n";
pass = false;
}
cudaFree( input );
return pass;
}
bool TestInstructionThroughput::testf32InstructionThroughput()
{
unsigned int* input;
float k=5;
cudaMalloc( ( void** ) &input, sizeof( unsigned int ) );
cudaMemcpy( input, &k, sizeof( unsigned int ), cudaMemcpyHostToDevice );
cudaConfigureCall( dim3( ctas, 1, 1 ), dim3( threads, 1, 1 ), 0, 0 );
cudaSetupArgument( &input, sizeof( long long unsigned int ), 0 );
std::stringstream program;
program << ".version 1.4\n";
program << ".target sm_10, map_f64_to_f32\n\n";
program << ".entry testf32InstructionThroughput( .param .u64 input )\n";
program << "{\n";
program << " .reg .u64 %r<7>;\n";
program << " .reg .f32 %sum;\n";
program << " .reg .f32 %initial;\n";
program << " .reg .pred %p0;\n";
program << " Entry:\n";
program << " ld.param.u64 %r0, [input];\n";
program << " ld.global.f32 %initial, [%r0];\n";
program << " mov.u64 %r2, " << iterations <<";\n";
program << " mov.u64 %r3, 0; \n";
program << " mov.f32 %sum, 0; \n";
program << " setp.eq.u64 %p0, %r3, %r2;\n";
program << " @%p0 bra Exit;\n";
program << " Begin_iter:\n";
for(int i=0; i<unroll; ++i )
{
program << " mad.f32 %sum, 0f3f800000, %initial, %sum;\n";
}
program << " add.u64 %r3, %r3, 1; \n";
program << " setp.lt.u64 %p0, %r3, %r2;\n";
program << " @%p0 bra Begin_iter;\n";
program << " End_loop:";
program << " st.global.f32 [%r0], %sum;\n";
program << " Exit:\n";
program << " exit;";
program << "}\n";
ocelot::registerPTXModule( program, "f32throughput" );
const char* kernelPointer = ocelot::getKernelPointer(
"testf32InstructionThroughput", "f32throughput" );
hydrazine::Timer timer;
timer.start();
cudaLaunch( kernelPointer );
cudaThreadSynchronize();
timer.stop();
status << "Operations/sec "
<< ( (threads * ctas * iterations * unroll * 2) / timer.seconds() )
<< " seconds. \n";
float result;
cudaMemcpy( &result, input, sizeof( float ),
cudaMemcpyDeviceToHost );
bool pass = true;
if( result != k * iterations * unroll && threads == 1 && ctas == 1 )
{
status << "Program generated incorrect output " << result
<< ", expecting " << (k * iterations * unroll ) << "\n";
pass = false;
}
cudaFree( input );
return pass;
}
bool TestInstructionThroughput::doTest()
{
return testu64InstructionThroughput() && testu32InstructionThroughput()
&& testf32InstructionThroughput();
}
TestInstructionThroughput::TestInstructionThroughput()
{
name = "TestInstructionThroughput";
description = "A benchmark for PTX Instruction Throughput.";
}
}
int main(int argc, char** argv)
{
hydrazine::ArgumentParser parser( argc, argv );
test::TestInstructionThroughput test;
parser.description( test.testDescription() );
//threads, ctas, unroll, iter
parser.parse( "-t", "--threads", test.threads, 8,
"The number of threads." );
parser.parse( "-c", "--ctas", test.ctas, 1, "The number of CTAs." );
parser.parse("-u", "--unroll", test.unroll, 10, "The unrolled times");
parser.parse( "-i", "--iterations", test.iterations, 10000,
"The number of times to run through the barrier region." );
parser.parse( "-s", "--seed", test.seed, 0,
"Set the random seed, 0 implies seed with time." );
parser.parse( "-v", "--verbose", test.verbose, false,
"Print out info after the test." );
parser.parse();
test.test();
return test.passed();
}
#endif
<|endoftext|> |
<commit_before>#include "ProceduralRenderer.h"
#include <glbinding/gl/gl.h>
#include "Shader.h"
#include "util.h"
using namespace gl;
ProceduralRenderer::ProceduralRenderer(const std::vector<std::string>& includes,
const std::map<std::string, std::string>& textureFiles)
: Renderer { }
, m_screen { }
, m_program { }
, m_includes { includes }
, m_textures { }
{
for (const auto& textureFile : textureFiles)
{
m_textures.push_back(Texture(textureFile.first, textureFile.second));
}
}
ProceduralRenderer::~ProceduralRenderer()
{
}
void ProceduralRenderer::init()
{
glClearColor(1.0, 0.0, 0.0, 1.0);
reload();
}
void ProceduralRenderer::reload()
{
const std::string shaderLocation = "../source/shader/";
auto fragmentCode = util::loadFile(shaderLocation + "procedural.frag");
std::string textureString = "", includeString = "";
for (const auto& texture : m_textures)
{
textureString += Shader::textureString(texture.name());
}
for (const auto& include : m_includes)
{
textureString += Shader::includeString(include);
}
util::replace(fragmentCode, "#textures", textureString);
util::replace(fragmentCode, "#includes", includeString);
util::Group<Shader> shaders (
Shader::vertex(shaderLocation + "screenalignedquad.vert"),
Shader("procedural.frag", fragmentCode, GL_FRAGMENT_SHADER, m_includes)
);
m_program = std::make_unique<Program>(shaders);
m_program->use();
unsigned int i = 0;
for (auto& texture : m_textures)
{
glActiveTexture(GL_TEXTURE0 + i);
texture.load();
auto location = m_program->getUniformLocation(texture.name());
glUniform1i(location, i);
++i;
}
}
void ProceduralRenderer::render(const util::viewport::Viewport& viewport)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
m_program->use();
auto loc = m_program->getUniformLocation("windowSize");
glUniform2i(loc, viewport.width, viewport.height);
m_screen.draw();
}
<commit_msg>Stop glGetError calls on shader linking failure<commit_after>#include "ProceduralRenderer.h"
#include <glbinding/gl/gl.h>
#include "Shader.h"
#include "util.h"
using namespace gl;
ProceduralRenderer::ProceduralRenderer(const std::vector<std::string>& includes,
const std::map<std::string, std::string>& textureFiles)
: Renderer { }
, m_screen { }
, m_program { }
, m_includes { includes }
, m_textures { }
{
for (const auto& textureFile : textureFiles)
{
m_textures.push_back(Texture(textureFile.first, textureFile.second));
}
}
ProceduralRenderer::~ProceduralRenderer()
{
}
void ProceduralRenderer::init()
{
glClearColor(1.0, 0.0, 0.0, 1.0);
reload();
}
void ProceduralRenderer::reload()
{
const std::string shaderLocation = "../source/shader/";
auto fragmentCode = util::loadFile(shaderLocation + "procedural.frag");
std::string textureString = "", includeString = "";
for (const auto& texture : m_textures)
{
textureString += Shader::textureString(texture.name());
}
for (const auto& include : m_includes)
{
textureString += Shader::includeString(include);
}
util::replace(fragmentCode, "#textures", textureString);
util::replace(fragmentCode, "#includes", includeString);
util::Group<Shader> shaders (
Shader::vertex(shaderLocation + "screenalignedquad.vert"),
Shader("procedural.frag", fragmentCode, GL_FRAGMENT_SHADER, m_includes)
);
m_program = std::make_unique<Program>(shaders);
if (!m_program->isLinked())
{
return;
}
m_program->use();
unsigned int i = 0;
for (auto& texture : m_textures)
{
glActiveTexture(GL_TEXTURE0 + i);
texture.load();
auto location = m_program->getUniformLocation(texture.name());
glUniform1i(location, i);
++i;
}
}
void ProceduralRenderer::render(const util::viewport::Viewport& viewport)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
if (!m_program->isLinked())
{
return;
}
m_program->use();
auto loc = m_program->getUniformLocation("windowSize");
glUniform2i(loc, viewport.width, viewport.height);
m_screen.draw();
}
<|endoftext|> |
<commit_before>/*
* TTBlue Audio Object Base Class
* Copyright © 2008, Timothy Place
*
* License: This code is licensed under the terms of the GNU LGPL
* http://www.gnu.org/licenses/lgpl.html
*/
#include "TTAudioObject.h"
#include "TTEnvironment.h"
// This coeff is used in GainDataspace mapping MIDI to and from linear gain
// so that MIDI=100 equals 0 dB and MIDI = 127 equals +10 dB
static const double kGainMidiPower = log(pow(10.,10./20.))/log(127./100.);
static const double kGainMidiPowerInv = 1./kGainMidiPower;
/****************************************************************************************************/
TTAudioObject::TTAudioObject(const char* name, TTUInt16 newMaxNumChannels)
: TTObject(name), attrMute(0), inputArray(NULL), outputArray(NULL)
{
registerAttribute(TT("maxNumChannels"), kTypeUInt8, &maxNumChannels, (TTSetterMethod)&TTAudioObject::setMaxNumChannels);
registerAttribute(TT("sr"), kTypeUInt32, &sr, (TTSetterMethod)&TTAudioObject::setSr);
registerAttribute(TT("bypass"), kTypeBoolean, &attrBypass, (TTSetterMethod)&TTAudioObject::setBypass);
registerAttribute(TT("mute"), kTypeBoolean, &attrMute, (TTSetterMethod)&TTAudioObject::setMute);
registerAttribute(TT("processInPlace"), kTypeBoolean, &attrProcessInPlace);
// Set Defaults...
// Commenting this out, thus making this initial argument unused.
// The problem is that if we set it here, then it is too early to trigger the notification in the subclass.
// And then because it is already defined, then our repetition filtering won't let it through to allocate memory...
// setAttributeValue(TT("maxNumChannels"), newMaxNumChannels);
TTObjectInstantiate(kTTSym_audiosignalarray, (TTObjectPtr*)&inputArray, 2);
TTObjectInstantiate(kTTSym_audiosignalarray, (TTObjectPtr*)&outputArray, 2);
setAttributeValue(TT("sr"), ttEnvironment->sr);
setProcess(&TTAudioObject::bypassProcess);
setCalculate(&TTAudioObject::defaultCalculateMethod);
setAttributeValue(TT("bypass"), *kTTBoolNo);
setAttributeValue(TT("processInPlace"), *kTTBoolNo);
}
TTAudioObject::~TTAudioObject()
{
TTObjectRelease((TTObjectPtr*)&inputArray);
TTObjectRelease((TTObjectPtr*)&outputArray);
}
TTErr TTAudioObject::setMaxNumChannels(const TTValue& newValue)
{
if(TTUInt16(newValue) != maxNumChannels){
TTValue oldMaxNumChannels = maxNumChannels;
maxNumChannels = newValue;
sendMessage(TT("updateMaxNumChannels"), oldMaxNumChannels);
}
return kTTErrNone;
}
TTErr TTAudioObject::setSr(const TTValue& newValue)
{
sr = newValue;
srInv = 1.0/sr;
srMill = sr * 0.001;
sendMessage(TT("updateSr"));
return kTTErrNone;
}
TTErr TTAudioObject::bypassProcess(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs)
{
for(TTUInt16 i=0; i<outputs->numAudioSignals; i++){
TTAudioSignal& out = outputs->getSignal(i);
if(i<inputs->numAudioSignals){
TTAudioSignal& in = inputs->getSignal(i);
TTAudioSignal::copy(in, out);
}
else
out.clear();
}
return kTTErrNone;
}
TTErr TTAudioObject::bypassCalculate(const TTFloat64& x, TTFloat64& y)
{
y = x;
return kTTErrNone;
}
TTErr TTAudioObject::muteProcess(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs)
{
for(TTUInt16 i=0; i<inputs->numAudioSignals; i++)
(inputs->getSignal(i)).clear();
for(TTUInt16 i=0; i<outputs->numAudioSignals; i++)
(outputs->getSignal(i)).clear();
return kTTErrNone;
}
TTErr TTAudioObject::defaultCalculateMethod(const TTFloat64& x, TTFloat64& y)
{
TTAudioSignal in(1);
TTAudioSignal out(1);
TTErr err;
in.setvectorSize(1);
out.setvectorSize(1);
in.sampleVectors[0][0] = x;
err = process(in, out);
y = out.sampleVectors[0][0];
return err;
}
TTErr TTAudioObject::setProcess(TTProcessMethod newProcessMethod)
{
processMethod = newProcessMethod;
if(!calculateMethod)
calculateMethod = &TTAudioObject::defaultCalculateMethod;
if(!attrBypass){
currentProcessMethod = processMethod;
currentCalculateMethod = calculateMethod;
}
return kTTErrNone;
}
TTErr TTAudioObject::setCalculate(TTCalculateMethod newCalculateMethod)
{
calculateMethod = newCalculateMethod;
if(!attrBypass)
currentCalculateMethod = calculateMethod;
return kTTErrNone;
}
TTErr TTAudioObject::setBypass(const TTValue& value)
{
attrBypass = value;
if(attrBypass){
currentProcessMethod = &TTAudioObject::bypassProcess;
currentCalculateMethod = &TTAudioObject::bypassCalculate;
}
else if(attrMute){
currentProcessMethod = &TTAudioObject::muteProcess;
}
else{
currentProcessMethod = processMethod;
if(calculateMethod)
currentCalculateMethod = calculateMethod;
else
currentCalculateMethod = &TTAudioObject::defaultCalculateMethod;
}
return kTTErrNone;
}
TTErr TTAudioObject::setMute(const TTValue& value)
{
attrMute = value;
if(attrBypass){
currentProcessMethod = &TTAudioObject::bypassProcess;
}
else if(attrMute){
currentProcessMethod = &TTAudioObject::muteProcess;
}
else{
currentProcessMethod = processMethod;
}
return kTTErrNone;
}
TTErr TTAudioObject::calculate(const TTFloat64& x, TTFloat64& y)
{
TTErr err = kTTErrGeneric;
if(valid){
lock();
err = (this->*currentCalculateMethod)(x, y);
unlock();
}
return err;
}
TTErr TTAudioObject::calculate(const TTValue& x, TTValue& y)
{
TTErr err = kTTErrGeneric;
if(valid){
TTFloat64 in;
TTFloat64 out;
TTUInt32 size;
lock();
// at the moment we are iterating through the values using the same call to the object
// however, if the calculation involves the history of previous input or output
// then this will not work --
// TODO: there needs to be a way to request a calculation of a list on the object if it defines such a method
y.clear();
size = x.getSize();
for(TTUInt32 i=0; i<size; i++){
x.get(i, in);
err = (this->*currentCalculateMethod)(in, out);
y.append(out);
}
unlock();
}
return err;
}
TTErr TTAudioObject::process(TTAudioSignal& in, TTAudioSignal& out)
{
TTErr err = kTTErrGeneric;
if(valid){
lock();
inputArray->numAudioSignals = 1;
inputArray->setSignal(0, &in);
outputArray->numAudioSignals = 1;
outputArray->setSignal(0, &out);
err = (this->*currentProcessMethod)(inputArray, outputArray);
unlock();
}
return err;
}
TTErr TTAudioObject::process(TTAudioSignal& out)
{
TTErr err = kTTErrGeneric;
if(valid){
lock();
inputArray->numAudioSignals = 0;
outputArray->numAudioSignals = 1;
outputArray->setSignal(0, &out);
err = (this->*currentProcessMethod)(inputArray, outputArray);
unlock();
}
return err;
}
TTErr TTAudioObject::process(TTAudioSignal& in1, TTAudioSignal& in2, TTAudioSignal& out1, TTAudioSignal& out2)
{
TTErr err = kTTErrGeneric;
if(valid){
lock();
inputArray->numAudioSignals = 2;
inputArray->setSignal(0, &in1);
inputArray->setSignal(1, &in2);
outputArray->numAudioSignals = 2;
outputArray->setSignal(0, &out1);
outputArray->setSignal(1, &out2);
err = (this->*currentProcessMethod)(inputArray, outputArray);
unlock();
}
return err;
}
TTErr TTAudioObject::process(TTAudioSignal& in1, TTAudioSignal& in2, TTAudioSignal& out)
{
TTErr err = kTTErrGeneric;
if(valid){
lock();
inputArray->numAudioSignals = 2;
inputArray->setSignal(0, &in1);
inputArray->setSignal(1, &in2);
outputArray->numAudioSignals = 1;
outputArray->setSignal(0, &out);
err = (this->*currentProcessMethod)(inputArray, outputArray);
unlock();
}
return err;
}
TTErr TTAudioObject::process(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs)
{
TTErr err = kTTErrGeneric;
if(valid){
lock();
err = (this->*currentProcessMethod)(inputs, outputs);
unlock();
}
return err;
}
#if 0
#pragma mark -
#pragma mark Utilities
#endif
// RADIANS CONVERSIONS: cannot make static because of access to a member data element
// hz-to-radians conversion
TTFloat64 TTAudioObject::hertzToRadians(const TTFloat64 hz) // NOTE: Be sure to set the sr before calling this function
{
return(hz * (kTTPi / (sr * 0.5)));
}
// radians-to-hz conversion
TTFloat64 TTAudioObject::radiansToHertz(const TTFloat64 radians) // NOTE: Be sure to set the sr before calling this function
{
return((radians * sr) / kTTTwoPi);
}
// degrees-to-radians conversion
TTFloat64 TTAudioObject::degreesToRadians(const TTFloat64 degrees)
{
return((degrees * kTTPi) / 180.);
}
// radians-to-degrees conversion
TTFloat64 TTAudioObject::radiansToDegrees(const TTFloat64 radians)
{
return((radians * 180.) / kTTPi);
}
// Decay Time (seconds) to feedback coefficient conversion
TTFloat64 TTAudioObject::decayToFeedback(const TTFloat64 decay_time, TTFloat64 delay)
{
TTFloat64 fb;
delay = delay * 0.001; // convert delay from milliseconds to seconds
if(decay_time < 0){
fb = delay / -decay_time;
fb = fb * -60.;
fb = pow(10., (fb / 20.));
fb *= -1.;
}
else{
fb = delay / decay_time;
fb = fb * -60.;
fb = pow(10., (fb / 20.));
}
return(fb);
}
// return the decay time based on the feedback coefficient
TTFloat64 TTAudioObject::feedbackToDecay(const TTFloat64 feedback, const TTFloat64 delay)
{
TTFloat64 decay_time;
if(feedback > 0){
decay_time = 20. * (log10(feedback));
decay_time = -60.0 / decay_time;
decay_time = decay_time * (delay);
}
else if(feedback < 0){
decay_time = 20. * (log10(fabs(feedback)));
decay_time = -60.0 / decay_time;
decay_time = decay_time * (-delay);
}
else
decay_time = 0;
return(decay_time);
}
// ************* DECIBEL CONVERSIONS **************
// Amplitude to decibels
TTFloat64 TTAudioObject::linearToDb(const TTFloat64 value)
{
if(value >= 0)
return(20. * (log10(value)));
else
return 0;
}
// Decibels to amplitude
TTFloat64 TTAudioObject::dbToLinear(TTFloat64 value)
{
return(pow(10., (value / 20.)));
}
TTFloat64 TTAudioObject::midiToLinearGain(TTFloat64 value)
{
return pow(value * 0.01, kGainMidiPower);
}
TTFloat64 TTAudioObject::linearGainToMidi(TTFloat64 value)
{
return 100.0 * pow(value, kGainMidiPowerInv);
}
// Deviate
TTFloat64 TTAudioObject::deviate(TTFloat64 value)
{
value += (2.0 * (TTFloat32(rand()) / TTFloat32(RAND_MAX))) - 1.0; // randomize input with +1 to -1 ms
value = value * 0.001 * sr; // convert from ms to samples
value = (TTFloat32)prime(TTUInt32(value)); // find the nearest prime number (in samples)
value = (value / sr) * 1000.0; // convert back to ms
return value;
}
// Prime
TTUInt32 TTAudioObject::prime(TTUInt32 value)
{
long candidate, last, i, isPrime;
if(value < 2)
candidate = 2;
else if(value == 2)
candidate = 3;
else{
candidate = value;
if (candidate % 2 == 0) // Test only odd numbers
candidate--;
do{
isPrime = true; // Assume glorious success
candidate += 2; // Bump to the next number to test
last = TTUInt32(sqrt((TTFloat32)candidate)); // We'll check to see if candidate has any factors, from 2 to last
for (i=3; (i <= last) && isPrime; i+=2){ // Loop through odd numbers only
if((candidate % i) == 0)
isPrime = false;
}
}
while (!isPrime);
}
return candidate;
}
<commit_msg>TTAudioObject: fixed default calculate method crashes (were not allocing memory for temp signals)<commit_after>/*
* TTBlue Audio Object Base Class
* Copyright © 2008, Timothy Place
*
* License: This code is licensed under the terms of the GNU LGPL
* http://www.gnu.org/licenses/lgpl.html
*/
#include "TTAudioObject.h"
#include "TTEnvironment.h"
// This coeff is used in GainDataspace mapping MIDI to and from linear gain
// so that MIDI=100 equals 0 dB and MIDI = 127 equals +10 dB
static const double kGainMidiPower = log(pow(10.,10./20.))/log(127./100.);
static const double kGainMidiPowerInv = 1./kGainMidiPower;
/****************************************************************************************************/
TTAudioObject::TTAudioObject(const char* name, TTUInt16 newMaxNumChannels)
: TTObject(name), attrMute(0), inputArray(NULL), outputArray(NULL)
{
registerAttribute(TT("maxNumChannels"), kTypeUInt8, &maxNumChannels, (TTSetterMethod)&TTAudioObject::setMaxNumChannels);
registerAttribute(TT("sr"), kTypeUInt32, &sr, (TTSetterMethod)&TTAudioObject::setSr);
registerAttribute(TT("bypass"), kTypeBoolean, &attrBypass, (TTSetterMethod)&TTAudioObject::setBypass);
registerAttribute(TT("mute"), kTypeBoolean, &attrMute, (TTSetterMethod)&TTAudioObject::setMute);
registerAttribute(TT("processInPlace"), kTypeBoolean, &attrProcessInPlace);
// Set Defaults...
// Commenting this out, thus making this initial argument unused.
// The problem is that if we set it here, then it is too early to trigger the notification in the subclass.
// And then because it is already defined, then our repetition filtering won't let it through to allocate memory...
// setAttributeValue(TT("maxNumChannels"), newMaxNumChannels);
TTObjectInstantiate(kTTSym_audiosignalarray, (TTObjectPtr*)&inputArray, 2);
TTObjectInstantiate(kTTSym_audiosignalarray, (TTObjectPtr*)&outputArray, 2);
setAttributeValue(TT("sr"), ttEnvironment->sr);
setProcess(&TTAudioObject::bypassProcess);
setCalculate(&TTAudioObject::defaultCalculateMethod);
setAttributeValue(TT("bypass"), *kTTBoolNo);
setAttributeValue(TT("processInPlace"), *kTTBoolNo);
}
TTAudioObject::~TTAudioObject()
{
TTObjectRelease((TTObjectPtr*)&inputArray);
TTObjectRelease((TTObjectPtr*)&outputArray);
}
TTErr TTAudioObject::setMaxNumChannels(const TTValue& newValue)
{
if(TTUInt16(newValue) != maxNumChannels){
TTValue oldMaxNumChannels = maxNumChannels;
maxNumChannels = newValue;
sendMessage(TT("updateMaxNumChannels"), oldMaxNumChannels);
}
return kTTErrNone;
}
TTErr TTAudioObject::setSr(const TTValue& newValue)
{
sr = newValue;
srInv = 1.0/sr;
srMill = sr * 0.001;
sendMessage(TT("updateSr"));
return kTTErrNone;
}
TTErr TTAudioObject::bypassProcess(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs)
{
for(TTUInt16 i=0; i<outputs->numAudioSignals; i++){
TTAudioSignal& out = outputs->getSignal(i);
if(i<inputs->numAudioSignals){
TTAudioSignal& in = inputs->getSignal(i);
TTAudioSignal::copy(in, out);
}
else
out.clear();
}
return kTTErrNone;
}
TTErr TTAudioObject::bypassCalculate(const TTFloat64& x, TTFloat64& y)
{
y = x;
return kTTErrNone;
}
TTErr TTAudioObject::muteProcess(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs)
{
for(TTUInt16 i=0; i<inputs->numAudioSignals; i++)
(inputs->getSignal(i)).clear();
for(TTUInt16 i=0; i<outputs->numAudioSignals; i++)
(outputs->getSignal(i)).clear();
return kTTErrNone;
}
TTErr TTAudioObject::defaultCalculateMethod(const TTFloat64& x, TTFloat64& y)
{
TTAudioSignal in(1);
TTAudioSignal out(1);
TTErr err;
in.allocWithVectorSize(1);
out.allocWithVectorSize(1);
in.sampleVectors[0][0] = x;
err = process(in, out);
y = out.sampleVectors[0][0];
return err;
}
TTErr TTAudioObject::setProcess(TTProcessMethod newProcessMethod)
{
processMethod = newProcessMethod;
if(!calculateMethod)
calculateMethod = &TTAudioObject::defaultCalculateMethod;
if(!attrBypass){
currentProcessMethod = processMethod;
currentCalculateMethod = calculateMethod;
}
return kTTErrNone;
}
TTErr TTAudioObject::setCalculate(TTCalculateMethod newCalculateMethod)
{
calculateMethod = newCalculateMethod;
if(!attrBypass)
currentCalculateMethod = calculateMethod;
return kTTErrNone;
}
TTErr TTAudioObject::setBypass(const TTValue& value)
{
attrBypass = value;
if(attrBypass){
currentProcessMethod = &TTAudioObject::bypassProcess;
currentCalculateMethod = &TTAudioObject::bypassCalculate;
}
else if(attrMute){
currentProcessMethod = &TTAudioObject::muteProcess;
}
else{
currentProcessMethod = processMethod;
if(calculateMethod)
currentCalculateMethod = calculateMethod;
else
currentCalculateMethod = &TTAudioObject::defaultCalculateMethod;
}
return kTTErrNone;
}
TTErr TTAudioObject::setMute(const TTValue& value)
{
attrMute = value;
if(attrBypass){
currentProcessMethod = &TTAudioObject::bypassProcess;
}
else if(attrMute){
currentProcessMethod = &TTAudioObject::muteProcess;
}
else{
currentProcessMethod = processMethod;
}
return kTTErrNone;
}
TTErr TTAudioObject::calculate(const TTFloat64& x, TTFloat64& y)
{
TTErr err = kTTErrGeneric;
if(valid){
lock();
err = (this->*currentCalculateMethod)(x, y);
unlock();
}
return err;
}
TTErr TTAudioObject::calculate(const TTValue& x, TTValue& y)
{
TTErr err = kTTErrGeneric;
if(valid){
TTFloat64 in;
TTFloat64 out;
TTUInt32 size;
lock();
// at the moment we are iterating through the values using the same call to the object
// however, if the calculation involves the history of previous input or output
// then this will not work --
// TODO: there needs to be a way to request a calculation of a list on the object if it defines such a method
y.clear();
size = x.getSize();
for(TTUInt32 i=0; i<size; i++){
x.get(i, in);
err = (this->*currentCalculateMethod)(in, out);
y.append(out);
}
unlock();
}
return err;
}
TTErr TTAudioObject::process(TTAudioSignal& in, TTAudioSignal& out)
{
TTErr err = kTTErrGeneric;
if(valid){
lock();
inputArray->numAudioSignals = 1;
inputArray->setSignal(0, &in);
outputArray->numAudioSignals = 1;
outputArray->setSignal(0, &out);
err = (this->*currentProcessMethod)(inputArray, outputArray);
unlock();
}
return err;
}
TTErr TTAudioObject::process(TTAudioSignal& out)
{
TTErr err = kTTErrGeneric;
if(valid){
lock();
inputArray->numAudioSignals = 0;
outputArray->numAudioSignals = 1;
outputArray->setSignal(0, &out);
err = (this->*currentProcessMethod)(inputArray, outputArray);
unlock();
}
return err;
}
TTErr TTAudioObject::process(TTAudioSignal& in1, TTAudioSignal& in2, TTAudioSignal& out1, TTAudioSignal& out2)
{
TTErr err = kTTErrGeneric;
if(valid){
lock();
inputArray->numAudioSignals = 2;
inputArray->setSignal(0, &in1);
inputArray->setSignal(1, &in2);
outputArray->numAudioSignals = 2;
outputArray->setSignal(0, &out1);
outputArray->setSignal(1, &out2);
err = (this->*currentProcessMethod)(inputArray, outputArray);
unlock();
}
return err;
}
TTErr TTAudioObject::process(TTAudioSignal& in1, TTAudioSignal& in2, TTAudioSignal& out)
{
TTErr err = kTTErrGeneric;
if(valid){
lock();
inputArray->numAudioSignals = 2;
inputArray->setSignal(0, &in1);
inputArray->setSignal(1, &in2);
outputArray->numAudioSignals = 1;
outputArray->setSignal(0, &out);
err = (this->*currentProcessMethod)(inputArray, outputArray);
unlock();
}
return err;
}
TTErr TTAudioObject::process(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs)
{
TTErr err = kTTErrGeneric;
if(valid){
lock();
err = (this->*currentProcessMethod)(inputs, outputs);
unlock();
}
return err;
}
#if 0
#pragma mark -
#pragma mark Utilities
#endif
// RADIANS CONVERSIONS: cannot make static because of access to a member data element
// hz-to-radians conversion
TTFloat64 TTAudioObject::hertzToRadians(const TTFloat64 hz) // NOTE: Be sure to set the sr before calling this function
{
return(hz * (kTTPi / (sr * 0.5)));
}
// radians-to-hz conversion
TTFloat64 TTAudioObject::radiansToHertz(const TTFloat64 radians) // NOTE: Be sure to set the sr before calling this function
{
return((radians * sr) / kTTTwoPi);
}
// degrees-to-radians conversion
TTFloat64 TTAudioObject::degreesToRadians(const TTFloat64 degrees)
{
return((degrees * kTTPi) / 180.);
}
// radians-to-degrees conversion
TTFloat64 TTAudioObject::radiansToDegrees(const TTFloat64 radians)
{
return((radians * 180.) / kTTPi);
}
// Decay Time (seconds) to feedback coefficient conversion
TTFloat64 TTAudioObject::decayToFeedback(const TTFloat64 decay_time, TTFloat64 delay)
{
TTFloat64 fb;
delay = delay * 0.001; // convert delay from milliseconds to seconds
if(decay_time < 0){
fb = delay / -decay_time;
fb = fb * -60.;
fb = pow(10., (fb / 20.));
fb *= -1.;
}
else{
fb = delay / decay_time;
fb = fb * -60.;
fb = pow(10., (fb / 20.));
}
return(fb);
}
// return the decay time based on the feedback coefficient
TTFloat64 TTAudioObject::feedbackToDecay(const TTFloat64 feedback, const TTFloat64 delay)
{
TTFloat64 decay_time;
if(feedback > 0){
decay_time = 20. * (log10(feedback));
decay_time = -60.0 / decay_time;
decay_time = decay_time * (delay);
}
else if(feedback < 0){
decay_time = 20. * (log10(fabs(feedback)));
decay_time = -60.0 / decay_time;
decay_time = decay_time * (-delay);
}
else
decay_time = 0;
return(decay_time);
}
// ************* DECIBEL CONVERSIONS **************
// Amplitude to decibels
TTFloat64 TTAudioObject::linearToDb(const TTFloat64 value)
{
if(value >= 0)
return(20. * (log10(value)));
else
return 0;
}
// Decibels to amplitude
TTFloat64 TTAudioObject::dbToLinear(TTFloat64 value)
{
return(pow(10., (value / 20.)));
}
TTFloat64 TTAudioObject::midiToLinearGain(TTFloat64 value)
{
return pow(value * 0.01, kGainMidiPower);
}
TTFloat64 TTAudioObject::linearGainToMidi(TTFloat64 value)
{
return 100.0 * pow(value, kGainMidiPowerInv);
}
// Deviate
TTFloat64 TTAudioObject::deviate(TTFloat64 value)
{
value += (2.0 * (TTFloat32(rand()) / TTFloat32(RAND_MAX))) - 1.0; // randomize input with +1 to -1 ms
value = value * 0.001 * sr; // convert from ms to samples
value = (TTFloat32)prime(TTUInt32(value)); // find the nearest prime number (in samples)
value = (value / sr) * 1000.0; // convert back to ms
return value;
}
// Prime
TTUInt32 TTAudioObject::prime(TTUInt32 value)
{
long candidate, last, i, isPrime;
if(value < 2)
candidate = 2;
else if(value == 2)
candidate = 3;
else{
candidate = value;
if (candidate % 2 == 0) // Test only odd numbers
candidate--;
do{
isPrime = true; // Assume glorious success
candidate += 2; // Bump to the next number to test
last = TTUInt32(sqrt((TTFloat32)candidate)); // We'll check to see if candidate has any factors, from 2 to last
for (i=3; (i <= last) && isPrime; i+=2){ // Loop through odd numbers only
if((candidate % i) == 0)
isPrime = false;
}
}
while (!isPrime);
}
return candidate;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2015 ARM Limited. All rights reserved.
* SPDX-License-Identifier: Apache-2.0
* Licensed under the Apache License, Version 2.0 (the License); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdio.h>
#include "include/m2mtlvdeserializer.h"
#include "mbed-client/m2mconstants.h"
#include "include/nsdllinker.h"
#include "mbed-trace/mbed_trace.h"
#define TRACE_GROUP "mClt"
#define BUFFER_SIZE 10
M2MTLVDeserializer::M2MTLVDeserializer()
{
}
M2MTLVDeserializer::~M2MTLVDeserializer()
{
}
bool M2MTLVDeserializer::is_object_instance(uint8_t *tlv)
{
return is_object_instance(tlv, 0);
}
bool M2MTLVDeserializer::is_resource(uint8_t *tlv)
{
return is_resource(tlv, 0);
}
bool M2MTLVDeserializer::is_multiple_resource(uint8_t *tlv)
{
return is_multiple_resource(tlv, 0);
}
bool M2MTLVDeserializer::is_resource_instance(uint8_t *tlv)
{
return is_resource_instance(tlv, 0);
}
M2MTLVDeserializer::Error M2MTLVDeserializer::deserialise_object_instances(uint8_t* tlv,
uint32_t tlv_size,
M2MObject &object,
M2MTLVDeserializer::Operation operation)
{
M2MTLVDeserializer::Error error = M2MTLVDeserializer::None;
if (is_object_instance(tlv) ) {
tr_debug("M2MTLVDeserializer::deserialise_object_instances");
error = deserialize_object_instances(tlv, tlv_size, 0, object,operation,false);
if(M2MTLVDeserializer::None == error) {
error = deserialize_object_instances(tlv, tlv_size, 0, object,operation,true);
}
} else {
tr_debug("M2MTLVDeserializer::deserialise_object_instances ::NotValid");
error = M2MTLVDeserializer::NotValid;
}
return error;
}
M2MTLVDeserializer::Error M2MTLVDeserializer::deserialize_resources(uint8_t *tlv,
uint32_t tlv_size,
M2MObjectInstance &object_instance,
M2MTLVDeserializer::Operation operation)
{
M2MTLVDeserializer::Error error = M2MTLVDeserializer::None;
if (!is_resource(tlv) && !is_multiple_resource(tlv)) {
error = M2MTLVDeserializer::NotValid;
} else {
error = deserialize_resources(tlv, tlv_size, 0, object_instance, operation,false);
if(M2MTLVDeserializer::None == error) {
error = deserialize_resources(tlv, tlv_size, 0, object_instance, operation,true);
}
}
return error;
}
M2MTLVDeserializer::Error M2MTLVDeserializer::deserialize_resource_instances(uint8_t *tlv,
uint32_t tlv_size,
M2MResource &resource,
M2MTLVDeserializer::Operation operation)
{
M2MTLVDeserializer::Error error = M2MTLVDeserializer::None;
if (!is_multiple_resource(tlv)) {
error = M2MTLVDeserializer::NotValid;
} else {
tr_debug("M2MTLVDeserializer::deserialize_resource_instances()");
uint8_t offset = 2;
((tlv[0] & 0x20) == 0) ? offset : offset++;
uint8_t length = tlv[0] & 0x18;
if(length == 0x08) {
offset+= 1;
} else if(length == 0x10) {
offset+= 2;
} else if(length == 0x18) {
offset+= 3;
}
tr_debug("M2MTLVDeserializer::deserialize_resource_instances() Offset %d", offset);
error = deserialize_resource_instances(tlv, tlv_size, offset, resource, operation,false);
if(M2MTLVDeserializer::None == error) {
error = deserialize_resource_instances(tlv, tlv_size, offset, resource, operation,true);
}
}
return error;
}
M2MTLVDeserializer::Error M2MTLVDeserializer::deserialize_object_instances(uint8_t *tlv,
uint32_t tlv_size,
uint32_t offset,
M2MObject &object,
M2MTLVDeserializer::Operation operation,
bool update_value)
{
tr_debug("M2MTLVDeserializer::deserialize_object_instances()");
M2MTLVDeserializer::Error error = M2MTLVDeserializer::None;
TypeIdLength *til = TypeIdLength::createTypeIdLength(tlv, offset)->deserialize();
offset = til->_offset;
M2MObjectInstanceList list = object.instances();
M2MObjectInstanceList::const_iterator it;
it = list.begin();
if (TYPE_OBJECT_INSTANCE == til->_type) {
for (; it!=list.end(); it++) {
if((*it)->instance_id() == til->_id) {
error = deserialize_resources(tlv, tlv_size, offset, (**it),operation, update_value);
}
}
offset += til->_length;
if(offset < tlv_size) {
error = deserialize_object_instances(tlv, tlv_size, offset, object, operation, update_value);
}
delete til;
}
return error;
}
M2MTLVDeserializer::Error M2MTLVDeserializer::deserialize_resources(uint8_t *tlv,
uint32_t tlv_size,
uint32_t offset,
M2MObjectInstance &object_instance,
M2MTLVDeserializer::Operation operation,
bool update_value)
{
tr_debug("M2MTLVDeserializer::deserialize_resources()");
M2MTLVDeserializer::Error error = M2MTLVDeserializer::None;
TypeIdLength *til = TypeIdLength::createTypeIdLength(tlv, offset)->deserialize();
offset = til->_offset;
M2MResourceList list = object_instance.resources();
M2MResourceList::const_iterator it;
it = list.begin();
if (TYPE_RESOURCE == til->_type || TYPE_RESOURCE_INSTANCE == til->_type) {
bool found = false;
for (; it!=list.end(); it++) {
if((*it)->name_id() == til->_id){
tr_debug("M2MTLVDeserializer::deserialize_resources() - Resource ID %d ", til->_id);
found = true;
if(update_value) {
if(til->_length > 0) {
tr_debug("M2MTLVDeserializer::deserialize_resources() - Update value");
(*it)->set_value(tlv+offset, til->_length);
} else {
tr_debug("M2MTLVDeserializer::deserialize_resources() - Clear Value");
(*it)->clear_value();
}
break;
} else if(0 == ((*it)->operation() & SN_GRS_PUT_ALLOWED)) {
tr_debug("M2MTLVDeserializer::deserialize_resources() - NOT_ALLOWED");
error = M2MTLVDeserializer::NotAllowed;
break;
}
}
}
if(!found) {
if(M2MTLVDeserializer::Post == operation) {
//Create a new Resource
String id;
id.append_int(til->_id);
M2MResource *resource = object_instance.create_dynamic_resource(id,"",M2MResourceInstance::INTEGER,true,false);
if(resource) {
resource->set_operation(M2MBase::GET_PUT_POST_DELETE_ALLOWED);
}
} else if(M2MTLVDeserializer::Put == operation) {
error = M2MTLVDeserializer::NotFound;
}
}
} else if (TYPE_MULTIPLE_RESOURCE == til->_type) {
for (; it!=list.end(); it++) {
if((*it)->supports_multiple_instances()) {
error = deserialize_resource_instances(tlv, tlv_size-offset, offset, (**it), object_instance, operation, update_value);
}
}
} else {
delete til;
error = M2MTLVDeserializer::NotValid;
return error;
}
offset += til->_length;
delete til;
if(offset < tlv_size) {
error = deserialize_resources(tlv, tlv_size, offset, object_instance, operation, update_value);
}
return error;
}
M2MTLVDeserializer::Error M2MTLVDeserializer::deserialize_resource_instances(uint8_t *tlv,
uint32_t tlv_size,
uint32_t offset,
M2MResource &resource,
M2MObjectInstance &object_instance,
M2MTLVDeserializer::Operation operation,
bool update_value)
{
M2MTLVDeserializer::Error error = M2MTLVDeserializer::None;
TypeIdLength *til = TypeIdLength::createTypeIdLength(tlv, offset)->deserialize();
offset = til->_offset;
if (TYPE_MULTIPLE_RESOURCE == til->_type || TYPE_RESOURCE_INSTANCE == til->_type) {
M2MResourceInstanceList list = resource.resource_instances();
M2MResourceInstanceList::const_iterator it;
it = list.begin();
bool found = false;
for (; it!=list.end(); it++) {
if((*it)->instance_id() == til->_id) {
found = true;
if(update_value) {
if(til->_length > 0) {
(*it)->set_value(tlv+offset, til->_length);
} else {
(*it)->clear_value();
}
break;
} else if(0 == ((*it)->operation() & SN_GRS_PUT_ALLOWED)) {
error = M2MTLVDeserializer::NotAllowed;
break;
}
}
}
if(!found) {
if(M2MTLVDeserializer::Post == operation) {
// Create a new Resource Instance
M2MResourceInstance *res_instance = object_instance.create_dynamic_resource_instance(resource.name(),"",
M2MResourceInstance::INTEGER,
true,
til->_id);
if(res_instance) {
res_instance->set_operation(M2MBase::GET_PUT_POST_DELETE_ALLOWED);
}
} else if(M2MTLVDeserializer::Put == operation) {
error = M2MTLVDeserializer::NotFound;
}
}
} else {
delete til;
error = M2MTLVDeserializer::NotValid;
return error;
}
offset += til->_length;
delete til;
if(offset < tlv_size) {
error = deserialize_resource_instances(tlv, tlv_size-offset, offset, resource, object_instance, operation, update_value);
}
return error;
}
M2MTLVDeserializer::Error M2MTLVDeserializer::deserialize_resource_instances(uint8_t *tlv,
uint32_t tlv_size,
uint32_t offset,
M2MResource &resource,
M2MTLVDeserializer::Operation operation,
bool update_value)
{
M2MTLVDeserializer::Error error = M2MTLVDeserializer::None;
TypeIdLength *til = TypeIdLength::createTypeIdLength(tlv, offset)->deserialize();
offset = til->_offset;
if (TYPE_RESOURCE_INSTANCE == til->_type) {
M2MResourceInstanceList list = resource.resource_instances();
M2MResourceInstanceList::const_iterator it;
it = list.begin();
bool found = false;
for (; it!=list.end(); it++) {
if((*it)->instance_id() == til->_id) {
found = true;
if(update_value) {
if(til->_length > 0) {
(*it)->set_value(tlv+offset, til->_length);
} else {
(*it)->clear_value();
}
break;
} else if(0 == ((*it)->operation() & SN_GRS_PUT_ALLOWED)) {
error = M2MTLVDeserializer::NotAllowed;
break;
}
}
}
if(!found) {
if(M2MTLVDeserializer::Post == operation) {
error = M2MTLVDeserializer::NotAllowed;
} else if(M2MTLVDeserializer::Put == operation) {
error = M2MTLVDeserializer::NotFound;
}
}
} else {
delete til;
error = M2MTLVDeserializer::NotValid;
return error;
}
offset += til->_length;
delete til;
if(offset < tlv_size) {
error = deserialize_resource_instances(tlv, tlv_size-offset, offset, resource, operation, update_value);
}
return error;
}
bool M2MTLVDeserializer::is_object_instance(uint8_t *tlv, uint32_t offset)
{
bool ret = false;
if (tlv) {
uint8_t value = tlv[offset];
ret = (TYPE_OBJECT_INSTANCE == (value & TYPE_RESOURCE));
}
return ret;
}
uint16_t M2MTLVDeserializer::instance_id(uint8_t *tlv)
{
TypeIdLength *til = TypeIdLength::createTypeIdLength(tlv, 0)->deserialize();
uint16_t id = til->_id;
delete til;
return id;
}
bool M2MTLVDeserializer::is_resource(uint8_t *tlv, uint32_t offset)
{
bool ret = false;
if (tlv) {
ret = (TYPE_RESOURCE == (tlv[offset] & TYPE_RESOURCE));
}
return ret;
}
bool M2MTLVDeserializer::is_multiple_resource(uint8_t *tlv, uint32_t offset)
{
bool ret = false;
if (tlv) {
ret = (TYPE_MULTIPLE_RESOURCE == (tlv[offset] & TYPE_RESOURCE));
}
return ret;
}
bool M2MTLVDeserializer::is_resource_instance(uint8_t *tlv, uint32_t offset)
{
bool ret = false;
if (tlv) {
ret = (TYPE_RESOURCE_INSTANCE == (tlv[offset] & TYPE_RESOURCE));
}
return ret;
}
TypeIdLength* TypeIdLength::createTypeIdLength(uint8_t *tlv, uint32_t offset)
{
TypeIdLength *til = new TypeIdLength();
til->_tlv = tlv;
til->_offset = offset;
til->_type = tlv[offset] & 0xC0;
til->_id = 0;
til->_length = 0;
return til;
}
TypeIdLength* TypeIdLength::deserialize()
{
uint32_t idLength = _tlv[_offset] & ID16;
uint32_t lengthType = _tlv[_offset] & LENGTH24;
if (0 == lengthType) {
_length = _tlv[_offset] & 0x07;
}
_offset++;
deserialiseID(idLength);
deserialiseLength(lengthType);
return this;
}
void TypeIdLength::deserialiseID(uint32_t idLength)
{
_id = _tlv[_offset++] & 0xFF;
if (ID16 == idLength) {
_id = (_id << 8) + (_tlv[_offset++] & 0xFF);
}
}
void TypeIdLength::deserialiseLength(uint32_t lengthType)
{
if (lengthType > 0) {
_length = _tlv[_offset++] & 0xFF;
}
if (lengthType > LENGTH8) {
_length = (_length << 8) + (_tlv[_offset++] & 0xFF);
}
if (lengthType > LENGTH16) {
_length = (_length << 8) + (_tlv[_offset++] & 0xFF);
}
}
<commit_msg>Fix memory leak in deserialize_object_instances<commit_after>/*
* Copyright (c) 2015 ARM Limited. All rights reserved.
* SPDX-License-Identifier: Apache-2.0
* Licensed under the Apache License, Version 2.0 (the License); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdio.h>
#include "include/m2mtlvdeserializer.h"
#include "mbed-client/m2mconstants.h"
#include "include/nsdllinker.h"
#include "mbed-trace/mbed_trace.h"
#define TRACE_GROUP "mClt"
#define BUFFER_SIZE 10
M2MTLVDeserializer::M2MTLVDeserializer()
{
}
M2MTLVDeserializer::~M2MTLVDeserializer()
{
}
bool M2MTLVDeserializer::is_object_instance(uint8_t *tlv)
{
return is_object_instance(tlv, 0);
}
bool M2MTLVDeserializer::is_resource(uint8_t *tlv)
{
return is_resource(tlv, 0);
}
bool M2MTLVDeserializer::is_multiple_resource(uint8_t *tlv)
{
return is_multiple_resource(tlv, 0);
}
bool M2MTLVDeserializer::is_resource_instance(uint8_t *tlv)
{
return is_resource_instance(tlv, 0);
}
M2MTLVDeserializer::Error M2MTLVDeserializer::deserialise_object_instances(uint8_t* tlv,
uint32_t tlv_size,
M2MObject &object,
M2MTLVDeserializer::Operation operation)
{
M2MTLVDeserializer::Error error = M2MTLVDeserializer::None;
if (is_object_instance(tlv) ) {
tr_debug("M2MTLVDeserializer::deserialise_object_instances");
error = deserialize_object_instances(tlv, tlv_size, 0, object,operation,false);
if(M2MTLVDeserializer::None == error) {
error = deserialize_object_instances(tlv, tlv_size, 0, object,operation,true);
}
} else {
tr_debug("M2MTLVDeserializer::deserialise_object_instances ::NotValid");
error = M2MTLVDeserializer::NotValid;
}
return error;
}
M2MTLVDeserializer::Error M2MTLVDeserializer::deserialize_resources(uint8_t *tlv,
uint32_t tlv_size,
M2MObjectInstance &object_instance,
M2MTLVDeserializer::Operation operation)
{
M2MTLVDeserializer::Error error = M2MTLVDeserializer::None;
if (!is_resource(tlv) && !is_multiple_resource(tlv)) {
error = M2MTLVDeserializer::NotValid;
} else {
error = deserialize_resources(tlv, tlv_size, 0, object_instance, operation,false);
if(M2MTLVDeserializer::None == error) {
error = deserialize_resources(tlv, tlv_size, 0, object_instance, operation,true);
}
}
return error;
}
M2MTLVDeserializer::Error M2MTLVDeserializer::deserialize_resource_instances(uint8_t *tlv,
uint32_t tlv_size,
M2MResource &resource,
M2MTLVDeserializer::Operation operation)
{
M2MTLVDeserializer::Error error = M2MTLVDeserializer::None;
if (!is_multiple_resource(tlv)) {
error = M2MTLVDeserializer::NotValid;
} else {
tr_debug("M2MTLVDeserializer::deserialize_resource_instances()");
uint8_t offset = 2;
((tlv[0] & 0x20) == 0) ? offset : offset++;
uint8_t length = tlv[0] & 0x18;
if(length == 0x08) {
offset+= 1;
} else if(length == 0x10) {
offset+= 2;
} else if(length == 0x18) {
offset+= 3;
}
tr_debug("M2MTLVDeserializer::deserialize_resource_instances() Offset %d", offset);
error = deserialize_resource_instances(tlv, tlv_size, offset, resource, operation,false);
if(M2MTLVDeserializer::None == error) {
error = deserialize_resource_instances(tlv, tlv_size, offset, resource, operation,true);
}
}
return error;
}
M2MTLVDeserializer::Error M2MTLVDeserializer::deserialize_object_instances(uint8_t *tlv,
uint32_t tlv_size,
uint32_t offset,
M2MObject &object,
M2MTLVDeserializer::Operation operation,
bool update_value)
{
tr_debug("M2MTLVDeserializer::deserialize_object_instances()");
M2MTLVDeserializer::Error error = M2MTLVDeserializer::None;
TypeIdLength *til = TypeIdLength::createTypeIdLength(tlv, offset)->deserialize();
offset = til->_offset;
M2MObjectInstanceList list = object.instances();
M2MObjectInstanceList::const_iterator it;
it = list.begin();
if (TYPE_OBJECT_INSTANCE == til->_type) {
for (; it!=list.end(); it++) {
if((*it)->instance_id() == til->_id) {
error = deserialize_resources(tlv, tlv_size, offset, (**it),operation, update_value);
}
}
offset += til->_length;
if(offset < tlv_size) {
error = deserialize_object_instances(tlv, tlv_size, offset, object, operation, update_value);
}
}
delete til;
return error;
}
M2MTLVDeserializer::Error M2MTLVDeserializer::deserialize_resources(uint8_t *tlv,
uint32_t tlv_size,
uint32_t offset,
M2MObjectInstance &object_instance,
M2MTLVDeserializer::Operation operation,
bool update_value)
{
tr_debug("M2MTLVDeserializer::deserialize_resources()");
M2MTLVDeserializer::Error error = M2MTLVDeserializer::None;
TypeIdLength *til = TypeIdLength::createTypeIdLength(tlv, offset)->deserialize();
offset = til->_offset;
M2MResourceList list = object_instance.resources();
M2MResourceList::const_iterator it;
it = list.begin();
if (TYPE_RESOURCE == til->_type || TYPE_RESOURCE_INSTANCE == til->_type) {
bool found = false;
for (; it!=list.end(); it++) {
if((*it)->name_id() == til->_id){
tr_debug("M2MTLVDeserializer::deserialize_resources() - Resource ID %d ", til->_id);
found = true;
if(update_value) {
if(til->_length > 0) {
tr_debug("M2MTLVDeserializer::deserialize_resources() - Update value");
(*it)->set_value(tlv+offset, til->_length);
} else {
tr_debug("M2MTLVDeserializer::deserialize_resources() - Clear Value");
(*it)->clear_value();
}
break;
} else if(0 == ((*it)->operation() & SN_GRS_PUT_ALLOWED)) {
tr_debug("M2MTLVDeserializer::deserialize_resources() - NOT_ALLOWED");
error = M2MTLVDeserializer::NotAllowed;
break;
}
}
}
if(!found) {
if(M2MTLVDeserializer::Post == operation) {
//Create a new Resource
String id;
id.append_int(til->_id);
M2MResource *resource = object_instance.create_dynamic_resource(id,"",M2MResourceInstance::INTEGER,true,false);
if(resource) {
resource->set_operation(M2MBase::GET_PUT_POST_DELETE_ALLOWED);
}
} else if(M2MTLVDeserializer::Put == operation) {
error = M2MTLVDeserializer::NotFound;
}
}
} else if (TYPE_MULTIPLE_RESOURCE == til->_type) {
for (; it!=list.end(); it++) {
if((*it)->supports_multiple_instances()) {
error = deserialize_resource_instances(tlv, tlv_size-offset, offset, (**it), object_instance, operation, update_value);
}
}
} else {
delete til;
error = M2MTLVDeserializer::NotValid;
return error;
}
offset += til->_length;
delete til;
if(offset < tlv_size) {
error = deserialize_resources(tlv, tlv_size, offset, object_instance, operation, update_value);
}
return error;
}
M2MTLVDeserializer::Error M2MTLVDeserializer::deserialize_resource_instances(uint8_t *tlv,
uint32_t tlv_size,
uint32_t offset,
M2MResource &resource,
M2MObjectInstance &object_instance,
M2MTLVDeserializer::Operation operation,
bool update_value)
{
M2MTLVDeserializer::Error error = M2MTLVDeserializer::None;
TypeIdLength *til = TypeIdLength::createTypeIdLength(tlv, offset)->deserialize();
offset = til->_offset;
if (TYPE_MULTIPLE_RESOURCE == til->_type || TYPE_RESOURCE_INSTANCE == til->_type) {
M2MResourceInstanceList list = resource.resource_instances();
M2MResourceInstanceList::const_iterator it;
it = list.begin();
bool found = false;
for (; it!=list.end(); it++) {
if((*it)->instance_id() == til->_id) {
found = true;
if(update_value) {
if(til->_length > 0) {
(*it)->set_value(tlv+offset, til->_length);
} else {
(*it)->clear_value();
}
break;
} else if(0 == ((*it)->operation() & SN_GRS_PUT_ALLOWED)) {
error = M2MTLVDeserializer::NotAllowed;
break;
}
}
}
if(!found) {
if(M2MTLVDeserializer::Post == operation) {
// Create a new Resource Instance
M2MResourceInstance *res_instance = object_instance.create_dynamic_resource_instance(resource.name(),"",
M2MResourceInstance::INTEGER,
true,
til->_id);
if(res_instance) {
res_instance->set_operation(M2MBase::GET_PUT_POST_DELETE_ALLOWED);
}
} else if(M2MTLVDeserializer::Put == operation) {
error = M2MTLVDeserializer::NotFound;
}
}
} else {
delete til;
error = M2MTLVDeserializer::NotValid;
return error;
}
offset += til->_length;
delete til;
if(offset < tlv_size) {
error = deserialize_resource_instances(tlv, tlv_size-offset, offset, resource, object_instance, operation, update_value);
}
return error;
}
M2MTLVDeserializer::Error M2MTLVDeserializer::deserialize_resource_instances(uint8_t *tlv,
uint32_t tlv_size,
uint32_t offset,
M2MResource &resource,
M2MTLVDeserializer::Operation operation,
bool update_value)
{
M2MTLVDeserializer::Error error = M2MTLVDeserializer::None;
TypeIdLength *til = TypeIdLength::createTypeIdLength(tlv, offset)->deserialize();
offset = til->_offset;
if (TYPE_RESOURCE_INSTANCE == til->_type) {
M2MResourceInstanceList list = resource.resource_instances();
M2MResourceInstanceList::const_iterator it;
it = list.begin();
bool found = false;
for (; it!=list.end(); it++) {
if((*it)->instance_id() == til->_id) {
found = true;
if(update_value) {
if(til->_length > 0) {
(*it)->set_value(tlv+offset, til->_length);
} else {
(*it)->clear_value();
}
break;
} else if(0 == ((*it)->operation() & SN_GRS_PUT_ALLOWED)) {
error = M2MTLVDeserializer::NotAllowed;
break;
}
}
}
if(!found) {
if(M2MTLVDeserializer::Post == operation) {
error = M2MTLVDeserializer::NotAllowed;
} else if(M2MTLVDeserializer::Put == operation) {
error = M2MTLVDeserializer::NotFound;
}
}
} else {
delete til;
error = M2MTLVDeserializer::NotValid;
return error;
}
offset += til->_length;
delete til;
if(offset < tlv_size) {
error = deserialize_resource_instances(tlv, tlv_size-offset, offset, resource, operation, update_value);
}
return error;
}
bool M2MTLVDeserializer::is_object_instance(uint8_t *tlv, uint32_t offset)
{
bool ret = false;
if (tlv) {
uint8_t value = tlv[offset];
ret = (TYPE_OBJECT_INSTANCE == (value & TYPE_RESOURCE));
}
return ret;
}
uint16_t M2MTLVDeserializer::instance_id(uint8_t *tlv)
{
TypeIdLength *til = TypeIdLength::createTypeIdLength(tlv, 0)->deserialize();
uint16_t id = til->_id;
delete til;
return id;
}
bool M2MTLVDeserializer::is_resource(uint8_t *tlv, uint32_t offset)
{
bool ret = false;
if (tlv) {
ret = (TYPE_RESOURCE == (tlv[offset] & TYPE_RESOURCE));
}
return ret;
}
bool M2MTLVDeserializer::is_multiple_resource(uint8_t *tlv, uint32_t offset)
{
bool ret = false;
if (tlv) {
ret = (TYPE_MULTIPLE_RESOURCE == (tlv[offset] & TYPE_RESOURCE));
}
return ret;
}
bool M2MTLVDeserializer::is_resource_instance(uint8_t *tlv, uint32_t offset)
{
bool ret = false;
if (tlv) {
ret = (TYPE_RESOURCE_INSTANCE == (tlv[offset] & TYPE_RESOURCE));
}
return ret;
}
TypeIdLength* TypeIdLength::createTypeIdLength(uint8_t *tlv, uint32_t offset)
{
TypeIdLength *til = new TypeIdLength();
til->_tlv = tlv;
til->_offset = offset;
til->_type = tlv[offset] & 0xC0;
til->_id = 0;
til->_length = 0;
return til;
}
TypeIdLength* TypeIdLength::deserialize()
{
uint32_t idLength = _tlv[_offset] & ID16;
uint32_t lengthType = _tlv[_offset] & LENGTH24;
if (0 == lengthType) {
_length = _tlv[_offset] & 0x07;
}
_offset++;
deserialiseID(idLength);
deserialiseLength(lengthType);
return this;
}
void TypeIdLength::deserialiseID(uint32_t idLength)
{
_id = _tlv[_offset++] & 0xFF;
if (ID16 == idLength) {
_id = (_id << 8) + (_tlv[_offset++] & 0xFF);
}
}
void TypeIdLength::deserialiseLength(uint32_t lengthType)
{
if (lengthType > 0) {
_length = _tlv[_offset++] & 0xFF;
}
if (lengthType > LENGTH8) {
_length = (_length << 8) + (_tlv[_offset++] & 0xFF);
}
if (lengthType > LENGTH16) {
_length = (_length << 8) + (_tlv[_offset++] & 0xFF);
}
}
<|endoftext|> |
<commit_before>//
// Created by david on 2019-01-29.
//
#include <string>
#include <tensors/class_tensors_finite.h>
#include <tensors/edges/class_edges_finite.h>
#include <tensors/edges/class_env_ene.h>
#include <tensors/model/class_model_finite.h>
#include <tensors/model/class_mpo_site.h>
#include <tensors/state/class_mps_site.h>
#include <tensors/state/class_state_finite.h>
#include <tools/common/log.h>
#include <tools/finite/print.h>
using Scalar = std::complex<double>;
void tools::finite::print::dimensions(const class_tensors_finite &tensors) {
for(size_t pos = 0; pos < tensors.get_length(); pos++) {
std::string tag;
if(pos == tensors.get_position()) tag = "<---- Position A";
if(pos == tensors.get_position() + 1) tag = "<---- Position B";
const auto &mps = tensors.state->get_mps_site(pos).dimensions();
const auto &envl = tensors.edges->get_ene(pos).L.get_block().dimensions();
const auto &envr = tensors.edges->get_ene(pos).R.get_block().dimensions();
const auto &mpo = tensors.model->get_mpo(pos).MPO().dimensions();
tools::log->info(
"Pos {:2}: ENVL [{:>3} {:>3} {:>2}] MPS [{:>2} {:>3} {:>3}] MPO [{:>1} {:>1} {:>1} {:>1}] ENVR [{:>3} {:>3} {:>2}] {}", pos,
envl[0], envl[1], envl[2], mps[0], mps[1], mps[2], mpo[0], mpo[1], mpo[2], mpo[3], envr[0],
envr[1], envr[2], tag);
if(tensors.state->get_mps_site(pos).isCenter())
tools::log->info("Pos {:2}: L [{:^4}] {:>70}", pos, tensors.state->get_mps_site(pos).get_L().dimension(0), "<---- Center");
}
}
void tools::finite::print::model(const class_model_finite &model) {
model.get_mpo(0).print_parameter_names();
for(size_t pos = 0; pos < model.get_length(); pos++) model.get_mpo(pos).print_parameter_values();
}
<commit_msg>Print direction when debugging dimensions<commit_after>//
// Created by david on 2019-01-29.
//
#include <string>
#include <tensors/class_tensors_finite.h>
#include <tensors/edges/class_edges_finite.h>
#include <tensors/edges/class_env_ene.h>
#include <tensors/model/class_model_finite.h>
#include <tensors/model/class_mpo_site.h>
#include <tensors/state/class_mps_site.h>
#include <tensors/state/class_state_finite.h>
#include <tools/common/log.h>
#include <tools/finite/print.h>
using Scalar = std::complex<double>;
void tools::finite::print::dimensions(const class_tensors_finite &tensors) {
for(size_t pos = 0; pos < tensors.get_length(); pos++) {
std::string tag;
if(pos == tensors.get_position()) tag = "<---- Position A";
if(pos == tensors.get_position() + 1) tag = "<---- Position B";
const auto &mps = tensors.state->get_mps_site(pos).dimensions();
const auto &envl = tensors.edges->get_ene(pos).L.get_block().dimensions();
const auto &envr = tensors.edges->get_ene(pos).R.get_block().dimensions();
const auto &mpo = tensors.model->get_mpo(pos).MPO().dimensions();
tools::log->info(
"Pos {:2}: ENVL [{:>3} {:>3} {:>2}] MPS [{:>2} {:>3} {:>3}] MPO [{:>1} {:>1} {:>1} {:>1}] ENVR [{:>3} {:>3} {:>2}] {}", pos,
envl[0], envl[1], envl[2], mps[0], mps[1], mps[2], mpo[0], mpo[1], mpo[2], mpo[3], envr[0],
envr[1], envr[2], tag);
if(tensors.state->get_mps_site(pos).isCenter())
tools::log->info("Pos {:2}: LC [{:^4}] {:>69}", pos, tensors.state->get_mps_site(pos).get_L().dimension(0), "<---- Center");
}
tools::log->info("Direction: {}", tensors.state->get_direction());
}
void tools::finite::print::model(const class_model_finite &model) {
model.get_mpo(0).print_parameter_names();
for(size_t pos = 0; pos < model.get_length(); pos++) model.get_mpo(pos).print_parameter_values();
}
<|endoftext|> |
<commit_before>#ifndef __NX_TCP_H__
#define __NX_TCP_H__
#include <stdint.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <functional>
#include <nx/handle.hpp>
#include <nx/endpoint.hpp>
#include <nx/callback_access.hpp>
namespace nx {
template <typename Derived, typename... Callbacks>
class tcp_base
: public handle<
Derived,
Callbacks...
>
{
public:
using base_type = handle<
Derived,
Callbacks...
>;
using this_type = tcp_base<Derived, Callbacks...>;
tcp_base()
: base_type(socket(PF_INET, SOCK_STREAM, 0))
{}
tcp_base(int fh)
: base_type(fh)
{ update_endpoints(); }
tcp_base(this_type&& other)
: base_type(std::forward<base_type>(other)),
local_(std::move(other.local_)),
remote_(std::move(other.remote_))
{}
virtual ~tcp_base()
{}
tcp_base(const this_type& other) = delete;
this_type& operator=(const this_type& other) = delete;
this_type& operator=(this_type&& other)
{
base_type::operator=(std::forward<base_type>(other));
local_ = std::move(other.local_);
remote_ = std::move(other.remote_);
return *this;
}
void set_reuseaddr()
{
int yes = 1;
handle_error(
base_type::derived(),
"setting address reuse",
setsockopt(
base_type::fh(),
SOL_SOCKET, SO_REUSEADDR,
&yes, sizeof(int)
)
);
}
endpoint& local()
{ return local_; }
const endpoint& local() const
{ return local_; }
endpoint& remote()
{ return remote_; }
const endpoint& remote() const
{ return remote_; }
void update_endpoints()
{
local_.set_from_local(base_type::fh());
remote_.set_from_remote(base_type::fh());
}
private:
endpoint local_;
endpoint remote_;
};
class tcp : public tcp_base<tcp>
{
using base_type = tcp_base<tcp>;
using base_type::tcp_base;
};
template <typename Handle, typename Connected>
Handle&
connect(
Handle& h,
const endpoint& to,
Connected&& cb
)
{
h.set_nonblocking();
h.set_reuseaddr();
h.remote() = to;
h[tags::on_drain] = [cb = std::move(cb)](Handle& h) {
// Socket is writable (connected)
h.update_endpoints();
cb(h);
h.start_read();
h[tags::on_drain] = nullptr;
};
h.start_write();
int rc = ::connect(h.fh(), h.remote(), h.remote().size());
if (rc != 0 && errno != EINPROGRESS) {
handle_error(h, "connect error", errno);
}
return h;
}
template <typename Handle, typename Connected>
Handle&
connect(
const endpoint& to,
Connected&& cb
)
{
auto p = new_handle<Handle>();
auto& h = *p;
return connect(h, to, std::move(cb));
}
template <typename Handle, typename Accepted, typename Readable>
const endpoint&
serve(
Handle& h,
const endpoint& from,
Accepted&& accept_cb,
Readable&& read_cb
)
{
h.local() = from;
h.set_reuseaddr();
bool error = handle_error(
h,
"bind error",
bind(h.fh(), h.local(), h.local().size())
);
h.local().set_from_local(h.fh());
error = error || handle_error(
h,
"listen error",
listen(h.fh(), 128)
);
if (!error) {
h.set_nonblocking();
h[tags::on_readable] = [
accept_cb = std::move(accept_cb),
read_cb = std::move(read_cb)
](Handle& h) {
// New connection
endpoint remote;
uint32_t size = 0;
int fd = ::accept(h.fh(), remote, &size);
if (fd == -1) {
handle_error(h, "accept error", fd);
} else {
auto cp = new_handle<Handle>(fd);
auto& c = *cp;
c[tags::on_close] = [](Handle& c) {
handle_error(
c,
"shutdown",
shutdown(c.fh(), SHUT_WR)
);
};
c[tags::on_read] = std::move(read_cb);
c.start_read();
accept_cb(c);
}
};
h.start_read(true);
}
return h.local();
}
template <typename Handle, typename Accepted, typename Readable>
const endpoint&
serve(
const endpoint& from,
Accepted&& accept_cb,
Readable&& read_cb
)
{
auto p = new_handle<Handle>();
auto& h = *p;
return serve(h, from, std::move(accept_cb), std::move(read_cb));
}
} // namesapce nx
#endif // __NX_TCP_H__
<commit_msg>cleanup<commit_after>#ifndef __NX_TCP_H__
#define __NX_TCP_H__
#include <stdint.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <functional>
#include <nx/handle.hpp>
#include <nx/endpoint.hpp>
#include <nx/callback_access.hpp>
namespace nx {
template <typename Derived, typename... Callbacks>
class tcp_base
: public handle<
Derived,
Callbacks...
>
{
public:
using base_type = handle<
Derived,
Callbacks...
>;
using this_type = tcp_base<Derived, Callbacks...>;
tcp_base()
: base_type(socket(PF_INET, SOCK_STREAM, 0))
{}
tcp_base(int fh)
: base_type(fh)
{ update_endpoints(); }
tcp_base(this_type&& other)
: base_type(std::forward<base_type>(other)),
local_(std::move(other.local_)),
remote_(std::move(other.remote_))
{}
virtual ~tcp_base()
{}
tcp_base(const this_type& other) = delete;
this_type& operator=(const this_type& other) = delete;
this_type& operator=(this_type&& other)
{
base_type::operator=(std::forward<base_type>(other));
local_ = std::move(other.local_);
remote_ = std::move(other.remote_);
return *this;
}
void set_reuseaddr()
{
int yes = 1;
handle_error(
base_type::derived(),
"setting address reuse",
setsockopt(
base_type::fh(),
SOL_SOCKET, SO_REUSEADDR,
&yes, sizeof(int)
)
);
}
endpoint& local()
{ return local_; }
const endpoint& local() const
{ return local_; }
endpoint& remote()
{ return remote_; }
const endpoint& remote() const
{ return remote_; }
void update_endpoints()
{
local_.set_from_local(base_type::fh());
remote_.set_from_remote(base_type::fh());
}
private:
endpoint local_;
endpoint remote_;
};
class tcp : public tcp_base<tcp>
{
using base_type = tcp_base<tcp>;
using base_type::tcp_base;
};
template <typename Handle, typename Connected>
Handle&
connect(
Handle& h,
const endpoint& to,
Connected&& cb
)
{
h.set_nonblocking();
h.remote() = to;
h[tags::on_drain] = [cb = std::move(cb)](Handle& h) {
// Socket is writable (connected)
h.update_endpoints();
cb(h);
h.start_read();
h[tags::on_drain] = nullptr;
};
h.start_write();
int rc = ::connect(h.fh(), h.remote(), h.remote().size());
if (rc != 0 && errno != EINPROGRESS) {
handle_error(h, "connect error", errno);
}
return h;
}
template <typename Handle, typename Connected>
Handle&
connect(
const endpoint& to,
Connected&& cb
)
{
auto p = new_handle<Handle>();
auto& h = *p;
return connect(h, to, std::move(cb));
}
template <typename Handle, typename Accepted, typename Readable>
const endpoint&
serve(
Handle& h,
const endpoint& from,
Accepted&& accept_cb,
Readable&& read_cb
)
{
h.local() = from;
h.set_reuseaddr();
bool error = handle_error(
h,
"bind error",
bind(h.fh(), h.local(), h.local().size())
);
h.local().set_from_local(h.fh());
error = error || handle_error(
h,
"listen error",
listen(h.fh(), 128)
);
if (!error) {
h.set_nonblocking();
h[tags::on_readable] = [
accept_cb = std::move(accept_cb),
read_cb = std::move(read_cb)
](Handle& h) {
// New connection
endpoint remote;
uint32_t size = 0;
int fd = ::accept(h.fh(), remote, &size);
if (fd == -1) {
handle_error(h, "accept error", fd);
} else {
auto cp = new_handle<Handle>(fd);
auto& c = *cp;
c[tags::on_close] = [](Handle& c) {
handle_error(
c,
"shutdown",
shutdown(c.fh(), SHUT_WR)
);
};
c[tags::on_read] = std::move(read_cb);
c.start_read();
accept_cb(c);
}
};
h.start_read(true);
}
return h.local();
}
template <typename Handle, typename Accepted, typename Readable>
const endpoint&
serve(
const endpoint& from,
Accepted&& accept_cb,
Readable&& read_cb
)
{
auto p = new_handle<Handle>();
auto& h = *p;
return serve(h, from, std::move(accept_cb), std::move(read_cb));
}
} // namesapce nx
#endif // __NX_TCP_H__
<|endoftext|> |
<commit_before>/*
* THIS SHOULD BE RENAMED AS PROCESS_HKL.CPP
*/
#include <iostream>
#include <iomanip>
#include <sys/time.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <gsl/gsl_spline.h>
#include <gsl/gsl_errno.h>
#include <algorithm>
#include "detector.h"
#include "beam.h"
#include "particle.h"
#include "diffraction.h"
#include "toolbox.h"
#include "diffraction.cuh"
#include "io.h"
#include <fstream>
#include <string>
#ifdef COMPILE_WITH_CXX11
#define ARMA_DONT_USE_CXX11
#endif
#include <armadillo>
#include <boost/tokenizer.hpp>
#include <boost/algorithm/string.hpp>
using namespace std;
using namespace arma;
using namespace detector;
using namespace beam;
using namespace particle;
using namespace diffraction;
using namespace toolbox;
#define USE_CUDA 0
int main( int argc, char* argv[] ){
string imageList;
string eulerList;
string quaternionList;
string rotationList;
string beamFile;
string geomFile;
int numImages = 0;
int mySize = 0;
string output;
string format;
// Let's parse input
for (int n = 1; n < argc; n++) {
cout << argv [ n ] << endl;
if(boost::algorithm::iequals(argv[ n ], "-i")) {
imageList = argv[ n+1 ];
} else if (boost::algorithm::iequals(argv[ n ], "-e")) {
eulerList = argv[ n+1 ];
} else if (boost::algorithm::iequals(argv[ n ], "-q")) {
quaternionList = argv[ n+1 ];
} else if (boost::algorithm::iequals(argv[ n ], "-r")) {
rotationList = argv[ n+1 ];
} else if (boost::algorithm::iequals(argv[ n ], "-b")) {
beamFile = argv[ n+1 ];
} else if (boost::algorithm::iequals(argv[ n ], "-g")) {
geomFile = argv[ n+1 ];
} else if (boost::algorithm::iequals(argv[ n ], "--num_images")) {
numImages = atoi(argv[ n+2 ]);
} else if (boost::algorithm::iequals(argv[ n ], "--vol_dim")) {
mySize = atof(argv[ n+2 ]);
} else if (boost::algorithm::iequals(argv[ n ], "--output_name")) {
output = argv[ n+2 ];
} else if (boost::algorithm::iequals(argv[ n ], "--format")) {
format = argv[ n+2 ];
}
}
//cout << numImages << endl;
//cout << inc_res << endl;
// image.lst and euler.lst are not neccessarily in the same order! So can not use like this. Perhaps use hdf5 to combine the two.
/****** Beam ******/
// Let's read in our beam file
double photon_energy = 0;
string line;
ifstream myFile(beamFile.c_str());
while (getline(myFile, line)) {
if (line.compare(0,1,"#") && line.compare(0,1,";") && line.length() > 0) {
// line now contains a valid input
cout << line << endl;
typedef boost::tokenizer<boost::char_separator<char> > Tok;
boost::char_separator<char> sep(" ="); // default constructed
Tok tok(line, sep);
for(Tok::iterator tok_iter = tok.begin(); tok_iter != tok.end(); ++tok_iter){
if ( boost::algorithm::iequals(*tok_iter,"beam/photon_energy") ) {
string temp = *++tok_iter;
photon_energy = atof(temp.c_str()); // photon energy to wavelength
break;
}
}
}
}
CBeam beam = CBeam();
beam.set_photon_energy(photon_energy);
/****** Detector ******/
double d = 0; // (m) detector distance
double pix_width = 0; // (m)
int px_in = 0; // number of pixel along x
string badpixmap = ""; // this information should go into the detector class
// Parse the geom file
ifstream myGeomFile(geomFile.c_str());
while (getline(myGeomFile, line)) {
if (line.compare(0,1,"#") && line.compare(0,1,";") && line.length() > 0) {
// line now contains a valid input
cout << line << endl;
typedef boost::tokenizer<boost::char_separator<char> > Tok;
boost::char_separator<char> sep(" ="); // default constructed
Tok tok(line, sep);
for(Tok::iterator tok_iter = tok.begin(); tok_iter != tok.end(); ++tok_iter){
if ( boost::algorithm::iequals(*tok_iter,"geom/d") ) {
string temp = *++tok_iter;
d = atof(temp.c_str());
break;
} else if ( boost::algorithm::iequals(*tok_iter,"geom/pix_width") ) {
string temp = *++tok_iter;
pix_width = atof(temp.c_str());
break;
} else if ( boost::algorithm::iequals(*tok_iter,"geom/px") ) {
string temp = *++tok_iter;
px_in = atof(temp.c_str());
break;
} else if ( boost::algorithm::iequals(*tok_iter,"geom/badpixmap") ) {
string temp = *++tok_iter;
cout << temp << endl;
badpixmap = temp;
break;
}
}
}
}
double pix_height = pix_width; // (m)
const int px = px_in; // number of pixels in x
const int py = px; // number of pixels in y
double cx = ((double) px-1)/2; // this can be user defined
double cy = ((double) py-1)/2; // this can be user defined
CDetector det = CDetector();
det.set_detector_dist(d);
det.set_pix_width(pix_width);
det.set_pix_height(pix_height);
det.set_numPix(py,px);
det.set_center_x(cx);
det.set_center_y(cy);
det.set_pixelMap(badpixmap);
det.init_dp(&beam);
uvec goodpix;
goodpix = det.get_goodPixelMap();
//cout << "Good pix:" << goodpix << endl;
double theta = atan((px/2*pix_height)/d);
double qmax = 2/beam.get_wavelength()*sin(theta/2);
double dmin = 1/(2*qmax);
cout << "max q to the edge: " << qmax << " m^-1" << endl;
cout << "Half period resolution: " << dmin << " m" << endl;
if(!USE_CUDA) {
int counter = 0;
fmat pix;
pix.zeros(det.numPix,3);
for (int i = 0; i < px; i++) {
for (int j = 0; j < py; j++) { // column-wise
pix(counter,0) = det.q_xyz(j,i,0);
pix(counter,1) = det.q_xyz(j,i,1);
pix(counter,2) = det.q_xyz(j,i,2);
counter++;
}
}
fvec pix_mod;
float pix_max;
pix = pix * 1e-10; // (nm)
pix_mod = sqrt(sum(pix%pix,1));
pix_max = max(pix_mod);
//cout << "pix_max: " << pix_max << endl;
float inc_res = (mySize-1)/(2*pix_max/sqrt(2));
pix = pix * inc_res;
pix_mod = sqrt(sum(pix%pix,1));
pix_max = cx;//max(pix_mod);
string filename;
//string datasetname = "/data/data";
fmat myDP;
//CDetector myDet;
//mat B;
//fmat temp;
fmat myR;
myR.zeros(3,3);
float psi,theta,phi;
fcube myWeight;
myWeight.zeros(mySize,mySize,mySize);
fcube myIntensity;
myIntensity.zeros(mySize,mySize,mySize);
cout << "Start" << endl;
//cout << mySize << endl;
int active = 1;
string interpolate = "linear";// "nearest";
cout << format << endl;
for (int r = 0; r < numImages; r++) {
if (format == "S2E") {
// Get image from hdf
stringstream sstm;
sstm << imageList << "/diffr_out_" << setfill('0') << setw(7) << r+1 << ".h5";
string inputName;
inputName = sstm.str();
// Read in diffraction
myDP = hdf5readT<fmat>(inputName,"/data/data");
// Read angle
fvec quat = hdf5readT<fvec>(inputName,"/data/angle");
myR = CToolbox::quaternion2rot3D(quat);
myR = trans(myR);
} else {
// Get image from dat file
std::stringstream sstm;
sstm << imageList << setfill('0') << setw(7) << r << ".dat";
filename = sstm.str();
cout << filename << endl;
myDP = load_asciiImage(filename);
// Get rotation matrix from dat file
std::stringstream sstm1;
sstm1 << rotationList << setfill('0') << setw(7) << r << ".dat";
string rotationName = sstm1.str();
cout << rotationName << endl;
myR = load_asciiRotation(rotationName);
}
//fvec euler;
//psi = euler(0);
//theta = euler(1);
//phi = euler(2);
//euler.print("euler:");
//myR = CToolbox::euler2rot3D(psi,theta,phi); // WARNING: euler2rot3D changed sign 24/7/14
myR.print("myR: ");
//myR = trans(myR);
CToolbox::merge3D(&myDP, &pix, &goodpix, &myR, pix_max, &myIntensity, &myWeight, active, interpolate);
}
// Normalize here
CToolbox::normalize(&myIntensity,&myWeight);
// ########### Save diffraction volume ##############
cout << "Saving diffraction volume..." << endl;
for (int i = 0; i < mySize; i++) {
std::stringstream sstm;
sstm << output << "vol_" << setfill('0') << setw(7) << i << ".dat";
string outputName = sstm.str();
myIntensity.slice(i).save(outputName,raw_ascii);
// empty voxels
std::stringstream sstm1;
sstm1 << output << "volGoodVoxels_" << setfill('0') << setw(7) << i << ".dat";
string outputName1 = sstm1.str();
fmat goodVoxels = sign(myWeight.slice(i));
goodVoxels.save(outputName1,raw_ascii);
}
}
//cout << "Total time: " <<timerMaster.toc()<<" seconds."<<endl;
return 0;
}
<commit_msg>Clean up diffraction merging<commit_after>/*
* THIS SHOULD BE RENAMED AS PROCESS_HKL.CPP
*/
#include <iostream>
#include <iomanip>
#include <sys/time.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <gsl/gsl_spline.h>
#include <gsl/gsl_errno.h>
#include <algorithm>
#include "detector.h"
#include "beam.h"
#include "particle.h"
#include "diffraction.h"
#include "toolbox.h"
#include "diffraction.cuh"
#include "io.h"
#include <fstream>
#include <string>
#ifdef COMPILE_WITH_CXX11
#define ARMA_DONT_USE_CXX11
#endif
#include <armadillo>
#include <boost/tokenizer.hpp>
#include <boost/algorithm/string.hpp>
using namespace std;
using namespace arma;
using namespace detector;
using namespace beam;
using namespace particle;
using namespace diffraction;
using namespace toolbox;
#define USE_CUDA 0
int main( int argc, char* argv[] ){
string imageList;
string eulerList;
string quaternionList;
string rotationList;
string beamFile;
string geomFile;
int numImages = 0;
int mySize = 0;
string output;
string format;
// Let's parse input
for (int n = 1; n < argc; n++) {
cout << argv [ n ] << endl;
if(boost::algorithm::iequals(argv[ n ], "-i")) {
imageList = argv[ n+1 ];
} else if (boost::algorithm::iequals(argv[ n ], "-e")) {
eulerList = argv[ n+1 ];
} else if (boost::algorithm::iequals(argv[ n ], "-q")) {
quaternionList = argv[ n+1 ];
} else if (boost::algorithm::iequals(argv[ n ], "-r")) {
rotationList = argv[ n+1 ];
} else if (boost::algorithm::iequals(argv[ n ], "-b")) {
beamFile = argv[ n+1 ];
} else if (boost::algorithm::iequals(argv[ n ], "-g")) {
geomFile = argv[ n+1 ];
} else if (boost::algorithm::iequals(argv[ n ], "--num_images")) {
numImages = atoi(argv[ n+2 ]);
} else if (boost::algorithm::iequals(argv[ n ], "--vol_dim")) {
mySize = atof(argv[ n+2 ]);
} else if (boost::algorithm::iequals(argv[ n ], "--output_name")) {
output = argv[ n+2 ];
} else if (boost::algorithm::iequals(argv[ n ], "--format")) {
format = argv[ n+2 ];
}
}
//cout << numImages << endl;
//cout << inc_res << endl;
// image.lst and euler.lst are not neccessarily in the same order! So can not use like this. Perhaps use hdf5 to combine the two.
/****** Beam ******/
// Let's read in our beam file
double photon_energy = 0;
string line;
ifstream myFile(beamFile.c_str());
while (getline(myFile, line)) {
if (line.compare(0,1,"#") && line.compare(0,1,";") && line.length() > 0) {
// line now contains a valid input
cout << line << endl;
typedef boost::tokenizer<boost::char_separator<char> > Tok;
boost::char_separator<char> sep(" ="); // default constructed
Tok tok(line, sep);
for(Tok::iterator tok_iter = tok.begin(); tok_iter != tok.end(); ++tok_iter){
if ( boost::algorithm::iequals(*tok_iter,"beam/photon_energy") ) {
string temp = *++tok_iter;
photon_energy = atof(temp.c_str()); // photon energy to wavelength
break;
}
}
}
}
CBeam beam = CBeam();
beam.set_photon_energy(photon_energy);
/****** Detector ******/
double d = 0; // (m) detector distance
double pix_width = 0; // (m)
int px_in = 0; // number of pixel along x
string badpixmap = ""; // this information should go into the detector class
// Parse the geom file
ifstream myGeomFile(geomFile.c_str());
while (getline(myGeomFile, line)) {
if (line.compare(0,1,"#") && line.compare(0,1,";") && line.length() > 0) {
// line now contains a valid input
cout << line << endl;
typedef boost::tokenizer<boost::char_separator<char> > Tok;
boost::char_separator<char> sep(" ="); // default constructed
Tok tok(line, sep);
for(Tok::iterator tok_iter = tok.begin(); tok_iter != tok.end(); ++tok_iter){
if ( boost::algorithm::iequals(*tok_iter,"geom/d") ) {
string temp = *++tok_iter;
d = atof(temp.c_str());
break;
} else if ( boost::algorithm::iequals(*tok_iter,"geom/pix_width") ) {
string temp = *++tok_iter;
pix_width = atof(temp.c_str());
break;
} else if ( boost::algorithm::iequals(*tok_iter,"geom/px") ) {
string temp = *++tok_iter;
px_in = atof(temp.c_str());
break;
} else if ( boost::algorithm::iequals(*tok_iter,"geom/badpixmap") ) {
string temp = *++tok_iter;
cout << temp << endl;
badpixmap = temp;
break;
}
}
}
}
double pix_height = pix_width; // (m)
const int px = px_in; // number of pixels in x
const int py = px; // number of pixels in y
double cx = ((double) px-1)/2; // this can be user defined
double cy = ((double) py-1)/2; // this can be user defined
CDetector det = CDetector();
det.set_detector_dist(d);
det.set_pix_width(pix_width);
det.set_pix_height(pix_height);
det.set_numPix(py,px);
det.set_center_x(cx);
det.set_center_y(cy);
det.set_pixelMap(badpixmap);
det.init_dp(&beam);
uvec goodpix;
goodpix = det.get_goodPixelMap();
//cout << "Good pix:" << goodpix << endl;
double theta = atan((px/2*pix_height)/d);
double qmax = 2/beam.get_wavelength()*sin(theta/2);
double dmin = 1/(2*qmax);
cout << "max q to the edge: " << qmax << " m^-1" << endl;
cout << "Half period resolution: " << dmin << " m" << endl;
if(!USE_CUDA) {
int counter = 0;
fmat pix;
pix.zeros(det.numPix,3);
for (int i = 0; i < px; i++) {
for (int j = 0; j < py; j++) { // column-wise
pix(counter,0) = det.q_xyz(j,i,0);
pix(counter,1) = det.q_xyz(j,i,1);
pix(counter,2) = det.q_xyz(j,i,2);
counter++;
}
}
fvec pix_mod;
float pix_max;
pix = pix * 1e-10; // (nm)
pix_mod = sqrt(sum(pix%pix,1));
pix_max = max(pix_mod);
float inc_res = (mySize-1)/(2*pix_max/sqrt(2));
pix = pix * inc_res;
pix_mod = sqrt(sum(pix%pix,1));
pix_max = cx;
string filename;
fmat myDP;
fmat myR;
myR.zeros(3,3);
float psi,theta,phi;
fcube myWeight;
myWeight.zeros(mySize,mySize,mySize);
fcube myIntensity;
myIntensity.zeros(mySize,mySize,mySize);
cout << "Start" << endl;
//cout << mySize << endl;
int active = 1;
string interpolate = "linear";// "nearest";
cout << format << endl;
for (int r = 0; r < numImages; r++) {
if (format == "S2E") {
// Get image from hdf
stringstream sstm;
sstm << imageList << "/diffr_out_" << setfill('0') << setw(7) << r+1 << ".h5";
string inputName;
inputName = sstm.str();
// Read in diffraction
myDP = hdf5readT<fmat>(inputName,"/data/data");
// Read angle
fvec quat = hdf5readT<fvec>(inputName,"/data/angle");
myR = CToolbox::quaternion2rot3D(quat);
myR = trans(myR);
} else {
// Get image from dat file
std::stringstream sstm;
sstm << imageList << setfill('0') << setw(7) << r << ".dat";
filename = sstm.str();
cout << filename << endl;
myDP = load_asciiImage(filename);
// Get rotation matrix from dat file
std::stringstream sstm1;
sstm1 << rotationList << setfill('0') << setw(7) << r << ".dat";
string rotationName = sstm1.str();
cout << rotationName << endl;
myR = load_asciiRotation(rotationName);
}
CToolbox::merge3D(&myDP, &pix, &goodpix, &myR, pix_max, &myIntensity, &myWeight, active, interpolate);
}
// Normalize here
CToolbox::normalize(&myIntensity,&myWeight);
// ########### Save diffraction volume ##############
cout << "Saving diffraction volume..." << endl;
for (int i = 0; i < mySize; i++) {
std::stringstream sstm;
sstm << output << "vol_" << setfill('0') << setw(7) << i << ".dat";
string outputName = sstm.str();
myIntensity.slice(i).save(outputName,raw_ascii);
// empty voxels
std::stringstream sstm1;
sstm1 << output << "volGoodVoxels_" << setfill('0') << setw(7) << i << ".dat";
string outputName1 = sstm1.str();
fmat goodVoxels = sign(myWeight.slice(i));
goodVoxels.save(outputName1,raw_ascii);
}
}
return 0;
}
<|endoftext|> |
<commit_before>
#include "json.h"
namespace mfast {
namespace json {
bool get_quoted_string(std::istream& strm, std::string* pstr, bool first_quote_extracted=false)
{
char c1;
if (!first_quote_extracted) {
// make sure the first non-whitespace character is a quote
strm >> std::skipws >> c1;
if (c1 != '"') {
strm.setstate(std::ios::failbit);
}
if (!strm)
return false;
}
if (pstr)
pstr->clear();
std::streambuf* buf = strm.rdbuf();
int c;
bool escaped = false;
do {
c = buf->sbumpc();
if (c != EOF) {
if (!escaped) {
if (c=='\\') {
escaped = true;
continue;
}
else if (c == '"') {
return true;
}
}
else {
// escape mode
const char* escapables="\b\f\n\r\t\v'\"\\";
const char* orig="bfnrtv'\"\\";
const char* pch = strchr(orig, c);
if (pch != 0) {
c = escapables[pch-orig];
escaped = false;
}
else {
break;
}
}
if (pstr)
(*pstr) += static_cast<char>(c);
}
else {
break;
}
}
while (1);
strm.setstate(std::ios::failbit);
return false;
}
bool skip_matching(std::istream& strm, char left_bracket)
{
char right_bracket;
if (left_bracket == '{')
right_bracket = '}';
else if (left_bracket == '[')
right_bracket = ']';
else {
strm.setstate(std::ios::failbit);
return false;
}
std::streambuf* buf = strm.rdbuf();
int c;
std::size_t count=1;
while ( (c = buf->sbumpc()) != EOF )
{
if (c == left_bracket)
++count;
else if (c == right_bracket) {
if ( --count == 0 )
return true;
}
else if (c == '"') {
if (!get_quoted_string(strm, 0, true))
return false;
}
}
return false;
}
bool skip_value (std::istream& strm)
{
char c1;
char rest[5];
strm >> std::skipws >> c1;
if (c1 == '{' || c1 == '[')
return skip_matching(strm, c1);
else if (c1 == '"')
return get_quoted_string(strm, 0, true);
else if (c1 == 'n') {
// check if it's null
strm.get(rest, 4);
if (strcmp(rest, "ull")==0)
return true;
}
else if (c1=='t') {
// check if it's "true"
strm.get(rest, 4);
if (strcmp(rest, "rue")==0)
return true;
}
else if (c1 == 'f') {
// check if it's "false"
strm.get(rest, 5);
if (strcmp(rest, "alse")==0)
return true;
}
else if (c1 == '-' || isdigit(c1)) {
// skip number
strm.putback(c1);
double d;
strm >> d;
return strm.good();
}
strm.setstate(std::ios::failbit);
return false;
}
bool get_decimal_string(std::istream& strm, std::string& str)
{
const int BUFFER_LEN=128;
char buf[BUFFER_LEN];
char* ptr = buf;
str.resize(0);
char c;
strm >> std::skipws >> c;
if (c != '-' && !isdigit(c)) {
strm.setstate(std::ios::failbit);
return false;
}
*ptr++ = c;
std::streambuf* sbuf = strm.rdbuf();
bool has_dot = false;
bool has_exp = false;
while ( (c = sbuf->sbumpc()) != EOF ) {
if (isdigit(c)) {}
else if (!has_dot && !has_exp && c == '.') {
has_dot = true;
}
else if (!has_exp && (c=='e' || c== 'E')) {
has_exp = true;
*ptr++ = c;
c = sbuf->sbumpc();
if (c != '+' && c != '-' && !isdigit(c))
break;
}
else {
break;
}
*ptr++ = c;
if (ptr >= buf+BUFFER_LEN-1) {
str.append(buf, ptr);
ptr = buf;
}
}
strm.putback(c);
if (buf != ptr)
str.append(buf, ptr);
return true;
}
struct decode_visitor
{
std::istream& strm_;
enum {
visit_absent = true
};
decode_visitor(std::istream& strm)
: strm_(strm)
{
}
template <typename NumericTypeMref>
void visit(const NumericTypeMref& ref)
{
typedef typename NumericTypeMref::value_type value_type;
value_type value;
if (strm_ >> value, strm_.good())
ref.as(value);
}
void visit(const mfast::decimal_mref& ref)
{
try {
// We cannot directly use the following
// decimal val; strm_ >> val;
// That is because boost::multiprecision::number
// cannot correctly extract value when the number
// is not terminate with a string separator (i.e. space, tab, etc).
// For example, the following code would fail
// stringstream strm("1.111,");
// decimal val; strm_ >> val;
// However, if you change the code from decimal to double
// the extraction would succeed.
std::string str;
if (get_decimal_string(strm_, str)) {
ref.as(mfast::decimal(str));
}
}
catch (...) {
strm_.setstate(std::ios::failbit);
}
}
void visit(const mfast::ascii_string_mref& ref)
{
std::string str;
if (get_quoted_string(strm_, &str)) {
ref.as(str);
}
}
void visit(const mfast::unicode_string_mref& ref)
{
std::string str;
if (get_quoted_string(strm_, &str)) {
ref.as(str);
}
}
void visit(const mfast::byte_vector_mref&)
{
}
// return false only when the parsed result is empty or error
bool visit_impl(const mfast::aggregate_mref& ref);
void visit(const mfast::sequence_mref& ref, int);
void visit(const mfast::sequence_element_mref& ref, int)
{
ref.accept_mutator(*this);
}
void visit(const mfast::group_mref& ref, int)
{
if (visit_impl(ref))
ref.as_present();
else {
ref.as_absent();
}
}
void visit(const mfast::nested_message_mref& ref, int)
{
// unsupported;
}
};
// return false only when the parsed result is empty or error
bool decode_visitor::visit_impl(const mfast::aggregate_mref& ref)
{
for (std::size_t i = 0; i < ref.num_fields(); ++i)
{
ref[i].as_absent();
}
char c;
strm_ >> std::skipws >> c;
if (strm_.good() && c == '{') {
// strm_ >> std::skipws >> c;
if (!strm_.good())
return false;
if (strm_.peek() == '}') {
strm_ >> c;
return false;
}
do {
std::string key;
if (!get_quoted_string(strm_, &key))
return false;
strm_ >> c;
if (!strm_.good() || c != ':')
{
strm_.setstate(std::ios::failbit);
return false;
}
int index = ref.field_index_with_name(key.c_str());
if (index != -1)
ref[index].accept_mutator(*this);
else {
// the field is unkown to us,
skip_value(strm_);
}
if (!strm_.good() )
return false;
strm_ >> c;
} while (strm_.good() && c == ',');
if (strm_.good() && c == '}') {
return true;
}
}
else if (c == 'n') {
// check if the result is null
char buf[4];
strm_ >> std::noskipws >> std::setw(3) >> buf;
if (strncmp(buf, "ull", 3) == 0)
return false;
}
strm_.setstate(std::ios::failbit);
return false;
}
void decode_visitor::visit(const mfast::sequence_mref& ref, int)
{
ref.clear();
char c;
strm_ >> std::skipws >> c;
if (!strm_.good())
return;
if (c != '[') {
strm_.setstate(std::ios::failbit);
return;
}
strm_ >> std::skipws;
if (strm_.peek() == ']') {
strm_ >> c;
ref.clear();
}
std::size_t i = 0;
do {
ref.resize(i + 1);
ref[i++].accept_mutator(*this);
strm_ >> std::skipws >> c;
if (!strm_.good())
return;
}
while (c == ',');
if (c == ']')
return;
strm_.setstate(std::ios::failbit);
}
bool decode(std::istream& is, const message_mref& msg)
{
decode_visitor visitor(is);
visitor.visit_impl(msg);
return !is.fail();
}
}
}
<commit_msg>avoid unnecessary compiler warning<commit_after>
#include "json.h"
namespace mfast {
namespace json {
bool get_quoted_string(std::istream& strm, std::string* pstr, bool first_quote_extracted=false)
{
char c1;
if (!first_quote_extracted) {
// make sure the first non-whitespace character is a quote
strm >> std::skipws >> c1;
if (c1 != '"') {
strm.setstate(std::ios::failbit);
}
if (!strm)
return false;
}
if (pstr)
pstr->clear();
std::streambuf* buf = strm.rdbuf();
int c;
bool escaped = false;
do {
c = buf->sbumpc();
if (c != EOF) {
if (!escaped) {
if (c=='\\') {
escaped = true;
continue;
}
else if (c == '"') {
return true;
}
}
else {
// escape mode
const char* escapables="\b\f\n\r\t\v'\"\\";
const char* orig="bfnrtv'\"\\";
const char* pch = strchr(orig, c);
if (pch != 0) {
c = escapables[pch-orig];
escaped = false;
}
else {
break;
}
}
if (pstr)
(*pstr) += static_cast<char>(c);
}
else {
break;
}
}
while (1);
strm.setstate(std::ios::failbit);
return false;
}
bool skip_matching(std::istream& strm, char left_bracket)
{
char right_bracket;
if (left_bracket == '{')
right_bracket = '}';
else if (left_bracket == '[')
right_bracket = ']';
else {
strm.setstate(std::ios::failbit);
return false;
}
std::streambuf* buf = strm.rdbuf();
int c;
std::size_t count=1;
while ( (c = buf->sbumpc()) != EOF )
{
if (c == left_bracket)
++count;
else if (c == right_bracket) {
if ( --count == 0 )
return true;
}
else if (c == '"') {
if (!get_quoted_string(strm, 0, true))
return false;
}
}
return false;
}
bool skip_value (std::istream& strm)
{
char c1;
char rest[5];
strm >> std::skipws >> c1;
if (c1 == '{' || c1 == '[')
return skip_matching(strm, c1);
else if (c1 == '"')
return get_quoted_string(strm, 0, true);
else if (c1 == 'n') {
// check if it's null
strm.get(rest, 4);
if (strcmp(rest, "ull")==0)
return true;
}
else if (c1=='t') {
// check if it's "true"
strm.get(rest, 4);
if (strcmp(rest, "rue")==0)
return true;
}
else if (c1 == 'f') {
// check if it's "false"
strm.get(rest, 5);
if (strcmp(rest, "alse")==0)
return true;
}
else if (c1 == '-' || isdigit(c1)) {
// skip number
strm.putback(c1);
double d;
strm >> d;
return strm.good();
}
strm.setstate(std::ios::failbit);
return false;
}
bool get_decimal_string(std::istream& strm, std::string& str)
{
const int BUFFER_LEN=128;
char buf[BUFFER_LEN];
char* ptr = buf;
str.resize(0);
char c;
strm >> std::skipws >> c;
if (c != '-' && !isdigit(c)) {
strm.setstate(std::ios::failbit);
return false;
}
*ptr++ = c;
std::streambuf* sbuf = strm.rdbuf();
bool has_dot = false;
bool has_exp = false;
while ( (c = sbuf->sbumpc()) != EOF ) {
if (isdigit(c)) {}
else if (!has_dot && !has_exp && c == '.') {
has_dot = true;
}
else if (!has_exp && (c=='e' || c== 'E')) {
has_exp = true;
*ptr++ = c;
c = sbuf->sbumpc();
if (c != '+' && c != '-' && !isdigit(c))
break;
}
else {
break;
}
*ptr++ = c;
if (ptr >= buf+BUFFER_LEN-1) {
str.append(buf, ptr);
ptr = buf;
}
}
strm.putback(c);
if (buf != ptr)
str.append(buf, ptr);
return true;
}
struct decode_visitor
{
std::istream& strm_;
enum {
visit_absent = true
};
decode_visitor(std::istream& strm)
: strm_(strm)
{
}
template <typename NumericTypeMref>
void visit(const NumericTypeMref& ref)
{
typedef typename NumericTypeMref::value_type value_type;
value_type value;
if (strm_ >> value, strm_.good())
ref.as(value);
}
void visit(const mfast::decimal_mref& ref)
{
try {
// We cannot directly use the following
// decimal val; strm_ >> val;
// That is because boost::multiprecision::number
// cannot correctly extract value when the number
// is not terminate with a string separator (i.e. space, tab, etc).
// For example, the following code would fail
// stringstream strm("1.111,");
// decimal val; strm_ >> val;
// However, if you change the code from decimal to double
// the extraction would succeed.
std::string str;
if (get_decimal_string(strm_, str)) {
ref.as(mfast::decimal(str));
}
}
catch (...) {
strm_.setstate(std::ios::failbit);
}
}
void visit(const mfast::ascii_string_mref& ref)
{
std::string str;
if (get_quoted_string(strm_, &str)) {
ref.as(str);
}
}
void visit(const mfast::unicode_string_mref& ref)
{
std::string str;
if (get_quoted_string(strm_, &str)) {
ref.as(str);
}
}
void visit(const mfast::byte_vector_mref&)
{
}
// return false only when the parsed result is empty or error
bool visit_impl(const mfast::aggregate_mref& ref);
void visit(const mfast::sequence_mref& ref, int);
void visit(const mfast::sequence_element_mref& ref, int)
{
ref.accept_mutator(*this);
}
void visit(const mfast::group_mref& ref, int)
{
if (visit_impl(ref))
ref.as_present();
else {
ref.as_absent();
}
}
void visit(const mfast::nested_message_mref&, int)
{
// unsupported;
}
};
// return false only when the parsed result is empty or error
bool decode_visitor::visit_impl(const mfast::aggregate_mref& ref)
{
for (std::size_t i = 0; i < ref.num_fields(); ++i)
{
ref[i].as_absent();
}
char c;
strm_ >> std::skipws >> c;
if (strm_.good() && c == '{') {
// strm_ >> std::skipws >> c;
if (!strm_.good())
return false;
if (strm_.peek() == '}') {
strm_ >> c;
return false;
}
do {
std::string key;
if (!get_quoted_string(strm_, &key))
return false;
strm_ >> c;
if (!strm_.good() || c != ':')
{
strm_.setstate(std::ios::failbit);
return false;
}
int index = ref.field_index_with_name(key.c_str());
if (index != -1)
ref[index].accept_mutator(*this);
else {
// the field is unkown to us,
skip_value(strm_);
}
if (!strm_.good() )
return false;
strm_ >> c;
} while (strm_.good() && c == ',');
if (strm_.good() && c == '}') {
return true;
}
}
else if (c == 'n') {
// check if the result is null
char buf[4];
strm_ >> std::noskipws >> std::setw(3) >> buf;
if (strncmp(buf, "ull", 3) == 0)
return false;
}
strm_.setstate(std::ios::failbit);
return false;
}
void decode_visitor::visit(const mfast::sequence_mref& ref, int)
{
ref.clear();
char c;
strm_ >> std::skipws >> c;
if (!strm_.good())
return;
if (c != '[') {
strm_.setstate(std::ios::failbit);
return;
}
strm_ >> std::skipws;
if (strm_.peek() == ']') {
strm_ >> c;
ref.clear();
}
std::size_t i = 0;
do {
ref.resize(i + 1);
ref[i++].accept_mutator(*this);
strm_ >> std::skipws >> c;
if (!strm_.good())
return;
}
while (c == ',');
if (c == ']')
return;
strm_.setstate(std::ios::failbit);
}
bool decode(std::istream& is, const message_mref& msg)
{
decode_visitor visitor(is);
visitor.visit_impl(msg);
return !is.fail();
}
}
}
<|endoftext|> |
<commit_before>/**
* @file adam_test.cpp
* @author Marcus Edel
*
* Tests the Adam optimizer on a couple test models.
*/
#include <mlpack/core.hpp>
#include <mlpack/methods/ann/activation_functions/logistic_function.hpp>
#include <mlpack/methods/ann/init_rules/random_init.hpp>
#include <mlpack/methods/ann/layer/bias_layer.hpp>
#include <mlpack/methods/ann/layer/linear_layer.hpp>
#include <mlpack/methods/ann/layer/base_layer.hpp>
#include <mlpack/methods/ann/layer/one_hot_layer.hpp>
#include <mlpack/methods/ann/trainer/trainer.hpp>
#include <mlpack/methods/ann/ffn.hpp>
#include <mlpack/methods/ann/performance_functions/mse_function.hpp>
#include <mlpack/methods/ann/optimizer/adam.hpp>
#include <boost/test/unit_test.hpp>
#include "old_boost_test_definitions.hpp"
using namespace mlpack;
using namespace mlpack::ann;
BOOST_AUTO_TEST_SUITE(AdamTest);
/**
* Train and evaluate a vanilla network with the specified structure. Using the
* iris data, the data set contains 3 classes. One class is linearly separable
* from the other 2. The other two aren't linearly separable from each other.
*/
BOOST_AUTO_TEST_CASE(SimpleAdamTestFunction)
{
const size_t hiddenLayerSize = 10;
const size_t maxEpochs = 100;
// Load the dataset.
arma::mat dataset, labels, labelsIdx;
data::Load("iris_train.csv", dataset, true);
data::Load("iris_train_labels.csv", labelsIdx, true);
// Create target matrix.
labels = arma::zeros<arma::mat>(labelsIdx.max() + 1, labelsIdx.n_cols);
for (size_t i = 0; i < labelsIdx.n_cols; i++)
labels(labelsIdx(0, i), i) = 1;
// Construct a feed forward network using the specified parameters.
RandomInitialization randInit(0.5, 0.5);
LinearLayer<Adam, RandomInitialization> inputLayer(dataset.n_rows,
hiddenLayerSize, randInit);
BiasLayer<Adam, RandomInitialization> inputBiasLayer(hiddenLayerSize,
1, randInit);
BaseLayer<LogisticFunction> inputBaseLayer;
LinearLayer<Adam, RandomInitialization> hiddenLayer1(hiddenLayerSize,
labels.n_rows, randInit);
BiasLayer<Adam, RandomInitialization> hiddenBiasLayer1(labels.n_rows,
1, randInit);
BaseLayer<LogisticFunction> outputLayer;
OneHotLayer classOutputLayer;
auto modules = std::tie(inputLayer, inputBiasLayer, inputBaseLayer,
hiddenLayer1, hiddenBiasLayer1, outputLayer);
FFN<decltype(modules), OneHotLayer, MeanSquaredErrorFunction>
net(modules, classOutputLayer);
arma::mat prediction;
size_t error = 0;
// Evaluate the feed forward network.
for (size_t i = 0; i < dataset.n_cols; i++)
{
arma::mat input = dataset.unsafe_col(i);
net.Predict(input, prediction);
if (arma::sum(arma::sum(arma::abs(
prediction - labels.unsafe_col(i)))) == 0)
error++;
}
// Check if the selected model isn't already optimized.
double classificationError = 1 - double(error) / dataset.n_cols;
BOOST_REQUIRE_GE(classificationError, 0.09);
// Train the feed forward network.
Trainer<decltype(net)> trainer(net, maxEpochs, 1, 0.01, false);
trainer.Train(dataset, labels, dataset, labels);
// Evaluate the feed forward network.
error = 0;
for (size_t i = 0; i < dataset.n_cols; i++)
{
arma::mat input = dataset.unsafe_col(i);
net.Predict(input, prediction);
if (arma::sum(arma::sum(arma::abs(
prediction - labels.unsafe_col(i)))) == 0)
error++;
}
classificationError = 1 - double(error) / dataset.n_cols;
BOOST_REQUIRE_LE(classificationError, 0.09);
}
BOOST_AUTO_TEST_SUITE_END();
<commit_msg>Optimizer transition Adam test file<commit_after>/**
* @file adam_test.cpp
* @author Marcus Edel
*
* Tests the Adam optimizer.
*/
#include <mlpack/core.hpp>
#include <mlpack/core/optimizers/adam/adam.hpp>
#include <mlpack/core/optimizers/sgd/test_function.hpp>
#include <mlpack/methods/logistic_regression/logistic_regression.hpp>
#include <mlpack/methods/ann/ffn.hpp>
#include <mlpack/methods/ann/init_rules/random_init.hpp>
#include <mlpack/methods/ann/performance_functions/mse_function.hpp>
#include <mlpack/methods/ann/layer/binary_classification_layer.hpp>
#include <mlpack/methods/ann/layer/bias_layer.hpp>
#include <mlpack/methods/ann/layer/linear_layer.hpp>
#include <mlpack/methods/ann/layer/base_layer.hpp>
#include <boost/test/unit_test.hpp>
#include "old_boost_test_definitions.hpp"
using namespace arma;
using namespace mlpack::optimization;
using namespace mlpack::optimization::test;
using namespace mlpack::distribution;
using namespace mlpack::regression;
using namespace mlpack;
using namespace mlpack::ann;
BOOST_AUTO_TEST_SUITE(AdamTest);
/**
* Tests the Adam optimizer using a simple test function.
*/
BOOST_AUTO_TEST_CASE(SimpleAdamTestFunction)
{
SGDTestFunction f;
Adam<SGDTestFunction> optimizer(f, 1e-3, 0.9, 0.999, 1e-8, 5000000, 1e-9, true);
arma::mat coordinates = f.GetInitialPoint();
optimizer.Optimize(coordinates);
BOOST_REQUIRE_SMALL(coordinates[0], 0.1);
BOOST_REQUIRE_SMALL(coordinates[1], 0.1);
BOOST_REQUIRE_SMALL(coordinates[2], 0.1);
}
/**
* Run Adam on logistic regression and make sure the results are acceptable.
*/
BOOST_AUTO_TEST_CASE(LogisticRegressionTest)
{
// Generate a two-Gaussian dataset.
GaussianDistribution g1(arma::vec("1.0 1.0 1.0"), arma::eye<arma::mat>(3, 3));
GaussianDistribution g2(arma::vec("9.0 9.0 9.0"), arma::eye<arma::mat>(3, 3));
arma::mat data(3, 1000);
arma::Row<size_t> responses(1000);
for (size_t i = 0; i < 500; ++i)
{
data.col(i) = g1.Random();
responses[i] = 0;
}
for (size_t i = 500; i < 1000; ++i)
{
data.col(i) = g2.Random();
responses[i] = 1;
}
// Shuffle the dataset.
arma::uvec indices = arma::shuffle(arma::linspace<arma::uvec>(0,
data.n_cols - 1, data.n_cols));
arma::mat shuffledData(3, 1000);
arma::Row<size_t> shuffledResponses(1000);
for (size_t i = 0; i < data.n_cols; ++i)
{
shuffledData.col(i) = data.col(indices[i]);
shuffledResponses[i] = responses[indices[i]];
}
// Create a test set.
arma::mat testData(3, 1000);
arma::Row<size_t> testResponses(1000);
for (size_t i = 0; i < 500; ++i)
{
testData.col(i) = g1.Random();
testResponses[i] = 0;
}
for (size_t i = 500; i < 1000; ++i)
{
testData.col(i) = g2.Random();
testResponses[i] = 1;
}
LogisticRegression<> lr(shuffledData.n_rows, 0.5);
LogisticRegressionFunction<> lrf(shuffledData, shuffledResponses, 0.5);
Adam<LogisticRegressionFunction<> > adam(lrf);
lr.Train(adam);
// Ensure that the error is close to zero.
const double acc = lr.ComputeAccuracy(data, responses);
BOOST_REQUIRE_CLOSE(acc, 100.0, 0.3); // 0.3% error tolerance.
const double testAcc = lr.ComputeAccuracy(testData, testResponses);
BOOST_REQUIRE_CLOSE(testAcc, 100.0, 0.6); // 0.6% error tolerance.
}
/**
* Run Adam on a feedforward neural network and make sure the results are
* acceptable.
*/
BOOST_AUTO_TEST_CASE(FeedforwardTest)
{
// Test on a non-linearly separable dataset (XOR).
arma::mat input, labels;
input << 0 << 1 << 1 << 0 << arma::endr
<< 1 << 0 << 1 << 0 << arma::endr;
labels << 1 << 1 << 0 << 0;
// Instantiate the first layer.
LinearLayer<> inputLayer(input.n_rows, 8);
BiasLayer<> biasLayer(8);
TanHLayer<> hiddenLayer0;
// Instantiate the second layer.
LinearLayer<> hiddenLayer1(8, labels.n_rows);
TanHLayer<> outputLayer;
// Instantiate the output layer.
BinaryClassificationLayer classOutputLayer;
// Instantiate the feedforward network.
auto modules = std::tie(inputLayer, biasLayer, hiddenLayer0, hiddenLayer1,
outputLayer);
FFN<decltype(modules), decltype(classOutputLayer), RandomInitialization,
MeanSquaredErrorFunction> net(modules, classOutputLayer);
Adam<decltype(net)> opt(net, 0.03, 0.9, 0.999, 1e-8, 300 * input.n_cols, -10);
net.Train(input, labels, opt);
arma::mat prediction;
net.Predict(input, prediction);
BOOST_REQUIRE_EQUAL(prediction(0), 1);
BOOST_REQUIRE_EQUAL(prediction(1), 1);
BOOST_REQUIRE_EQUAL(prediction(2), 0);
BOOST_REQUIRE_EQUAL(prediction(3), 0);
}
BOOST_AUTO_TEST_SUITE_END();
<|endoftext|> |
<commit_before>#include "io/ibstream.h"
#include "io/obstream.h"
#include "math/random.h"
#include "math/numeric.h"
#include "tensor/numeric.h"
#include "text/to_string.h"
#include "text/algorithm.h"
#include "forward_network.h"
#include "logger.h"
namespace nano
{
rmodel_t forward_network_t::clone() const
{
return std::make_unique<forward_network_t>(*this);
}
bool forward_network_t::save(const string_t& path) const
{
obstream_t ob(path);
return ob.write(m_idims) &&
ob.write(m_odims) &&
ob.write(m_configuration) &&
ob.write_vector(m_pdata);
}
bool forward_network_t::load(const string_t& path)
{
ibstream_t ib(path);
return ib.read(m_idims) &&
ib.read(m_odims) &&
ib.read(m_configuration) &&
configure(m_idims, m_odims) &&
ib.read_vector(m_pdata) &&
m_pdata.size() == psize();
}
bool forward_network_t::save(vector_t& x) const
{
return (x = m_pdata).size() == psize();
}
bool forward_network_t::load(const vector_t& x)
{
return (x.size() == psize()) && (m_pdata = x).size() == psize();
}
const tensor3d_t& forward_network_t::output(const tensor3d_t& input)
{
assert(input.dims() == idims());
scalar_t* pxdata = m_xdata.data();
scalar_t* ppdata = m_pdata.data();
// forward step
map_vector(pxdata, nano::size(idims())) = input.vector();
for (size_t l = 0; l < n_layers(); ++ l)
{
auto& layer = m_layers[l];
layer.output(pxdata, ppdata, pxdata + layer.isize());
pxdata += layer.isize();
ppdata += layer.psize();
}
m_odata = map_tensor(pxdata, odims());
pxdata += nano::size(odims());
assert(pxdata == m_xdata.data() + m_xdata.size());
assert(ppdata == m_pdata.data() + m_pdata.size());
return m_odata;
}
const tensor3d_t& forward_network_t::ginput(const vector_t& output)
{
assert(output.size() == nano::size(odims()));
assert(!m_layers.empty());
scalar_t* pxdata = m_xdata.data() + m_xdata.size();
scalar_t* ppdata = m_pdata.data() + m_pdata.size();
// backward step
map_vector(pxdata - nano::size(odims()), nano::size(odims())) = output;
for (size_t l = n_layers(); l > 0; -- l)
{
auto& layer = m_layers[l - 1];
layer.ginput(pxdata - layer.xsize(), ppdata - layer.psize(), pxdata - layer.osize());
pxdata -= layer.osize();
ppdata -= layer.psize();
}
pxdata -= nano::size(idims());
m_idata = map_tensor(pxdata, idims());
assert(pxdata == m_xdata.data());
assert(ppdata == m_pdata.data());
return m_idata;
}
const vector_t& forward_network_t::gparam(const vector_t& output)
{
assert(output.size() == nano::size(odims()));
assert(!m_layers.empty());
scalar_t* pxdata = m_xdata.data() + m_xdata.size();
scalar_t* ppdata = m_pdata.data() + m_pdata.size();
scalar_t* pgdata = m_gdata.data() + m_gdata.size();
// backward step
map_vector(pxdata - nano::size(odims()), nano::size(odims())) = output;
for (size_t l = n_layers(); l > 0; -- l)
{
auto& layer = m_layers[l - 1];
layer.gparam(pxdata - layer.xsize(), pgdata - layer.psize(), pxdata - layer.osize());
if (l > 1)
{
layer.ginput(pxdata - layer.xsize(), ppdata - layer.psize(), pxdata - layer.osize());
}
pxdata -= layer.osize();
ppdata -= layer.psize();
pgdata -= layer.psize();
}
pxdata -= nano::size(idims());
assert(pxdata == m_xdata.data());
assert(ppdata == m_pdata.data());
assert(pgdata == m_gdata.data());
return m_gdata;
}
void forward_network_t::random()
{
scalar_t* ppdata = m_pdata.data();
for (const auto& layer : m_layers)
{
const auto div = static_cast<scalar_t>(layer.m_layer->fanin());
const auto min = -std::sqrt(6 / (1 + div));
const auto max = +std::sqrt(6 / (1 + div));
nano::set_random(random_t<scalar_t>(min, max), map_vector(ppdata, layer.psize()));
ppdata += layer.psize();
}
assert(ppdata == m_pdata.data() + m_pdata.size());
}
bool forward_network_t::configure(const tensor3d_dims_t& idims, const tensor3d_dims_t& odims)
{
m_idims = idims;
m_odims = odims;
auto xdims = idims;
auto xsize = nano::size(idims);
auto psize = tensor_size_t(0);
m_layers.clear();
// create layers
const auto net_params = nano::split(config(), ";");
for (size_t l = 0; l < net_params.size(); ++ l)
{
if (net_params[l].size() <= 1)
{
continue;
}
const auto layer_tokens = nano::split(net_params[l], ":");
if (layer_tokens.size() != 2 && layer_tokens.size() != 1)
{
log_error() << "forward network: invalid layer description <"
<< net_params[l] << ">! expecting <layer_id[:layer_parameters]>!";
throw std::invalid_argument("invalid layer description");
}
const auto layer_id = layer_tokens[0];
const auto layer_params = layer_tokens.size() == 2 ? layer_tokens[1] : string_t();
const auto layer_name = "[" + align(to_string(l + 1), 2, alignment::right, '0') + ":" +
align(layer_id, 10, alignment::left, '.') + "]";
auto layer = nano::get_layers().get(layer_id, layer_params);
layer->configure(xdims);
xsize += nano::size(layer->odims());
psize += layer->psize();
xdims = layer->odims();
m_layers.emplace_back(layer_name, std::move(layer));
}
// check output size to match the target
if (xdims != odims)
{
log_error() << "forward network: miss-matching output size " << xdims << ", expecting " << odims << "!";
throw std::invalid_argument("invalid output layer description");
}
// allocate buffers
m_idata.resize(idims);
m_odata.resize(odims);
m_xdata.resize(xsize);
m_pdata.resize(psize);
m_gdata.resize(psize);
m_pdata.setZero();
return true;
}
tensor3d_dims_t forward_network_t::idims() const
{
return m_idims;
}
tensor3d_dims_t forward_network_t::odims() const
{
return m_odims;
}
void forward_network_t::describe() const
{
const scalar_t* ppdata = m_pdata.data();
log_info() << "forward network [" << config() << "]";
for (size_t l = 0; l < n_layers(); ++ l)
{
const auto& layer = m_layers[l];
// collect & print statistics for its parameters / layer
const auto param = map_vector(ppdata, layer.psize());
ppdata += layer.psize();
if (layer.psize())
{
const auto l2 = param.lpNorm<2>();
const auto li = param.lpNorm<Eigen::Infinity>();
log_info()
<< "forward network " << layer.m_name
<< ": in(" << layer.idims() << ") -> " << "out(" << layer.odims() << ")"
<< ", kFLOPs = " << nano::idiv(layer.flops(), 1024)
<< ", params = " << layer.psize() << " [L2=" << l2 << ", Li=" << li << "].";
}
else
{
log_info()
<< "forward network " << layer.m_name
<< ": in(" << layer.idims() << ") -> " << "out(" << layer.odims() << ")"
<< ", kFLOPs = " << nano::idiv(layer.flops(), 1024) << ".";
}
}
log_info() << "forward network: parameters = " << psize() << ".";
}
tensor_size_t forward_network_t::psize() const
{
return m_gdata.size();
}
timings_t forward_network_t::timings() const
{
timings_t ret;
for (const auto& layer : m_layers)
{
if (layer.m_output_timings.count() > 1) ret[layer.m_name + " (output)"] = layer.m_output_timings;
if (layer.m_ginput_timings.count() > 1) ret[layer.m_name + " (ginput)"] = layer.m_ginput_timings;
if (layer.m_gparam_timings.count() > 1) ret[layer.m_name + " (gparam)"] = layer.m_gparam_timings;
}
return ret;
}
}
<commit_msg>improve description of the network<commit_after>#include "io/ibstream.h"
#include "io/obstream.h"
#include "math/random.h"
#include "math/numeric.h"
#include "tensor/numeric.h"
#include "text/to_string.h"
#include "text/algorithm.h"
#include "forward_network.h"
#include "logger.h"
namespace nano
{
rmodel_t forward_network_t::clone() const
{
return std::make_unique<forward_network_t>(*this);
}
bool forward_network_t::save(const string_t& path) const
{
obstream_t ob(path);
return ob.write(m_idims) &&
ob.write(m_odims) &&
ob.write(m_configuration) &&
ob.write_vector(m_pdata);
}
bool forward_network_t::load(const string_t& path)
{
ibstream_t ib(path);
return ib.read(m_idims) &&
ib.read(m_odims) &&
ib.read(m_configuration) &&
configure(m_idims, m_odims) &&
ib.read_vector(m_pdata) &&
m_pdata.size() == psize();
}
bool forward_network_t::save(vector_t& x) const
{
return (x = m_pdata).size() == psize();
}
bool forward_network_t::load(const vector_t& x)
{
return (x.size() == psize()) && (m_pdata = x).size() == psize();
}
const tensor3d_t& forward_network_t::output(const tensor3d_t& input)
{
assert(input.dims() == idims());
scalar_t* pxdata = m_xdata.data();
scalar_t* ppdata = m_pdata.data();
// forward step
map_vector(pxdata, nano::size(idims())) = input.vector();
for (size_t l = 0; l < n_layers(); ++ l)
{
auto& layer = m_layers[l];
layer.output(pxdata, ppdata, pxdata + layer.isize());
pxdata += layer.isize();
ppdata += layer.psize();
}
m_odata = map_tensor(pxdata, odims());
pxdata += nano::size(odims());
assert(pxdata == m_xdata.data() + m_xdata.size());
assert(ppdata == m_pdata.data() + m_pdata.size());
return m_odata;
}
const tensor3d_t& forward_network_t::ginput(const vector_t& output)
{
assert(output.size() == nano::size(odims()));
assert(!m_layers.empty());
scalar_t* pxdata = m_xdata.data() + m_xdata.size();
scalar_t* ppdata = m_pdata.data() + m_pdata.size();
// backward step
map_vector(pxdata - nano::size(odims()), nano::size(odims())) = output;
for (size_t l = n_layers(); l > 0; -- l)
{
auto& layer = m_layers[l - 1];
layer.ginput(pxdata - layer.xsize(), ppdata - layer.psize(), pxdata - layer.osize());
pxdata -= layer.osize();
ppdata -= layer.psize();
}
pxdata -= nano::size(idims());
m_idata = map_tensor(pxdata, idims());
assert(pxdata == m_xdata.data());
assert(ppdata == m_pdata.data());
return m_idata;
}
const vector_t& forward_network_t::gparam(const vector_t& output)
{
assert(output.size() == nano::size(odims()));
assert(!m_layers.empty());
scalar_t* pxdata = m_xdata.data() + m_xdata.size();
scalar_t* ppdata = m_pdata.data() + m_pdata.size();
scalar_t* pgdata = m_gdata.data() + m_gdata.size();
// backward step
map_vector(pxdata - nano::size(odims()), nano::size(odims())) = output;
for (size_t l = n_layers(); l > 0; -- l)
{
auto& layer = m_layers[l - 1];
layer.gparam(pxdata - layer.xsize(), pgdata - layer.psize(), pxdata - layer.osize());
if (l > 1)
{
layer.ginput(pxdata - layer.xsize(), ppdata - layer.psize(), pxdata - layer.osize());
}
pxdata -= layer.osize();
ppdata -= layer.psize();
pgdata -= layer.psize();
}
pxdata -= nano::size(idims());
assert(pxdata == m_xdata.data());
assert(ppdata == m_pdata.data());
assert(pgdata == m_gdata.data());
return m_gdata;
}
void forward_network_t::random()
{
scalar_t* ppdata = m_pdata.data();
for (const auto& layer : m_layers)
{
const auto div = static_cast<scalar_t>(layer.m_layer->fanin());
const auto min = -std::sqrt(6 / (1 + div));
const auto max = +std::sqrt(6 / (1 + div));
nano::set_random(random_t<scalar_t>(min, max), map_vector(ppdata, layer.psize()));
ppdata += layer.psize();
}
assert(ppdata == m_pdata.data() + m_pdata.size());
}
bool forward_network_t::configure(const tensor3d_dims_t& idims, const tensor3d_dims_t& odims)
{
m_idims = idims;
m_odims = odims;
auto xdims = idims;
auto xsize = nano::size(idims);
auto psize = tensor_size_t(0);
m_layers.clear();
// create layers
const auto net_params = nano::split(config(), ";");
for (size_t l = 0; l < net_params.size(); ++ l)
{
if (net_params[l].size() <= 1)
{
continue;
}
const auto layer_tokens = nano::split(net_params[l], ":");
if (layer_tokens.size() != 2 && layer_tokens.size() != 1)
{
log_error() << "forward network: invalid layer description <"
<< net_params[l] << ">! expecting <layer_id[:layer_parameters]>!";
throw std::invalid_argument("invalid layer description");
}
const auto layer_id = layer_tokens[0];
const auto layer_params = layer_tokens.size() == 2 ? layer_tokens[1] : string_t();
const auto layer_name = "[" + align(to_string(l + 1), 2, alignment::right, '0') + ":" +
align(layer_id, 10, alignment::left, '.') + "]";
auto layer = nano::get_layers().get(layer_id, layer_params);
layer->configure(xdims);
xsize += nano::size(layer->odims());
psize += layer->psize();
xdims = layer->odims();
m_layers.emplace_back(layer_name, std::move(layer));
}
// check output size to match the target
if (xdims != odims)
{
log_error() << "forward network: miss-matching output size " << xdims << ", expecting " << odims << "!";
throw std::invalid_argument("invalid output layer description");
}
// allocate buffers
m_idata.resize(idims);
m_odata.resize(odims);
m_xdata.resize(xsize);
m_pdata.resize(psize);
m_gdata.resize(psize);
m_pdata.setZero();
return true;
}
tensor3d_dims_t forward_network_t::idims() const
{
return m_idims;
}
tensor3d_dims_t forward_network_t::odims() const
{
return m_odims;
}
void forward_network_t::describe() const
{
const scalar_t* ppdata = m_pdata.data();
log_info() << "forward network [" << config() << "]";
for (size_t l = 0; l < n_layers(); ++ l)
{
const auto& layer = m_layers[l];
// collect & print statistics for its parameters / layer
const auto param = map_vector(ppdata, layer.psize());
ppdata += layer.psize();
if (layer.psize())
{
const auto min = param.minCoeff();
const auto max = param.maxCoeff();
log_info()
<< "forward network " << layer.m_name
<< ": in(" << layer.idims() << ") -> " << "out(" << layer.odims() << ")"
<< ", kFLOPs = " << nano::idiv(layer.flops(), 1024)
<< ", params = " << layer.psize()
<< ", range = [" << min << ", " << max << "].";
}
else
{
log_info()
<< "forward network " << layer.m_name
<< ": in(" << layer.idims() << ") -> " << "out(" << layer.odims() << ")"
<< ", kFLOPs = " << nano::idiv(layer.flops(), 1024) << ".";
}
}
log_info() << "forward network: parameters = " << psize() << ".";
}
tensor_size_t forward_network_t::psize() const
{
return m_gdata.size();
}
timings_t forward_network_t::timings() const
{
timings_t ret;
for (const auto& layer : m_layers)
{
if (layer.m_output_timings.count() > 1) ret[layer.m_name + " (output)"] = layer.m_output_timings;
if (layer.m_ginput_timings.count() > 1) ret[layer.m_name + " (ginput)"] = layer.m_ginput_timings;
if (layer.m_gparam_timings.count() > 1) ret[layer.m_name + " (gparam)"] = layer.m_gparam_timings;
}
return ret;
}
}
<|endoftext|> |
<commit_before>/*
* This file is part of the AzerothCore Project. See AUTHORS file for Copyright information
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published by the
* Free Software Foundation; either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "GameObject.h"
#include "GameObjectAI.h"
#include "InstanceScript.h"
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "blackwing_lair.h"
enum Say
{
SAY_AGGRO = 0,
SAY_LEASH = 1
};
enum Spells
{
SPELL_CLEAVE = 26350,
SPELL_BLASTWAVE = 23331,
SPELL_MORTALSTRIKE = 24573,
SPELL_KNOCKBACK = 25778,
SPELL_SUPPRESSION_AURA = 22247 // Suppression Device Spell
};
enum Events
{
EVENT_CLEAVE = 1,
EVENT_BLASTWAVE = 2,
EVENT_MORTALSTRIKE = 3,
EVENT_KNOCKBACK = 4,
EVENT_CHECK = 5,
// Suppression Device Events
EVENT_SUPPRESSION_CAST = 6,
EVENT_SUPPRESSION_RESET = 7
};
enum Actions
{
ACTION_DEACTIVATE = 0,
ACTION_DISARMED = 1
};
class boss_broodlord : public CreatureScript
{
public:
boss_broodlord() : CreatureScript("boss_broodlord") { }
struct boss_broodlordAI : public BossAI
{
boss_broodlordAI(Creature* creature) : BossAI(creature, DATA_BROODLORD_LASHLAYER) { }
void EnterCombat(Unit* who) override
{
BossAI::EnterCombat(who);
Talk(SAY_AGGRO);
events.ScheduleEvent(EVENT_CLEAVE, 8000);
events.ScheduleEvent(EVENT_BLASTWAVE, 12000);
events.ScheduleEvent(EVENT_MORTALSTRIKE, 20000);
events.ScheduleEvent(EVENT_KNOCKBACK, 30000);
events.ScheduleEvent(EVENT_CHECK, 1000);
}
void JustDied(Unit* /*killer*/) override
{
_JustDied();
std::list<GameObject*> _goList;
GetGameObjectListWithEntryInGrid(_goList, me, GO_SUPPRESSION_DEVICE, 200.0f);
for (std::list<GameObject*>::const_iterator itr = _goList.begin(); itr != _goList.end(); itr++)
((*itr)->AI()->DoAction(ACTION_DEACTIVATE));
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
return;
events.Update(diff);
while (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_CLEAVE:
DoCastVictim(SPELL_CLEAVE);
events.ScheduleEvent(EVENT_CLEAVE, 7000);
break;
case EVENT_BLASTWAVE:
DoCastVictim(SPELL_BLASTWAVE);
events.ScheduleEvent(EVENT_BLASTWAVE, 8000, 16000);
break;
case EVENT_MORTALSTRIKE:
DoCastVictim(SPELL_MORTALSTRIKE);
events.ScheduleEvent(EVENT_MORTALSTRIKE, 25000, 35000);
break;
case EVENT_KNOCKBACK:
DoCastVictim(SPELL_KNOCKBACK);
if (DoGetThreat(me->GetVictim()))
DoModifyThreatPercent(me->GetVictim(), -50);
events.ScheduleEvent(EVENT_KNOCKBACK, 15000, 30000);
break;
case EVENT_CHECK:
if (me->GetDistance(me->GetHomePosition()) > 150.0f)
{
Talk(SAY_LEASH);
EnterEvadeMode();
}
events.ScheduleEvent(EVENT_CHECK, 1000);
break;
}
}
DoMeleeAttackIfReady();
}
};
CreatureAI* GetAI(Creature* creature) const override
{
return GetBlackwingLairAI<boss_broodlordAI>(creature);
}
};
class go_suppression_device : public GameObjectScript
{
public:
go_suppression_device() : GameObjectScript("go_suppression_device") { }
void OnLootStateChanged(GameObject* go, uint32 state, Unit* /*unit*/) override
{
switch (state)
{
case GO_JUST_DEACTIVATED: // This case prevents the Gameobject despawn by Disarm Trap
go->SetLootState(GO_READY);
[[fallthrough]];
case GO_ACTIVATED:
go->AI()->DoAction(ACTION_DISARMED);
break;
}
}
struct go_suppression_deviceAI : public GameObjectAI
{
go_suppression_deviceAI(GameObject* go) : GameObjectAI(go), _instance(go->GetInstanceScript()), _active(true) { }
void InitializeAI() override
{
if (_instance->GetBossState(DATA_BROODLORD_LASHLAYER) == DONE)
{
Deactivate();
return;
}
_events.ScheduleEvent(EVENT_SUPPRESSION_CAST, 5000);
}
void UpdateAI(uint32 diff) override
{
_events.Update(diff);
while (uint32 eventId = _events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_SUPPRESSION_CAST:
if (me->GetGoState() == GO_STATE_READY)
{
me->CastSpell(nullptr, SPELL_SUPPRESSION_AURA);
me->SendCustomAnim(0);
}
_events.ScheduleEvent(EVENT_SUPPRESSION_CAST, 5000);
break;
case EVENT_SUPPRESSION_RESET:
Activate();
break;
}
}
}
void DoAction(int32 action) override
{
if (action == ACTION_DEACTIVATE)
{
Deactivate();
_events.CancelEvent(EVENT_SUPPRESSION_RESET);
}
else if (action == ACTION_DISARMED)
{
Deactivate();
_events.CancelEvent(EVENT_SUPPRESSION_CAST);
_events.ScheduleEvent(EVENT_SUPPRESSION_RESET, urand(30000, 120000));
}
}
void Activate()
{
if (_active)
return;
_active = true;
if (me->GetGoState() == GO_STATE_ACTIVE)
me->SetGoState(GO_STATE_READY);
me->SetLootState(GO_READY);
me->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE);
_events.ScheduleEvent(EVENT_SUPPRESSION_CAST, 1000);
me->Respawn();
}
void Deactivate()
{
if (!_active)
return;
_active = false;
me->SetGoState(GO_STATE_ACTIVE);
me->SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE);
_events.CancelEvent(EVENT_SUPPRESSION_CAST);
}
private:
InstanceScript* _instance;
EventMap _events;
bool _active;
};
GameObjectAI* GetAI(GameObject* go) const override
{
return new go_suppression_deviceAI(go);
}
};
void AddSC_boss_broodlord()
{
new boss_broodlord();
new go_suppression_device();
}
<commit_msg>fix(Scripts/BWL): Blast Wave timer (#10622)<commit_after>/*
* This file is part of the AzerothCore Project. See AUTHORS file for Copyright information
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published by the
* Free Software Foundation; either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "GameObject.h"
#include "GameObjectAI.h"
#include "InstanceScript.h"
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "blackwing_lair.h"
enum Say
{
SAY_AGGRO = 0,
SAY_LEASH = 1
};
enum Spells
{
SPELL_CLEAVE = 26350,
SPELL_BLASTWAVE = 23331,
SPELL_MORTALSTRIKE = 24573,
SPELL_KNOCKBACK = 25778,
SPELL_SUPPRESSION_AURA = 22247 // Suppression Device Spell
};
enum Events
{
EVENT_CLEAVE = 1,
EVENT_BLASTWAVE = 2,
EVENT_MORTALSTRIKE = 3,
EVENT_KNOCKBACK = 4,
EVENT_CHECK = 5,
// Suppression Device Events
EVENT_SUPPRESSION_CAST = 6,
EVENT_SUPPRESSION_RESET = 7
};
enum Actions
{
ACTION_DEACTIVATE = 0,
ACTION_DISARMED = 1
};
class boss_broodlord : public CreatureScript
{
public:
boss_broodlord() : CreatureScript("boss_broodlord") { }
struct boss_broodlordAI : public BossAI
{
boss_broodlordAI(Creature* creature) : BossAI(creature, DATA_BROODLORD_LASHLAYER) { }
void EnterCombat(Unit* who) override
{
BossAI::EnterCombat(who);
Talk(SAY_AGGRO);
events.ScheduleEvent(EVENT_CLEAVE, 8000);
events.ScheduleEvent(EVENT_BLASTWAVE, 12000);
events.ScheduleEvent(EVENT_MORTALSTRIKE, 20000);
events.ScheduleEvent(EVENT_KNOCKBACK, 30000);
events.ScheduleEvent(EVENT_CHECK, 1000);
}
void JustDied(Unit* /*killer*/) override
{
_JustDied();
std::list<GameObject*> _goList;
GetGameObjectListWithEntryInGrid(_goList, me, GO_SUPPRESSION_DEVICE, 200.0f);
for (std::list<GameObject*>::const_iterator itr = _goList.begin(); itr != _goList.end(); itr++)
((*itr)->AI()->DoAction(ACTION_DEACTIVATE));
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
return;
events.Update(diff);
while (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_CLEAVE:
DoCastVictim(SPELL_CLEAVE);
events.ScheduleEvent(EVENT_CLEAVE, 7000);
break;
case EVENT_BLASTWAVE:
DoCastVictim(SPELL_BLASTWAVE);
events.ScheduleEvent(EVENT_BLASTWAVE, 20000, 35000);
break;
case EVENT_MORTALSTRIKE:
DoCastVictim(SPELL_MORTALSTRIKE);
events.ScheduleEvent(EVENT_MORTALSTRIKE, 25000, 35000);
break;
case EVENT_KNOCKBACK:
DoCastVictim(SPELL_KNOCKBACK);
if (DoGetThreat(me->GetVictim()))
DoModifyThreatPercent(me->GetVictim(), -50);
events.ScheduleEvent(EVENT_KNOCKBACK, 15000, 30000);
break;
case EVENT_CHECK:
if (me->GetDistance(me->GetHomePosition()) > 150.0f)
{
Talk(SAY_LEASH);
EnterEvadeMode();
}
events.ScheduleEvent(EVENT_CHECK, 1000);
break;
}
}
DoMeleeAttackIfReady();
}
};
CreatureAI* GetAI(Creature* creature) const override
{
return GetBlackwingLairAI<boss_broodlordAI>(creature);
}
};
class go_suppression_device : public GameObjectScript
{
public:
go_suppression_device() : GameObjectScript("go_suppression_device") { }
void OnLootStateChanged(GameObject* go, uint32 state, Unit* /*unit*/) override
{
switch (state)
{
case GO_JUST_DEACTIVATED: // This case prevents the Gameobject despawn by Disarm Trap
go->SetLootState(GO_READY);
[[fallthrough]];
case GO_ACTIVATED:
go->AI()->DoAction(ACTION_DISARMED);
break;
}
}
struct go_suppression_deviceAI : public GameObjectAI
{
go_suppression_deviceAI(GameObject* go) : GameObjectAI(go), _instance(go->GetInstanceScript()), _active(true) { }
void InitializeAI() override
{
if (_instance->GetBossState(DATA_BROODLORD_LASHLAYER) == DONE)
{
Deactivate();
return;
}
_events.ScheduleEvent(EVENT_SUPPRESSION_CAST, 5000);
}
void UpdateAI(uint32 diff) override
{
_events.Update(diff);
while (uint32 eventId = _events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_SUPPRESSION_CAST:
if (me->GetGoState() == GO_STATE_READY)
{
me->CastSpell(nullptr, SPELL_SUPPRESSION_AURA);
me->SendCustomAnim(0);
}
_events.ScheduleEvent(EVENT_SUPPRESSION_CAST, 5000);
break;
case EVENT_SUPPRESSION_RESET:
Activate();
break;
}
}
}
void DoAction(int32 action) override
{
if (action == ACTION_DEACTIVATE)
{
Deactivate();
_events.CancelEvent(EVENT_SUPPRESSION_RESET);
}
else if (action == ACTION_DISARMED)
{
Deactivate();
_events.CancelEvent(EVENT_SUPPRESSION_CAST);
_events.ScheduleEvent(EVENT_SUPPRESSION_RESET, urand(30000, 120000));
}
}
void Activate()
{
if (_active)
return;
_active = true;
if (me->GetGoState() == GO_STATE_ACTIVE)
me->SetGoState(GO_STATE_READY);
me->SetLootState(GO_READY);
me->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE);
_events.ScheduleEvent(EVENT_SUPPRESSION_CAST, 1000);
me->Respawn();
}
void Deactivate()
{
if (!_active)
return;
_active = false;
me->SetGoState(GO_STATE_ACTIVE);
me->SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE);
_events.CancelEvent(EVENT_SUPPRESSION_CAST);
}
private:
InstanceScript* _instance;
EventMap _events;
bool _active;
};
GameObjectAI* GetAI(GameObject* go) const override
{
return new go_suppression_deviceAI(go);
}
};
void AddSC_boss_broodlord()
{
new boss_broodlord();
new go_suppression_device();
}
<|endoftext|> |
<commit_before>//
// MessagePack for C++ static resolution routine
//
// Copyright (C) 2008-2015 FURUHASHI Sadayuki
//
// 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 MSGPACK_ADAPTOR_STRING_HPP
#define MSGPACK_ADAPTOR_STRING_HPP
#include "types.hpp"
#include "msgpack/versioning.hpp"
#include "msgpack/object_fwd.hpp"
#include "msgpack/adaptor/check_container_size.hpp"
namespace msgpack {
MSGPACK_API_VERSION_NAMESPACE(v1) {
inline msgpack::object const& operator>> (msgpack::object const& o, String& v)
{
switch (o.type) {
case msgpack::type::BIN:
v.assign(o.via.bin.ptr, o.via.bin.size);
break;
case msgpack::type::STR:
v.assign(o.via.str.ptr, o.via.str.size);
break;
default:
throw msgpack::type_error();
break;
}
return o;
}
template <typename Stream>
inline msgpack::packer<Stream>& operator<< (msgpack::packer<Stream>& o, const String& v)
{
uint32_t size = checked_get_container_size(v.size());
o.pack_str(size);
o.pack_str_body(v.data(), size);
return o;
}
inline void operator<< (msgpack::object::with_zone& o, const String& v)
{
uint32_t size = checked_get_container_size(v.size());
o.type = msgpack::type::STR;
char* ptr = static_cast<char*>(o.zone.allocate_align(size));
o.via.str.ptr = ptr;
o.via.str.size = size;
std::memcpy(ptr, v.data(), v.size());
}
inline void operator<< (msgpack::object& o, const String& v)
{
uint32_t size = checked_get_container_size(v.size());
o.type = msgpack::type::STR;
o.via.str.ptr = v.data();
o.via.str.size = size;
}
} // MSGPACK_API_VERSION_NAMESPACE(v1)
} // namespace msgpack
#endif // MSGPACK_ADAPTOR_STRING_HPP
<commit_msg>convert from/to Utf8<commit_after>//
// MessagePack for C++ static resolution routine
//
// Copyright (C) 2008-2015 FURUHASHI Sadayuki
//
// 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 MSGPACK_ADAPTOR_STRING_HPP
#define MSGPACK_ADAPTOR_STRING_HPP
#include "types.hpp"
#include "msgpack/versioning.hpp"
#include "msgpack/object_fwd.hpp"
#include "msgpack/adaptor/check_container_size.hpp"
#include "sesame/utils/string.hpp"
namespace msgpack {
MSGPACK_API_VERSION_NAMESPACE(v1) {
inline msgpack::object const& operator>> (msgpack::object const& o, String& s)
{
switch (o.type) {
case msgpack::type::BIN:
s.assign(o.via.bin.ptr, o.via.bin.size);
break;
case msgpack::type::STR:
s.assign(o.via.str.ptr, o.via.str.size);
break;
default:
throw msgpack::type_error();
break;
}
s = sesame::utils::fromUtf8( s );
return o;
}
template <typename Stream>
inline msgpack::packer<Stream>& operator<< (msgpack::packer<Stream>& o, const String& s)
{
String v( sesame::utils::toUtf8( s ) );
uint32_t size = checked_get_container_size(v.size());
o.pack_str(size);
o.pack_str_body(v.data(), size);
return o;
}
inline void operator<< (msgpack::object::with_zone& o, const String& s)
{
String v( sesame::utils::toUtf8( s ) );
uint32_t size = checked_get_container_size(v.size());
o.type = msgpack::type::STR;
char* ptr = static_cast<char*>(o.zone.allocate_align(size));
o.via.str.ptr = ptr;
o.via.str.size = size;
std::memcpy(ptr, v.data(), v.size());
}
inline void operator<< (msgpack::object& o, const String& s)
{
String v( sesame::utils::toUtf8( s ) );
uint32_t size = checked_get_container_size(v.size());
o.type = msgpack::type::STR;
o.via.str.ptr = v.data();
o.via.str.size = size;
}
} // MSGPACK_API_VERSION_NAMESPACE(v1)
} // namespace msgpack
#endif // MSGPACK_ADAPTOR_STRING_HPP
<|endoftext|> |
<commit_before>#include "mugen_background.h"
#include <math.h>
#include <ostream>
#include <cstring>
#include <string>
#include <algorithm>
#include "globals.h"
#include "mugen_sprite.h"
#include "util/bitmap.h"
//static double pi = 3.14159265;
using namespace std;
static double interpolate(double f1, double f2, double p){
return (f1 * (1.0 - p)) + (f2 * p);
}
static int calculateTile( int length, int width ){
int loc = 0;
for( int i = 1; ; ++i ){
if( loc > length )return i;
loc+=width;
}
}
static void doParallax(Bitmap &bmp, Bitmap &work, int leftx, int lefty, int xoffset, double top, double bot, int yscalestart, double yscaledelta, double yoffset, bool mask){
const int height = bmp.getHeight();
const int w = bmp.getWidth();
int movex = 0;
//double z = 1.0 / z1;
//const double z_add = ((1.0 / z2) - z) / (y2 - y1);
Global::debug(3) << "background leftx " << leftx << endl;
for (int localy = 0; localy < height; ++localy ){
//int width = bmp.getWidth()*z;
const double range = (double)localy / (double)height;
const double scale = interpolate(top, bot, range) - top;
//const double newHeight = height*((yscalestart+(yoffset*yscaledelta))/100);
//const double yscale = (newHeight/height);
movex = (int)(leftx + (leftx - xoffset) * scale);
bmp.Stretch(work, 0, localy, w, 1,movex, lefty+localy, w,1);
//z += z_add;
//Global::debug(1) << "Height: " << height << " | yscalestart: " << yscalestart << " | yscaledelta: " << yscaledelta << " | yoffset: " << yoffset << " | New Height: " << newHeight << " | yscale: " << yscale << endl;
}
}
// mugen background
MugenBackground::MugenBackground( const unsigned long int &ticker ):
type(Normal),
groupNumber(-1),
imageNumber(-1),
actionno(-1),
id(0),
layerno(0),
startx(0),
starty(0),
deltax(1),
deltay(1),
trans(None),
alphalow(0),
alphahigh(0),
mask(true),
tilex(0),
tiley(0),
tilespacingx(0),
tilespacingy(0),
windowdeltax(0),
windowdeltay(0),
xscaletop(0),
xscalebot(0),
yscalestart(100),
yscaledelta(100),
positionlink(false),
velocityx(0),
velocityy(0),
sinx_amp(0),
sinx_period(0),
sinx_offset(0),
sinx_angle(0),
siny_amp(0),
siny_period(0),
siny_offset(0),
siny_angle(0),
xoffset(0),
yoffset(0),
movex(0),
movey(0),
velx(0),
vely(0),
stageTicker( ticker ),
x(0),
y(0),
visible(true),
enabled(true),
controller_offsetx(0),
controller_offsety(0),
sprite(0),
spriteBmp(0),
action(0),
linked(0),
runLink(false){
}
MugenBackground::MugenBackground( const MugenBackground © ):
stageTicker( copy.stageTicker ){
}
MugenBackground::~MugenBackground(){
// Kill the bmp
if( spriteBmp )delete spriteBmp;
}
MugenBackground & MugenBackground::operator=( const MugenBackground © ){
return *this;
}
void MugenBackground::logic( const double x, const double y, const double placementx, const double placementy ){
if (enabled){
movex = movey = 0;
movex += x * deltax;
movey += y * deltay;
velx += velocityx;
vely += velocityy;
/* how much should sin_angle be incremented by each frame?
* I think the total angle should be (ticks % sin_period) * 2pi / sin_period
* M (decimal) is the magnitude in pixels (amp)
* P (decimal) is the period in game ticks (period)
* O (decimal) is the time offset in game ticks (offset)
* From updates.txt: M * sine ((ticks+O)/P * 2 * Pi)
* sinx_amp * sin((stageTicker+sinx_offset)/sinx_period * 2 * pi)) ? useless it seems
*/
//sin_angle += 0.00005;
sinx_angle += 0.00005;
siny_angle += 0.00005;
if( type == Anim ) action->logic();
this->x = (int)(placementx + xoffset + movex + velx + controller_offsetx + sinx_amp * sin(sinx_angle*sinx_period + sinx_offset));
this->y = (int)(placementy + yoffset + movey + vely + controller_offsety + siny_amp * sin(siny_angle*siny_period + siny_offset));
}
}
void MugenBackground::render( const int totalLength, const int totalHeight, Bitmap *work ){
if (visible){
switch( type ){
case Normal:{
// Normal is a sprite
// see if we need to tile this beyatch
int tilexloc = x;
const int width = spriteBmp->getWidth();
const int height = spriteBmp->getHeight();
bool dirx = false, diry = false;
// Figure out total we need to tile (this crap doesn't work needs fix)
const int repeath = (tilex > 0 ? (tilex > 1 ? tilex : ( calculateTile( totalLength, width ) ) ) : 1 );
const int repeatv = ( tiley > 0 ? (tiley > 1 ? tiley : ( calculateTile( totalLength, height ) ) ) : 1 );
const int addw = width + tilespacingx;
const int addh = height + tilespacingy;
// We need to repeat and wrap
for( int h = 0; h < repeath; h++ ){
int tileyloc = y;
for( int v = 0; v < repeatv; v++ ){
draw( tilexloc, tileyloc, *work );
if( !diry )tileyloc += addh;
else tileyloc -= addh;
if( tileyloc >= work->getHeight() ){
diry = true;
tileyloc = y - addh;
}
}
if( !dirx )tilexloc += addw;
else tilexloc -= addw;
if( tilexloc >= work->getWidth() ){
dirx = true;
tilexloc = x - addw;
}
}
break;
}
case Parallax:{
// This is also a sprite but we must parallax it across the top and bottom to give the illusion of depth
doParallax( *spriteBmp, *work, x, y, xoffset, xscaletop, xscalebot, yscalestart, yscaledelta, (movey-deltay), mask);
break;
}
case Anim:{
// there is no sprite use our action!
//action->render( x, y, *work );
// Need to tile as well
int tilexloc = x;
const int width = action->getCurrentFrame()->bmp->getWidth();
const int height = action->getCurrentFrame()->bmp->getHeight();
bool dirx = false, diry = false;
// Figure out total we need to tile
const int repeath = (tilex > 0 ? (tilex > 1 ? tilex : ( calculateTile( totalLength, width ) ) ) : 1 );
const int repeatv = ( tiley > 0 ? (tiley > 1 ? tiley : ( calculateTile( totalLength, height ) ) ) : 1 );
const int addw = tilespacingx;
const int addh = tilespacingy;
// We need to repeat and wrap
for( int h = 0; h < repeath; h++ ){
int tileyloc = y;
for( int v = 0; v < repeatv; v++ ){
action->render( tilexloc, tileyloc, *work );
if( !diry )tileyloc += addh;
else tileyloc -= addh;
if( tileyloc >= work->getHeight() ){
diry = true;
tileyloc = y - addh;
}
}
if( !dirx )tilexloc += addw;
else tilexloc -= addw;
if( tilexloc >= work->getWidth() ){
dirx = true;
tilexloc = x - addw;
}
}
break;
}
case Dummy:
// Do nothing
default:
break;
}
}
}
void MugenBackground::preload( const int xaxis, const int yaxis ){
// Do positionlink crap
if (positionlink && !runLink){
if (linked){
linked->setPositionLink(this);
}
runLink = true;
}
if(sprite){
// Lets load our sprite
spriteBmp = new Bitmap(Bitmap::memoryPCX((unsigned char*) sprite->pcx, sprite->newlength));
// Set our initial offsets
xoffset = 160 + (xaxis - sprite->x) + startx;
yoffset = (yaxis - sprite->y) + starty;
velx = vely = 0;
}
else{
// Set our initial offsets
xoffset = 160 + (xaxis) + startx;
yoffset = (yaxis) + starty;
velx = vely = 0;
}
}
void MugenBackground::draw( const int ourx, const int oury, Bitmap &work ){
// This needs to be a switch trans = None, Add, Add1, Sub1, Addalpha
switch( trans ){
case Addalpha:{
// Need to figure out blend correctly addalpha is given to two locations low and high ?
Bitmap::addBlender( 255, 255, 255, alphalow );
spriteBmp->drawTrans( ourx, oury, work);
break;
}
case Add:{
// this additive 100% I assume... not totally sure
Bitmap::addBlender( 255, 255, 255, 255 );
spriteBmp->drawTrans( ourx, oury, work);
break;
}
case Add1:{
// 50%
Bitmap::addBlender( 128, 128, 128, 255 );
spriteBmp->drawTrans( ourx, oury, work);
break;
}
case Sub:{
// Shadow effect
Bitmap::differenceBlender( 128, 128, 128, 255 );
spriteBmp->drawTrans( ourx, oury, work);
break;
}
case None:
default:{
if( mask )spriteBmp->draw( ourx,oury, work );
else spriteBmp->Blit( ourx, oury, work );
break;
}
}
}
// Lets do our positionlink stuff
void MugenBackground::setPositionLink(MugenBackground *bg){
if (positionlink){
if (linked){
linked->setPositionLink(bg);
return;
}
}
bg->startx += startx;
bg->starty += starty;
bg->deltax = deltax;
bg->deltay = deltay;
bg->sinx_amp = sinx_amp;
bg->sinx_offset = sinx_offset;
bg->sinx_period = sinx_period;
bg->siny_amp = siny_amp;
bg->siny_offset = siny_offset;
bg->siny_period = siny_period;
bg->velocityx = velocityx;
bg->velocityy = velocityy;
//Global::debug(1) << "Positionlinked bg: " << bg->name << " set to x: " << bg->startx << " y: " << bg->starty << endl;
}
<commit_msg>AddAlpha should be transBlender not addBlender<commit_after>#include "mugen_background.h"
#include <math.h>
#include <ostream>
#include <cstring>
#include <string>
#include <algorithm>
#include "globals.h"
#include "mugen_sprite.h"
#include "util/bitmap.h"
//static double pi = 3.14159265;
using namespace std;
static double interpolate(double f1, double f2, double p){
return (f1 * (1.0 - p)) + (f2 * p);
}
static int calculateTile( int length, int width ){
int loc = 0;
for( int i = 1; ; ++i ){
if( loc > length )return i;
loc+=width;
}
}
static void doParallax(Bitmap &bmp, Bitmap &work, int leftx, int lefty, int xoffset, double top, double bot, int yscalestart, double yscaledelta, double yoffset, bool mask){
const int height = bmp.getHeight();
const int w = bmp.getWidth();
int movex = 0;
//double z = 1.0 / z1;
//const double z_add = ((1.0 / z2) - z) / (y2 - y1);
Global::debug(3) << "background leftx " << leftx << endl;
for (int localy = 0; localy < height; ++localy ){
//int width = bmp.getWidth()*z;
const double range = (double)localy / (double)height;
const double scale = interpolate(top, bot, range) - top;
//const double newHeight = height*((yscalestart+(yoffset*yscaledelta))/100);
//const double yscale = (newHeight/height);
movex = (int)(leftx + (leftx - xoffset) * scale);
bmp.Stretch(work, 0, localy, w, 1,movex, lefty+localy, w,1);
//z += z_add;
//Global::debug(1) << "Height: " << height << " | yscalestart: " << yscalestart << " | yscaledelta: " << yscaledelta << " | yoffset: " << yoffset << " | New Height: " << newHeight << " | yscale: " << yscale << endl;
}
}
// mugen background
MugenBackground::MugenBackground( const unsigned long int &ticker ):
type(Normal),
groupNumber(-1),
imageNumber(-1),
actionno(-1),
id(0),
layerno(0),
startx(0),
starty(0),
deltax(1),
deltay(1),
trans(None),
alphalow(0),
alphahigh(0),
mask(true),
tilex(0),
tiley(0),
tilespacingx(0),
tilespacingy(0),
windowdeltax(0),
windowdeltay(0),
xscaletop(0),
xscalebot(0),
yscalestart(100),
yscaledelta(100),
positionlink(false),
velocityx(0),
velocityy(0),
sinx_amp(0),
sinx_period(0),
sinx_offset(0),
sinx_angle(0),
siny_amp(0),
siny_period(0),
siny_offset(0),
siny_angle(0),
xoffset(0),
yoffset(0),
movex(0),
movey(0),
velx(0),
vely(0),
stageTicker( ticker ),
x(0),
y(0),
visible(true),
enabled(true),
controller_offsetx(0),
controller_offsety(0),
sprite(0),
spriteBmp(0),
action(0),
linked(0),
runLink(false){
}
MugenBackground::MugenBackground( const MugenBackground © ):
stageTicker( copy.stageTicker ){
}
MugenBackground::~MugenBackground(){
// Kill the bmp
if( spriteBmp )delete spriteBmp;
}
MugenBackground & MugenBackground::operator=( const MugenBackground © ){
return *this;
}
void MugenBackground::logic( const double x, const double y, const double placementx, const double placementy ){
if (enabled){
movex = movey = 0;
movex += x * deltax;
movey += y * deltay;
velx += velocityx;
vely += velocityy;
/* how much should sin_angle be incremented by each frame?
* I think the total angle should be (ticks % sin_period) * 2pi / sin_period
* M (decimal) is the magnitude in pixels (amp)
* P (decimal) is the period in game ticks (period)
* O (decimal) is the time offset in game ticks (offset)
* From updates.txt: M * sine ((ticks+O)/P * 2 * Pi)
* sinx_amp * sin((stageTicker+sinx_offset)/sinx_period * 2 * pi)) ? useless it seems
*/
//sin_angle += 0.00005;
sinx_angle += 0.00005;
siny_angle += 0.00005;
if( type == Anim ) action->logic();
this->x = (int)(placementx + xoffset + movex + velx + controller_offsetx + sinx_amp * sin(sinx_angle*sinx_period + sinx_offset));
this->y = (int)(placementy + yoffset + movey + vely + controller_offsety + siny_amp * sin(siny_angle*siny_period + siny_offset));
}
}
void MugenBackground::render( const int totalLength, const int totalHeight, Bitmap *work ){
if (visible){
switch( type ){
case Normal:{
// Normal is a sprite
// see if we need to tile this beyatch
int tilexloc = x;
const int width = spriteBmp->getWidth();
const int height = spriteBmp->getHeight();
bool dirx = false, diry = false;
// Figure out total we need to tile (this crap doesn't work needs fix)
const int repeath = (tilex > 0 ? (tilex > 1 ? tilex : ( calculateTile( totalLength, width ) ) ) : 1 );
const int repeatv = ( tiley > 0 ? (tiley > 1 ? tiley : ( calculateTile( totalLength, height ) ) ) : 1 );
const int addw = width + tilespacingx;
const int addh = height + tilespacingy;
// We need to repeat and wrap
for( int h = 0; h < repeath; h++ ){
int tileyloc = y;
for( int v = 0; v < repeatv; v++ ){
draw( tilexloc, tileyloc, *work );
if( !diry )tileyloc += addh;
else tileyloc -= addh;
if( tileyloc >= work->getHeight() ){
diry = true;
tileyloc = y - addh;
}
}
if( !dirx )tilexloc += addw;
else tilexloc -= addw;
if( tilexloc >= work->getWidth() ){
dirx = true;
tilexloc = x - addw;
}
}
break;
}
case Parallax:{
// This is also a sprite but we must parallax it across the top and bottom to give the illusion of depth
doParallax( *spriteBmp, *work, x, y, xoffset, xscaletop, xscalebot, yscalestart, yscaledelta, (movey-deltay), mask);
break;
}
case Anim:{
// there is no sprite use our action!
//action->render( x, y, *work );
// Need to tile as well
int tilexloc = x;
const int width = action->getCurrentFrame()->bmp->getWidth();
const int height = action->getCurrentFrame()->bmp->getHeight();
bool dirx = false, diry = false;
// Figure out total we need to tile
const int repeath = (tilex > 0 ? (tilex > 1 ? tilex : ( calculateTile( totalLength, width ) ) ) : 1 );
const int repeatv = ( tiley > 0 ? (tiley > 1 ? tiley : ( calculateTile( totalLength, height ) ) ) : 1 );
const int addw = tilespacingx;
const int addh = tilespacingy;
// We need to repeat and wrap
for( int h = 0; h < repeath; h++ ){
int tileyloc = y;
for( int v = 0; v < repeatv; v++ ){
action->render( tilexloc, tileyloc, *work );
if( !diry )tileyloc += addh;
else tileyloc -= addh;
if( tileyloc >= work->getHeight() ){
diry = true;
tileyloc = y - addh;
}
}
if( !dirx )tilexloc += addw;
else tilexloc -= addw;
if( tilexloc >= work->getWidth() ){
dirx = true;
tilexloc = x - addw;
}
}
break;
}
case Dummy:
// Do nothing
default:
break;
}
}
}
void MugenBackground::preload( const int xaxis, const int yaxis ){
// Do positionlink crap
if (positionlink && !runLink){
if (linked){
linked->setPositionLink(this);
}
runLink = true;
}
if(sprite){
// Lets load our sprite
spriteBmp = new Bitmap(Bitmap::memoryPCX((unsigned char*) sprite->pcx, sprite->newlength));
// Set our initial offsets
xoffset = 160 + (xaxis - sprite->x) + startx;
yoffset = (yaxis - sprite->y) + starty;
velx = vely = 0;
}
else{
// Set our initial offsets
xoffset = 160 + (xaxis) + startx;
yoffset = (yaxis) + starty;
velx = vely = 0;
}
}
void MugenBackground::draw( const int ourx, const int oury, Bitmap &work ){
// This needs to be a switch trans = None, Add, Add1, Sub1, Addalpha
switch( trans ){
case Addalpha:{
// Need to figure out blend correctly addalpha is given to two locations low and high ?
Bitmap::transBlender( 255, 255, 255, alphalow );
spriteBmp->drawTrans( ourx, oury, work);
break;
}
case Add:{
// this additive 100% I assume... not totally sure
Bitmap::addBlender( 255, 255, 255, 255 );
spriteBmp->drawTrans( ourx, oury, work);
break;
}
case Add1:{
// 50%
Bitmap::addBlender( 128, 128, 128, 255 );
spriteBmp->drawTrans( ourx, oury, work);
break;
}
case Sub:{
// Shadow effect
Bitmap::differenceBlender( 128, 128, 128, 255 );
spriteBmp->drawTrans( ourx, oury, work);
break;
}
case None:
default:{
if( mask )spriteBmp->draw( ourx,oury, work );
else spriteBmp->Blit( ourx, oury, work );
break;
}
}
}
// Lets do our positionlink stuff
void MugenBackground::setPositionLink(MugenBackground *bg){
if (positionlink){
if (linked){
linked->setPositionLink(bg);
return;
}
}
bg->startx += startx;
bg->starty += starty;
bg->deltax = deltax;
bg->deltay = deltay;
bg->sinx_amp = sinx_amp;
bg->sinx_offset = sinx_offset;
bg->sinx_period = sinx_period;
bg->siny_amp = siny_amp;
bg->siny_offset = siny_offset;
bg->siny_period = siny_period;
bg->velocityx = velocityx;
bg->velocityy = velocityy;
//Global::debug(1) << "Positionlinked bg: " << bg->name << " set to x: " << bg->startx << " y: " << bg->starty << endl;
}
<|endoftext|> |
<commit_before>// [WriteFile Name=GenerateOfflineMap_Overrides, Category=Maps]
// [Legal]
// Copyright 2018 Esri.
// 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.
// [Legal]
#include "GenerateOfflineMap_Overrides.h"
#include "AuthenticationManager.h"
#include "Envelope.h"
#include "FeatureLayer.h"
#include "GeometryEngine.h"
#include "Map.h"
#include "MapQuickView.h"
#include "Portal.h"
#include "PortalItem.h"
#include "OfflineMapTask.h"
#include "Point.h"
using namespace Esri::ArcGISRuntime;
const QString GenerateOfflineMap_Overrides::s_webMapId = QStringLiteral("acc027394bc84c2fb04d1ed317aac674");
QString GenerateOfflineMap_Overrides::webMapId()
{
return s_webMapId;
}
GenerateOfflineMap_Overrides::GenerateOfflineMap_Overrides(QQuickItem* parent /* = nullptr */):
QQuickItem(parent)
{
}
void GenerateOfflineMap_Overrides::init()
{
// Register the map view for QML
qmlRegisterType<MapQuickView>("Esri.Samples", 1, 0, "MapView");
qmlRegisterType<GenerateOfflineMap_Overrides>("Esri.Samples", 1, 0, "GenerateOfflineMap_OverridesSample");
qmlRegisterUncreatableType<AuthenticationManager>("Esri.Samples", 1, 0, "AuthenticationManager", "AuthenticationManager is uncreateable");
}
void GenerateOfflineMap_Overrides::componentComplete()
{
QQuickItem::componentComplete();
// find QML MapView component
m_mapView = findChild<MapQuickView*>("mapView");
// Create a Portal Item for use by the Map and OfflineMapTask
const bool loginRequired = true;
Portal* portal = new Portal(loginRequired, this);
m_portalItem = new PortalItem(portal, webMapId(), this);
// Create a map from the Portal Item
m_map = new Map(m_portalItem, this);
// Update property once map is done loading
connect(m_map, &Map::doneLoading, this, [this](Error e)
{
if (!e.isEmpty())
return;
m_mapLoaded = true;
emit mapLoadedChanged();
});
// Set map to map view
m_mapView->setMap(m_map);
// Create the OfflineMapTask with the PortalItem
m_offlineMapTask = new OfflineMapTask(m_portalItem, this);
// connect to the error signal
connect(m_offlineMapTask, &OfflineMapTask::errorOccurred, this, [](Error e)
{
if (e.isEmpty())
return;
qDebug() << e.message() << e.additionalMessage();
});
// connect to the signal for when the default parameters are generated
connect(m_offlineMapTask, &OfflineMapTask::createDefaultGenerateOfflineMapParametersCompleted,
this, [this](QUuid, const GenerateOfflineMapParameters& params)
{
// Use the parameters to create a set of overrides.
m_parameters = params;
m_offlineMapTask->createGenerateOfflineMapParameterOverrides(params);
});
connect(m_offlineMapTask, &OfflineMapTask::createGenerateOfflineMapParameterOverridesCompleted,
this, [this](QUuid /*id*/, GenerateOfflineMapParameterOverrides* parameterOverrides)
{
m_parameterOverrides = parameterOverrides;
emit overridesReadyChanged();
setBusy(false);
emit taskBusyChanged();
});
}
void GenerateOfflineMap_Overrides::setAreaOfInterest(double xCorner1, double yCorner1, double xCorner2, double yCorner2)
{
// create an envelope from the QML rectangle corners
const Point corner1 = m_mapView->screenToLocation(xCorner1, yCorner1);
const Point corner2 = m_mapView->screenToLocation(xCorner2, yCorner2);
const Envelope extent(corner1, corner2);
const Envelope mapExtent = GeometryEngine::project(extent, SpatialReference::webMercator());
// generate parameters
m_offlineMapTask->createDefaultGenerateOfflineMapParameters(mapExtent);
setBusy(true);
emit taskBusyChanged();
}
void GenerateOfflineMap_Overrides::setBasemapLOD(int min, int max)
{
if (!overridesReady())
return;
LayerListModel* layers = m_map->basemap()->baseLayers();
if (layers && layers->size() < 1)
return;
// Obtain a key for the given basemap-layer.
OfflineMapParametersKey keyForTiledLayer(layers->at(0));
// Check that the key is valid.
if (keyForTiledLayer.isEmpty() || keyForTiledLayer.type() != OfflineMapParametersType::ExportTileCache)
return;
// Obtain the dictionary of parameters for taking the basemap offline.
QMap<OfflineMapParametersKey, ExportTileCacheParameters> dictionary = m_parameterOverrides->exportTileCacheParameters();
if (!dictionary.contains(keyForTiledLayer))
return;
// Create a new sublist of LODs in the range requested by the user.
QList<int> newLODs;
for (int i = min; i < max; ++i )
newLODs.append(i);
// Apply the sublist as the LOD level in tilecache parameters for the given
// service.
ExportTileCacheParameters& exportTileCacheParam = dictionary[keyForTiledLayer];
exportTileCacheParam.setLevelIds(newLODs);
m_parameterOverrides->setExportTileCacheParameters(dictionary);
}
void GenerateOfflineMap_Overrides::setBasemapBuffer(int bufferMeters)
{
if (!overridesReady())
return;
LayerListModel* layers = m_map->basemap()->baseLayers();
if (layers && layers->isEmpty())
return;
OfflineMapParametersKey keyForTiledLayer(layers->at(0));
if (keyForTiledLayer.isEmpty() || keyForTiledLayer.type() != OfflineMapParametersType::ExportTileCache)
return;
// Obtain the dictionary of parameters for taking the basemap offline.
QMap<OfflineMapParametersKey, ExportTileCacheParameters> dictionary = m_parameterOverrides->exportTileCacheParameters();
if (!dictionary.contains(keyForTiledLayer))
return;
// Create a new geometry around the original area of interest.
auto bufferGeom = GeometryEngine::buffer(m_parameters.areaOfInterest(), bufferMeters);
// Apply the geometry to the ExportTileCacheParameters.
ExportTileCacheParameters& exportTileCacheParam = dictionary[keyForTiledLayer];
// Set the parameters back into the dictionary.
exportTileCacheParam.setAreaOfInterest(bufferGeom);
// Store the dictionary.
m_parameterOverrides->setExportTileCacheParameters(dictionary);
}
void GenerateOfflineMap_Overrides::removeSystemValves()
{
removeFeatureLayer(QStringLiteral("System Valve"));
}
void GenerateOfflineMap_Overrides::removeServiceConnection()
{
removeFeatureLayer(QStringLiteral("Service Connection"));
}
void GenerateOfflineMap_Overrides::setHydrantWhereClause(const QString& whereClause)
{
if (!overridesReady())
return;
FeatureLayer* targetLayer = getFeatureLayerByName(QStringLiteral("Hydrant"));
if (!targetLayer)
return;
// Get the parameter key for the layer.
OfflineMapParametersKey keyForTargetLayer(targetLayer);
if (keyForTargetLayer.isEmpty() || keyForTargetLayer.type() != OfflineMapParametersType::GenerateGeodatabase)
return;
// Get the dictionary of GenerateGeoDatabaseParameters.
QMap<OfflineMapParametersKey, GenerateGeodatabaseParameters> dictionary = m_parameterOverrides->generateGeodatabaseParameters();
auto keyIt = dictionary.find(keyForTargetLayer);
if (keyIt == dictionary.end())
return;
// Grab the GenerateGeoDatabaseParameters associated with the given key.
GenerateGeodatabaseParameters& generateGdbParam = keyIt.value();
ServiceFeatureTable* table = qobject_cast<ServiceFeatureTable*>(targetLayer->featureTable());
if (!table)
return;
// Get the service layer id for the given layer.
const qint64 targetLayerId = table->layerInfo().serviceLayerId();
// Set the whereClause on the required layer option.
QList<GenerateLayerOption> layerOptions = generateGdbParam.layerOptions();
for (auto& it : layerOptions)
{
GenerateLayerOption& option = it;
if (option.layerId() == targetLayerId)
{
option.setWhereClause(whereClause);
option.setQueryOption(GenerateLayerQueryOption::UseFilter);
break;
}
}
// Add layer options back to parameters and re-add to the dictionary.
generateGdbParam.setLayerOptions(layerOptions);
dictionary[keyForTargetLayer] = generateGdbParam;
m_parameterOverrides->setGenerateGeodatabaseParameters(dictionary);
}
void GenerateOfflineMap_Overrides::setClipWaterPipesAOI(bool clip)
{
if (!overridesReady())
return;
FeatureLayer* targetLayer = getFeatureLayerByName(QStringLiteral("Main"));
if (!targetLayer)
return;
// Get the parameter key for the layer.
OfflineMapParametersKey keyForTargetLayer(targetLayer);
if (keyForTargetLayer.isEmpty() || keyForTargetLayer.type() != OfflineMapParametersType::GenerateGeodatabase)
return;
// Get the dictionary of GenerateGeoDatabaseParameters.
QMap<OfflineMapParametersKey, GenerateGeodatabaseParameters> dictionary = m_parameterOverrides->generateGeodatabaseParameters();
auto keyIt = dictionary.find(keyForTargetLayer);
if (keyIt == dictionary.end())
return;
// Grab the GenerateGeoDatabaseParameters associated with the given key.
GenerateGeodatabaseParameters& generateGdbParam = keyIt.value();
ServiceFeatureTable* table = qobject_cast<ServiceFeatureTable*>(targetLayer->featureTable());
if (!table)
return;
// Get the service layer id for the given layer.
const qint64 targetLayerId = table->layerInfo().serviceLayerId();
// Set whether to use the geometry filter to clip the waterpipes.
// If not then we get all the features.
QList<GenerateLayerOption> layerOptions = generateGdbParam.layerOptions();
for (auto& it : layerOptions)
{
GenerateLayerOption& option = it;
if (option.layerId() == targetLayerId)
{
option.setUseGeometry(clip);
break;
}
}
// Add layer options back to parameters and re-add to the dictionary.
generateGdbParam.setLayerOptions(layerOptions);
dictionary[keyForTargetLayer] = generateGdbParam;
m_parameterOverrides->setGenerateGeodatabaseParameters(dictionary);
}
void GenerateOfflineMap_Overrides::takeMapOffline(const QString& dataPath)
{
if (!overridesReady())
return;
// Take the map offline with the original paramaters and the customized overrides.
GenerateOfflineMapJob* generateJob = m_offlineMapTask->generateOfflineMap(m_parameters, dataPath, m_parameterOverrides);
// check if there is a valid job
if (!generateJob)
return;
// connect to the job's status changed signal
connect(generateJob, &GenerateOfflineMapJob::jobStatusChanged, this, [this, generateJob]()
{
// connect to the job's status changed signal to know once it is done
switch (generateJob->jobStatus()) {
case JobStatus::Failed:
emit updateStatus("Generate failed");
emit hideWindow(5000, false);
break;
case JobStatus::NotStarted:
emit updateStatus("Job not started");
break;
case JobStatus::Paused:
emit updateStatus("Job paused");
break;
case JobStatus::Started:
emit updateStatus("In progress");
break;
case JobStatus::Succeeded:
// show any layer errors
if (generateJob->result()->hasErrors())
{
QString layerErrors = "";
const QMap<Layer*, Error>& layerErrorsMap = generateJob->result()->layerErrors();
for (const auto& it : layerErrorsMap.toStdMap())
{
layerErrors += it.first->name() + ": " + it.second.message() + "\n";
}
emit showLayerErrors(layerErrors);
}
// show the map
emit updateStatus("Complete");
emit hideWindow(1500, true);
m_mapView->setMap(generateJob->result()->offlineMap(this));
break;
}
});
// connect to progress changed signal
connect(generateJob, &GenerateOfflineMapJob::progressChanged, this, [this, generateJob]()
{
emit updateProgress(generateJob->progress());
});
// connect to the error signal
connect(generateJob, &GenerateOfflineMapJob::errorOccurred, this, [](Error e)
{
if (e.isEmpty())
return;
qDebug() << e.message() << e.additionalMessage();
});
// start the generate job
generateJob->start();
}
bool GenerateOfflineMap_Overrides::taskBusy() const
{
return m_taskBusy;
}
AuthenticationManager* GenerateOfflineMap_Overrides::authenticationManager() const
{
return AuthenticationManager::instance();
}
bool GenerateOfflineMap_Overrides::overridesReady() const
{
return m_parameterOverrides;
}
void GenerateOfflineMap_Overrides::removeFeatureLayer(const QString& layerName)
{
if (!overridesReady())
return;
FeatureLayer* targetLayer = getFeatureLayerByName(layerName);
if (!targetLayer)
return;
// Get the parameter key for the layer.
OfflineMapParametersKey keyForTargetLayer(targetLayer);
if (keyForTargetLayer.isEmpty() || keyForTargetLayer.type() != OfflineMapParametersType::GenerateGeodatabase)
return;
// Get the dictionary of GenerateGeoDatabaseParameters.
QMap<OfflineMapParametersKey, GenerateGeodatabaseParameters> dictionary = m_parameterOverrides->generateGeodatabaseParameters();
auto keyIt = dictionary.find(keyForTargetLayer);
if (keyIt == dictionary.end())
return;
// Grab the GenerateGeoDatabaseParameters associated with the given key.
GenerateGeodatabaseParameters& generateGdbParam = keyIt.value();
ServiceFeatureTable* table = qobject_cast<ServiceFeatureTable*>(targetLayer->featureTable());
if (!table)
return;
// Get the service layer id for the given layer.
const qint64 targetLayerId = table->layerInfo().serviceLayerId();
// Remove the layer option from the list.
QList<GenerateLayerOption> layerOptions = generateGdbParam.layerOptions();
for (auto it = layerOptions.begin(); it != layerOptions.end(); ++it)
{
if (it->layerId() == targetLayerId)
{
layerOptions.erase(it);
break;
}
}
// Add layer options back to parameters and re-add to the dictionary.
generateGdbParam.setLayerOptions(layerOptions);
dictionary[keyForTargetLayer] = generateGdbParam;
m_parameterOverrides->setGenerateGeodatabaseParameters(dictionary);
}
FeatureLayer* GenerateOfflineMap_Overrides::getFeatureLayerByName(const QString& layerName)
{
// Find the feature layer with the given name
LayerListModel* opLayers = m_map->operationalLayers();
for (int i = 0; i < opLayers->rowCount(); ++i)
{
Layer* candidateLayer = opLayers->at(i);
if (!candidateLayer)
continue;
if (candidateLayer->layerType() == LayerType::FeatureLayer && candidateLayer->name().contains(layerName, Qt::CaseInsensitive))
{
return qobject_cast<FeatureLayer*>(candidateLayer);
}
}
return nullptr;
}
void GenerateOfflineMap_Overrides::setBusy(bool busy)
{
m_taskBusy = busy;
emit taskBusyChanged();
}
bool GenerateOfflineMap_Overrides::mapLoaded() const
{
return m_mapLoaded;
}
<commit_msg>adjusting formatting mistake<commit_after>// [WriteFile Name=GenerateOfflineMap_Overrides, Category=Maps]
// [Legal]
// Copyright 2018 Esri.
// 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.
// [Legal]
#include "GenerateOfflineMap_Overrides.h"
#include "AuthenticationManager.h"
#include "Envelope.h"
#include "FeatureLayer.h"
#include "GeometryEngine.h"
#include "Map.h"
#include "MapQuickView.h"
#include "Portal.h"
#include "PortalItem.h"
#include "OfflineMapTask.h"
#include "Point.h"
using namespace Esri::ArcGISRuntime;
const QString GenerateOfflineMap_Overrides::s_webMapId = QStringLiteral("acc027394bc84c2fb04d1ed317aac674");
QString GenerateOfflineMap_Overrides::webMapId()
{
return s_webMapId;
}
GenerateOfflineMap_Overrides::GenerateOfflineMap_Overrides(QQuickItem* parent /* = nullptr */):
QQuickItem(parent)
{
}
void GenerateOfflineMap_Overrides::init()
{
// Register the map view for QML
qmlRegisterType<MapQuickView>("Esri.Samples", 1, 0, "MapView");
qmlRegisterType<GenerateOfflineMap_Overrides>("Esri.Samples", 1, 0, "GenerateOfflineMap_OverridesSample");
qmlRegisterUncreatableType<AuthenticationManager>("Esri.Samples", 1, 0, "AuthenticationManager", "AuthenticationManager is uncreateable");
}
void GenerateOfflineMap_Overrides::componentComplete()
{
QQuickItem::componentComplete();
// find QML MapView component
m_mapView = findChild<MapQuickView*>("mapView");
// Create a Portal Item for use by the Map and OfflineMapTask
const bool loginRequired = true;
Portal* portal = new Portal(loginRequired, this);
m_portalItem = new PortalItem(portal, webMapId(), this);
// Create a map from the Portal Item
m_map = new Map(m_portalItem, this);
// Update property once map is done loading
connect(m_map, &Map::doneLoading, this, [this](Error e)
{
if (!e.isEmpty())
return;
m_mapLoaded = true;
emit mapLoadedChanged();
});
// Set map to map view
m_mapView->setMap(m_map);
// Create the OfflineMapTask with the PortalItem
m_offlineMapTask = new OfflineMapTask(m_portalItem, this);
// connect to the error signal
connect(m_offlineMapTask, &OfflineMapTask::errorOccurred, this, [](Error e)
{
if (e.isEmpty())
return;
qDebug() << e.message() << e.additionalMessage();
});
// connect to the signal for when the default parameters are generated
connect(m_offlineMapTask, &OfflineMapTask::createDefaultGenerateOfflineMapParametersCompleted,
this, [this](QUuid, const GenerateOfflineMapParameters& params)
{
// Use the parameters to create a set of overrides.
m_parameters = params;
m_offlineMapTask->createGenerateOfflineMapParameterOverrides(params);
});
connect(m_offlineMapTask, &OfflineMapTask::createGenerateOfflineMapParameterOverridesCompleted,
this, [this](QUuid /*id*/, GenerateOfflineMapParameterOverrides* parameterOverrides)
{
m_parameterOverrides = parameterOverrides;
emit overridesReadyChanged();
setBusy(false);
emit taskBusyChanged();
});
}
void GenerateOfflineMap_Overrides::setAreaOfInterest(double xCorner1, double yCorner1, double xCorner2, double yCorner2)
{
// create an envelope from the QML rectangle corners
const Point corner1 = m_mapView->screenToLocation(xCorner1, yCorner1);
const Point corner2 = m_mapView->screenToLocation(xCorner2, yCorner2);
const Envelope extent(corner1, corner2);
const Envelope mapExtent = GeometryEngine::project(extent, SpatialReference::webMercator());
// generate parameters
m_offlineMapTask->createDefaultGenerateOfflineMapParameters(mapExtent);
setBusy(true);
emit taskBusyChanged();
}
void GenerateOfflineMap_Overrides::setBasemapLOD(int min, int max)
{
if (!overridesReady())
return;
LayerListModel* layers = m_map->basemap()->baseLayers();
if (layers && layers->size() < 1)
return;
// Obtain a key for the given basemap-layer.
OfflineMapParametersKey keyForTiledLayer(layers->at(0));
// Check that the key is valid.
if (keyForTiledLayer.isEmpty() || keyForTiledLayer.type() != OfflineMapParametersType::ExportTileCache)
return;
// Obtain the dictionary of parameters for taking the basemap offline.
QMap<OfflineMapParametersKey, ExportTileCacheParameters> dictionary = m_parameterOverrides->exportTileCacheParameters();
if (!dictionary.contains(keyForTiledLayer))
return;
// Create a new sublist of LODs in the range requested by the user.
QList<int> newLODs;
for (int i = min; i < max; ++i )
newLODs.append(i);
// Apply the sublist as the LOD level in tilecache parameters for the given
// service.
ExportTileCacheParameters& exportTileCacheParam = dictionary[keyForTiledLayer];
exportTileCacheParam.setLevelIds(newLODs);
m_parameterOverrides->setExportTileCacheParameters(dictionary);
}
void GenerateOfflineMap_Overrides::setBasemapBuffer(int bufferMeters)
{
if (!overridesReady())
return;
LayerListModel* layers = m_map->basemap()->baseLayers();
if (layers && layers->isEmpty())
return;
OfflineMapParametersKey keyForTiledLayer(layers->at(0));
if (keyForTiledLayer.isEmpty() || keyForTiledLayer.type() != OfflineMapParametersType::ExportTileCache)
return;
// Obtain the dictionary of parameters for taking the basemap offline.
QMap<OfflineMapParametersKey, ExportTileCacheParameters> dictionary = m_parameterOverrides->exportTileCacheParameters();
if (!dictionary.contains(keyForTiledLayer))
return;
// Create a new geometry around the original area of interest.
auto bufferGeom = GeometryEngine::buffer(m_parameters.areaOfInterest(), bufferMeters);
// Apply the geometry to the ExportTileCacheParameters.
ExportTileCacheParameters& exportTileCacheParam = dictionary[keyForTiledLayer];
// Set the parameters back into the dictionary.
exportTileCacheParam.setAreaOfInterest(bufferGeom);
// Store the dictionary.
m_parameterOverrides->setExportTileCacheParameters(dictionary);
}
void GenerateOfflineMap_Overrides::removeSystemValves()
{
removeFeatureLayer(QStringLiteral("System Valve"));
}
void GenerateOfflineMap_Overrides::removeServiceConnection()
{
removeFeatureLayer(QStringLiteral("Service Connection"));
}
void GenerateOfflineMap_Overrides::setHydrantWhereClause(const QString& whereClause)
{
if (!overridesReady())
return;
FeatureLayer* targetLayer = getFeatureLayerByName(QStringLiteral("Hydrant"));
if (!targetLayer)
return;
// Get the parameter key for the layer.
OfflineMapParametersKey keyForTargetLayer(targetLayer);
if (keyForTargetLayer.isEmpty() || keyForTargetLayer.type() != OfflineMapParametersType::GenerateGeodatabase)
return;
// Get the dictionary of GenerateGeoDatabaseParameters.
QMap<OfflineMapParametersKey, GenerateGeodatabaseParameters> dictionary = m_parameterOverrides->generateGeodatabaseParameters();
auto keyIt = dictionary.find(keyForTargetLayer);
if (keyIt == dictionary.end())
return;
// Grab the GenerateGeoDatabaseParameters associated with the given key.
GenerateGeodatabaseParameters& generateGdbParam = keyIt.value();
ServiceFeatureTable* table = qobject_cast<ServiceFeatureTable*>(targetLayer->featureTable());
if (!table)
return;
// Get the service layer id for the given layer.
const qint64 targetLayerId = table->layerInfo().serviceLayerId();
// Set the whereClause on the required layer option.
QList<GenerateLayerOption> layerOptions = generateGdbParam.layerOptions();
for (auto& it : layerOptions)
{
GenerateLayerOption& option = it;
if (option.layerId() == targetLayerId)
{
option.setWhereClause(whereClause);
option.setQueryOption(GenerateLayerQueryOption::UseFilter);
break;
}
}
// Add layer options back to parameters and re-add to the dictionary.
generateGdbParam.setLayerOptions(layerOptions);
dictionary[keyForTargetLayer] = generateGdbParam;
m_parameterOverrides->setGenerateGeodatabaseParameters(dictionary);
}
void GenerateOfflineMap_Overrides::setClipWaterPipesAOI(bool clip)
{
if (!overridesReady())
return;
FeatureLayer* targetLayer = getFeatureLayerByName(QStringLiteral("Main"));
if (!targetLayer)
return;
// Get the parameter key for the layer.
OfflineMapParametersKey keyForTargetLayer(targetLayer);
if (keyForTargetLayer.isEmpty() || keyForTargetLayer.type() != OfflineMapParametersType::GenerateGeodatabase)
return;
// Get the dictionary of GenerateGeoDatabaseParameters.
QMap<OfflineMapParametersKey, GenerateGeodatabaseParameters> dictionary = m_parameterOverrides->generateGeodatabaseParameters();
auto keyIt = dictionary.find(keyForTargetLayer);
if (keyIt == dictionary.end())
return;
// Grab the GenerateGeoDatabaseParameters associated with the given key.
GenerateGeodatabaseParameters& generateGdbParam = keyIt.value();
ServiceFeatureTable* table = qobject_cast<ServiceFeatureTable*>(targetLayer->featureTable());
if (!table)
return;
// Get the service layer id for the given layer.
const qint64 targetLayerId = table->layerInfo().serviceLayerId();
// Set whether to use the geometry filter to clip the waterpipes.
// If not then we get all the features.
QList<GenerateLayerOption> layerOptions = generateGdbParam.layerOptions();
for (auto& it : layerOptions)
{
GenerateLayerOption& option = it;
if (option.layerId() == targetLayerId)
{
option.setUseGeometry(clip);
break;
}
}
// Add layer options back to parameters and re-add to the dictionary.
generateGdbParam.setLayerOptions(layerOptions);
dictionary[keyForTargetLayer] = generateGdbParam;
m_parameterOverrides->setGenerateGeodatabaseParameters(dictionary);
}
void GenerateOfflineMap_Overrides::takeMapOffline(const QString& dataPath)
{
if (!overridesReady())
return;
// Take the map offline with the original paramaters and the customized overrides.
GenerateOfflineMapJob* generateJob = m_offlineMapTask->generateOfflineMap(m_parameters, dataPath, m_parameterOverrides);
// check if there is a valid job
if (!generateJob)
return;
// connect to the job's status changed signal
connect(generateJob, &GenerateOfflineMapJob::jobStatusChanged, this, [this, generateJob]()
{
// connect to the job's status changed signal to know once it is done
switch (generateJob->jobStatus()) {
case JobStatus::Failed:
emit updateStatus("Generate failed");
emit hideWindow(5000, false);
break;
case JobStatus::NotStarted:
emit updateStatus("Job not started");
break;
case JobStatus::Paused:
emit updateStatus("Job paused");
break;
case JobStatus::Started:
emit updateStatus("In progress");
break;
case JobStatus::Succeeded:
// show any layer errors
if (generateJob->result()->hasErrors())
{
QString layerErrors = "";
const QMap<Layer*, Error>& layerErrorsMap = generateJob->result()->layerErrors();
for (const auto& it : layerErrorsMap.toStdMap())
{
layerErrors += it.first->name() + ": " + it.second.message() + "\n";
}
emit showLayerErrors(layerErrors);
}
// show the map
emit updateStatus("Complete");
emit hideWindow(1500, true);
m_mapView->setMap(generateJob->result()->offlineMap(this));
break;
}
});
// connect to progress changed signal
connect(generateJob, &GenerateOfflineMapJob::progressChanged, this, [this, generateJob]()
{
emit updateProgress(generateJob->progress());
});
// connect to the error signal
connect(generateJob, &GenerateOfflineMapJob::errorOccurred, this, [](Error e)
{
if (e.isEmpty())
return;
qDebug() << e.message() << e.additionalMessage();
});
// start the generate job
generateJob->start();
}
bool GenerateOfflineMap_Overrides::taskBusy() const
{
return m_taskBusy;
}
AuthenticationManager* GenerateOfflineMap_Overrides::authenticationManager() const
{
return AuthenticationManager::instance();
}
bool GenerateOfflineMap_Overrides::overridesReady() const
{
return m_parameterOverrides;
}
void GenerateOfflineMap_Overrides::removeFeatureLayer(const QString& layerName)
{
if (!overridesReady())
return;
FeatureLayer* targetLayer = getFeatureLayerByName(layerName);
if (!targetLayer)
return;
// Get the parameter key for the layer.
OfflineMapParametersKey keyForTargetLayer(targetLayer);
if (keyForTargetLayer.isEmpty() || keyForTargetLayer.type() != OfflineMapParametersType::GenerateGeodatabase)
return;
// Get the dictionary of GenerateGeoDatabaseParameters.
QMap<OfflineMapParametersKey, GenerateGeodatabaseParameters> dictionary = m_parameterOverrides->generateGeodatabaseParameters();
auto keyIt = dictionary.find(keyForTargetLayer);
if (keyIt == dictionary.end())
return;
// Grab the GenerateGeoDatabaseParameters associated with the given key.
GenerateGeodatabaseParameters& generateGdbParam = keyIt.value();
ServiceFeatureTable* table = qobject_cast<ServiceFeatureTable*>(targetLayer->featureTable());
if (!table)
return;
// Get the service layer id for the given layer.
const qint64 targetLayerId = table->layerInfo().serviceLayerId();
// Remove the layer option from the list.
QList<GenerateLayerOption> layerOptions = generateGdbParam.layerOptions();
for (auto it = layerOptions.begin(); it != layerOptions.end(); ++it)
{
if (it->layerId() == targetLayerId)
{
layerOptions.erase(it);
break;
}
}
// Add layer options back to parameters and re-add to the dictionary.
generateGdbParam.setLayerOptions(layerOptions);
dictionary[keyForTargetLayer] = generateGdbParam;
m_parameterOverrides->setGenerateGeodatabaseParameters(dictionary);
}
FeatureLayer* GenerateOfflineMap_Overrides::getFeatureLayerByName(const QString& layerName)
{
// Find the feature layer with the given name
LayerListModel* opLayers = m_map->operationalLayers();
for (int i = 0; i < opLayers->rowCount(); ++i)
{
Layer* candidateLayer = opLayers->at(i);
if (!candidateLayer)
continue;
if (candidateLayer->layerType() == LayerType::FeatureLayer && candidateLayer->name().contains(layerName, Qt::CaseInsensitive))
{
return qobject_cast<FeatureLayer*>(candidateLayer);
}
}
return nullptr;
}
void GenerateOfflineMap_Overrides::setBusy(bool busy)
{
m_taskBusy = busy;
emit taskBusyChanged();
}
bool GenerateOfflineMap_Overrides::mapLoaded() const
{
return m_mapLoaded;
}
<|endoftext|> |
<commit_before>#include <osg/Notify>
#include <osg/BoundingBox>
#include <osg/PagedLOD>
#include <osg/Timer>
#include <osgUtil/CullVisitor>
#include <iostream>
#include <vector>
#include <algorithm>
#include "TileMapper.h"
#include "TXPNode.h"
#include "TXPPagedLOD.h"
using namespace txp;
using namespace osg;
#define TXPNodeERROR(s) osg::notify(osg::NOTICE) << "txp::TXPNode::" << (s) << " error: "
TXPNode::TXPNode():
osg::Group(),
_originX(0.0),
_originY(0.0)
{
setNumChildrenRequiringUpdateTraversal(1);
}
TXPNode::TXPNode(const TXPNode& txpNode,const osg::CopyOp& copyop):
osg::Group(txpNode,copyop),
_originX(txpNode._originX),
_originY(txpNode._originY)
{
setNumChildrenRequiringUpdateTraversal(1);
}
TXPNode::~TXPNode()
{
}
TXPArchive* TXPNode::getArchive()
{
return _archive.get();
}
void TXPNode::traverse(osg::NodeVisitor& nv)
{
switch(nv.getVisitorType())
{
case osg::NodeVisitor::CULL_VISITOR:
{
osgUtil::CullVisitor* cv = dynamic_cast<osgUtil::CullVisitor*>(&nv);
if (cv)
{
//#define PRINT_TILEMAPP_TIMEINFO
#ifdef PRINT_TILEMAPP_TIMEINFO
const osg::Timer& timer = *osg::Timer::instance();
osg::Timer_t start = timer.tick();
std::cout<<"Doing visible tile search"<<std::endl;
#endif // PRINT_TILEMAPP_TIMEINFO
osg::ref_ptr<TileMapper> tileMapper = new TileMapper;
tileMapper->setLODScale(cv->getLODScale());
tileMapper->pushViewport(cv->getViewport());
tileMapper->pushProjectionMatrix(&(cv->getProjectionMatrix()));
tileMapper->pushModelViewMatrix(&(cv->getModelViewMatrix()));
// traverse the scene graph to search for valid tiles
accept(*tileMapper);
tileMapper->popModelViewMatrix();
tileMapper->popProjectionMatrix();
tileMapper->popViewport();
//std::cout<<" found " << tileMapper._tileMap.size() << std::endl;
tileMapper->checkValidityOfAllVisibleTiles();
cv->setUserData(tileMapper.get());
#ifdef PRINT_TILEMAPP_TIMEINFO
std::cout<<"Completed visible tile search in "<<timer.delta_m(start,timer.tick())<<std::endl;
#endif // PRINT_TILEMAPP_TIMEINFO
}
updateEye(nv);
break;
}
case osg::NodeVisitor::UPDATE_VISITOR:
updateSceneGraph();
break;
default:
break;
}
Group::traverse(nv);
}
bool TXPNode::computeBound() const
{
if (getNumChildren() == 0)
{
_bsphere.init();
_bsphere.expandBy(_extents);
_bsphere_computed = true;
return true;
}
return Group::computeBound();
}
void TXPNode::setArchiveName(const std::string& archiveName)
{
_archiveName = archiveName;
}
void TXPNode::setOptions(const std::string& options)
{
_options = options;
}
const std::string& TXPNode::getOptions() const
{
return _options;
}
const std::string& TXPNode::getArchiveName() const
{
return _archiveName;
}
bool TXPNode::loadArchive()
{
if (_archive.get())
{
TXPNodeERROR("loadArchive()") << "archive already open" << std::endl;
return false;
}
_archive = new TXPArchive;
if (_archive->openFile(_archiveName) == false)
{
TXPNodeERROR("loadArchive()") << "failed to load archive: \"" << _archiveName << "\"" << std::endl;
return false;
}
/*
if (_archive->loadMaterials() == false)
{
TXPNodeERROR("loadArchive()") << "failed to load materials from archive: \"" << _archiveName << "\"" << std::endl;
return false;
}
if (_archive->loadModels() == false)
{
TXPNodeERROR("loadArchive()") << "failed to load models from archive: \"" << _archiveName << "\"" << std::endl;
return false;
}
if (_archive->loadLightAttributes() == false)
{
TXPNodeERROR("loadArchive()") << "failed to load light attributes from archive: \"" << _archiveName << "\"" << std::endl;
return false;
}
*/
_archive->getOrigin(_originX,_originY);
_archive->getExtents(_extents);
int32 numLod;
_archive->GetHeader()->GetNumLods(numLod);
trpg2iPoint tileSize;
_archive->GetHeader()->GetLodSize(0,tileSize);
_pageManager = new TXPPageManager;
_pageManager->Init(_archive.get());
return true;
}
void TXPNode::updateEye(osg::NodeVisitor& nv)
{
trpg2dPoint loc;
loc.x = nv.getEyePoint().x() - _originX;
loc.y = nv.getEyePoint().y() - _originY;
if (_pageManager->SetLocation(loc))
{
trpgManagedTile *tile=NULL;
while((tile = _pageManager->GetNextUnload()))
{
int x,y,lod;
tile->GetTileLoc(x,y,lod);
if (lod == 0)
{
osg::Node* node = (osg::Node*)(tile->GetLocalData());
_nodesToRemove.push_back(node);
//osg::notify(osg::NOTICE) << "Tile unload: " << x << " " << y << " " << lod << std::endl;
}
_pageManager->AckUnload();
}
while ((tile = _pageManager->GetNextLoad()))
{
int x,y,lod;
tile->GetTileLoc(x,y,lod);
if (lod==0)
{
osg::Node* node = addPagedLODTile(x,y,lod);
tile->SetLocalData(node);
//osg::notify(osg::NOTICE) << "Tile load: " << x << " " << y << " " << lod << std::endl;
}
_pageManager->AckLoad();
}
}
}
osg::Node* TXPNode::addPagedLODTile(int x, int y, int lod)
{
char pagedLODfile[1024];
sprintf(pagedLODfile,"%s\\tile%d_%dx%d_%d.txp",_archive->getDir(),lod,x,y,_archive->getId());
TXPArchive::TileInfo info;
_archive->getTileInfo(x,y,lod,info);
osg::PagedLOD* pagedLOD = new osg::PagedLOD;
pagedLOD->setFileName(0,pagedLODfile);
pagedLOD->setPriorityOffset(0,_archive->getNumLODs());
pagedLOD->setPriorityScale(0,1.0f);
pagedLOD->setRange(0,0.0,info.maxRange);
pagedLOD->setCenter(info.center);
pagedLOD->setRadius(info.radius);
pagedLOD->setNumChildrenThatCannotBeExpired(1);
_nodesToAdd.push_back(pagedLOD);
return pagedLOD;
}
void TXPNode::updateSceneGraph()
{
if (!_nodesToRemove.empty())
{
for (unsigned int i = 0; i < _nodesToRemove.size(); i++)
{
removeChild(_nodesToRemove[i]);
}
_nodesToRemove.clear();
}
if (!_nodesToAdd.empty())
{
for (unsigned int i = 0; i < _nodesToAdd.size(); i++)
{
addChild(_nodesToAdd[i]);
}
_nodesToAdd.clear();
}
}
<commit_msg>Quick fix to crash in TXPNode.<commit_after>#include <osg/Notify>
#include <osg/BoundingBox>
#include <osg/PagedLOD>
#include <osg/Timer>
#include <osgUtil/CullVisitor>
#include <iostream>
#include <vector>
#include <algorithm>
#include "TileMapper.h"
#include "TXPNode.h"
#include "TXPPagedLOD.h"
using namespace txp;
using namespace osg;
#define TXPNodeERROR(s) osg::notify(osg::NOTICE) << "txp::TXPNode::" << (s) << " error: "
TXPNode::TXPNode():
osg::Group(),
_originX(0.0),
_originY(0.0)
{
setNumChildrenRequiringUpdateTraversal(1);
}
TXPNode::TXPNode(const TXPNode& txpNode,const osg::CopyOp& copyop):
osg::Group(txpNode,copyop),
_originX(txpNode._originX),
_originY(txpNode._originY)
{
setNumChildrenRequiringUpdateTraversal(1);
}
TXPNode::~TXPNode()
{
}
TXPArchive* TXPNode::getArchive()
{
return _archive.get();
}
void TXPNode::traverse(osg::NodeVisitor& nv)
{
switch(nv.getVisitorType())
{
case osg::NodeVisitor::CULL_VISITOR:
{
osgUtil::CullVisitor* cv = dynamic_cast<osgUtil::CullVisitor*>(&nv);
if (cv)
{
//#define PRINT_TILEMAPP_TIMEINFO
#ifdef PRINT_TILEMAPP_TIMEINFO
const osg::Timer& timer = *osg::Timer::instance();
osg::Timer_t start = timer.tick();
std::cout<<"Doing visible tile search"<<std::endl;
#endif // PRINT_TILEMAPP_TIMEINFO
osg::ref_ptr<TileMapper> tileMapper = new TileMapper;
tileMapper->setLODScale(cv->getLODScale());
tileMapper->pushViewport(cv->getViewport());
tileMapper->pushProjectionMatrix(&(cv->getProjectionMatrix()));
tileMapper->pushModelViewMatrix(&(cv->getModelViewMatrix()));
// traverse the scene graph to search for valid tiles
accept(*tileMapper);
tileMapper->popModelViewMatrix();
tileMapper->popProjectionMatrix();
tileMapper->popViewport();
//std::cout<<" found " << tileMapper._tileMap.size() << std::endl;
tileMapper->checkValidityOfAllVisibleTiles();
cv->setUserData(tileMapper.get());
#ifdef PRINT_TILEMAPP_TIMEINFO
std::cout<<"Completed visible tile search in "<<timer.delta_m(start,timer.tick())<<std::endl;
#endif // PRINT_TILEMAPP_TIMEINFO
}
updateEye(nv);
break;
}
case osg::NodeVisitor::UPDATE_VISITOR:
updateSceneGraph();
break;
default:
break;
}
Group::traverse(nv);
}
bool TXPNode::computeBound() const
{
if (getNumChildren() == 0)
{
_bsphere.init();
_bsphere.expandBy(_extents);
_bsphere_computed = true;
return true;
}
return Group::computeBound();
}
void TXPNode::setArchiveName(const std::string& archiveName)
{
_archiveName = archiveName;
}
void TXPNode::setOptions(const std::string& options)
{
_options = options;
}
const std::string& TXPNode::getOptions() const
{
return _options;
}
const std::string& TXPNode::getArchiveName() const
{
return _archiveName;
}
bool TXPNode::loadArchive()
{
if (_archive.get())
{
TXPNodeERROR("loadArchive()") << "archive already open" << std::endl;
return false;
}
_archive = new TXPArchive;
if (_archive->openFile(_archiveName) == false)
{
TXPNodeERROR("loadArchive()") << "failed to load archive: \"" << _archiveName << "\"" << std::endl;
return false;
}
/*
if (_archive->loadMaterials() == false)
{
TXPNodeERROR("loadArchive()") << "failed to load materials from archive: \"" << _archiveName << "\"" << std::endl;
return false;
}
if (_archive->loadModels() == false)
{
TXPNodeERROR("loadArchive()") << "failed to load models from archive: \"" << _archiveName << "\"" << std::endl;
return false;
}
if (_archive->loadLightAttributes() == false)
{
TXPNodeERROR("loadArchive()") << "failed to load light attributes from archive: \"" << _archiveName << "\"" << std::endl;
return false;
}
*/
_archive->getOrigin(_originX,_originY);
_archive->getExtents(_extents);
int32 numLod;
_archive->GetHeader()->GetNumLods(numLod);
trpg2iPoint tileSize;
_archive->GetHeader()->GetLodSize(0,tileSize);
_pageManager = new TXPPageManager;
_pageManager->Init(_archive.get());
return true;
}
void TXPNode::updateEye(osg::NodeVisitor& nv)
{
if (!_pageManager)
{
osg::notify(osg::NOTICE)<<"TXPNode::updateEye() no pageManager created"<<std::endl;
return;
}
trpg2dPoint loc;
loc.x = nv.getEyePoint().x() - _originX;
loc.y = nv.getEyePoint().y() - _originY;
if (_pageManager->SetLocation(loc))
{
trpgManagedTile *tile=NULL;
while((tile = _pageManager->GetNextUnload()))
{
int x,y,lod;
tile->GetTileLoc(x,y,lod);
if (lod == 0)
{
osg::Node* node = (osg::Node*)(tile->GetLocalData());
_nodesToRemove.push_back(node);
//osg::notify(osg::NOTICE) << "Tile unload: " << x << " " << y << " " << lod << std::endl;
}
_pageManager->AckUnload();
}
while ((tile = _pageManager->GetNextLoad()))
{
int x,y,lod;
tile->GetTileLoc(x,y,lod);
if (lod==0)
{
osg::Node* node = addPagedLODTile(x,y,lod);
tile->SetLocalData(node);
//osg::notify(osg::NOTICE) << "Tile load: " << x << " " << y << " " << lod << std::endl;
}
_pageManager->AckLoad();
}
}
}
osg::Node* TXPNode::addPagedLODTile(int x, int y, int lod)
{
char pagedLODfile[1024];
sprintf(pagedLODfile,"%s\\tile%d_%dx%d_%d.txp",_archive->getDir(),lod,x,y,_archive->getId());
TXPArchive::TileInfo info;
_archive->getTileInfo(x,y,lod,info);
osg::PagedLOD* pagedLOD = new osg::PagedLOD;
pagedLOD->setFileName(0,pagedLODfile);
pagedLOD->setPriorityOffset(0,_archive->getNumLODs());
pagedLOD->setPriorityScale(0,1.0f);
pagedLOD->setRange(0,0.0,info.maxRange);
pagedLOD->setCenter(info.center);
pagedLOD->setRadius(info.radius);
pagedLOD->setNumChildrenThatCannotBeExpired(1);
_nodesToAdd.push_back(pagedLOD);
return pagedLOD;
}
void TXPNode::updateSceneGraph()
{
if (!_nodesToRemove.empty())
{
for (unsigned int i = 0; i < _nodesToRemove.size(); i++)
{
removeChild(_nodesToRemove[i]);
}
_nodesToRemove.clear();
}
if (!_nodesToAdd.empty())
{
for (unsigned int i = 0; i < _nodesToAdd.size(); i++)
{
addChild(_nodesToAdd[i]);
}
_nodesToAdd.clear();
}
}
<|endoftext|> |
<commit_before>#include "can/canutil.h"
#include "canutil_pic32.h"
#include "signals.h"
#include "util/log.h"
#include "gpio.h"
#if defined(CROSSCHASM_C5)
#define CAN1_TRANSCEIVER_SWITCHED
#define CAN1_TRANSCEIVER_ENABLE_POLARITY 0
#define CAN1_TRANSCEIVER_ENABLE_PIN 38 // PORTD BIT10 (RD10)
#endif
#define BUS_MEMORY_BUFFER_SIZE 2 * 8 * 16
namespace gpio = openxc::gpio;
using openxc::gpio::GpioValue;
using openxc::util::log::debugNoNewline;
using openxc::signals::initializeFilters;
using openxc::gpio::GPIO_VALUE_LOW;
using openxc::gpio::GPIO_VALUE_HIGH;
using openxc::gpio::GPIO_DIRECTION_OUTPUT;
CAN can1Actual(CAN::CAN1);
CAN can2Actual(CAN::CAN2);
CAN* can1 = &can1Actual;
CAN* can2 = &can2Actual;
/* Private: A message area for 2 channels to store 8 16 byte messages - rqeuired
* by the PIC32 CAN library. We could add this to the CanBus struct, but the
* PIC32 has way more memory than some of our other supported platforms so I
* don't want to burden them unnecessarily.
*/
uint8_t CAN_CONTROLLER_BUFFER[BUS_MEMORY_BUFFER_SIZE];
/* Private: Initializes message filters on the CAN controller.
*
* bus - The CanBus instance to configure the filters for.
* filters - An array of filters to initialize.
* filterCount - The length of the filters array.
*/
void configureFilters(CanBus* bus, CanFilter* filters, int filterCount) {
if(filterCount > 0) {
debugNoNewline("Configuring %d filters...", filterCount);
CAN_CONTROLLER(bus)->configureFilterMask(CAN::FILTER_MASK0, 0xFFF,
CAN::SID, CAN::FILTER_MASK_IDE_TYPE);
for(int i = 0; i < filterCount; i++) {
CAN_CONTROLLER(bus)->configureFilter(
(CAN::FILTER) filters[i].number, filters[i].value,
CAN::SID);
CAN_CONTROLLER(bus)->linkFilterToChannel(
(CAN::FILTER) filters[i].number, CAN::FILTER_MASK0,
(CAN::CHANNEL) filters[i].channel);
CAN_CONTROLLER(bus)->enableFilter((CAN::FILTER) filters[i].number,
true);
}
debug("Done.");
} else {
debug("No filters configured, turning off acceptance filter");
CAN_CONTROLLER(bus)->configureFilterMask(CAN::FILTER_MASK0, 0, CAN::SID,
CAN::FILTER_MASK_IDE_TYPE);
CAN_CONTROLLER(bus)->configureFilter(
CAN::FILTER0, 0, CAN::SID);
CAN_CONTROLLER(bus)->linkFilterToChannel(
CAN::FILTER0, CAN::FILTER_MASK0, CAN::CHANNEL1);
CAN_CONTROLLER(bus)->enableFilter(CAN::FILTER0,
true);
}
}
/* Public: Change the operational mode of the specified CAN module to
* CAN_DISABLE. Also set state of any off-chip CAN line driver as needed for
* platform.
*
* CAN module will still be capable of wake from sleep.
* The OP_MODE of the CAN module itself is actually irrelevant
* when going to sleep. The main reason for this is to provide a generic
* function call to disable the off-chip transceiver(s), which saves power,
* without disabling the CAN module itself.
*/
void openxc::can::deinitialize(CanBus* bus) {
GpioValue value;
// set the operational mode
CAN_CONTROLLER(bus)->setOperatingMode(CAN::DISABLE);
while(CAN_CONTROLLER(bus)->getOperatingMode() != CAN::DISABLE);
// disable off-chip line driver
#if defined(CAN1_TRANSCEIVER_SWITCHED)
value = CAN1_TRANSCEIVER_ENABLE_POLARITY ? GPIO_VALUE_LOW : GPIO_VALUE_HIGH;
gpio::setDirection(0, CAN1_TRANSCEIVER_ENABLE_PIN, GPIO_DIRECTION_OUTPUT);
gpio::setValue(0, CAN1_TRANSCEIVER_ENABLE_PIN, value);
#endif
}
void openxc::can::initialize(CanBus* bus, bool writable) {
can::initializeCommon(bus);
GpioValue value;
// Switch the CAN module ON and switch it to Configuration mode. Wait till
// the switch is complete
CAN_CONTROLLER(bus)->enableModule(true);
CAN_CONTROLLER(bus)->setOperatingMode(CAN::CONFIGURATION);
while(CAN_CONTROLLER(bus)->getOperatingMode() != CAN::CONFIGURATION);
// Configure the CAN Module Clock. The CAN::BIT_CONFIG data structure is
// used for this purpose. The propagation, phase segment 1 and phase segment
// 2 are configured to have 3TQ. The CANSetSpeed() function sets the baud.
CAN::BIT_CONFIG canBitConfig;
canBitConfig.phaseSeg2Tq = CAN::BIT_3TQ;
canBitConfig.phaseSeg1Tq = CAN::BIT_3TQ;
canBitConfig.propagationSegTq = CAN::BIT_3TQ;
canBitConfig.phaseSeg2TimeSelect = CAN::TRUE;
canBitConfig.sample3Time = CAN::TRUE;
canBitConfig.syncJumpWidth = CAN::BIT_2TQ;
CAN_CONTROLLER(bus)->setSpeed(&canBitConfig, SYS_FREQ, bus->speed);
// Assign the buffer area to the CAN module. Note the size of each Channel
// area. It is 2 (Channels) * 8 (Messages Buffers) 16 (bytes/per message
// buffer) bytes. Each CAN module should have its own message area.
CAN_CONTROLLER(bus)->assignMemoryBuffer(CAN_CONTROLLER_BUFFER,
BUS_MEMORY_BUFFER_SIZE);
// Configure channel 0 for TX with 8 byte buffers and with "Remote Transmit
// Request" disabled, meaning that other nodes can't request for us to
// transmit data.
CAN_CONTROLLER(bus)->configureChannelForTx(CAN::CHANNEL0, 8,
CAN::TX_RTR_DISABLED, CAN::LOW_MEDIUM_PRIORITY);
// Configure channel 1 for RX with 8 byte buffers - remember this is channel
// 1 on the given bus, it doesn't mean CAN1 or CAN2 on the chipKIT board.
CAN_CONTROLLER(bus)->configureChannelForRx(CAN::CHANNEL1, 8,
CAN::RX_FULL_RECEIVE);
int filterCount;
CanFilter* filters = initializeFilters(bus->address, &filterCount);
configureFilters(bus, filters, filterCount);
// Enable interrupt and events. Enable the receive channel not empty event
// (channel event) and the receive channel event (module event). The
// interrrupt peripheral library is used to enable the CAN interrupt to the
// CPU.
CAN_CONTROLLER(bus)->enableChannelEvent(CAN::CHANNEL1,
CAN::RX_CHANNEL_NOT_EMPTY, true);
CAN_CONTROLLER(bus)->enableModuleEvent(CAN::RX_EVENT, true);
// enable the bus acvitity wake-up event (to enable wake from sleep)
CAN_CONTROLLER(bus)->enableModuleEvent(
CAN::BUS_ACTIVITY_WAKEUP_EVENT, true);
CAN_CONTROLLER(bus)->enableFeature(CAN::WAKEUP_BUS_FILTER, true);
// switch ON off-chip CAN line drivers (if necessary)
#if defined(CAN1_TRANSCEIVER_SWITCHED)
value = CAN1_TRANSCEIVER_ENABLE_POLARITY ? GPIO_VALUE_HIGH : GPIO_VALUE_LOW;
gpio::setDirection(0, CAN1_TRANSCEIVER_ENABLE_PIN, GPIO_DIRECTION_OUTPUT);
gpio::setValue(0, CAN1_TRANSCEIVER_ENABLE_PIN, value);
#endif
// move CAN module to OPERATIONAL state (go on bus)
OP_MODE mode = LISTEN_ONLY;
if(writable) {
debug("Initializing bus %d in writable mode", bus->address);
mode = NORMAL_OPERATION;
} else {
debug("Initializing bus %d in listen only mode", bus->address);
}
CAN_CONTROLLER(bus)->setOperatingMode(mode);
while(CAN_CONTROLLER(bus)->getOperatingMode() != mode);
CAN_CONTROLLER(bus)->attachInterrupt(bus->interruptHandler);
debug("Done.");
}
<commit_msg>Fix includes for CAN modes in PIC32 build.<commit_after>#include "can/canutil.h"
#include "canutil_pic32.h"
#include "signals.h"
#include "util/log.h"
#include "gpio.h"
#if defined(CROSSCHASM_C5)
#define CAN1_TRANSCEIVER_SWITCHED
#define CAN1_TRANSCEIVER_ENABLE_POLARITY 0
#define CAN1_TRANSCEIVER_ENABLE_PIN 38 // PORTD BIT10 (RD10)
#endif
#define BUS_MEMORY_BUFFER_SIZE 2 * 8 * 16
namespace gpio = openxc::gpio;
using openxc::gpio::GpioValue;
using openxc::util::log::debugNoNewline;
using openxc::signals::initializeFilters;
using openxc::gpio::GPIO_VALUE_LOW;
using openxc::gpio::GPIO_VALUE_HIGH;
using openxc::gpio::GPIO_DIRECTION_OUTPUT;
CAN can1Actual(CAN::CAN1);
CAN can2Actual(CAN::CAN2);
CAN* can1 = &can1Actual;
CAN* can2 = &can2Actual;
/* Private: A message area for 2 channels to store 8 16 byte messages - rqeuired
* by the PIC32 CAN library. We could add this to the CanBus struct, but the
* PIC32 has way more memory than some of our other supported platforms so I
* don't want to burden them unnecessarily.
*/
uint8_t CAN_CONTROLLER_BUFFER[BUS_MEMORY_BUFFER_SIZE];
/* Private: Initializes message filters on the CAN controller.
*
* bus - The CanBus instance to configure the filters for.
* filters - An array of filters to initialize.
* filterCount - The length of the filters array.
*/
void configureFilters(CanBus* bus, CanFilter* filters, int filterCount) {
if(filterCount > 0) {
debugNoNewline("Configuring %d filters...", filterCount);
CAN_CONTROLLER(bus)->configureFilterMask(CAN::FILTER_MASK0, 0xFFF,
CAN::SID, CAN::FILTER_MASK_IDE_TYPE);
for(int i = 0; i < filterCount; i++) {
CAN_CONTROLLER(bus)->configureFilter(
(CAN::FILTER) filters[i].number, filters[i].value,
CAN::SID);
CAN_CONTROLLER(bus)->linkFilterToChannel(
(CAN::FILTER) filters[i].number, CAN::FILTER_MASK0,
(CAN::CHANNEL) filters[i].channel);
CAN_CONTROLLER(bus)->enableFilter((CAN::FILTER) filters[i].number,
true);
}
debug("Done.");
} else {
debug("No filters configured, turning off acceptance filter");
CAN_CONTROLLER(bus)->configureFilterMask(CAN::FILTER_MASK0, 0, CAN::SID,
CAN::FILTER_MASK_IDE_TYPE);
CAN_CONTROLLER(bus)->configureFilter(
CAN::FILTER0, 0, CAN::SID);
CAN_CONTROLLER(bus)->linkFilterToChannel(
CAN::FILTER0, CAN::FILTER_MASK0, CAN::CHANNEL1);
CAN_CONTROLLER(bus)->enableFilter(CAN::FILTER0,
true);
}
}
/* Public: Change the operational mode of the specified CAN module to
* CAN_DISABLE. Also set state of any off-chip CAN line driver as needed for
* platform.
*
* CAN module will still be capable of wake from sleep.
* The OP_MODE of the CAN module itself is actually irrelevant
* when going to sleep. The main reason for this is to provide a generic
* function call to disable the off-chip transceiver(s), which saves power,
* without disabling the CAN module itself.
*/
void openxc::can::deinitialize(CanBus* bus) {
GpioValue value;
// set the operational mode
CAN_CONTROLLER(bus)->setOperatingMode(CAN::DISABLE);
while(CAN_CONTROLLER(bus)->getOperatingMode() != CAN::DISABLE);
// disable off-chip line driver
#if defined(CAN1_TRANSCEIVER_SWITCHED)
value = CAN1_TRANSCEIVER_ENABLE_POLARITY ? GPIO_VALUE_LOW : GPIO_VALUE_HIGH;
gpio::setDirection(0, CAN1_TRANSCEIVER_ENABLE_PIN, GPIO_DIRECTION_OUTPUT);
gpio::setValue(0, CAN1_TRANSCEIVER_ENABLE_PIN, value);
#endif
}
void openxc::can::initialize(CanBus* bus, bool writable) {
can::initializeCommon(bus);
GpioValue value;
// Switch the CAN module ON and switch it to Configuration mode. Wait till
// the switch is complete
CAN_CONTROLLER(bus)->enableModule(true);
CAN_CONTROLLER(bus)->setOperatingMode(CAN::CONFIGURATION);
while(CAN_CONTROLLER(bus)->getOperatingMode() != CAN::CONFIGURATION);
// Configure the CAN Module Clock. The CAN::BIT_CONFIG data structure is
// used for this purpose. The propagation, phase segment 1 and phase segment
// 2 are configured to have 3TQ. The CANSetSpeed() function sets the baud.
CAN::BIT_CONFIG canBitConfig;
canBitConfig.phaseSeg2Tq = CAN::BIT_3TQ;
canBitConfig.phaseSeg1Tq = CAN::BIT_3TQ;
canBitConfig.propagationSegTq = CAN::BIT_3TQ;
canBitConfig.phaseSeg2TimeSelect = CAN::TRUE;
canBitConfig.sample3Time = CAN::TRUE;
canBitConfig.syncJumpWidth = CAN::BIT_2TQ;
CAN_CONTROLLER(bus)->setSpeed(&canBitConfig, SYS_FREQ, bus->speed);
// Assign the buffer area to the CAN module. Note the size of each Channel
// area. It is 2 (Channels) * 8 (Messages Buffers) 16 (bytes/per message
// buffer) bytes. Each CAN module should have its own message area.
CAN_CONTROLLER(bus)->assignMemoryBuffer(CAN_CONTROLLER_BUFFER,
BUS_MEMORY_BUFFER_SIZE);
// Configure channel 0 for TX with 8 byte buffers and with "Remote Transmit
// Request" disabled, meaning that other nodes can't request for us to
// transmit data.
CAN_CONTROLLER(bus)->configureChannelForTx(CAN::CHANNEL0, 8,
CAN::TX_RTR_DISABLED, CAN::LOW_MEDIUM_PRIORITY);
// Configure channel 1 for RX with 8 byte buffers - remember this is channel
// 1 on the given bus, it doesn't mean CAN1 or CAN2 on the chipKIT board.
CAN_CONTROLLER(bus)->configureChannelForRx(CAN::CHANNEL1, 8,
CAN::RX_FULL_RECEIVE);
int filterCount;
CanFilter* filters = initializeFilters(bus->address, &filterCount);
configureFilters(bus, filters, filterCount);
// Enable interrupt and events. Enable the receive channel not empty event
// (channel event) and the receive channel event (module event). The
// interrrupt peripheral library is used to enable the CAN interrupt to the
// CPU.
CAN_CONTROLLER(bus)->enableChannelEvent(CAN::CHANNEL1,
CAN::RX_CHANNEL_NOT_EMPTY, true);
CAN_CONTROLLER(bus)->enableModuleEvent(CAN::RX_EVENT, true);
// enable the bus acvitity wake-up event (to enable wake from sleep)
CAN_CONTROLLER(bus)->enableModuleEvent(
CAN::BUS_ACTIVITY_WAKEUP_EVENT, true);
CAN_CONTROLLER(bus)->enableFeature(CAN::WAKEUP_BUS_FILTER, true);
// switch ON off-chip CAN line drivers (if necessary)
#if defined(CAN1_TRANSCEIVER_SWITCHED)
value = CAN1_TRANSCEIVER_ENABLE_POLARITY ? GPIO_VALUE_HIGH : GPIO_VALUE_LOW;
gpio::setDirection(0, CAN1_TRANSCEIVER_ENABLE_PIN, GPIO_DIRECTION_OUTPUT);
gpio::setValue(0, CAN1_TRANSCEIVER_ENABLE_PIN, value);
#endif
// move CAN module to OPERATIONAL state (go on bus)
CAN::OP_MODE mode = CAN::LISTEN_ONLY;
if(writable) {
debug("Initializing bus %d in writable mode", bus->address);
mode = CAN::NORMAL_OPERATION;
} else {
debug("Initializing bus %d in listen only mode", bus->address);
}
CAN_CONTROLLER(bus)->setOperatingMode(mode);
while(CAN_CONTROLLER(bus)->getOperatingMode() != mode);
CAN_CONTROLLER(bus)->attachInterrupt(bus->interruptHandler);
debug("Done.");
}
<|endoftext|> |
<commit_before>// Player.cpp
// Created by Evan Almonte
//
#include "Player.hpp"
#include "Hand.hpp"
#include <iostream>
using std::cout;
Player::Player( ) : name(""), isCPU(false), score(0) {}
Player::Player(std::string name, bool isCPU) : name(name), isCPU(isCPU), score(0) {}
int Player::getScore ( ) const { return score; }
std::string Player::getName ( ) const { return name; }
bool Player::isHuman ( ) const { return !isCPU; }
bool Player::handIsEmpty( ) const {
return playerHand.getSize ( ) == 0;
}
void Player::addCard (Card* cardToAdd) { playerHand.insert (cardToAdd); }
bool Player::askForCard(Player& otherPlayer, Card& aCard) {
Card* cardFound = otherPlayer.playerHand.find (&aCard);
if (cardFound == nullptr) { return false; }
playerHand.insert (cardFound);
otherPlayer.playerHand.remove (cardFound);
return true;
}
void Player::setName (std::string name) { this->name = name; }
void Player::evaluateHand( ) {
score = playerHand.evaluate();
}
std::ostream& operator<<(std::ostream& output, const Player& aPlayer) {
cout << "Player: " << aPlayer.name << "\n";
cout << "CPU: " << (aPlayer.isCPU == true ? "true" : "false") << "\n";
cout << "Score: " << aPlayer.score << "\n";
cout << aPlayer.playerHand << "\n";
return output;
}<commit_msg>Fixes a bug in the evaluate hand method which overwrote current score<commit_after>// Player.cpp
// Created by Evan Almonte
//
#include "Player.hpp"
#include "Hand.hpp"
#include <iostream>
using std::cout;
Player::Player( ) : name(""), isCPU(false), score(0) {}
Player::Player(std::string name, bool isCPU) : name(name), isCPU(isCPU), score(0) {}
int Player::getScore ( ) const { return score; }
std::string Player::getName ( ) const { return name; }
bool Player::isHuman ( ) const { return !isCPU; }
bool Player::handIsEmpty( ) const {
return playerHand.getSize ( ) == 0;
}
void Player::addCard (Card* cardToAdd) { playerHand.insert (cardToAdd); }
bool Player::askForCard(Player& otherPlayer, Card& aCard) {
Card* cardFound = otherPlayer.playerHand.find (&aCard);
if (cardFound == nullptr) { return false; }
playerHand.insert (cardFound);
otherPlayer.playerHand.remove (cardFound);
return true;
}
void Player::setName (std::string name) { this->name = name; }
void Player::evaluateHand ( ) {
score += playerHand.evaluate ( );
}
std::ostream& operator<<(std::ostream& output, const Player& aPlayer) {
cout << "Player: " << aPlayer.name << "\n";
cout << "CPU: " << (aPlayer.isCPU == true ? "true" : "false") << "\n";
cout << "Score: " << aPlayer.score << "\n";
cout << aPlayer.playerHand << "\n";
return output;
}<|endoftext|> |
<commit_before>#include <Riostream.h>
#include "AliRun.h"
#ifndef WIN32
# define stupre stupre_
#else
# define stupre STUPRE
#endif
//
// Fluka include
#include "Fdimpar.h" //(DIMPAR) fluka include
// Fluka commons
#include "Fdblprc.h" //(DBLPRC) fluka common
#include "Femfstk.h" //(EMFSTK) fluka common
#include "Fevtflg.h" //(EVTFLG) fluka common
#include "Fpaprop.h" //(PAPROP) fluka common
#include "Ftrackr.h" //(TRACKR) fluka common
//Virtual MC
#include "TFluka.h"
#include "TVirtualMCStack.h"
#include "TVirtualMCApplication.h"
#include "TParticle.h"
#include "TVector3.h"
extern "C" {
void stupre()
{
//*----------------------------------------------------------------------*
//* *
//* SeT User PRoperties for Emf particles *
//* *
//*----------------------------------------------------------------------*
Int_t lbhabh = 0;
if (EVTFLG.ldltry == 1) {
if (EMFSTK.ichemf[EMFSTK.npemf-1] * EMFSTK.ichemf[EMFSTK.npemf-2] < 0) lbhabh = 1;
}
// mkbmx1 = dimension for kwb real spare array in fluka stack in DIMPAR
// mkbmx2 = dimension for kwb int. spare array in fluka stack in DIMPAR
// EMFSTK.espark = spare real variables available for
// EMFSTK.iespak = spare integer variables available for
// TRACKR.spausr = user defined spare variables for the current particle
// TRACKR.ispusr = user defined spare flags for the current particle
// EMFSTK.louemf = user flag
// TRACKR.llouse = user defined flag for the current particle
Int_t npnw, ispr;
for (npnw=EMFSTK.npstrt-1; npnw<=EMFSTK.npemf-1; npnw++) {
for (ispr=0; ispr<=mkbmx1-1; ispr++)
EMFSTK.espark[npnw][ispr] = TRACKR.spausr[ispr];
for (ispr=0; ispr<=mkbmx2-1; ispr++)
EMFSTK.iespak[npnw][ispr] = TRACKR.ispusr[ispr];
EMFSTK.louemf[npnw] = TRACKR.llouse;
}
// Get the pointer to the VMC
TFluka* fluka = (TFluka*) gMC;
Int_t verbosityLevel = fluka->GetVerbosityLevel();
Bool_t debug = (verbosityLevel>=3)?kTRUE:kFALSE;
fluka->SetTrackIsNew(kTRUE);
// TVirtualMC* fluka = TFluka::GetMC();
// Get the stack produced from the generator
TVirtualMCStack* cppstack = fluka->GetStack();
// EVTFLG.ntrcks = track number
// Increment the track number and put it into the last flag
Int_t kp;
for (kp = EMFSTK.npstrt - 1; kp <= EMFSTK.npemf - 1; kp++) {
//* save the parent track number and reset it at each loop
Int_t done = 0;
Int_t parent = TRACKR.ispusr[mkbmx2-1];
Int_t flukaid = 0;
if (EMFSTK.ichemf[kp] == -1) flukaid = 3;
else if (EMFSTK.ichemf[kp] == 0) flukaid = 7;
else if (EMFSTK.ichemf[kp] == 0) flukaid = 4;
Int_t pdg = fluka->PDGFromId(flukaid);
Double_t e = EMFSTK.etemf[kp] * emvgev;
Double_t p = sqrt(e * e - PAPROP.am[flukaid+6] * PAPROP.am[flukaid+6]);
Double_t px = p * EMFSTK.u[kp];
Double_t pz = p * EMFSTK.v[kp];
Double_t py = p * EMFSTK.w[kp];
Double_t tof = EMFSTK.agemf[kp];
Double_t polx = EMFSTK.upol[kp];
Double_t poly = EMFSTK.vpol[kp];
Double_t polz = EMFSTK.wpol[kp];
Double_t vx = EMFSTK.x[kp];
Double_t vy = EMFSTK.y[kp];
Double_t vz = EMFSTK.z[kp];
Double_t weight = EMFSTK.wtemf[kp];
Int_t ntr;
TMCProcess mech;
Int_t is = 0;
//* case of no parent left (pair, photoelectric, annihilation):
//* all secondaries are true
if ((EVTFLG.lpairp == 1) || (EVTFLG.lphoel == 1) ||
(EVTFLG.lannfl == 1) || (EVTFLG.lannrs == 1)) {
if (EVTFLG.lpairp == 1) mech = kPPair;
else if (EVTFLG.lphoel == 1) mech = kPPhotoelectric;
else mech = kPAnnihilation;
cppstack->PushTrack(done, parent, pdg,
px, py, pz, e, vx, vy, vz, tof,
polx, poly, polz, mech, ntr, weight, is);
if (debug) cout << endl << " !!! stupre (PAIR, ..) : ntr=" << ntr << "pdg " << pdg << " parent=" << parent << endl;
EMFSTK.iespak[kp][mkbmx2-1] = ntr;
EMFSTK.iespak[kp][mkbmx2-2] = 0;
} // end of lpairp, lphoel, lannfl, lannrs
//* Compton: secondary is true only if charged (e+, e-)
else if ((EVTFLG.lcmptn == 1)) {
if (EMFSTK.ichemf[kp] != 0) {
mech = kPCompton;
cppstack->PushTrack(done, parent, pdg,
px, py, pz, e, vx, vy, vz, tof,
polx, poly, polz, mech, ntr, weight, is);
if (debug) cout << endl << " !!! stupre (COMPTON) : ntr=" << ntr << "pdg " << pdg << " parent=" << parent << endl;
EMFSTK.iespak[kp][mkbmx2-1] = ntr;
EMFSTK.iespak[kp][mkbmx2-2] = 0;
}
} // end of lcmptn
//* Bremsstrahlung: true secondary only if charge = 0 (photon)
else if ((EVTFLG.lbrmsp == 1)) {
if (EMFSTK.ichemf[kp] == 0) {
mech = kPBrem;
cppstack->PushTrack(done, parent, pdg,
px, py, pz, e, vx, vy, vz, tof,
polx, poly, polz, mech, ntr, weight, is);
if (debug) cout << endl << " !!! stupre (BREMS) : ntr=" << ntr << "pdg " << pdg << " parent=" << parent << endl;
EMFSTK.iespak[kp][mkbmx2-1] = ntr;
EMFSTK.iespak[kp][mkbmx2-2] = 0;
}
} // end of lbrmsp
//* Delta ray: If Bhabha, true secondary only if negative (electron)
else if ((EVTFLG.ldltry == 1)) {
if (lbhabh == 1) {
if (EMFSTK.ichemf[kp] == -1) {
mech = kPDeltaRay;
cppstack->PushTrack(done, parent, pdg,
px, py, pz, e, vx, vy, vz, tof,
polx, poly, polz, mech, ntr, weight, is);
EMFSTK.iespak[kp][mkbmx2-1] = ntr;
EMFSTK.iespak[kp][mkbmx2-2] = 0;
if (debug) cout << endl << " !!! stupre (BHABA) : ntr=" << ntr << "pdg " << pdg << " parent=" << parent << endl;
} // end of Bhabha
} // lbhabh == 1
//* Delta ray: Otherwise Moller: true secondary is the electron with
//* lower energy, which has been put higher in the stack
else if (kp == EMFSTK.npemf-1) {
mech = kPDeltaRay;
cppstack->PushTrack(done, parent, pdg,
px, py, pz, e, vx, vy, vz, tof,
polx, poly, polz, mech, ntr, weight, is);
if (debug) cout << endl << " !!! stupre (Moller) : ntr=" << ntr << "pdg " << pdg << " parent=" << parent << endl;
EMFSTK.iespak[kp][mkbmx2-1] = ntr;
EMFSTK.iespak[kp][mkbmx2-2] = 0;
} // end of Delta ray
} // end of ldltry
} // end of loop
// !!! TO BE CONFIRMED !!!
} // end of stupre
} // end of extern "C"
<commit_msg>Correct flukaid for positron.<commit_after>#include <Riostream.h>
#include "AliRun.h"
#ifndef WIN32
# define stupre stupre_
#else
# define stupre STUPRE
#endif
//
// Fluka include
#include "Fdimpar.h" //(DIMPAR) fluka include
// Fluka commons
#include "Fdblprc.h" //(DBLPRC) fluka common
#include "Femfstk.h" //(EMFSTK) fluka common
#include "Fevtflg.h" //(EVTFLG) fluka common
#include "Fpaprop.h" //(PAPROP) fluka common
#include "Ftrackr.h" //(TRACKR) fluka common
//Virtual MC
#include "TFluka.h"
#include "TVirtualMCStack.h"
#include "TVirtualMCApplication.h"
#include "TParticle.h"
#include "TVector3.h"
extern "C" {
void stupre()
{
//*----------------------------------------------------------------------*
//* *
//* SeT User PRoperties for Emf particles *
//* *
//*----------------------------------------------------------------------*
Int_t lbhabh = 0;
if (EVTFLG.ldltry == 1) {
if (EMFSTK.ichemf[EMFSTK.npemf-1] * EMFSTK.ichemf[EMFSTK.npemf-2] < 0) lbhabh = 1;
}
// mkbmx1 = dimension for kwb real spare array in fluka stack in DIMPAR
// mkbmx2 = dimension for kwb int. spare array in fluka stack in DIMPAR
// EMFSTK.espark = spare real variables available for
// EMFSTK.iespak = spare integer variables available for
// TRACKR.spausr = user defined spare variables for the current particle
// TRACKR.ispusr = user defined spare flags for the current particle
// EMFSTK.louemf = user flag
// TRACKR.llouse = user defined flag for the current particle
Int_t npnw, ispr;
for (npnw=EMFSTK.npstrt-1; npnw<=EMFSTK.npemf-1; npnw++) {
for (ispr=0; ispr<=mkbmx1-1; ispr++)
EMFSTK.espark[npnw][ispr] = TRACKR.spausr[ispr];
for (ispr=0; ispr<=mkbmx2-1; ispr++)
EMFSTK.iespak[npnw][ispr] = TRACKR.ispusr[ispr];
EMFSTK.louemf[npnw] = TRACKR.llouse;
}
// Get the pointer to the VMC
TFluka* fluka = (TFluka*) gMC;
Int_t verbosityLevel = fluka->GetVerbosityLevel();
Bool_t debug = (verbosityLevel>=3)?kTRUE:kFALSE;
fluka->SetTrackIsNew(kTRUE);
// TVirtualMC* fluka = TFluka::GetMC();
// Get the stack produced from the generator
TVirtualMCStack* cppstack = fluka->GetStack();
// EVTFLG.ntrcks = track number
// Increment the track number and put it into the last flag
Int_t kp;
for (kp = EMFSTK.npstrt - 1; kp <= EMFSTK.npemf - 1; kp++) {
//* save the parent track number and reset it at each loop
Int_t done = 0;
Int_t parent = TRACKR.ispusr[mkbmx2-1];
Int_t flukaid = 0;
if (EMFSTK.ichemf[kp] == -1) flukaid = 3;
else if (EMFSTK.ichemf[kp] == 0) flukaid = 7;
else if (EMFSTK.ichemf[kp] == 1) flukaid = 4;
Int_t pdg = fluka->PDGFromId(flukaid);
Double_t e = EMFSTK.etemf[kp] * emvgev;
Double_t p = sqrt(e * e - PAPROP.am[flukaid+6] * PAPROP.am[flukaid+6]);
Double_t px = p * EMFSTK.u[kp];
Double_t pz = p * EMFSTK.v[kp];
Double_t py = p * EMFSTK.w[kp];
Double_t tof = EMFSTK.agemf[kp];
Double_t polx = EMFSTK.upol[kp];
Double_t poly = EMFSTK.vpol[kp];
Double_t polz = EMFSTK.wpol[kp];
Double_t vx = EMFSTK.x[kp];
Double_t vy = EMFSTK.y[kp];
Double_t vz = EMFSTK.z[kp];
Double_t weight = EMFSTK.wtemf[kp];
Int_t ntr;
TMCProcess mech;
Int_t is = 0;
//* case of no parent left (pair, photoelectric, annihilation):
//* all secondaries are true
if ((EVTFLG.lpairp == 1) || (EVTFLG.lphoel == 1) ||
(EVTFLG.lannfl == 1) || (EVTFLG.lannrs == 1)) {
if (EVTFLG.lpairp == 1) mech = kPPair;
else if (EVTFLG.lphoel == 1) mech = kPPhotoelectric;
else mech = kPAnnihilation;
cppstack->PushTrack(done, parent, pdg,
px, py, pz, e, vx, vy, vz, tof,
polx, poly, polz, mech, ntr, weight, is);
if (debug) cout << endl << " !!! stupre (PAIR, ..) : ntr=" << ntr << "pdg " << pdg << " parent=" << parent << endl;
EMFSTK.iespak[kp][mkbmx2-1] = ntr;
EMFSTK.iespak[kp][mkbmx2-2] = 0;
} // end of lpairp, lphoel, lannfl, lannrs
//* Compton: secondary is true only if charged (e+, e-)
else if ((EVTFLG.lcmptn == 1)) {
if (EMFSTK.ichemf[kp] != 0) {
mech = kPCompton;
cppstack->PushTrack(done, parent, pdg,
px, py, pz, e, vx, vy, vz, tof,
polx, poly, polz, mech, ntr, weight, is);
if (debug) cout << endl << " !!! stupre (COMPTON) : ntr=" << ntr << "pdg " << pdg << " parent=" << parent << endl;
EMFSTK.iespak[kp][mkbmx2-1] = ntr;
EMFSTK.iespak[kp][mkbmx2-2] = 0;
}
} // end of lcmptn
//* Bremsstrahlung: true secondary only if charge = 0 (photon)
else if ((EVTFLG.lbrmsp == 1)) {
if (EMFSTK.ichemf[kp] == 0) {
mech = kPBrem;
cppstack->PushTrack(done, parent, pdg,
px, py, pz, e, vx, vy, vz, tof,
polx, poly, polz, mech, ntr, weight, is);
if (debug) cout << endl << " !!! stupre (BREMS) : ntr=" << ntr << "pdg " << pdg << " parent=" << parent << endl;
EMFSTK.iespak[kp][mkbmx2-1] = ntr;
EMFSTK.iespak[kp][mkbmx2-2] = 0;
}
} // end of lbrmsp
//* Delta ray: If Bhabha, true secondary only if negative (electron)
else if ((EVTFLG.ldltry == 1)) {
if (lbhabh == 1) {
if (EMFSTK.ichemf[kp] == -1) {
mech = kPDeltaRay;
cppstack->PushTrack(done, parent, pdg,
px, py, pz, e, vx, vy, vz, tof,
polx, poly, polz, mech, ntr, weight, is);
EMFSTK.iespak[kp][mkbmx2-1] = ntr;
EMFSTK.iespak[kp][mkbmx2-2] = 0;
if (debug) cout << endl << " !!! stupre (BHABA) : ntr=" << ntr << "pdg " << pdg << " parent=" << parent << endl;
} // end of Bhabha
} // lbhabh == 1
//* Delta ray: Otherwise Moller: true secondary is the electron with
//* lower energy, which has been put higher in the stack
else if (kp == EMFSTK.npemf-1) {
mech = kPDeltaRay;
cppstack->PushTrack(done, parent, pdg,
px, py, pz, e, vx, vy, vz, tof,
polx, poly, polz, mech, ntr, weight, is);
if (debug) cout << endl << " !!! stupre (Moller) : ntr=" << ntr << "pdg " << pdg << " parent=" << parent << endl;
EMFSTK.iespak[kp][mkbmx2-1] = ntr;
EMFSTK.iespak[kp][mkbmx2-2] = 0;
} // end of Delta ray
} // end of ldltry
} // end of loop
// !!! TO BE CONFIRMED !!!
} // end of stupre
} // end of extern "C"
<|endoftext|> |
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved
*/
// TEST Foundation::Containers::DataStructures::LockFree
#include "Stroika/Foundation/StroikaPreComp.h"
#include <iostream>
#include <sstream>
#if 0
#ifdef _MSC_VER //for doing leak detection
#define _CRTDBG_MAP_ALLOC
#include <crtdbg.h>
#include <stdlib.h>
#define DUMP _CrtDumpMemoryLeaks ()
#else
#define DUMP
#endif
#endif
#include <cassert>
#include <iostream>
#include <mutex>
#include <set>
#include <thread>
#include <vector>
#include "Stroika/Foundation/Debug/Assertions.h"
#include "Stroika/Foundation/Debug/Trace.h"
#include "Stroika/Foundation/Containers/LockFreeDataStructures/forward_list.h"
#include "../TestHarness/SimpleClass.h"
#include "../TestHarness/TestHarness.h"
using namespace Stroika;
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Containers;
using namespace Stroika::Foundation::Containers::LockFreeDataStructures;
namespace {
class concurrent_forward_list_tests {
public:
static void test_01 ()
{
{
concurrent_forward_list<int> a;
}
// DUMP;
}
static void test_02 ()
{
{
concurrent_forward_list<int> a;
a.push_front (2);
int v = 0;
assert (a.pop_front (&v));
assert (v == 2);
assert (a.empty ());
}
// DUMP;
}
static void test_03 ()
{
{
concurrent_forward_list<int> a;
a.push_front (2);
a.push_front (5);
int v = 0;
assert (a.pop_front (&v));
assert (v == 5);
assert (a.pop_front (&v));
assert (v == 2);
assert (a.empty ());
}
// DUMP;
}
static void test_04 ()
{
{
concurrent_forward_list<int> a;
std::vector<std::thread> threads;
int threadCount = 5;
int perThreadElementCount = 1000;
for (int i = 0; i < threadCount; i++) {
threads.emplace_back ([&] () {
for (int j = 0; j < perThreadElementCount; j++) {
a.push_front (j);
}
});
}
for (auto& thread : threads) {
thread.join ();
}
int totalElementCount = perThreadElementCount * threadCount;
for (int k = 0; k < totalElementCount; k++) {
int v = 0;
assert (a.pop_front (&v));
std::cout << v << " ";
}
assert (a.empty ());
}
// DUMP;
}
static void test_05 ()
{
{
concurrent_forward_list<int> a;
std::vector<std::thread> threads;
for (int i = 0; i < 5; i++) {
threads.emplace_back ([&a] () {
for (int j = 0; j < 1000; j++) {
int y = rand ();
a.push_front (y);
std::this_thread::sleep_for (std::chrono::microseconds (rand () % 10));
int x;
a.pop_front (&x);
if (x == y) {
std::cout << "y";
}
else {
std::cout << "n";
}
}
});
}
for (auto& thread : threads) {
thread.join ();
}
assert (a.empty ());
}
// DUMP;
}
static void test_06 ()
{
{
concurrent_forward_list<int> a;
std::vector<std::thread> threads;
int threadCount = 5;
int perThreadElementCount = 1000;
for (int i = 0; i < threadCount; i++) {
threads.emplace_back ([&a, i, perThreadElementCount] () {
for (int j = 0; j < perThreadElementCount; j++) {
a.push_front (j + i * perThreadElementCount);
}
});
}
for (auto& thread : threads) {
thread.join ();
}
std::set<int> remainingNumbers;
int totalElementCount = perThreadElementCount * threadCount;
for (int k = 0; k < totalElementCount; k++) {
remainingNumbers.insert (k);
}
for (int k = 0; k < totalElementCount; k++) {
int v;
assert (a.pop_front (&v));
std::cout << v << " ";
assert (remainingNumbers.erase (v));
}
assert (remainingNumbers.empty ());
assert (a.empty ());
}
// DUMP;
}
static void test_07 ()
{
{
concurrent_forward_list<int> a;
std::vector<std::thread> threads;
int threadCount = 5;
int perThreadElementCount = 1000;
int totalElementCount = perThreadElementCount * threadCount;
std::mutex mutex;
std::cout << "Initializing concurrent_forward_list_tests::test_07\n";
std::set<int> remainingNumbers;
for (int k = 0; k < totalElementCount; k++) {
remainingNumbers.insert (k);
}
for (int i = 0; i < threadCount; i++) {
threads.emplace_back ([&, i] () {
for (int j = 0; j < perThreadElementCount; j++) {
int y = j + i * perThreadElementCount;
a.push_front (y);
std::this_thread::sleep_for (std::chrono::microseconds (rand () % 50));
int x;
a.pop_front (&x);
{
std::unique_lock<std::mutex> lock (mutex);
assert (remainingNumbers.erase (x));
}
if (x == y) {
std::cout << "y";
}
else {
std::cout << "n";
}
}
});
}
for (auto& thread : threads) {
thread.join ();
}
assert (a.empty ());
assert (remainingNumbers.empty ());
}
// DUMP;
}
static void test_08 ()
{
{
concurrent_forward_list<int> a;
std::vector<std::thread> threads;
int threadCount = 5;
int perThreadElementCount = 1000;
int totalElementCount = perThreadElementCount * threadCount;
std::mutex mutex;
std::set<int> remainingNumbers;
std::cout << "Initializing concurrent_forward_list_tests::test_08\n";
for (int k = 0; k < totalElementCount; k++) {
remainingNumbers.insert (k);
}
for (int i = 0; i < threadCount; i++) {
threads.emplace_back ([&, i] () {
for (int j = 0; j < perThreadElementCount; j++) {
int y = j + i * perThreadElementCount;
a.push_front (y);
}
});
}
for (int i = 0; i < threadCount; i++) {
threads.emplace_back ([&, i] () {
for (int j = 0; j < perThreadElementCount; j++) {
int x;
a.pop_front (&x);
{
std::unique_lock<std::mutex> lock (mutex);
assert (remainingNumbers.erase (x));
}
std::cout << x << " ";
}
});
}
for (auto& thread : threads) {
thread.join ();
}
assert (a.empty ());
assert (remainingNumbers.empty ());
}
// DUMP;
}
static void test_09 ()
{
{
concurrent_forward_list<int> a;
a.push_front (2);
a.push_front (5);
auto i = a.begin ();
assert (*i == 5);
++i;
assert (*i == 2);
++i;
assert (i == a.end ());
}
// DUMP;
}
static void test_10 ()
{
{
concurrent_forward_list<int> a;
a.push_front (2);
auto i = a.begin ();
assert (*i == 2);
a.push_front (5);
++i;
assert (i == a.end ());
}
// DUMP;
}
static void test_11 ()
{
{
concurrent_forward_list<int> a;
a.push_front (2);
auto i = a.begin ();
int v;
a.pop_front (&v);
a.push_front (5);
auto j = a.begin ();
assert (*i == 2);
assert (*j == 5);
++i;
assert (i == a.end ());
++j;
assert (j == a.end ());
}
// DUMP;
}
static void test_12 ()
{
{
concurrent_forward_list<int> a;
a.push_front (2);
a.push_front (5);
a.insert_after (a.begin (), 3);
auto i = a.begin ();
assert (*i == 5);
++i;
assert (*i == 3);
++i;
assert (*i == 2);
++i;
assert (i == a.end ());
}
// DUMP;
}
static void test_13 ()
{
{
concurrent_forward_list<int> a;
a.push_front (2);
a.push_front (3);
a.push_front (5);
auto i = a.begin ();
assert (*i == 5);
++i;
int v;
a.erase_after (a.begin (), &v);
assert (v == 3);
assert (*i == 3);
++i;
assert (i == a.end ());
assert (*(++a.begin ()) == 2);
}
// DUMP;
}
static void test_14 ()
{
{
std::cout << "\ntest_14\n";
concurrent_forward_list<int> a;
for (int i = 0; i < 100000; i++) {
a.push_front (i);
}
}
// DUMP;
}
static void test_15 ()
{
{
concurrent_forward_list<int> a;
std::vector<std::thread> threads1;
std::vector<std::thread> threads2;
int const threadCount = 5;
int const perThreadOpCount = 100000;
bool done = false;
for (int i = 0; i < threadCount; i++) {
threads1.emplace_back ([&, i] () {
for (int j = 0; j < perThreadOpCount; j++) {
int op = rand () % (perThreadOpCount / 100);
if (op == 0) {
std::cout << "\n"
<< a.clear () << "\n";
}
else {
a.push_front (rand () % 20);
}
}
});
}
for (int i = 0; i < threadCount; i++) {
threads2.emplace_back ([&, i] () {
auto iterator = a.begin ();
while (!done) {
if (iterator != a.end ()) {
std::cout << *iterator << " ";
}
if (iterator == a.end ()) {
iterator = a.begin ();
}
else {
++iterator;
}
}
});
}
for (auto& thread : threads1) {
thread.join ();
}
done = true;
for (auto& thread : threads2) {
thread.join ();
}
}
// DUMP;
}
//static void test_() {
// {
// concurrent_forward_list<int> a;
// }
// DUMP;
//}
static void test_all ()
{
for (int repeat = 0; repeat < 10; repeat++) {
test_01 ();
test_02 ();
test_03 ();
test_04 ();
test_05 ();
test_06 ();
test_07 ();
test_08 ();
test_09 ();
test_10 ();
test_11 ();
test_12 ();
test_13 ();
test_14 ();
test_15 ();
}
}
};
}
namespace {
void DoRegressionTests_ ()
{
concurrent_forward_list_tests::test_all ();
}
}
int main ([[maybe_unused]] int argc, [[maybe_unused]] const char* argv[])
{
Stroika::TestHarness::Setup ();
return Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_);
}
<commit_msg>cleanup regtests for LockFreeDataStructures<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved
*/
// TEST Foundation::Containers::DataStructures::LockFree
#include "Stroika/Foundation/StroikaPreComp.h"
#include <iostream>
#include <sstream>
#if 0
#ifdef _MSC_VER //for doing leak detection
#define _CRTDBG_MAP_ALLOC
#include <crtdbg.h>
#include <stdlib.h>
#define DUMP _CrtDumpMemoryLeaks ()
#else
#define DUMP
#endif
#endif
#include <cassert>
#include <iostream>
#include <mutex>
#include <set>
#include <thread>
#include <vector>
#include "Stroika/Foundation/Debug/Assertions.h"
#include "Stroika/Foundation/Debug/Trace.h"
#include "Stroika/Foundation/Containers/LockFreeDataStructures/forward_list.h"
#include "../TestHarness/SimpleClass.h"
#include "../TestHarness/TestHarness.h"
using namespace Stroika;
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Containers;
using namespace Stroika::Foundation::Containers::LockFreeDataStructures;
// Comment this in to turn on aggressive noisy DbgTrace in this module
//#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1
namespace {
class concurrent_forward_list_tests {
public:
static void test_01 ()
{
Debug::TraceContextBumper ctx{"{}::test_01"};
concurrent_forward_list<int> a;
}
static void test_02 ()
{
Debug::TraceContextBumper ctx{"{}::test_02"};
concurrent_forward_list<int> a;
a.push_front (2);
int v = 0;
VerifyTestResult (a.pop_front (&v));
VerifyTestResult (v == 2);
VerifyTestResult (a.empty ());
}
static void test_03 ()
{
Debug::TraceContextBumper ctx{"{}::test_03"};
concurrent_forward_list<int> a;
a.push_front (2);
a.push_front (5);
int v = 0;
VerifyTestResult (a.pop_front (&v));
VerifyTestResult (v == 5);
VerifyTestResult (a.pop_front (&v));
VerifyTestResult (v == 2);
VerifyTestResult (a.empty ());
}
static void test_04 ()
{
Debug::TraceContextBumper ctx{"{}::test_04"};
concurrent_forward_list<int> a;
std::vector<std::thread> threads;
int threadCount = 5;
int perThreadElementCount = 1000;
for (int i = 0; i < threadCount; i++) {
threads.emplace_back ([&] () {
for (int j = 0; j < perThreadElementCount; j++) {
a.push_front (j);
}
});
}
for (auto& thread : threads) {
thread.join ();
}
int totalElementCount = perThreadElementCount * threadCount;
for (int k = 0; k < totalElementCount; k++) {
int v = 0;
assert (a.pop_front (&v));
}
VerifyTestResult (a.empty ());
}
static void test_05 ()
{
Debug::TraceContextBumper ctx{"{}::test_05"};
concurrent_forward_list<int> a;
std::vector<std::thread> threads;
for (int i = 0; i < 5; i++) {
threads.emplace_back ([&a] () {
for (int j = 0; j < 1000; j++) {
int y = rand ();
a.push_front (y);
std::this_thread::sleep_for (std::chrono::microseconds (rand () % 10));
int x;
a.pop_front (&x);
#if USE_NOISY_TRACE_IN_THIS_MODULE_
if (x == y) {
DbgTrace (L"y");
}
else {
DbgTrace (L"n");
}
#endif
}
});
}
for (auto& thread : threads) {
thread.join ();
}
VerifyTestResult (a.empty ());
}
static void test_06 ()
{
Debug::TraceContextBumper ctx{"{}::test_06"};
concurrent_forward_list<int> a;
std::vector<std::thread> threads;
int threadCount = 5;
int perThreadElementCount = 1000;
for (int i = 0; i < threadCount; i++) {
threads.emplace_back ([&a, i, perThreadElementCount] () {
for (int j = 0; j < perThreadElementCount; j++) {
a.push_front (j + i * perThreadElementCount);
}
});
}
for (auto& thread : threads) {
thread.join ();
}
std::set<int> remainingNumbers;
int totalElementCount = perThreadElementCount * threadCount;
for (int k = 0; k < totalElementCount; k++) {
remainingNumbers.insert (k);
}
for (int k = 0; k < totalElementCount; k++) {
int v;
VerifyTestResult (a.pop_front (&v));
VerifyTestResult (remainingNumbers.erase (v));
}
VerifyTestResult (remainingNumbers.empty ());
VerifyTestResult (a.empty ());
}
static void test_07 ()
{
Debug::TraceContextBumper ctx{"{}::test_07"};
concurrent_forward_list<int> a;
std::vector<std::thread> threads;
int threadCount = 5;
int perThreadElementCount = 1000;
int totalElementCount = perThreadElementCount * threadCount;
std::mutex mutex;
std::set<int> remainingNumbers;
for (int k = 0; k < totalElementCount; k++) {
remainingNumbers.insert (k);
}
for (int i = 0; i < threadCount; i++) {
threads.emplace_back ([&, i] () {
for (int j = 0; j < perThreadElementCount; j++) {
int y = j + i * perThreadElementCount;
a.push_front (y);
std::this_thread::sleep_for (std::chrono::microseconds (rand () % 50));
int x;
a.pop_front (&x);
{
std::unique_lock<std::mutex> lock (mutex);
VerifyTestResult (remainingNumbers.erase (x));
}
#if USE_NOISY_TRACE_IN_THIS_MODULE_
if (x == y) {
DbgTrace (L"y");
}
else {
DbgTrace (L"n");
}
#endif
}
});
}
for (auto& thread : threads) {
thread.join ();
}
VerifyTestResult (a.empty ());
VerifyTestResult (remainingNumbers.empty ());
}
static void test_08 ()
{
Debug::TraceContextBumper ctx{"{}::test_08"};
concurrent_forward_list<int> a;
std::vector<std::thread> threads;
int threadCount = 5;
int perThreadElementCount = 1000;
int totalElementCount = perThreadElementCount * threadCount;
std::mutex mutex;
std::set<int> remainingNumbers;
for (int k = 0; k < totalElementCount; k++) {
remainingNumbers.insert (k);
}
for (int i = 0; i < threadCount; i++) {
threads.emplace_back ([&, i] () {
for (int j = 0; j < perThreadElementCount; j++) {
int y = j + i * perThreadElementCount;
a.push_front (y);
}
});
}
for (int i = 0; i < threadCount; i++) {
threads.emplace_back ([&, i] () {
for (int j = 0; j < perThreadElementCount; j++) {
int x;
a.pop_front (&x);
{
std::unique_lock<std::mutex> lock (mutex);
VerifyTestResult (remainingNumbers.erase (x));
}
}
});
}
for (auto& thread : threads) {
thread.join ();
}
VerifyTestResult (a.empty ());
VerifyTestResult (remainingNumbers.empty ());
}
static void test_09 ()
{
Debug::TraceContextBumper ctx{"{}::test_09"};
concurrent_forward_list<int> a;
a.push_front (2);
a.push_front (5);
auto i = a.begin ();
VerifyTestResult (*i == 5);
++i;
VerifyTestResult (*i == 2);
++i;
VerifyTestResult (i == a.end ());
}
static void test_10 ()
{
Debug::TraceContextBumper ctx{"{}::test_10"};
concurrent_forward_list<int> a;
a.push_front (2);
auto i = a.begin ();
VerifyTestResult (*i == 2);
a.push_front (5);
++i;
VerifyTestResult (i == a.end ());
}
static void test_11 ()
{
Debug::TraceContextBumper ctx{"{}::test_11"};
concurrent_forward_list<int> a;
a.push_front (2);
auto i = a.begin ();
int v;
a.pop_front (&v);
a.push_front (5);
auto j = a.begin ();
VerifyTestResult (*i == 2);
VerifyTestResult (*j == 5);
++i;
VerifyTestResult (i == a.end ());
++j;
VerifyTestResult (j == a.end ());
}
static void test_12 ()
{
Debug::TraceContextBumper ctx{"{}::test_12"};
concurrent_forward_list<int> a;
a.push_front (2);
a.push_front (5);
a.insert_after (a.begin (), 3);
auto i = a.begin ();
VerifyTestResult (*i == 5);
++i;
VerifyTestResult (*i == 3);
++i;
VerifyTestResult (*i == 2);
++i;
VerifyTestResult (i == a.end ());
}
static void test_13 ()
{
Debug::TraceContextBumper ctx{"{}::test_13"};
concurrent_forward_list<int> a;
a.push_front (2);
a.push_front (3);
a.push_front (5);
auto i = a.begin ();
VerifyTestResult (*i == 5);
++i;
int v;
a.erase_after (a.begin (), &v);
VerifyTestResult (v == 3);
VerifyTestResult (*i == 3);
++i;
VerifyTestResult (i == a.end ());
VerifyTestResult (*(++a.begin ()) == 2);
}
static void test_14 ()
{
Debug::TraceContextBumper ctx{"{}::test_14"};
concurrent_forward_list<int> a;
for (int i = 0; i < 100000; i++) {
a.push_front (i);
}
}
static void test_15 ()
{
Debug::TraceContextBumper ctx{"{}::test_15"};
concurrent_forward_list<int> a;
std::vector<std::thread> threads1;
std::vector<std::thread> threads2;
int const threadCount = 5;
int const perThreadOpCount = 100000;
bool done = false;
for (int i = 0; i < threadCount; i++) {
threads1.emplace_back ([&, i] () {
for (int j = 0; j < perThreadOpCount; j++) {
int op = rand () % (perThreadOpCount / 100);
if (op == 0) {
auto cleared = a.clear ();
DbgTrace ("cleared=%d", cleared);
}
else {
a.push_front (rand () % 20);
}
}
});
}
for (int i = 0; i < threadCount; i++) {
threads2.emplace_back ([&, i] () {
auto iterator = a.begin ();
while (!done) {
if (iterator != a.end ()) {
//std::cout << *iterator << " ";
}
if (iterator == a.end ()) {
iterator = a.begin ();
}
else {
++iterator;
}
}
});
}
for (auto& thread : threads1) {
thread.join ();
}
done = true;
for (auto& thread : threads2) {
thread.join ();
}
}
static void test_all ()
{
constexpr int kMaxRepeat_{1}; // was 10
for (int repeat = 0; repeat < kMaxRepeat_; repeat++) {
test_01 ();
test_02 ();
test_03 ();
test_04 ();
test_05 ();
test_06 ();
test_07 ();
test_08 ();
test_09 ();
test_10 ();
test_11 ();
test_12 ();
test_13 ();
test_14 ();
test_15 ();
}
}
};
}
namespace {
void DoRegressionTests_ ()
{
concurrent_forward_list_tests::test_all ();
}
}
int main ([[maybe_unused]] int argc, [[maybe_unused]] const char* argv[])
{
Stroika::TestHarness::Setup ();
return Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_);
}
<|endoftext|> |
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2014. All rights reserved
*/
// TEST Foundation::Execution::ThreadSafetyBuiltinObject
#include "Stroika/Foundation/StroikaPreComp.h"
#include <mutex>
#include "Stroika/Foundation/Characters/String.h"
#include "Stroika/Foundation/Containers/Bijection.h"
#include "Stroika/Foundation/Containers/Collection.h"
#include "Stroika/Foundation/Containers/Deque.h"
#include "Stroika/Foundation/Containers/Queue.h"
#include "Stroika/Foundation/Containers/Mapping.h"
#include "Stroika/Foundation/Containers/MultiSet.h"
#include "Stroika/Foundation/Containers/Sequence.h"
#include "Stroika/Foundation/Containers/Set.h"
#include "Stroika/Foundation/Containers/Stack.h"
#include "Stroika/Foundation/Containers/SortedCollection.h"
#include "Stroika/Foundation/Containers/SortedMapping.h"
#include "Stroika/Foundation/Containers/SortedMultiSet.h"
#include "Stroika/Foundation/Containers/SortedSet.h"
#include "Stroika/Foundation/Containers/Mapping.h"
#include "Stroika/Foundation/Execution/Thread.h"
#include "Stroika/Foundation/Math/Common.h"
#include "../TestHarness/TestHarness.h"
using namespace Stroika::Foundation;
using namespace Characters;
using namespace Containers;
using Execution::Thread;
using Execution::WaitableEvent;
namespace {
/*
* To REALLY this this code for thread-safety, use ExternallySynchronizedLock, but to verify it works
* without worrying about races, just use mutex.
*/
struct no_lock_ {
void lock () {}
void unlock () {}
};
}
namespace {
void RunThreads_ (const initializer_list<Thread>& threads)
{
for (Thread i : threads) {
i.Start ();
}
for (Thread i : threads) {
i.WaitForDone ();
}
}
}
namespace {
template <typename ITERABLE_TYPE, typename LOCK_TYPE>
Thread mkIterateOverThread_ (ITERABLE_TYPE* iterable, LOCK_TYPE* lock, unsigned int repeatCount)
{
using ElementType = typename ITERABLE_TYPE::ElementType;
return Thread ([iterable, lock, repeatCount] () {
for (unsigned int i = 0; i < repeatCount; ++i) {
lock_guard<decltype(*lock)> critSec (*lock);
for (ElementType e : *iterable) {
ElementType e2 = e; // do something
}
}
});
};
}
namespace {
template <typename ITERABLE_TYPE, typename LOCK_TYPE>
Thread mkOverwriteThread_ (ITERABLE_TYPE* oneToKeepOverwriting, ITERABLE_TYPE elt1, ITERABLE_TYPE elt2, LOCK_TYPE* lock, unsigned int repeatCount)
{
return Thread ([oneToKeepOverwriting, lock, repeatCount, elt1, elt2] () {
for (unsigned int i = 0; i < repeatCount; ++i) {
for (int ii = 0; ii <= 100; ++ii) {
if (Math::IsOdd (ii)) {
lock_guard<decltype(*lock)> critSec (*lock);
(*oneToKeepOverwriting) = elt1;
}
else {
lock_guard<decltype(*lock)> critSec (*lock);
(*oneToKeepOverwriting) = elt2;
}
}
}
});
};
}
namespace {
namespace AssignAndIterateAtSameTimeTest_1_ {
template <typename ITERABLE_TYPE>
void DoItOnce_ (ITERABLE_TYPE elt1, ITERABLE_TYPE elt2, unsigned int repeatCount)
{
no_lock_ lock ;
//mutex lock;
ITERABLE_TYPE oneToKeepOverwriting = elt1;
Thread iterateThread = mkIterateOverThread_ (&oneToKeepOverwriting, &lock, repeatCount);
Thread overwriteThread = mkOverwriteThread_ (&oneToKeepOverwriting, elt1, elt2, &lock, repeatCount);
RunThreads_ ({iterateThread, overwriteThread});
}
void DoIt ()
{
static const initializer_list<int> kOrigValueInit_ = {1, 3, 4, 5, 6, 33, 12, 13};
static const initializer_list<int> kUpdateValueInit_ = {4, 5, 6, 33, 12, 34, 596, 13, 1, 3, 99, 33, 4, 5};
static const initializer_list<pair<int, int>> kOrigPairValueInit_ = {pair<int, int> (1, 3), pair<int, int> (4, 5), pair<int, int> (6, 33), pair<int, int> (12, 13)};
static const initializer_list<pair<int, int>> kUPairpdateValueInit_ = {pair<int, int> (4, 5), pair<int, int> (6, 33), pair<int, int> (12, 34), pair<int, int> (596, 13), pair<int, int> (1, 3), pair<int, int> (99, 33), pair<int, int> (4, 5)};
Debug::TraceContextBumper traceCtx (SDKSTR ("AssignAndIterateAtSameTimeTest_1_::DoIt ()"));
DoItOnce_<String> (String (L"123456789"), String (L"abcdedfghijkqlmopqrstuvwxyz"), 1000);
DoItOnce_<Bijection<int, int>> (Bijection<int, int> (kOrigPairValueInit_), Bijection<int, int> (kUPairpdateValueInit_), 1000);
DoItOnce_<Collection<int>> (Collection<int> (kOrigValueInit_), Collection<int> (kUpdateValueInit_), 1000);
// Queue/Deque NYI here cuz of assign from initializer
//DoItOnce_<Deque<int>> (Deque<int> (kOrigValueInit_), Deque<int> (kUpdateValueInit_), 1000);
//DoItOnce_<Queue<int>> (Queue<int> (kOrigValueInit_), Queue<int> (kUpdateValueInit_), 1000);
DoItOnce_<MultiSet<int>> (MultiSet<int> (kOrigValueInit_), MultiSet<int> (kUpdateValueInit_), 1000);
DoItOnce_<Mapping<int, int>> (Mapping<int, int> (kOrigPairValueInit_), Mapping<int, int> (kUPairpdateValueInit_), 1000);
DoItOnce_<Sequence<int>> (Sequence<int> (kOrigValueInit_), Sequence<int> (kUpdateValueInit_), 1000);
DoItOnce_<Set<int>> (Set<int> (kOrigValueInit_), Set<int> (kUpdateValueInit_), 1000);
DoItOnce_<SortedMapping<int, int>> (SortedMapping<int, int> (kOrigPairValueInit_), SortedMapping<int, int> (kUPairpdateValueInit_), 1000);
DoItOnce_<SortedMultiSet<int>> (SortedMultiSet<int> (kOrigValueInit_), SortedMultiSet<int> (kUpdateValueInit_), 1000);
DoItOnce_<SortedSet<int>> (SortedSet<int> (kOrigValueInit_), SortedSet<int> (kUpdateValueInit_), 1000);
// Stack NYI cuz not enough of stack implemented (op=)
//DoItOnce_<Stack<int>> (Stack<int> (kOrigValueInit_), Stack<int> (kUpdateValueInit_), 1000);
}
}
}
namespace {
namespace IterateWhileMutatingContainer_Test_2_ {
template <typename ITERABLE_TYPE, typename LOCK, typename MUTATE_FUNCTION>
void DoItOnce_ (LOCK* lock, ITERABLE_TYPE elt1, unsigned int repeatCount, MUTATE_FUNCTION baseMutateFunction)
{
ITERABLE_TYPE oneToKeepOverwriting = elt1;
auto mutateFunction = [&oneToKeepOverwriting, lock, repeatCount, &baseMutateFunction] () {
for (unsigned int i = 0; i < repeatCount; ++i) {
baseMutateFunction (&oneToKeepOverwriting);
}
};
Thread iterateThread = mkIterateOverThread_ (&oneToKeepOverwriting, lock, repeatCount);
Thread mutateThread = mutateFunction;
RunThreads_ ({iterateThread, mutateThread});
}
void DoIt ()
{
// This test demonstrates the need for qStroika_Foundation_Traveral_IteratorHoldsSharedPtr_
Debug::TraceContextBumper traceCtx (SDKSTR ("IterateWhileMutatingContainer_Test_2_::DoIt ()"));
// @TODO - DEBUG!!!!
no_lock_ lock;
//mutex lock;
#if 0
// doesnt work with 'no_lock' but does with mutext lock
// @todo - FIX - cuz of RACE CONDITION STILL
DoItOnce_<Set<int>> (
&lock,
Set<int> ({1, 3, 4, 5, 6, 33, 12, 13}),
1000,
[&lock] (Set<int>* oneToKeepOverwriting) {
for (int ii = 0; ii <= 100; ++ii) {
if (Math::IsOdd (ii)) {
lock_guard<decltype(lock)> critSec (lock);
(*oneToKeepOverwriting) = Set<int> {3, 5};
}
else {
lock_guard<decltype(lock)> critSec (lock);
(*oneToKeepOverwriting) = Set<int> {3, 5};
}
}
});
#endif
DoItOnce_<String> (
&lock,
String (L"123456789"),
1000,
[&lock] (String * oneToKeepOverwriting) {
for (int ii = 0; ii <= 100; ++ii) {
if (Math::IsOdd (ii)) {
lock_guard<decltype(lock)> critSec (lock);
(*oneToKeepOverwriting) = String {L"abc123"};
}
else {
lock_guard<decltype(lock)> critSec (lock);
(*oneToKeepOverwriting) = String {L"123abc"};
}
}
});
}
}
}
namespace {
void DoRegressionTests_ ()
{
AssignAndIterateAtSameTimeTest_1_::DoIt ();
IterateWhileMutatingContainer_Test_2_::DoIt ();
}
}
int main (int argc, const char* argv[])
{
Stroika::TestHarness::Setup ();
Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_);
return EXIT_SUCCESS;
}
<commit_msg>enhanced ThreadSafetyBuiltinObject reg-test and enabled a bunch of tests that were disbaled cuz of previously checked in bugfix (iteratorimplhelper)<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2014. All rights reserved
*/
// TEST Foundation::Execution::ThreadSafetyBuiltinObject
#include "Stroika/Foundation/StroikaPreComp.h"
#include <mutex>
#include "Stroika/Foundation/Characters/String.h"
#include "Stroika/Foundation/Containers/Bijection.h"
#include "Stroika/Foundation/Containers/Collection.h"
#include "Stroika/Foundation/Containers/Deque.h"
#include "Stroika/Foundation/Containers/Queue.h"
#include "Stroika/Foundation/Containers/Mapping.h"
#include "Stroika/Foundation/Containers/MultiSet.h"
#include "Stroika/Foundation/Containers/Sequence.h"
#include "Stroika/Foundation/Containers/Set.h"
#include "Stroika/Foundation/Containers/Stack.h"
#include "Stroika/Foundation/Containers/SortedCollection.h"
#include "Stroika/Foundation/Containers/SortedMapping.h"
#include "Stroika/Foundation/Containers/SortedMultiSet.h"
#include "Stroika/Foundation/Containers/SortedSet.h"
#include "Stroika/Foundation/Containers/Mapping.h"
#include "Stroika/Foundation/Execution/Thread.h"
#include "Stroika/Foundation/Math/Common.h"
#include "../TestHarness/TestHarness.h"
using namespace Stroika::Foundation;
using namespace Characters;
using namespace Containers;
using Execution::Thread;
using Execution::WaitableEvent;
namespace {
/*
* To REALLY this this code for thread-safety, use ExternallySynchronizedLock, but to verify it works
* without worrying about races, just use mutex.
*/
struct no_lock_ {
void lock () {}
void unlock () {}
};
}
namespace {
void RunThreads_ (const initializer_list<Thread>& threads)
{
for (Thread i : threads) {
i.Start ();
}
for (Thread i : threads) {
i.WaitForDone ();
}
}
}
namespace {
template <typename ITERABLE_TYPE, typename LOCK_TYPE>
Thread mkIterateOverThread_ (ITERABLE_TYPE* iterable, LOCK_TYPE* lock, unsigned int repeatCount)
{
using ElementType = typename ITERABLE_TYPE::ElementType;
return Thread ([iterable, lock, repeatCount] () {
Debug::TraceContextBumper traceCtx (SDKSTR ("{}IterateOverThread::MAIN..."));
for (unsigned int i = 0; i < repeatCount; ++i) {
//DbgTrace ("Iterate thread loop %d", i);
lock_guard<decltype(*lock)> critSec (*lock);
for (ElementType e : *iterable) {
ElementType e2 = e; // do something
}
}
});
};
}
namespace {
template <typename ITERABLE_TYPE, typename LOCK_TYPE>
Thread mkOverwriteThread_ (ITERABLE_TYPE* oneToKeepOverwriting, ITERABLE_TYPE elt1, ITERABLE_TYPE elt2, LOCK_TYPE* lock, unsigned int repeatCount)
{
return Thread ([oneToKeepOverwriting, lock, repeatCount, elt1, elt2] () {
Debug::TraceContextBumper traceCtx (SDKSTR ("{}OverwriteThread::MAIN..."));
for (unsigned int i = 0; i < repeatCount; ++i) {
for (int ii = 0; ii <= 100; ++ii) {
if (Math::IsOdd (ii)) {
lock_guard<decltype(*lock)> critSec (*lock);
(*oneToKeepOverwriting) = elt1;
}
else {
lock_guard<decltype(*lock)> critSec (*lock);
(*oneToKeepOverwriting) = elt2;
}
}
}
});
};
}
namespace {
namespace AssignAndIterateAtSameTimeTest_1_ {
template <typename ITERABLE_TYPE>
void DoItOnce_ (ITERABLE_TYPE elt1, ITERABLE_TYPE elt2, unsigned int repeatCount)
{
Debug::TraceContextBumper traceCtx (SDKSTR ("{}::AssignAndIterateAtSameTimeTest_1_::DoIt::DoItOnce_ ()"));
no_lock_ lock ;
//mutex lock;
ITERABLE_TYPE oneToKeepOverwriting = elt1;
Thread iterateThread = mkIterateOverThread_ (&oneToKeepOverwriting, &lock, repeatCount);
Thread overwriteThread = mkOverwriteThread_ (&oneToKeepOverwriting, elt1, elt2, &lock, repeatCount);
RunThreads_ ({iterateThread, overwriteThread});
}
void DoIt ()
{
Debug::TraceContextBumper traceCtx (SDKSTR ("AssignAndIterateAtSameTimeTest_1_::DoIt ()"));
const unsigned int kRepeatCount_ = 500;
//const unsigned int kRepeatCount_ = 1;
static const initializer_list<int> kOrigValueInit_ = {1, 3, 4, 5, 6, 33, 12, 13};
static const initializer_list<int> kUpdateValueInit_ = {4, 5, 6, 33, 12, 34, 596, 13, 1, 3, 99, 33, 4, 5};
static const initializer_list<pair<int, int>> kOrigPairValueInit_ = {pair<int, int> (1, 3), pair<int, int> (4, 5), pair<int, int> (6, 33), pair<int, int> (12, 13)};
static const initializer_list<pair<int, int>> kUPairpdateValueInit_ = {pair<int, int> (4, 5), pair<int, int> (6, 33), pair<int, int> (12, 34), pair<int, int> (596, 13), pair<int, int> (1, 3), pair<int, int> (99, 33), pair<int, int> (4, 5)};
DoItOnce_<String> (String (L"123456789"), String (L"abcdedfghijkqlmopqrstuvwxyz"), kRepeatCount_);
DoItOnce_<Bijection<int, int>> (Bijection<int, int> (kOrigPairValueInit_), Bijection<int, int> (kUPairpdateValueInit_), kRepeatCount_);
DoItOnce_<Collection<int>> (Collection<int> (kOrigValueInit_), Collection<int> (kUpdateValueInit_), kRepeatCount_);
// Queue/Deque NYI here cuz of assign from initializer
//DoItOnce_<Deque<int>> (Deque<int> (kOrigValueInit_), Deque<int> (kUpdateValueInit_), kRepeatCount_);
//DoItOnce_<Queue<int>> (Queue<int> (kOrigValueInit_), Queue<int> (kUpdateValueInit_), kRepeatCount_);
DoItOnce_<MultiSet<int>> (MultiSet<int> (kOrigValueInit_), MultiSet<int> (kUpdateValueInit_), kRepeatCount_);
DoItOnce_<Mapping<int, int>> (Mapping<int, int> (kOrigPairValueInit_), Mapping<int, int> (kUPairpdateValueInit_), kRepeatCount_);
DoItOnce_<Sequence<int>> (Sequence<int> (kOrigValueInit_), Sequence<int> (kUpdateValueInit_), kRepeatCount_);
DoItOnce_<Set<int>> (Set<int> (kOrigValueInit_), Set<int> (kUpdateValueInit_), kRepeatCount_);
DoItOnce_<SortedMapping<int, int>> (SortedMapping<int, int> (kOrigPairValueInit_), SortedMapping<int, int> (kUPairpdateValueInit_), kRepeatCount_);
DoItOnce_<SortedMultiSet<int>> (SortedMultiSet<int> (kOrigValueInit_), SortedMultiSet<int> (kUpdateValueInit_), kRepeatCount_);
DoItOnce_<SortedSet<int>> (SortedSet<int> (kOrigValueInit_), SortedSet<int> (kUpdateValueInit_), kRepeatCount_);
// Stack NYI cuz not enough of stack implemented (op=)
//DoItOnce_<Stack<int>> (Stack<int> (kOrigValueInit_), Stack<int> (kUpdateValueInit_), kRepeatCount_);
}
}
}
namespace {
namespace IterateWhileMutatingContainer_Test_2_ {
template <typename ITERABLE_TYPE, typename LOCK, typename MUTATE_FUNCTION>
void DoItOnce_ (LOCK* lock, ITERABLE_TYPE elt1, unsigned int repeatCount, MUTATE_FUNCTION baseMutateFunction)
{
ITERABLE_TYPE oneToKeepOverwriting = elt1;
auto mutateFunction = [&oneToKeepOverwriting, lock, repeatCount, &baseMutateFunction] () {
Debug::TraceContextBumper traceCtx (SDKSTR ("{}::MutateFunction ()"));
DbgTrace ("(type %s)", typeid (ITERABLE_TYPE).name());
for (unsigned int i = 0; i < repeatCount; ++i) {
baseMutateFunction (&oneToKeepOverwriting);
}
};
Thread iterateThread = mkIterateOverThread_ (&oneToKeepOverwriting, lock, repeatCount);
Thread mutateThread = mutateFunction;
RunThreads_ ({iterateThread, mutateThread});
}
void DoIt ()
{
// This test demonstrates the need for qStroika_Foundation_Traveral_IteratorHoldsSharedPtr_
Debug::TraceContextBumper traceCtx (SDKSTR ("IterateWhileMutatingContainer_Test_2_::DoIt ()"));
const unsigned int kRepeatCount_ = 250;
static const initializer_list<int> kOrigValueInit_ = {1, 3, 4, 5, 6, 33, 12, 13};
static const initializer_list<int> kUpdateValueInit_ = {4, 5, 6, 33, 12, 34, 596, 13, 1, 3, 99, 33, 4, 5};
no_lock_ lock;
//mutex lock;
DoItOnce_<Set<int>> (
&lock,
Set<int> (kOrigValueInit_),
kRepeatCount_,
[&lock] (Set<int>* oneToKeepOverwriting) {
for (int ii = 0; ii <= 100; ++ii) {
//DbgTrace ("doing update loop %d", ii);
if (Math::IsOdd (ii)) {
lock_guard<decltype(lock)> critSec (lock);
(*oneToKeepOverwriting) = Set<int> { kUpdateValueInit_ };
}
else {
lock_guard<decltype(lock)> critSec (lock);
(*oneToKeepOverwriting) = Set<int> { kUpdateValueInit_ };
}
}
});
DoItOnce_<Sequence<int>> (
&lock,
Sequence<int> (kOrigValueInit_),
kRepeatCount_,
[&lock] (Sequence<int>* oneToKeepOverwriting) {
for (int ii = 0; ii <= 100; ++ii) {
if (Math::IsOdd (ii)) {
lock_guard<decltype(lock)> critSec (lock);
(*oneToKeepOverwriting) = Sequence<int> { kUpdateValueInit_ };
}
else {
lock_guard<decltype(lock)> critSec (lock);
(*oneToKeepOverwriting) = Sequence<int> { kUpdateValueInit_ };
}
}
});
DoItOnce_<String> (
&lock,
String (L"123456789"),
kRepeatCount_,
[&lock] (String * oneToKeepOverwriting) {
for (int ii = 0; ii <= 100; ++ii) {
if (Math::IsOdd (ii)) {
lock_guard<decltype(lock)> critSec (lock);
(*oneToKeepOverwriting) = String {L"abc123"};
}
else {
lock_guard<decltype(lock)> critSec (lock);
(*oneToKeepOverwriting) = String {L"123abc"};
}
}
});
}
}
}
namespace {
void DoRegressionTests_ ()
{
AssignAndIterateAtSameTimeTest_1_::DoIt ();
IterateWhileMutatingContainer_Test_2_::DoIt ();
}
}
int main (int argc, const char* argv[])
{
Stroika::TestHarness::Setup ();
Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_);
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2018. All rights reserved
*/
// TEST Foundation::Execution::ProcessRunner
#include "Stroika/Foundation/StroikaPreComp.h"
#include "Stroika/Foundation/Debug/Trace.h"
#include "Stroika/Foundation/Execution/ProcessRunner.h"
#if qPlatform_POSIX
#include "Stroika/Foundation/Execution/SignalHandlers.h"
#endif
#include "Stroika/Foundation/Execution/Sleep.h"
#include "Stroika/Foundation/Streams/MemoryStream.h"
#include "Stroika/Foundation/Streams/SharedMemoryStream.h"
#include "../TestHarness/TestHarness.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Execution;
using Characters::String;
namespace {
void RegressionTest1_ ()
{
Debug::TraceContextBumper ctx{L"RegressionTest1_"};
Streams::MemoryStream<Byte>::Ptr myStdOut = Streams::MemoryStream<Byte>::New ();
// quickie about to test..
ProcessRunner pr (L"echo hi mom", nullptr, myStdOut);
pr.Run ();
}
void RegressionTest2_ ()
{
Debug::TraceContextBumper ctx{L"RegressionTest2_"};
Streams::MemoryStream<Byte>::Ptr myStdOut = Streams::MemoryStream<Byte>::New ();
// quickie about to test..
ProcessRunner pr (L"echo hi mom");
String out = pr.Run (L"");
VerifyTestResult (out.Trim () == L"hi mom");
}
void RegressionTest3_Pipe_ ()
{
Debug::TraceContextBumper ctx{L"RegressionTest3_Pipe_"};
Streams::MemoryStream<Byte>::Ptr myStdOut = Streams::MemoryStream<Byte>::New ();
ProcessRunner pr1 (L"echo hi mom");
Streams::MemoryStream<Byte>::Ptr pipe = Streams::MemoryStream<Byte>::New ();
ProcessRunner pr2 (L"cat");
pr1.SetStdOut (pipe);
pr2.SetStdIn (pipe);
Streams::MemoryStream<Byte>::Ptr pr2Out = Streams::MemoryStream<Byte>::New ();
pr2.SetStdOut (pr2Out);
pr1.Run ();
pr2.Run ();
String out = String::FromUTF8 (pr2Out.As<string> ());
VerifyTestResult (out.Trim () == L"hi mom");
}
void RegressionTest4_DocSample_ ()
{
Debug::TraceContextBumper ctx{L"RegressionTest4_DocSample_"};
// cat doesn't exist on windows (without cygwin or some such) - but the regression test code depends on that anyhow
// so this should be OK for now... -- LGP 2017-06-31
Memory::BLOB kData_{Memory::BLOB::Raw ("this is a test")};
Streams::MemoryStream<Byte>::Ptr processStdIn = Streams::MemoryStream<Byte>::New (kData_);
Streams::MemoryStream<Byte>::Ptr processStdOut = Streams::MemoryStream<Byte>::New ();
ProcessRunner pr (L"cat", processStdIn, processStdOut);
pr.Run ();
VerifyTestResult (processStdOut.ReadAll () == kData_);
}
}
namespace {
namespace LargeDataSentThroughPipe_Test5_ {
namespace Private_ {
const Memory::BLOB k1K_ = Memory::BLOB::Raw ("0123456789abcdef").Repeat (1024 / 16);
const Memory::BLOB k1MB_ = k1K_.Repeat (1024);
const Memory::BLOB k16MB_ = k1MB_.Repeat (16);
void SingleProcessLargeDataSend_ ()
{
/*
* "Valgrind's memory management: out of memory:"
* This only happens with DEBUG builds and valgrind/helgrind. So run with less memory used, and it works better.
*/
Memory::BLOB testBLOB = (Debug::IsRunningUnderValgrind () && qDebug) ? k1K_ : k16MB_;
Streams::MemoryStream<Byte>::Ptr myStdIn = Streams::MemoryStream<Byte>::New (testBLOB);
Streams::MemoryStream<Byte>::Ptr myStdOut = Streams::MemoryStream<Byte>::New ();
ProcessRunner pr (L"cat", myStdIn, myStdOut);
pr.Run ();
VerifyTestResult (myStdOut.ReadAll () == testBLOB);
}
}
void DoTests ()
{
Debug::TraceContextBumper ctx{L"LargeDataSentThroughPipe_Test5_::DoTests"};
Private_::SingleProcessLargeDataSend_ ();
}
}
}
namespace {
namespace LargeDataSentThroughPipeBackground_Test6_ {
namespace Private_ {
const Memory::BLOB k1K_ = Memory::BLOB::Raw ("0123456789abcdef").Repeat (1024 / 16);
const Memory::BLOB k1MB_ = k1K_.Repeat (1024);
const Memory::BLOB k16MB_ = k1MB_.Repeat (16);
void SingleProcessLargeDataSend_ ()
{
Assert (k1MB_.size () == 1024 * 1024);
Streams::SharedMemoryStream<Byte>::Ptr myStdIn = Streams::SharedMemoryStream<Byte>::New (); // note must use SharedMemoryStream cuz we want to distinguish EOF from no data written yet
Streams::SharedMemoryStream<Byte>::Ptr myStdOut = Streams::SharedMemoryStream<Byte>::New ();
ProcessRunner pr (L"cat", myStdIn, myStdOut);
ProcessRunner::BackgroundProcess bg = pr.RunInBackground ();
Execution::Sleep (1);
VerifyTestResult (myStdOut.ReadNonBlocking ().IsMissing ()); // sb no data available, but NOT EOF
/*
* "Valgrind's memory management: out of memory:"
* This only happens with DEBUG builds and valgrind/helgrind. So run with less memory used, and it works better.
*/
Memory::BLOB testBLOB = (Debug::IsRunningUnderValgrind () && qDebug) ? k1K_ : k16MB_;
myStdIn.Write (testBLOB);
myStdIn.CloseWrite (); // so cat process can finish
bg.WaitForDone ();
myStdOut.CloseWrite (); // one process done, no more writes to this stream
VerifyTestResult (myStdOut.ReadAll () == testBLOB);
}
}
void DoTests ()
{
Debug::TraceContextBumper ctx{L"LargeDataSentThroughPipeBackground_Test6_::DoTests"};
Private_::SingleProcessLargeDataSend_ ();
}
}
}
namespace {
void DoRegressionTests_ ()
{
Debug::TraceContextBumper ctx{L"DoRegressionTests_"};
#if qPlatform_POSIX
// Many performance instruments use pipes
// @todo - REVIEW IF REALLY NEEDED AND WHY? SO LONG AS NO FAIL SHOULDNT BE?
// --LGP 2014-02-05
Execution::SignalHandlerRegistry::Get ().SetSignalHandlers (SIGPIPE, Execution::SignalHandlerRegistry::kIGNORED);
#endif
RegressionTest1_ ();
RegressionTest2_ ();
RegressionTest3_Pipe_ ();
RegressionTest4_DocSample_ ();
LargeDataSentThroughPipe_Test5_::DoTests ();
LargeDataSentThroughPipeBackground_Test6_::DoTests ();
}
}
int main (int argc, const char* argv[])
{
Stroika::TestHarness::Setup ();
return Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_);
}
<commit_msg>Added RegressionTes7_FaledRun_ regression test<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2018. All rights reserved
*/
// TEST Foundation::Execution::ProcessRunner
#include "Stroika/Foundation/StroikaPreComp.h"
#include "Stroika/Foundation/Debug/Trace.h"
#include "Stroika/Foundation/Execution/ProcessRunner.h"
#if qPlatform_POSIX
#include "Stroika/Foundation/Execution/SignalHandlers.h"
#endif
#include "Stroika/Foundation/Execution/Sleep.h"
#include "Stroika/Foundation/Streams/MemoryStream.h"
#include "Stroika/Foundation/Streams/SharedMemoryStream.h"
#include "../TestHarness/TestHarness.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Execution;
using Characters::String;
namespace {
void RegressionTest1_ ()
{
Debug::TraceContextBumper ctx{L"RegressionTest1_"};
Streams::MemoryStream<Byte>::Ptr myStdOut = Streams::MemoryStream<Byte>::New ();
// quickie about to test..
ProcessRunner pr (L"echo hi mom", nullptr, myStdOut);
pr.Run ();
}
void RegressionTest2_ ()
{
Debug::TraceContextBumper ctx{L"RegressionTest2_"};
Streams::MemoryStream<Byte>::Ptr myStdOut = Streams::MemoryStream<Byte>::New ();
// quickie about to test..
ProcessRunner pr (L"echo hi mom");
String out = pr.Run (L"");
VerifyTestResult (out.Trim () == L"hi mom");
}
void RegressionTest3_Pipe_ ()
{
Debug::TraceContextBumper ctx{L"RegressionTest3_Pipe_"};
Streams::MemoryStream<Byte>::Ptr myStdOut = Streams::MemoryStream<Byte>::New ();
ProcessRunner pr1 (L"echo hi mom");
Streams::MemoryStream<Byte>::Ptr pipe = Streams::MemoryStream<Byte>::New ();
ProcessRunner pr2 (L"cat");
pr1.SetStdOut (pipe);
pr2.SetStdIn (pipe);
Streams::MemoryStream<Byte>::Ptr pr2Out = Streams::MemoryStream<Byte>::New ();
pr2.SetStdOut (pr2Out);
pr1.Run ();
pr2.Run ();
String out = String::FromUTF8 (pr2Out.As<string> ());
VerifyTestResult (out.Trim () == L"hi mom");
}
void RegressionTest4_DocSample_ ()
{
Debug::TraceContextBumper ctx{L"RegressionTest4_DocSample_"};
// cat doesn't exist on windows (without cygwin or some such) - but the regression test code depends on that anyhow
// so this should be OK for now... -- LGP 2017-06-31
Memory::BLOB kData_{Memory::BLOB::Raw ("this is a test")};
Streams::MemoryStream<Byte>::Ptr processStdIn = Streams::MemoryStream<Byte>::New (kData_);
Streams::MemoryStream<Byte>::Ptr processStdOut = Streams::MemoryStream<Byte>::New ();
ProcessRunner pr (L"cat", processStdIn, processStdOut);
pr.Run ();
VerifyTestResult (processStdOut.ReadAll () == kData_);
}
}
namespace {
namespace LargeDataSentThroughPipe_Test5_ {
namespace Private_ {
const Memory::BLOB k1K_ = Memory::BLOB::Raw ("0123456789abcdef").Repeat (1024 / 16);
const Memory::BLOB k1MB_ = k1K_.Repeat (1024);
const Memory::BLOB k16MB_ = k1MB_.Repeat (16);
void SingleProcessLargeDataSend_ ()
{
/*
* "Valgrind's memory management: out of memory:"
* This only happens with DEBUG builds and valgrind/helgrind. So run with less memory used, and it works better.
*/
Memory::BLOB testBLOB = (Debug::IsRunningUnderValgrind () && qDebug) ? k1K_ : k16MB_;
Streams::MemoryStream<Byte>::Ptr myStdIn = Streams::MemoryStream<Byte>::New (testBLOB);
Streams::MemoryStream<Byte>::Ptr myStdOut = Streams::MemoryStream<Byte>::New ();
ProcessRunner pr (L"cat", myStdIn, myStdOut);
pr.Run ();
VerifyTestResult (myStdOut.ReadAll () == testBLOB);
}
}
void DoTests ()
{
Debug::TraceContextBumper ctx{L"LargeDataSentThroughPipe_Test5_::DoTests"};
Private_::SingleProcessLargeDataSend_ ();
}
}
}
namespace {
namespace LargeDataSentThroughPipeBackground_Test6_ {
namespace Private_ {
const Memory::BLOB k1K_ = Memory::BLOB::Raw ("0123456789abcdef").Repeat (1024 / 16);
const Memory::BLOB k1MB_ = k1K_.Repeat (1024);
const Memory::BLOB k16MB_ = k1MB_.Repeat (16);
void SingleProcessLargeDataSend_ ()
{
Assert (k1MB_.size () == 1024 * 1024);
Streams::SharedMemoryStream<Byte>::Ptr myStdIn = Streams::SharedMemoryStream<Byte>::New (); // note must use SharedMemoryStream cuz we want to distinguish EOF from no data written yet
Streams::SharedMemoryStream<Byte>::Ptr myStdOut = Streams::SharedMemoryStream<Byte>::New ();
ProcessRunner pr (L"cat", myStdIn, myStdOut);
ProcessRunner::BackgroundProcess bg = pr.RunInBackground ();
Execution::Sleep (1);
VerifyTestResult (myStdOut.ReadNonBlocking ().IsMissing ()); // sb no data available, but NOT EOF
/*
* "Valgrind's memory management: out of memory:"
* This only happens with DEBUG builds and valgrind/helgrind. So run with less memory used, and it works better.
*/
Memory::BLOB testBLOB = (Debug::IsRunningUnderValgrind () && qDebug) ? k1K_ : k16MB_;
myStdIn.Write (testBLOB);
myStdIn.CloseWrite (); // so cat process can finish
bg.WaitForDone ();
myStdOut.CloseWrite (); // one process done, no more writes to this stream
VerifyTestResult (myStdOut.ReadAll () == testBLOB);
}
}
void DoTests ()
{
Debug::TraceContextBumper ctx{L"LargeDataSentThroughPipeBackground_Test6_::DoTests"};
Private_::SingleProcessLargeDataSend_ ();
}
}
}
void RegressionTes7_FaledRun_ ()
{
Debug::TraceContextBumper ctx{L"RegressionTes7_FaledRun_"};
try {
ProcessRunner pr (L"mount /fasdkfjasdfjasdkfjasdklfjasldkfjasdfkj /dadsf/a/sdf/asdf//");
pr.Run ();
VerifyTestResult (false);
}
catch (...) {
DbgTrace (L"got failure msg: %s", Characters::ToString (current_exception ()).c_str ());
}
}
namespace {
void DoRegressionTests_ ()
{
Debug::TraceContextBumper ctx{L"DoRegressionTests_"};
#if qPlatform_POSIX
// Many performance instruments use pipes
// @todo - REVIEW IF REALLY NEEDED AND WHY? SO LONG AS NO FAIL SHOULDNT BE?
// --LGP 2014-02-05
Execution::SignalHandlerRegistry::Get ().SetSignalHandlers (SIGPIPE, Execution::SignalHandlerRegistry::kIGNORED);
#endif
RegressionTest1_ ();
RegressionTest2_ ();
RegressionTest3_Pipe_ ();
RegressionTest4_DocSample_ ();
LargeDataSentThroughPipe_Test5_::DoTests ();
LargeDataSentThroughPipeBackground_Test6_::DoTests ();
RegressionTes7_FaledRun_ ();
}
}
int main (int argc, const char* argv[])
{
Stroika::TestHarness::Setup ();
return Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_);
}
<|endoftext|> |
<commit_before>/*********************************************************************************
- Contact: Brigitte Cheynis [email protected]
- Link: http
- Raw data test file :
- Reference run number :
- Run Type: PHYSICS
- DA Type: MON
- Number of events needed: >=500
- Input Files: argument list
- Output Files: local files VZERO_Histos.root, V0_Pedestals.dat (Online mapping)
FXS file V0_Ped_Width_Gain.dat (Offline mapping)
- Trigger types used: PHYSICS_EVENT
**********************************************************************************/
/**********************************************************************************
* *
* VZERO Detector Algorithm used for extracting calibration parameters *
* *
* This program connects to the DAQ data source passed as argument. *
* It computes calibration parameters, populates local "./V0_Ped_Width_Gain.dat" *
* file, exports it to the FES, and stores it into DAQ DB *
* The program exits when being asked to shut down (daqDA_checkshutdown) *
* or on End of Run event. *
* We have 128 channels instead of 64 as expected for V0 due to the two sets of *
* charge integrators which are used by the FEE ... *
* *
***********************************************************************************/
// DATE
#include "event.h"
#include "monitor.h"
#include "daqDA.h"
//AliRoot
#include <AliVZERORawStream.h>
#include <AliRawReaderDate.h>
#include <AliRawReader.h>
#include <AliDAQ.h>
// standard
#include <stdio.h>
#include <stdlib.h>
//ROOT
#include "TROOT.h"
#include "TPluginManager.h"
#include <TFile.h>
#include <TH1F.h>
#include <TMath.h>
Int_t GetOfflineChannel(Int_t channel);
/* Main routine --- Arguments: monitoring data source */
int main(int argc, char **argv) {
/* magic line from Cvetan */
gROOT->GetPluginManager()->AddHandler("TVirtualStreamerInfo",
"*",
"TStreamerInfo",
"RIO",
"TStreamerInfo()");
int status;
if (argc!=2) {
printf("Wrong number of arguments\n");
return -1;
}
// Online values (using FEE channel numbering),
// stored into local V0_Pedestals.dat:
Double_t ADCmean[128];
Double_t ADCsigma[128];
Double_t PEDmean[128];
Double_t PEDsigma[128];
// Offline values(same but ordered as in aliroot for offliners)
// stored into V0_Ped_Width_Gain.dat:
Double_t ADCmean_Off[128];
Double_t ADCsigma_Off[128];
Double_t PEDmean_Off[128];
Double_t PEDsigma_Off[128];
//___________________________________________________
// Get cuts from V00DA.config file
Int_t kClockMin; // = 16; LHC Clock Min for pedestal calculation
Int_t kClockMax; // = 19; LHC Clock Max for pedestal calculation
Int_t kLowCut; // = 60; low cut on signal distribution - to be tuned
Int_t kHighCut; // = 50; high cut on pedestal distribution - to be tuned
status = daqDA_DB_getFile("V00DA.config","./V00DA.config");
if (status) {
printf("Failed to get Config file (V00DA.config) from DAQ DB, status=%d\n", status);
printf("Take default values of parameters for pedestal calculation \n");
kClockMin = 16;
kClockMax = 19;
kLowCut = 60;
kHighCut = 50;
} else {
/* open the config file and retrieve cuts */
FILE *fpConfig = fopen("V00DA.config","r");
int res = fscanf(fpConfig,"%d %d %d %d ",&kClockMin,&kClockMax,&kLowCut,&kHighCut);
if(res!=4) {
printf("Failed to get values from Config file (V00DA.config): wrong file format - 4 integers are expected - \n");
kClockMin = 16;
kClockMax = 19;
kLowCut = 60;
kHighCut = 50;
}
fclose(fpConfig);
}
printf("LHC Clock Min for pedestal calculation = %d; LHC Clock Max for pedestal calculation = %d; LowCut on signal = %d ; HighCut on pedestal = %d\n",
kClockMin, kClockMax, kLowCut, kHighCut);
//___________________________________________________
// Book HISTOGRAMS - dynamics of p-p collisions -
char ADCname[6];
char PEDname[6];
TH1F *hADCname[128];
TH1F *hPEDname[128];
char texte[12];
for (Int_t i=0; i<128; i++) {
sprintf(ADCname,"hADC%d",i);
sprintf(texte,"ADC cell%d",i);
hADCname[i] = new TH1F(ADCname,texte,1024,-0.5, 1023.5);
sprintf(PEDname,"hPED%d",i);
sprintf(texte,"PED cell%d",i);
hPEDname[i] = new TH1F(PEDname,texte,1024,-0.5, 1023.5);
}
//___________________________________________________
/* open result file to be exported to FES */
FILE *fpLocal=NULL;
fpLocal=fopen("./V0_Pedestals.dat","w");
if (fpLocal==NULL) {
printf("Failed to open local result file\n");
return -1;}
/* open result file to be exported to FES */
FILE *fp=NULL;
fp=fopen("./V0_Ped_Width_Gain.dat","w");
if (fp==NULL) {
printf("Failed to open result file\n");
return -1;}
/* define data source : this is argument 1 */
status=monitorSetDataSource( argv[1] );
if (status!=0) {
printf("monitorSetDataSource() failed : %s\n",monitorDecodeError(status));
return -1;
}
/* declare monitoring program */
status=monitorDeclareMp( __FILE__ );
if (status!=0) {
printf("monitorDeclareMp() failed : %s\n",monitorDecodeError(status));
return -1;
}
/* define wait event timeout - 1s max */
monitorSetNowait();
monitorSetNoWaitNetworkTimeout(1000);
/* init counters on events */
int nevents_physics=0;
int nevents_total=0;
/* loop on events (infinite) */
for(;;) {
struct eventHeaderStruct *event;
eventTypeType eventT;
/* check shutdown condition */
if (daqDA_checkShutdown()) {break;}
/* get next event (blocking call until timeout) */
status=monitorGetEventDynamic((void **)&event);
if (status==MON_ERR_EOF) {
printf ("End of File detected\n");
break; /* end of monitoring file has been reached */
}
if (status!=0) {
printf("monitorGetEventDynamic() failed : %s\n",monitorDecodeError(status));
break;
}
/* retry if got no event */
if (event==NULL) continue;
/* decode event */
eventT=event->eventType;
switch (event->eventType){
case START_OF_RUN:
break;
case END_OF_RUN:
printf("End Of Run detected\n");
break;
case PHYSICS_EVENT:
nevents_physics++;
AliRawReader *rawReader = new AliRawReaderDate((void*)event);
AliVZERORawStream* rawStream = new AliVZERORawStream(rawReader);
rawStream->Next();
for(Int_t i=0; i<64; i++) {
Int_t nFlag = 0;
for(Int_t j=kClockMin; j <= kClockMax; j++) { // Check flags on clock range used for pedestal calculation
if((rawStream->GetBBFlag(i,j)) || (rawStream->GetBGFlag(i,j))) nFlag++;
}
if(nFlag == 0){ // Fill 64*2 pedestal histograms - 2 integrators -
for(Int_t j=kClockMin;j <= kClockMax;j++){
Int_t Integrator = rawStream->GetIntegratorFlag(i,j);
Float_t pedestal = (float)(rawStream->GetPedestal(i,j));
hPEDname[i + 64 * Integrator]->Fill(pedestal);
}
}
if((rawStream->GetBBFlag(i,10)) || (rawStream->GetBGFlag(i,10))){ // Charge
Int_t Integrator = rawStream->GetIntegratorFlag(i,10);
Float_t charge = (float)(rawStream->GetADC(i)); // Fill 64*2 ADCmax histograms
hADCname[i + 64 * Integrator]->Fill(charge);
}
}
delete rawStream;
rawStream = 0x0;
delete rawReader;
rawReader = 0x0;
} // end of switch on event type
nevents_total++;
/* free resources */
free(event);
/* exit when last event received, no need to wait for TERM signal */
if (eventT==END_OF_RUN) {
printf("End Of Run event detected\n");
break;
}
} // loop over events
printf("%d physics events processed\n",nevents_physics);
//___________________________________________________________________________
// Computes mean values, converts FEE channels into Offline AliRoot channels
// and dumps the ordered values into the output text file for SHUTTLE
for(Int_t i=0; i<128; i++) {
hPEDname[i]->GetXaxis()->SetRange(0,kHighCut);
PEDmean[i] = hPEDname[i]->GetMean();
PEDsigma[i] = hPEDname[i]->GetRMS();
hADCname[i]->GetXaxis()->SetRange(kLowCut,1024);
ADCmean[i] = hADCname[i]->GetMean();
ADCsigma[i] = hADCname[i]->GetRMS();
// printf(" i = %d, %.3f %.3f %.3f %.3f\n",i,PEDmean[i],PEDsigma[i],ADCmean[i],ADCsigma[i]);
fprintf(fpLocal," %.3f %.3f %.3f %.3f\n",PEDmean[i],PEDsigma[i],
ADCmean[i],ADCsigma[i]);
if (i < 64) {
Int_t j = GetOfflineChannel(i);
PEDmean_Off[j] = PEDmean[i];
PEDsigma_Off[j] = PEDsigma[i];
ADCmean_Off[j] = ADCmean[i];
ADCsigma_Off[j] = ADCsigma[i]; }
else{
Int_t j = GetOfflineChannel(i-64);
PEDmean_Off[j+64] = PEDmean[i];
PEDsigma_Off[j+64] = PEDsigma[i];
ADCmean_Off[j+64] = ADCmean[i];
ADCsigma_Off[j+64] = ADCsigma[i];
}
}
for(Int_t j=0; j<128; j++) {
// printf(" j = %d, %.3f %.3f %.3f %.3f\n",j,PEDmean_Off[j],PEDsigma_Off[j],
// ADCmean_Off[j],ADCsigma_Off[j]);
fprintf(fp," %.3f %.3f %.3f %.3f\n",PEDmean_Off[j],PEDsigma_Off[j],
ADCmean_Off[j],ADCsigma_Off[j]);
}
//________________________________________________________________________
// Write root file with histos for users further check - just in case -
TFile *histoFile = new TFile("VZERO_histos.root","RECREATE");
for (Int_t i=0; i<128; i++) {
hADCname[i]->GetXaxis()->SetRange(0,1024);
hADCname[i]->Write();
hPEDname[i]->Write(); }
histoFile->Close();
delete histoFile;
//________________________________________________________________________
/* close local result file and FXS result file*/
fclose(fpLocal);
fclose(fp);
/* export result file to FES */
status=daqDA_FES_storeFile("./V0_Ped_Width_Gain.dat","V00da_results");
if (status) {
printf("Failed to export file : %d\n",status);
return -1; }
/* store result file into Online DB */
status=daqDA_DB_storeFile("./V0_Pedestals.dat","V00da_results");
if (status) {
printf("Failed to store file into Online DB: %d\n",status);
return -1; }
return status;
}
Int_t GetOfflineChannel(Int_t channel) {
// Channel mapping Online - Offline:
Int_t fOfflineChannel[64] = {39, 38, 37, 36, 35, 34, 33, 32,
47, 46, 45, 44, 43, 42, 41, 40,
55, 54, 53, 52, 51, 50, 49, 48,
63, 62, 61, 60, 59, 58, 57, 56,
7, 6, 5, 4, 3, 2, 1, 0,
15, 14, 13, 12, 11, 10, 9, 8,
23, 22, 21, 20, 19, 18, 17, 16,
31, 30, 29, 28, 27, 26, 25, 24};
return fOfflineChannel[channel];
}
<commit_msg>Protection added<commit_after>/*********************************************************************************
- Contact: Brigitte Cheynis [email protected]
- Link: http
- Raw data test file :
- Reference run number :
- Run Type: PHYSICS
- DA Type: MON
- Number of events needed: >=500
- Input Files: argument list
- Output Files: local files VZERO_Histos.root, V0_Pedestals.dat (Online mapping)
FXS file V0_Ped_Width_Gain.dat (Offline mapping)
- Trigger types used: PHYSICS_EVENT
**********************************************************************************/
/**********************************************************************************
* *
* VZERO Detector Algorithm used for extracting calibration parameters *
* *
* This program connects to the DAQ data source passed as argument. *
* It computes calibration parameters, populates local "./V0_Ped_Width_Gain.dat" *
* file, exports it to the FES, and stores it into DAQ DB *
* The program exits when being asked to shut down (daqDA_checkshutdown) *
* or on End of Run event. *
* We have 128 channels instead of 64 as expected for V0 due to the two sets of *
* charge integrators which are used by the FEE ... *
* *
***********************************************************************************/
// DATE
#include "event.h"
#include "monitor.h"
#include "daqDA.h"
//AliRoot
#include <AliVZERORawStream.h>
#include <AliRawReaderDate.h>
#include <AliRawReader.h>
#include <AliDAQ.h>
// standard
#include <stdio.h>
#include <stdlib.h>
//ROOT
#include "TROOT.h"
#include "TPluginManager.h"
#include <TFile.h>
#include <TH1F.h>
#include <TMath.h>
Int_t GetOfflineChannel(Int_t channel);
/* Main routine --- Arguments: monitoring data source */
int main(int argc, char **argv) {
/* magic line from Cvetan */
gROOT->GetPluginManager()->AddHandler("TVirtualStreamerInfo",
"*",
"TStreamerInfo",
"RIO",
"TStreamerInfo()");
int status;
if (argc!=2) {
printf("Wrong number of arguments\n");
return -1;
}
// Online values (using FEE channel numbering),
// stored into local V0_Pedestals.dat:
Double_t ADCmean[128];
Double_t ADCsigma[128];
Double_t PEDmean[128];
Double_t PEDsigma[128];
// Offline values(same but ordered as in aliroot for offliners)
// stored into V0_Ped_Width_Gain.dat:
Double_t ADCmean_Off[128];
Double_t ADCsigma_Off[128];
Double_t PEDmean_Off[128];
Double_t PEDsigma_Off[128];
//___________________________________________________
// Get cuts from V00DA.config file
Int_t kClockMin; // = 16; LHC Clock Min for pedestal calculation
Int_t kClockMax; // = 19; LHC Clock Max for pedestal calculation
Int_t kLowCut; // = 60; low cut on signal distribution - to be tuned
Int_t kHighCut; // = 50; high cut on pedestal distribution - to be tuned
status = daqDA_DB_getFile("V00DA.config","./V00DA.config");
if (status) {
printf("Failed to get Config file (V00DA.config) from DAQ DB, status=%d\n", status);
printf("Take default values of parameters for pedestal calculation \n");
kClockMin = 16;
kClockMax = 19;
kLowCut = 60;
kHighCut = 50;
} else {
/* open the config file and retrieve cuts */
FILE *fpConfig = fopen("V00DA.config","r");
int res = fscanf(fpConfig,"%d %d %d %d ",&kClockMin,&kClockMax,&kLowCut,&kHighCut);
if(res!=4) {
printf("Failed to get values from Config file (V00DA.config): wrong file format - 4 integers are expected - \n");
kClockMin = 16;
kClockMax = 19;
kLowCut = 60;
kHighCut = 50;
}
fclose(fpConfig);
}
printf("LHC Clock Min for pedestal calculation = %d; LHC Clock Max for pedestal calculation = %d; LowCut on signal = %d ; HighCut on pedestal = %d\n",
kClockMin, kClockMax, kLowCut, kHighCut);
//___________________________________________________
// Book HISTOGRAMS - dynamics of p-p collisions -
char ADCname[6];
char PEDname[6];
TH1F *hADCname[128];
TH1F *hPEDname[128];
char texte[12];
for (Int_t i=0; i<128; i++) {
sprintf(ADCname,"hADC%d",i);
sprintf(texte,"ADC cell%d",i);
hADCname[i] = new TH1F(ADCname,texte,1024,-0.5, 1023.5);
sprintf(PEDname,"hPED%d",i);
sprintf(texte,"PED cell%d",i);
hPEDname[i] = new TH1F(PEDname,texte,1024,-0.5, 1023.5);
}
//___________________________________________________
/* open result file to be exported to FES */
FILE *fpLocal=NULL;
fpLocal=fopen("./V0_Pedestals.dat","w");
if (fpLocal==NULL) {
printf("Failed to open local result file\n");
return -1;}
/* open result file to be exported to FES */
FILE *fp=NULL;
fp=fopen("./V0_Ped_Width_Gain.dat","w");
if (fp==NULL) {
printf("Failed to open result file\n");
return -1;}
/* define data source : this is argument 1 */
status=monitorSetDataSource( argv[1] );
if (status!=0) {
printf("monitorSetDataSource() failed : %s\n",monitorDecodeError(status));
return -1;
}
/* declare monitoring program */
status=monitorDeclareMp( __FILE__ );
if (status!=0) {
printf("monitorDeclareMp() failed : %s\n",monitorDecodeError(status));
return -1;
}
/* define wait event timeout - 1s max */
monitorSetNowait();
monitorSetNoWaitNetworkTimeout(1000);
/* init counters on events */
int nevents_physics=0;
int nevents_total=0;
/* loop on events (infinite) */
for(;;) {
struct eventHeaderStruct *event;
eventTypeType eventT;
/* check shutdown condition */
if (daqDA_checkShutdown()) {break;}
/* get next event (blocking call until timeout) */
status=monitorGetEventDynamic((void **)&event);
if (status==MON_ERR_EOF) {
printf ("End of File detected\n");
break; /* end of monitoring file has been reached */
}
if (status!=0) {
printf("monitorGetEventDynamic() failed : %s\n",monitorDecodeError(status));
break;
}
/* retry if got no event */
if (event==NULL) continue;
/* decode event */
eventT=event->eventType;
switch (event->eventType){
case START_OF_RUN:
break;
case END_OF_RUN:
printf("End Of Run detected\n");
break;
case PHYSICS_EVENT:
nevents_physics++;
AliRawReader *rawReader = new AliRawReaderDate((void*)event);
AliVZERORawStream* rawStream = new AliVZERORawStream(rawReader);
if (rawStream.Next()) {
for(Int_t i=0; i<64; i++) {
Int_t nFlag = 0;
for(Int_t j=kClockMin; j <= kClockMax; j++) { // Check flags on clock range used for pedestal calculation
if((rawStream->GetBBFlag(i,j)) || (rawStream->GetBGFlag(i,j))) nFlag++;
}
if(nFlag == 0){ // Fill 64*2 pedestal histograms - 2 integrators -
for(Int_t j=kClockMin;j <= kClockMax;j++){
Int_t Integrator = rawStream->GetIntegratorFlag(i,j);
Float_t pedestal = (float)(rawStream->GetPedestal(i,j));
hPEDname[i + 64 * Integrator]->Fill(pedestal);
}
}
if((rawStream->GetBBFlag(i,10)) || (rawStream->GetBGFlag(i,10))){ // Charge
Int_t Integrator = rawStream->GetIntegratorFlag(i,10);
Float_t charge = (float)(rawStream->GetADC(i)); // Fill 64*2 ADCmax histograms
hADCname[i + 64 * Integrator]->Fill(charge);
}
}
}
delete rawStream;
rawStream = 0x0;
delete rawReader;
rawReader = 0x0;
} // end of switch on event type
nevents_total++;
/* free resources */
free(event);
/* exit when last event received, no need to wait for TERM signal */
if (eventT==END_OF_RUN) {
printf("End Of Run event detected\n");
break;
}
} // loop over events
printf("%d physics events processed\n",nevents_physics);
//___________________________________________________________________________
// Computes mean values, converts FEE channels into Offline AliRoot channels
// and dumps the ordered values into the output text file for SHUTTLE
for(Int_t i=0; i<128; i++) {
hPEDname[i]->GetXaxis()->SetRange(0,kHighCut);
PEDmean[i] = hPEDname[i]->GetMean();
PEDsigma[i] = hPEDname[i]->GetRMS();
hADCname[i]->GetXaxis()->SetRange(kLowCut,1024);
ADCmean[i] = hADCname[i]->GetMean();
ADCsigma[i] = hADCname[i]->GetRMS();
// printf(" i = %d, %.3f %.3f %.3f %.3f\n",i,PEDmean[i],PEDsigma[i],ADCmean[i],ADCsigma[i]);
fprintf(fpLocal," %.3f %.3f %.3f %.3f\n",PEDmean[i],PEDsigma[i],
ADCmean[i],ADCsigma[i]);
if (i < 64) {
Int_t j = GetOfflineChannel(i);
PEDmean_Off[j] = PEDmean[i];
PEDsigma_Off[j] = PEDsigma[i];
ADCmean_Off[j] = ADCmean[i];
ADCsigma_Off[j] = ADCsigma[i]; }
else{
Int_t j = GetOfflineChannel(i-64);
PEDmean_Off[j+64] = PEDmean[i];
PEDsigma_Off[j+64] = PEDsigma[i];
ADCmean_Off[j+64] = ADCmean[i];
ADCsigma_Off[j+64] = ADCsigma[i];
}
}
for(Int_t j=0; j<128; j++) {
// printf(" j = %d, %.3f %.3f %.3f %.3f\n",j,PEDmean_Off[j],PEDsigma_Off[j],
// ADCmean_Off[j],ADCsigma_Off[j]);
fprintf(fp," %.3f %.3f %.3f %.3f\n",PEDmean_Off[j],PEDsigma_Off[j],
ADCmean_Off[j],ADCsigma_Off[j]);
}
//________________________________________________________________________
// Write root file with histos for users further check - just in case -
TFile *histoFile = new TFile("VZERO_histos.root","RECREATE");
for (Int_t i=0; i<128; i++) {
hADCname[i]->GetXaxis()->SetRange(0,1024);
hADCname[i]->Write();
hPEDname[i]->Write(); }
histoFile->Close();
delete histoFile;
//________________________________________________________________________
/* close local result file and FXS result file*/
fclose(fpLocal);
fclose(fp);
/* export result file to FES */
status=daqDA_FES_storeFile("./V0_Ped_Width_Gain.dat","V00da_results");
if (status) {
printf("Failed to export file : %d\n",status);
return -1; }
/* store result file into Online DB */
status=daqDA_DB_storeFile("./V0_Pedestals.dat","V00da_results");
if (status) {
printf("Failed to store file into Online DB: %d\n",status);
return -1; }
return status;
}
Int_t GetOfflineChannel(Int_t channel) {
// Channel mapping Online - Offline:
Int_t fOfflineChannel[64] = {39, 38, 37, 36, 35, 34, 33, 32,
47, 46, 45, 44, 43, 42, 41, 40,
55, 54, 53, 52, 51, 50, 49, 48,
63, 62, 61, 60, 59, 58, 57, 56,
7, 6, 5, 4, 3, 2, 1, 0,
15, 14, 13, 12, 11, 10, 9, 8,
23, 22, 21, 20, 19, 18, 17, 16,
31, 30, 29, 28, 27, 26, 25, 24};
return fOfflineChannel[channel];
}
<|endoftext|> |
<commit_before>#include "VersatileFile.h"
#include "HttpRequestHandler.h"
VersatileFile::VersatileFile(const QString& file_name)
: file_name_(file_name)
{
}
VersatileFile::~VersatileFile()
{
if (device_->isOpen()) device_->close();
}
bool VersatileFile::open(QIODevice::OpenMode mode)
{
if (!file_name_.toLower().startsWith("http"))
{
// local file
file_ = QSharedPointer<QFile>(new QFile(file_name_));
file_.data()->open(mode);
device_ = file_;
}
else
{
// remote file
try
{
reply_data_ = HttpRequestHandler(HttpRequestHandler::NONE).get(file_name_);
}
catch (Exception& e)
{
qWarning() << "Could not get file location:" << e.message();
}
buffer_ = QSharedPointer<QBuffer>(new QBuffer(&reply_data_));
buffer_.data()->open(mode);
if (!buffer_.data()->isOpen())
{
qDebug() << "Could not open remote file for reading:" << file_name_;
}
device_ = buffer_;
}
return device_.data()->isOpen();
}
bool VersatileFile::open(FILE* f, QIODevice::OpenMode ioFlags)
{
if (!file_name_.toLower().startsWith("http"))
{
file_ = QSharedPointer<QFile>(new QFile(file_name_));
file_.data()->open(f, ioFlags);
device_ = file_;
return device_.data()->isOpen();
}
return false;
}
QIODevice::OpenMode VersatileFile::openMode() const
{
return device_.data()->openMode();
}
bool VersatileFile::isOpen() const
{
return device_.data()->isOpen();
}
bool VersatileFile::isReadable() const
{
checkIfOpen();
return device_.data()->isReadable();
}
qint64 VersatileFile::read(char* data, qint64 maxlen)
{
checkIfOpen();
return device_->read(data, maxlen);
}
QByteArray VersatileFile::read(qint64 maxlen)
{
checkIfOpen();
return device_.data()->read(maxlen);
}
QByteArray VersatileFile::readAll()
{
checkIfOpen();
return device_.data()->readAll();
}
qint64 VersatileFile::readLine(char* data, qint64 maxlen)
{
checkIfOpen();
return device_.data()->readLine(data, maxlen);
}
QByteArray VersatileFile::readLine(qint64 maxlen)
{
checkIfOpen();
return device_.data()->readLine(maxlen);
}
bool VersatileFile::canReadLine() const
{
checkIfOpen();
return device_.data()->canReadLine();
}
bool VersatileFile::atEnd() const
{
checkIfOpen();
return device_.data()->atEnd();
}
bool VersatileFile::exists()
{
if (file_ != nullptr) return file_.data()->exists();
if (buffer_ != nullptr) return buffer_.data()->data() != nullptr;
return false;
}
void VersatileFile::close()
{
if (device_->isOpen()) device_.data()->close();
}
bool VersatileFile::reset()
{
checkIfOpen();
return device_.data()->reset();
}
bool VersatileFile::isSequential() const
{
checkIfOpen();
return device_.data()->isSequential();
}
qint64 VersatileFile::pos() const
{
checkIfOpen();
return device_.data()->pos();
}
bool VersatileFile::seek(qint64 offset)
{
checkIfOpen();
return device_.data()->seek(offset);
}
qint64 VersatileFile::size() const
{
checkIfOpen();
return device_.data()->size();
}
QTextStream& VersatileFile::createTextStream()
{
checkIfOpen();
text_stream.setDevice(device_.data());
return text_stream;
}
void VersatileFile::checkIfOpen() const
{
if (!device_->isOpen())
{
THROW(FileAccessException, "IODevice in VersatileFile is closed!");
}
}
<commit_msg>Added accessibility check for VersatileFile<commit_after>#include "VersatileFile.h"
#include "HttpRequestHandler.h"
VersatileFile::VersatileFile(const QString& file_name)
: file_name_(file_name)
{
}
VersatileFile::~VersatileFile()
{
if (device_->isOpen()) device_->close();
}
bool VersatileFile::open(QIODevice::OpenMode mode)
{
if (!file_name_.toLower().startsWith("http"))
{
// local file
file_ = QSharedPointer<QFile>(new QFile(file_name_));
file_.data()->open(mode);
device_ = file_;
}
else
{
// remote file
bool remote_file_accessed = false;
try
{
reply_data_ = HttpRequestHandler(HttpRequestHandler::NONE).get(file_name_);
remote_file_accessed = true;
}
catch (Exception& e)
{
qWarning() << "Could not get file location:" << e.message();
}
buffer_ = QSharedPointer<QBuffer>(new QBuffer(&reply_data_));
if (remote_file_accessed) buffer_.data()->open(mode);
device_ = buffer_;
}
return device_.data()->isOpen();
}
bool VersatileFile::open(FILE* f, QIODevice::OpenMode ioFlags)
{
if (!file_name_.toLower().startsWith("http"))
{
file_ = QSharedPointer<QFile>(new QFile(file_name_));
file_.data()->open(f, ioFlags);
device_ = file_;
return device_.data()->isOpen();
}
return false;
}
QIODevice::OpenMode VersatileFile::openMode() const
{
return device_.data()->openMode();
}
bool VersatileFile::isOpen() const
{
return device_.data()->isOpen();
}
bool VersatileFile::isReadable() const
{
checkIfOpen();
return device_.data()->isReadable();
}
qint64 VersatileFile::read(char* data, qint64 maxlen)
{
checkIfOpen();
return device_->read(data, maxlen);
}
QByteArray VersatileFile::read(qint64 maxlen)
{
checkIfOpen();
return device_.data()->read(maxlen);
}
QByteArray VersatileFile::readAll()
{
checkIfOpen();
return device_.data()->readAll();
}
qint64 VersatileFile::readLine(char* data, qint64 maxlen)
{
checkIfOpen();
return device_.data()->readLine(data, maxlen);
}
QByteArray VersatileFile::readLine(qint64 maxlen)
{
checkIfOpen();
return device_.data()->readLine(maxlen);
}
bool VersatileFile::canReadLine() const
{
checkIfOpen();
return device_.data()->canReadLine();
}
bool VersatileFile::atEnd() const
{
checkIfOpen();
return device_.data()->atEnd();
}
bool VersatileFile::exists()
{
if (file_ != nullptr) return file_.data()->exists();
if (buffer_ != nullptr) return buffer_.data()->data() != nullptr;
return false;
}
void VersatileFile::close()
{
if (device_->isOpen()) device_.data()->close();
}
bool VersatileFile::reset()
{
checkIfOpen();
return device_.data()->reset();
}
bool VersatileFile::isSequential() const
{
checkIfOpen();
return device_.data()->isSequential();
}
qint64 VersatileFile::pos() const
{
checkIfOpen();
return device_.data()->pos();
}
bool VersatileFile::seek(qint64 offset)
{
checkIfOpen();
return device_.data()->seek(offset);
}
qint64 VersatileFile::size() const
{
checkIfOpen();
return device_.data()->size();
}
QTextStream& VersatileFile::createTextStream()
{
checkIfOpen();
text_stream.setDevice(device_.data());
return text_stream;
}
void VersatileFile::checkIfOpen() const
{
if (!device_->isOpen())
{
THROW(FileAccessException, "IODevice in VersatileFile is closed!");
}
}
<|endoftext|> |
<commit_before>
#include "Math_basics.h"
namespace P_RVD
{
namespace Math
{
Vector3d computeCenter(const Vector3d p1, const Vector3d p2, const Vector3d p3)
{
return Vector3d((p1.x + p2.x + p3.x) / 3,
(p1.y + p2.y + p3.y) / 3,
(p1.z + p2.z + p3.z) / 3);
}
double computeDistance(const Vector3d p1, const Vector3d p2)
{
return (p1.x - p2.x) * (p1.x - p2.x)
+ (p1.y - p2.y) * (p1.y - p2.y)
+ (p1.z - p2.z) * (p1.z - p2.z);
}
double computeTriangleArea(const Vector3d p1, const Vector3d p2, const Vector3d p3)
{
double a = computeDistance(p1, p2);
double b = computeDistance(p2, p3);
double c = computeDistance(p1, p3);
//Heron's Formula to compute the area of the triangle
double p = (a + b + c) / 2;
double tmp = geo_max(a, b);
if (p > geo_max(tmp, c))
return sqrt(p * (p - a) * (p - b) * (p - c));
else
fprintf(stderr, "the three point cannot construct a triangle!");
return 0.0;
}
}
}<commit_msg>recover the mistake in computing the distance<commit_after>
#include "Math_basics.h"
namespace P_RVD
{
namespace Math
{
Vector3d computeCenter(const Vector3d p1, const Vector3d p2, const Vector3d p3)
{
return Vector3d((p1.x + p2.x + p3.x) / 3,
(p1.y + p2.y + p3.y) / 3,
(p1.z + p2.z + p3.z) / 3);
}
double computeDistance(const Vector3d p1, const Vector3d p2)
{
return sqrt((p1.x - p2.x) * (p1.x - p2.x)
+ (p1.y - p2.y) * (p1.y - p2.y)
+ (p1.z - p2.z) * (p1.z - p2.z));
}
double computeTriangleArea(const Vector3d p1, const Vector3d p2, const Vector3d p3)
{
double a = computeDistance(p1, p2);
double b = computeDistance(p2, p3);
double c = computeDistance(p1, p3);
//Heron's Formula to compute the area of the triangle
double p = (a + b + c) / 2;
if (p >= a && p >= b && p >= c)
return sqrt(p * (p - a) * (p - b) * (p - c));
else
fprintf(stderr, "the three point cannot construct a triangle!\n");
return 0.0;
}
}
}<|endoftext|> |
<commit_before>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2010 Interactive Visualization and Data Analysis Group.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
//! File : RenderMeshGL.cpp
//! Author : Jens Krueger
//! IVCI & DFKI & MMCI, Saarbruecken
//! SCI Institute, University of Utah
//! Date : July 2010
//
//! Copyright (C) 2010 DFKI, MMCI, SCI Institute
#include <cassert>
#include <stdexcept>
#include "RenderMeshGL.h"
#include "KDTree.h"
using namespace tuvok;
RenderMeshGL::RenderMeshGL(const Mesh& other) :
RenderMesh(other),
m_bGLInitialized(false)
{
UnrollArrays();
}
RenderMeshGL::RenderMeshGL(const VertVec& vertices, const NormVec& normals,
const TexCoordVec& texcoords, const ColorVec& colors,
const IndexVec& vIndices, const IndexVec& nIndices,
const IndexVec& tIndices, const IndexVec& cIndices,
bool bBuildKDTree, bool bScaleToUnitCube,
const std::string& desc, EMeshType meshType) :
RenderMesh(vertices,normals,texcoords,colors,
vIndices,nIndices,tIndices,cIndices,
bBuildKDTree, bScaleToUnitCube, desc, meshType),
m_bGLInitialized(false)
{
UnrollArrays();
}
RenderMeshGL::~RenderMeshGL() {
if (m_bGLInitialized) {
glDeleteBuffers(DATA_VBO_COUNT, m_VBOs);
glDeleteBuffers(1, &m_IndexVBOOpaque);
glDeleteBuffers(1, &m_IndexVBOFront);
glDeleteBuffers(1, &m_IndexVBOBehind);
glDeleteBuffers(1, &m_IndexVBOInside);
}
}
void RenderMeshGL::PrepareOpaqueBuffers() {
if (m_VertIndices.empty()) return;
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_IndexVBOOpaque);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, m_splitIndex*sizeof(UINT32), &m_VertIndices[0], GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, m_VBOs[POSITION_VBO]);
glBufferData(GL_ARRAY_BUFFER, m_vertices.size()*sizeof(float)*3, &m_vertices[0], GL_STATIC_DRAW);
if (m_NormalIndices.size() == m_VertIndices.size()) {
glBindBuffer(GL_ARRAY_BUFFER, m_VBOs[NORMAL_VBO]);
glBufferData(GL_ARRAY_BUFFER, m_normals.size()*sizeof(float)*3, &m_normals[0], GL_STATIC_DRAW);
}
if (m_TCIndices.size() == m_VertIndices.size()) {
glBindBuffer(GL_ARRAY_BUFFER, m_VBOs[TEXCOORD_VBO]);
glBufferData(GL_ARRAY_BUFFER, m_texcoords.size()*sizeof(float)*2, &m_texcoords[0], GL_STATIC_DRAW);
}
if (m_COLIndices.size() == m_VertIndices.size()) {
glBindBuffer(GL_ARRAY_BUFFER, m_VBOs[COLOR_VBO]);
glBufferData(GL_ARRAY_BUFFER, m_colors.size()*sizeof(float)*4, &m_colors[0], GL_STATIC_DRAW);
}
}
void RenderMeshGL::RenderGeometry(GLuint IndexVBO, size_t count) {
if (!m_bGLInitialized || count == 0) return;
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IndexVBO);
glBindBuffer(GL_ARRAY_BUFFER, m_VBOs[POSITION_VBO]);
glVertexPointer(3, GL_FLOAT, 0, 0);
glEnableClientState(GL_VERTEX_ARRAY);
if (m_NormalIndices.size() == m_VertIndices.size()) {
glBindBuffer(GL_ARRAY_BUFFER, m_VBOs[NORMAL_VBO]);
glNormalPointer(GL_FLOAT, 0, 0);
glEnableClientState(GL_NORMAL_ARRAY);
} else {
glNormal3f(2,2,2); // tells the shader to disable lighting
}
if (m_TCIndices.size() == m_VertIndices.size()) {
glBindBuffer(GL_ARRAY_BUFFER, m_VBOs[TEXCOORD_VBO]);
glTexCoordPointer(2, GL_FLOAT, 0, 0);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
} else {
glTexCoord2f(0,0);
}
if (m_COLIndices.size() == m_VertIndices.size()) {
glBindBuffer(GL_ARRAY_BUFFER, m_VBOs[COLOR_VBO]);
glColorPointer(4, GL_FLOAT, 0, 0);
glEnableClientState(GL_COLOR_ARRAY);
} else {
glColor4f(m_DefColor.x, m_DefColor.y, m_DefColor.z, m_DefColor.w);
}
switch (m_meshType) {
case MT_LINES :
glDrawElements(GL_LINES, GLsizei(count), GL_UNSIGNED_INT, 0);
break;
case MT_TRIANGLES:
glDrawElements(GL_TRIANGLES, GLsizei(count), GL_UNSIGNED_INT, 0);
break;
default :
throw std::runtime_error("rendering unsupported mesh type");
}
glDisableClientState(GL_VERTEX_ARRAY);
if (m_NormalIndices.size() == m_VertIndices.size())
glDisableClientState(GL_NORMAL_ARRAY);
if (m_TCIndices.size() == m_VertIndices.size())
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
if (m_COLIndices.size() == m_VertIndices.size())
glDisableClientState(GL_COLOR_ARRAY);
}
void RenderMeshGL::RenderOpaqueGeometry() {
RenderGeometry(m_IndexVBOOpaque, m_splitIndex);
}
void RenderMeshGL::RenderTransGeometryFront() {
PrepareTransBuffers(m_IndexVBOFront, GetFrontPointList());
RenderGeometry(m_IndexVBOFront, m_FrontPointList.size()*m_VerticesPerPoly);
}
void RenderMeshGL::RenderTransGeometryBehind() {
PrepareTransBuffers(m_IndexVBOBehind, GetBehindPointList());
RenderGeometry(m_IndexVBOBehind, m_BehindPointList.size()*m_VerticesPerPoly);
}
void RenderMeshGL::RenderTransGeometryInside() {
PrepareTransBuffers(m_IndexVBOInside, GetSortedInPointList());
RenderGeometry(m_IndexVBOInside, m_InPointList.size()*m_VerticesPerPoly);
}
void RenderMeshGL::InitRenderer() {
m_bGLInitialized = true;
glGenBuffers(DATA_VBO_COUNT, m_VBOs);
glGenBuffers(1, &m_IndexVBOOpaque);
glGenBuffers(1, &m_IndexVBOFront);
glGenBuffers(1, &m_IndexVBOBehind);
glGenBuffers(1, &m_IndexVBOInside);
PrepareOpaqueBuffers();
}
void RenderMeshGL::GeometryHasChanged(bool bUpdateAABB, bool bUpdateKDtree) {
RenderMesh::GeometryHasChanged(bUpdateAABB, bUpdateKDtree);
if (m_bGLInitialized) PrepareOpaqueBuffers();
}
void RenderMeshGL::PrepareTransBuffers(GLuint IndexVBO, const SortIndexPVec& list) {
if (list.empty()) return;
IndexVec VertIndices;
VertIndices.reserve(list.size());
for (SortIndexPVec::const_iterator index = list.begin();
index != list.end();
index++) {
size_t iIndex = (*index)->m_index;
for (size_t i = 0;i<m_VerticesPerPoly;i++)
VertIndices.push_back(m_VertIndices[iIndex+i]);
}
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IndexVBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, VertIndices.size()*sizeof(UINT32), &VertIndices[0], GL_STREAM_DRAW);
}
// since OpenGL is a "piece-of-shit" API that does only support
// a single index array and not multiple arrays per component
// e.g. one for position, color, etc. So we have to maintain
// separate color, normal, vertex and texcoord buffers, if the indices
// differ
void RenderMeshGL::UnrollArrays() {
bool bSeparateArraysNecessary =
(m_NormalIndices.size() == m_VertIndices.size() && m_NormalIndices != m_VertIndices) ||
(m_COLIndices.size() == m_VertIndices.size() && m_COLIndices != m_VertIndices) ||
(m_TCIndices.size() == m_VertIndices.size() && m_TCIndices != m_VertIndices);
if (!bSeparateArraysNecessary) return;
VertVec vertices(m_VertIndices.size());
NormVec normals;
if (m_NormalIndices.size() == m_VertIndices.size())
normals.resize(m_VertIndices.size());
ColorVec colors;
if (m_COLIndices.size() == m_VertIndices.size())
colors.resize(m_VertIndices.size());
TexCoordVec texcoords;
if (m_TCIndices.size() == m_VertIndices.size())
texcoords.resize(m_VertIndices.size());
for (size_t i = 0;i<m_VertIndices.size();i++) {
vertices[i] = m_vertices[m_VertIndices[i]];
if (m_NormalIndices.size() == m_VertIndices.size())
normals[i] = m_normals[m_NormalIndices[i]];
if (m_COLIndices.size() == m_VertIndices.size())
colors[i] = m_colors[m_COLIndices[i]];
if (m_TCIndices.size() == m_VertIndices.size())
texcoords[i] = m_texcoords[m_TCIndices[i]];
}
m_vertices = vertices;
m_normals = normals;
m_texcoords = texcoords;
m_colors = colors;
// effectively disable indices
for (size_t i = 0;i<m_VertIndices.size();i++) m_VertIndices[i] = i;
// equalize index arrays
if (m_NormalIndices.size() == m_VertIndices.size()) m_NormalIndices = m_VertIndices;
if (m_COLIndices.size() == m_VertIndices.size()) m_COLIndices = m_VertIndices;
if (m_TCIndices.size() == m_VertIndices.size()) m_TCIndices = m_VertIndices;
GeometryHasChanged(false,false);
}
<commit_msg>fixed a size_t to unsigned int conversion warning on 64 bit windows<commit_after>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2010 Interactive Visualization and Data Analysis Group.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
//! File : RenderMeshGL.cpp
//! Author : Jens Krueger
//! IVCI & DFKI & MMCI, Saarbruecken
//! SCI Institute, University of Utah
//! Date : July 2010
//
//! Copyright (C) 2010 DFKI, MMCI, SCI Institute
#include <cassert>
#include <stdexcept>
#include "RenderMeshGL.h"
#include "KDTree.h"
using namespace tuvok;
RenderMeshGL::RenderMeshGL(const Mesh& other) :
RenderMesh(other),
m_bGLInitialized(false)
{
UnrollArrays();
}
RenderMeshGL::RenderMeshGL(const VertVec& vertices, const NormVec& normals,
const TexCoordVec& texcoords, const ColorVec& colors,
const IndexVec& vIndices, const IndexVec& nIndices,
const IndexVec& tIndices, const IndexVec& cIndices,
bool bBuildKDTree, bool bScaleToUnitCube,
const std::string& desc, EMeshType meshType) :
RenderMesh(vertices,normals,texcoords,colors,
vIndices,nIndices,tIndices,cIndices,
bBuildKDTree, bScaleToUnitCube, desc, meshType),
m_bGLInitialized(false)
{
UnrollArrays();
}
RenderMeshGL::~RenderMeshGL() {
if (m_bGLInitialized) {
glDeleteBuffers(DATA_VBO_COUNT, m_VBOs);
glDeleteBuffers(1, &m_IndexVBOOpaque);
glDeleteBuffers(1, &m_IndexVBOFront);
glDeleteBuffers(1, &m_IndexVBOBehind);
glDeleteBuffers(1, &m_IndexVBOInside);
}
}
void RenderMeshGL::PrepareOpaqueBuffers() {
if (m_VertIndices.empty()) return;
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_IndexVBOOpaque);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, m_splitIndex*sizeof(UINT32), &m_VertIndices[0], GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, m_VBOs[POSITION_VBO]);
glBufferData(GL_ARRAY_BUFFER, m_vertices.size()*sizeof(float)*3, &m_vertices[0], GL_STATIC_DRAW);
if (m_NormalIndices.size() == m_VertIndices.size()) {
glBindBuffer(GL_ARRAY_BUFFER, m_VBOs[NORMAL_VBO]);
glBufferData(GL_ARRAY_BUFFER, m_normals.size()*sizeof(float)*3, &m_normals[0], GL_STATIC_DRAW);
}
if (m_TCIndices.size() == m_VertIndices.size()) {
glBindBuffer(GL_ARRAY_BUFFER, m_VBOs[TEXCOORD_VBO]);
glBufferData(GL_ARRAY_BUFFER, m_texcoords.size()*sizeof(float)*2, &m_texcoords[0], GL_STATIC_DRAW);
}
if (m_COLIndices.size() == m_VertIndices.size()) {
glBindBuffer(GL_ARRAY_BUFFER, m_VBOs[COLOR_VBO]);
glBufferData(GL_ARRAY_BUFFER, m_colors.size()*sizeof(float)*4, &m_colors[0], GL_STATIC_DRAW);
}
}
void RenderMeshGL::RenderGeometry(GLuint IndexVBO, size_t count) {
if (!m_bGLInitialized || count == 0) return;
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IndexVBO);
glBindBuffer(GL_ARRAY_BUFFER, m_VBOs[POSITION_VBO]);
glVertexPointer(3, GL_FLOAT, 0, 0);
glEnableClientState(GL_VERTEX_ARRAY);
if (m_NormalIndices.size() == m_VertIndices.size()) {
glBindBuffer(GL_ARRAY_BUFFER, m_VBOs[NORMAL_VBO]);
glNormalPointer(GL_FLOAT, 0, 0);
glEnableClientState(GL_NORMAL_ARRAY);
} else {
glNormal3f(2,2,2); // tells the shader to disable lighting
}
if (m_TCIndices.size() == m_VertIndices.size()) {
glBindBuffer(GL_ARRAY_BUFFER, m_VBOs[TEXCOORD_VBO]);
glTexCoordPointer(2, GL_FLOAT, 0, 0);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
} else {
glTexCoord2f(0,0);
}
if (m_COLIndices.size() == m_VertIndices.size()) {
glBindBuffer(GL_ARRAY_BUFFER, m_VBOs[COLOR_VBO]);
glColorPointer(4, GL_FLOAT, 0, 0);
glEnableClientState(GL_COLOR_ARRAY);
} else {
glColor4f(m_DefColor.x, m_DefColor.y, m_DefColor.z, m_DefColor.w);
}
switch (m_meshType) {
case MT_LINES :
glDrawElements(GL_LINES, GLsizei(count), GL_UNSIGNED_INT, 0);
break;
case MT_TRIANGLES:
glDrawElements(GL_TRIANGLES, GLsizei(count), GL_UNSIGNED_INT, 0);
break;
default :
throw std::runtime_error("rendering unsupported mesh type");
}
glDisableClientState(GL_VERTEX_ARRAY);
if (m_NormalIndices.size() == m_VertIndices.size())
glDisableClientState(GL_NORMAL_ARRAY);
if (m_TCIndices.size() == m_VertIndices.size())
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
if (m_COLIndices.size() == m_VertIndices.size())
glDisableClientState(GL_COLOR_ARRAY);
}
void RenderMeshGL::RenderOpaqueGeometry() {
RenderGeometry(m_IndexVBOOpaque, m_splitIndex);
}
void RenderMeshGL::RenderTransGeometryFront() {
PrepareTransBuffers(m_IndexVBOFront, GetFrontPointList());
RenderGeometry(m_IndexVBOFront, m_FrontPointList.size()*m_VerticesPerPoly);
}
void RenderMeshGL::RenderTransGeometryBehind() {
PrepareTransBuffers(m_IndexVBOBehind, GetBehindPointList());
RenderGeometry(m_IndexVBOBehind, m_BehindPointList.size()*m_VerticesPerPoly);
}
void RenderMeshGL::RenderTransGeometryInside() {
PrepareTransBuffers(m_IndexVBOInside, GetSortedInPointList());
RenderGeometry(m_IndexVBOInside, m_InPointList.size()*m_VerticesPerPoly);
}
void RenderMeshGL::InitRenderer() {
m_bGLInitialized = true;
glGenBuffers(DATA_VBO_COUNT, m_VBOs);
glGenBuffers(1, &m_IndexVBOOpaque);
glGenBuffers(1, &m_IndexVBOFront);
glGenBuffers(1, &m_IndexVBOBehind);
glGenBuffers(1, &m_IndexVBOInside);
PrepareOpaqueBuffers();
}
void RenderMeshGL::GeometryHasChanged(bool bUpdateAABB, bool bUpdateKDtree) {
RenderMesh::GeometryHasChanged(bUpdateAABB, bUpdateKDtree);
if (m_bGLInitialized) PrepareOpaqueBuffers();
}
void RenderMeshGL::PrepareTransBuffers(GLuint IndexVBO, const SortIndexPVec& list) {
if (list.empty()) return;
IndexVec VertIndices;
VertIndices.reserve(list.size());
for (SortIndexPVec::const_iterator index = list.begin();
index != list.end();
index++) {
size_t iIndex = (*index)->m_index;
for (size_t i = 0;i<m_VerticesPerPoly;i++)
VertIndices.push_back(m_VertIndices[iIndex+i]);
}
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IndexVBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, VertIndices.size()*sizeof(UINT32), &VertIndices[0], GL_STREAM_DRAW);
}
// since OpenGL is a "piece-of-shit" API that does only support
// a single index array and not multiple arrays per component
// e.g. one for position, color, etc. So we have to maintain
// separate color, normal, vertex and texcoord buffers, if the indices
// differ
void RenderMeshGL::UnrollArrays() {
bool bSeparateArraysNecessary =
(m_NormalIndices.size() == m_VertIndices.size() && m_NormalIndices != m_VertIndices) ||
(m_COLIndices.size() == m_VertIndices.size() && m_COLIndices != m_VertIndices) ||
(m_TCIndices.size() == m_VertIndices.size() && m_TCIndices != m_VertIndices);
if (!bSeparateArraysNecessary) return;
VertVec vertices(m_VertIndices.size());
NormVec normals;
if (m_NormalIndices.size() == m_VertIndices.size())
normals.resize(m_VertIndices.size());
ColorVec colors;
if (m_COLIndices.size() == m_VertIndices.size())
colors.resize(m_VertIndices.size());
TexCoordVec texcoords;
if (m_TCIndices.size() == m_VertIndices.size())
texcoords.resize(m_VertIndices.size());
for (size_t i = 0;i<m_VertIndices.size();i++) {
vertices[i] = m_vertices[m_VertIndices[i]];
if (m_NormalIndices.size() == m_VertIndices.size())
normals[i] = m_normals[m_NormalIndices[i]];
if (m_COLIndices.size() == m_VertIndices.size())
colors[i] = m_colors[m_COLIndices[i]];
if (m_TCIndices.size() == m_VertIndices.size())
texcoords[i] = m_texcoords[m_TCIndices[i]];
}
m_vertices = vertices;
m_normals = normals;
m_texcoords = texcoords;
m_colors = colors;
// effectively disable indices
for (size_t i = 0;i<m_VertIndices.size();i++) m_VertIndices[i] = UINT32(i);
// equalize index arrays
if (m_NormalIndices.size() == m_VertIndices.size()) m_NormalIndices = m_VertIndices;
if (m_COLIndices.size() == m_VertIndices.size()) m_COLIndices = m_VertIndices;
if (m_TCIndices.size() == m_VertIndices.size()) m_TCIndices = m_VertIndices;
GeometryHasChanged(false,false);
}
<|endoftext|> |
<commit_before>// Copyright 2015-2016 Vagen Ayrapetyan
#include "Rade.h"
#include "RadeGameMode.h"
#include "System/SystemSaveGame.h"
#include "System/RadeGameState.h"
#include "System/RadePlayerState.h"
#include "Custom/LevelBlockConstructor.h"
ARadeGameMode::ARadeGameMode(const class FObjectInitializer& PCIP) : Super(PCIP)
{
// Overriden Player State Class
PlayerStateClass = ARadePlayerState::StaticClass();
// Overriden Game State Class
GameStateClass = ARadeGameState::StaticClass();
}
void ARadeGameMode::BeginPlay()
{
Super::BeginPlay();
// Start Post begin delay
FTimerHandle MyHandle;
GetWorldTimerManager().SetTimer(MyHandle, this, &ARadeGameMode::PostBeginPlay, 0.1f, false);
}
// Post begin Play
void ARadeGameMode::PostBeginPlay()
{
if (Role < ROLE_Authority)return;
// Loading Save file
USystemSaveGame* LoadGameInstance = Cast<USystemSaveGame>(UGameplayStatics::CreateSaveGameObject(USystemSaveGame::StaticClass()));
if (LoadGameInstance)
{
LoadGameInstance = Cast<USystemSaveGame>(UGameplayStatics::LoadGameFromSlot(LoadGameInstance->SaveSlotName, LoadGameInstance->UserIndex));
if (LoadGameInstance)
{
// The Save File Found
SaveFile = LoadGameInstance;
}
}
if (SaveFile)
{
// Load level block data that was saved
if (TheLevelBlockConstructor && TheLevelBlockConstructor->bLoadBlocks)
{
TheLevelBlockConstructor->CurrentBlocks = SaveFile->LevelBlocks;
TheLevelBlockConstructor->Server_UpdateBlocksStatus();
}
}
}
// End Game
void ARadeGameMode::EndPlay(const EEndPlayReason::Type EndPlayReason)
{
if (Role>=ROLE_Authority)
{
// No Save File, Creating new
if (!SaveFile)
{
USystemSaveGame* SaveFile = Cast<USystemSaveGame>(UGameplayStatics::CreateSaveGameObject(USystemSaveGame::StaticClass()));
UGameplayStatics::SaveGameToSlot(SaveFile, SaveFile->SaveSlotName, SaveFile->UserIndex);
}
if (SaveFile)
{
// Saving level block data
if (TheLevelBlockConstructor && TheLevelBlockConstructor->bSaveBlocks)
{
SaveFile->LevelBlocks = TheLevelBlockConstructor->CurrentBlocks;
}
// Saving Save File
UGameplayStatics::SaveGameToSlot(SaveFile, SaveFile->SaveSlotName, SaveFile->UserIndex);
}
}
Super::EndPlay(EndPlayReason);
}
<commit_msg>Rebuilt under 4.12.5 on Linux<commit_after>// Copyright 2015-2016 Vagen Ayrapetyan
#include "Rade.h"
#include "RadeGameMode.h"
#include "System/SystemSaveGame.h"
#include "System/RadeGameState.h"
#include "System/RadePlayerState.h"
#include "Custom/LevelBlockConstructor.h"
ARadeGameMode::ARadeGameMode(const class FObjectInitializer& PCIP) : Super(PCIP)
{
// Overriden Player State Class
PlayerStateClass = ARadePlayerState::StaticClass();
// Overriden Game State Class
GameStateClass = ARadeGameState::StaticClass();
}
void ARadeGameMode::BeginPlay()
{
Super::BeginPlay();
// Start Post begin delay
FTimerHandle MyHandle;
GetWorldTimerManager().SetTimer(MyHandle, this, &ARadeGameMode::PostBeginPlay, 0.1f, false);
}
// Post begin Play
void ARadeGameMode::PostBeginPlay()
{
if (Role < ROLE_Authority)return;
// Loading Save file
USystemSaveGame* LoadGameInstance = Cast<USystemSaveGame>(UGameplayStatics::CreateSaveGameObject(USystemSaveGame::StaticClass()));
if (LoadGameInstance)
{
LoadGameInstance = Cast<USystemSaveGame>(UGameplayStatics::LoadGameFromSlot(LoadGameInstance->SaveSlotName, LoadGameInstance->UserIndex));
if (LoadGameInstance)
{
// The Save File Found
SaveFile = LoadGameInstance;
}
}
if (SaveFile)
{
// Load level block data that was saved
if (TheLevelBlockConstructor && TheLevelBlockConstructor->bLoadBlocks)
{
TheLevelBlockConstructor->CurrentBlocks = SaveFile->LevelBlocks;
TheLevelBlockConstructor->Server_UpdateBlocksStatus();
}
}
}
// End Game
void ARadeGameMode::EndPlay(const EEndPlayReason::Type EndPlayReason)
{
if (Role>=ROLE_Authority)
{
// No Save File, Creating new
if (!SaveFile)
{
USystemSaveGame* saveFile = Cast<USystemSaveGame>(UGameplayStatics::CreateSaveGameObject(USystemSaveGame::StaticClass()));
UGameplayStatics::SaveGameToSlot(saveFile, saveFile->SaveSlotName, saveFile->UserIndex);
}
if (SaveFile)
{
// Saving level block data
if (TheLevelBlockConstructor && TheLevelBlockConstructor->bSaveBlocks)
{
SaveFile->LevelBlocks = TheLevelBlockConstructor->CurrentBlocks;
}
// Saving Save File
UGameplayStatics::SaveGameToSlot(SaveFile, SaveFile->SaveSlotName, SaveFile->UserIndex);
}
}
Super::EndPlay(EndPlayReason);
}
<|endoftext|> |
<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2013-2016.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://www.opensource.org/licenses/MIT)
//=======================================================================
#include <stdarg.h>
#include "tlib/print.hpp"
void tlib::print(char c){
asm volatile("mov rax, 0; mov rbx, %[c]; int 50"
: //No outputs
: [c] "g" (static_cast<size_t>(c))
: "rax", "rbx");
}
void tlib::print(const char* s){
asm volatile("mov rax, 1; mov rbx, %[s]; int 50"
: //No outputs
: [s] "g" (reinterpret_cast<size_t>(s))
: "rax", "rbx");
}
void log(const char* s){
asm volatile("mov rax, 2; mov rbx, %[s]; int 50"
: //No outputs
: [s] "g" (reinterpret_cast<size_t>(s))
: "rax", "rbx");
}
void tlib::print(uint8_t v){
print(std::to_string(v));
}
void tlib::print(uint16_t v){
print(std::to_string(v));
}
void tlib::print(uint32_t v){
print(std::to_string(v));
}
void tlib::print(uint64_t v){
print(std::to_string(v));
}
void tlib::print(int8_t v){
print(std::to_string(v));
}
void tlib::print(int16_t v){
print(std::to_string(v));
}
void tlib::print(int32_t v){
print(std::to_string(v));
}
void tlib::print(int64_t v){
print(std::to_string(v));
}
void tlib::set_canonical(bool can){
size_t value = can;
asm volatile("mov rax, 0x20; mov rbx, %[value]; int 50;"
:
: [value] "g" (value)
: "rax", "rbx");
}
void tlib::set_mouse(bool m){
size_t value = m;
asm volatile("mov rax, 0x21; mov rbx, %[value]; int 50;"
:
: [value] "g" (value)
: "rax", "rbx");
}
size_t tlib::read_input(char* buffer, size_t max){
size_t value;
asm volatile("mov rax, 0x10; mov rbx, %[buffer]; mov rcx, %[max]; int 50; mov %[read], rax"
: [read] "=m" (value)
: [buffer] "g" (buffer), [max] "g" (max)
: "rax", "rbx", "rcx");
return value;
}
size_t tlib::read_input(char* buffer, size_t max, size_t ms){
size_t value;
asm volatile("mov rax, 0x11; mov rbx, %[buffer]; mov rcx, %[max]; mov rdx, %[ms]; int 50; mov %[read], rax"
: [read] "=m" (value)
: [buffer] "g" (buffer), [max] "g" (max), [ms] "g" (ms)
: "rax", "rbx", "rcx");
return value;
}
std::keycode tlib::read_input_raw(){
size_t value;
asm volatile("mov rax, 0x12; int 50; mov %[input], rax"
: [input] "=m" (value)
:
: "rax");
return static_cast<std::keycode>(value);
}
std::keycode tlib::read_input_raw(size_t ms){
size_t value;
asm volatile("mov rax, 0x13; mov rbx, %[ms]; int 50; mov %[input], rax"
: [input] "=m" (value)
: [ms] "g" (ms)
: "rax");
return static_cast<std::keycode>(value);
}
void tlib::clear(){
asm volatile("mov rax, 100; int 50;"
: //No outputs
: //No inputs
: "rax");
}
size_t tlib::get_columns(){
size_t value;
asm volatile("mov rax, 101; int 50; mov %[columns], rax"
: [columns] "=m" (value)
: //No inputs
: "rax");
return value;
}
size_t tlib::get_rows(){
size_t value;
asm volatile("mov rax, 102; int 50; mov %[rows], rax"
: [rows] "=m" (value)
: //No inputs
: "rax");
return value;
}
void tlib::print(const std::string& s){
return print(s.c_str());
}
void tlib::print_line(){
print('\n');
}
void tlib::print_line(const char* s){
print(s);
print_line();
}
void tlib::print_line(size_t v){
print(v);
print_line();
}
void tlib::print_line(const std::string& s){
print(s);
print_line();
}
void tlib::user_logf(const char* s, ...){
va_list va;
va_start(va, s);
char buffer[512];
vsprintf_raw(buffer, 512, s, va);
log(buffer);
va_end(va);
}
namespace tlib {
#include "printf_def.hpp"
void __printf(const std::string& formatted){
print(formatted);
}
void __printf_raw(const char* formatted){
print(formatted);
}
} // end of namespace tlib
<commit_msg>Use the handles to print<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2013-2016.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://www.opensource.org/licenses/MIT)
//=======================================================================
#include <stdarg.h>
#include "tlib/print.hpp"
#include "tlib/file.hpp"
namespace {
size_t strlen(const char* c){
size_t s = 0;
while(*c++){
++s;
}
return s;
}
} //end of anonymous namespace
void tlib::print(char c){
tlib::write(1, &c, 1, 0);
}
void tlib::print(const char* s){
tlib::write(1, s, strlen(s), 0);
}
void tlib::print(const std::string& s){
tlib::write(1, s.c_str(), s.size(), 0);
}
void log(const char* s){
asm volatile("mov rax, 2; mov rbx, %[s]; int 50"
: //No outputs
: [s] "g" (reinterpret_cast<size_t>(s))
: "rax", "rbx");
}
void tlib::print(uint8_t v){
print(std::to_string(v));
}
void tlib::print(uint16_t v){
print(std::to_string(v));
}
void tlib::print(uint32_t v){
print(std::to_string(v));
}
void tlib::print(uint64_t v){
print(std::to_string(v));
}
void tlib::print(int8_t v){
print(std::to_string(v));
}
void tlib::print(int16_t v){
print(std::to_string(v));
}
void tlib::print(int32_t v){
print(std::to_string(v));
}
void tlib::print(int64_t v){
print(std::to_string(v));
}
void tlib::set_canonical(bool can){
size_t value = can;
asm volatile("mov rax, 0x20; mov rbx, %[value]; int 50;"
:
: [value] "g" (value)
: "rax", "rbx");
}
void tlib::set_mouse(bool m){
size_t value = m;
asm volatile("mov rax, 0x21; mov rbx, %[value]; int 50;"
:
: [value] "g" (value)
: "rax", "rbx");
}
size_t tlib::read_input(char* buffer, size_t max){
size_t value;
asm volatile("mov rax, 0x10; mov rbx, %[buffer]; mov rcx, %[max]; int 50; mov %[read], rax"
: [read] "=m" (value)
: [buffer] "g" (buffer), [max] "g" (max)
: "rax", "rbx", "rcx");
return value;
}
size_t tlib::read_input(char* buffer, size_t max, size_t ms){
size_t value;
asm volatile("mov rax, 0x11; mov rbx, %[buffer]; mov rcx, %[max]; mov rdx, %[ms]; int 50; mov %[read], rax"
: [read] "=m" (value)
: [buffer] "g" (buffer), [max] "g" (max), [ms] "g" (ms)
: "rax", "rbx", "rcx");
return value;
}
std::keycode tlib::read_input_raw(){
size_t value;
asm volatile("mov rax, 0x12; int 50; mov %[input], rax"
: [input] "=m" (value)
:
: "rax");
return static_cast<std::keycode>(value);
}
std::keycode tlib::read_input_raw(size_t ms){
size_t value;
asm volatile("mov rax, 0x13; mov rbx, %[ms]; int 50; mov %[input], rax"
: [input] "=m" (value)
: [ms] "g" (ms)
: "rax");
return static_cast<std::keycode>(value);
}
void tlib::clear(){
asm volatile("mov rax, 100; int 50;"
: //No outputs
: //No inputs
: "rax");
}
size_t tlib::get_columns(){
size_t value;
asm volatile("mov rax, 101; int 50; mov %[columns], rax"
: [columns] "=m" (value)
: //No inputs
: "rax");
return value;
}
size_t tlib::get_rows(){
size_t value;
asm volatile("mov rax, 102; int 50; mov %[rows], rax"
: [rows] "=m" (value)
: //No inputs
: "rax");
return value;
}
void tlib::print_line(){
print('\n');
}
void tlib::print_line(const char* s){
print(s);
print_line();
}
void tlib::print_line(size_t v){
print(v);
print_line();
}
void tlib::print_line(const std::string& s){
print(s);
print_line();
}
void tlib::user_logf(const char* s, ...){
va_list va;
va_start(va, s);
char buffer[512];
vsprintf_raw(buffer, 512, s, va);
log(buffer);
va_end(va);
}
namespace tlib {
#include "printf_def.hpp"
void __printf(const std::string& formatted){
print(formatted);
}
void __printf_raw(const char* formatted){
print(formatted);
}
} // end of namespace tlib
<|endoftext|> |
<commit_before>/**
* @file MapUtils.cpp
*
* @see MapUtils.hpp
*/
#include <cmath>
#include "../../include/terrain/MapUtils.hpp"
Biome findClosestBiome(Vertex2D & pos,
voro::container & container, std::vector<Seed> & seeds){
double rx, ry, rz;
int seedID;
if (!(container.find_voronoi_cell(pos.first, pos.second, 0.0,
rx, ry, rz, seedID)))
exit(EXIT_FAILURE);
return seeds[seedID].getBiome();
}
float distanceV2D(Vertex2D & a, Vertex2D & b) {
float aX = a.first;
float aY = a.second;
float bX = b.first;
float bY = b.second;
float u = bX - aX;
float v = bY - aY;
return sqrt(u*u + v*v);
}
<commit_msg>[Map] Refactoring code<commit_after>/**
* @file MapUtils.cpp
*
* @see MapUtils.hpp
*/
#include <cmath>
#include "../../include/terrain/MapUtils.hpp"
Biome findClosestBiome(
Vertex2D & pos,
voro::container & container,
std::vector<Seed> & seeds
){
double rx, ry, rz;
int seedID;
if (
!(
container.find_voronoi_cell(
pos.first,
pos.second,
0.0,
rx,
ry,
rz,
seedID
)
)
) {
exit(EXIT_FAILURE);
}
return seeds[seedID].getBiome();
}
float distanceV2D(Vertex2D & a, Vertex2D & b) {
float aX = a.first;
float aY = a.second;
float bX = b.first;
float bY = b.second;
float u = bX - aX;
float v = bY - aY;
return sqrt(u*u + v*v);
}
<|endoftext|> |
<commit_before>// Copyright(c) Andre Caron, 2009-2010
//
// This document is covered by the Artistic License 2.0 (Open Source Initiative
// approved license). A copy of the license should have been provided alongside
// this software package (see "license.rtf"). If not, the license is available
// online at "http://www.opensource.org/licenses/artistic-license-2.0.php".
/*!
* @file w32.io/AnonymousPipe.cpp
* @author Andre Caron ([email protected])
*/
#include <w32.io/AnonymousPipe.hpp>
#include <w32/Error.hpp>
namespace {
void allocate ( ::PHANDLE input, ::PHANDLE output )
{
::SECURITY_ATTRIBUTES attributes;
attributes.nLength = sizeof(attributes);
attributes.lpSecurityDescriptor = 0;
attributes.bInheritHandle = TRUE;
const ::BOOL result = ::CreatePipe(input, output, &attributes, 0);
if ( result == FALSE )
{
const ::DWORD error = ::GetLastError();
UNCHECKED_WIN32C_ERROR(CreatePipe, error);
}
}
}
namespace w32 { namespace io {
AnonymousPipe::AnonymousPipe ()
{
// Allocate handles.
::HANDLE handles[2] = { 0 };
allocate(&handles[0], &handles[1]);
// Wrap them.
myHandles[0] = Object::claim(handles[0]);
myHandles[1] = Object::claim(handles[1]);
}
AnonymousPipe::operator InputStream () const
{
return (InputStream(myHandles[0]));
}
AnonymousPipe::operator OutputStream () const
{
return (OutputStream(myHandles[0]));
}
} }
<commit_msg>Fixes output handle.<commit_after>// Copyright(c) Andre Caron, 2009-2010
//
// This document is covered by the Artistic License 2.0 (Open Source Initiative
// approved license). A copy of the license should have been provided alongside
// this software package (see "license.rtf"). If not, the license is available
// online at "http://www.opensource.org/licenses/artistic-license-2.0.php".
/*!
* @file w32.io/AnonymousPipe.cpp
* @author Andre Caron ([email protected])
*/
#include <w32.io/AnonymousPipe.hpp>
#include <w32/Error.hpp>
namespace {
void allocate ( ::PHANDLE input, ::PHANDLE output )
{
::SECURITY_ATTRIBUTES attributes;
attributes.nLength = sizeof(attributes);
attributes.lpSecurityDescriptor = 0;
attributes.bInheritHandle = TRUE;
const ::BOOL result = ::CreatePipe(input, output, &attributes, 0);
if ( result == FALSE )
{
const ::DWORD error = ::GetLastError();
UNCHECKED_WIN32C_ERROR(CreatePipe, error);
}
}
}
namespace w32 { namespace io {
AnonymousPipe::AnonymousPipe ()
{
// Allocate handles.
::HANDLE handles[2] = { 0 };
allocate(&handles[0], &handles[1]);
// Wrap them.
myHandles[0] = Object::claim(handles[0]);
myHandles[1] = Object::claim(handles[1]);
}
AnonymousPipe::operator InputStream () const
{
return (InputStream(myHandles[0]));
}
AnonymousPipe::operator OutputStream () const
{
return (OutputStream(myHandles[1]));
}
} }
<|endoftext|> |
<commit_before>#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
#include <cstdio>
#include <cstdlib>
#include <vector>
#include "nthash.hpp"
using namespace std;
namespace opt {
unsigned threads=1;
unsigned kmerLen=64;
const unsigned nhash=7;
const unsigned nbuck=512;
const unsigned nbits=9;
}
int main(int argc, const char *argv[]){
std::ifstream in(argv[1]);
uint64_t tVec[opt::nbuck];
for (unsigned j=0; j<opt::nbuck; j++)
tVec[j]=0;
size_t buffCard=0,buffSize=20000000;
//vector<string> readBuffer(buffSize);
string *readBuffer = new string [buffSize];
bool good=true;
#pragma omp parallel
{
uint64_t mVec[opt::nbuck];
for (unsigned j=0; j<opt::nbuck; j++)
mVec[j]=0;
while(good){
#pragma omp single
{
string seq, hseq;
for(buffCard=0; buffCard<buffSize; buffCard++) {
good = getline(in, hseq);
good = getline(in, seq);
good = getline(in, hseq);
good = getline(in, hseq);
if(good) readBuffer[buffCard]=seq;
else break;
}
//std::cerr << buffCard << "\t";
}
int rInd;
#pragma omp for
for(rInd=0; rInd<buffCard; rInd++) {
string seq = readBuffer[rInd];
string kmer = seq.substr(0, opt::kmerLen);
uint64_t hVal = NTP64(kmer.c_str(), opt::kmerLen);
if(hVal>>opt::nbits) {
int run0 = __builtin_clzll(hVal&(~(uint64_t)opt::nbuck-1));
if(run0 > mVec[hVal&(opt::nbuck-1)]) mVec[hVal&(opt::nbuck-1)]=run0;
}
for (size_t i = 0; i < seq.length() - opt::kmerLen; i++) {
hVal = NTP64(hVal, seq[i], seq[i+opt::kmerLen], opt::kmerLen);
if(hVal&(~(uint64_t)opt::nbuck-1)) {
int run0 = __builtin_clzll(hVal&(~(uint64_t)opt::nbuck-1));;
if(run0 > mVec[hVal&(opt::nbuck-1)]) mVec[hVal&(opt::nbuck-1)]=run0;
}
}
}
}
//bool good = true;
/*for(string seq, hseq; good;) {
#pragma omp critical(in)
{
good = getline(in, hseq);
good = getline(in, seq);
good = getline(in, hseq);
good = getline(in, hseq);
}*/
/*if(good) {
string kmer = seq.substr(0, opt::kmerLen);
uint64_t hVal = NTP64(kmer.c_str(), opt::kmerLen);
if(hVal>>opt::nbits) {
int run0 = __builtin_clzll(hVal&(~(uint64_t)opt::nbuck-1));
if(run0 > mVec[hVal&(opt::nbuck-1)]) mVec[hVal&(opt::nbuck-1)]=run0;
}
for (size_t i = 0; i < seq.length() - opt::kmerLen; i++) {
hVal = NTP64(hVal, seq[i], seq[i+opt::kmerLen], opt::kmerLen);
if(hVal&(~(uint64_t)opt::nbuck-1)) {
int run0 = __builtin_clzll(hVal&(~(uint64_t)opt::nbuck-1));;
if(run0 > mVec[hVal&(opt::nbuck-1)]) mVec[hVal&(opt::nbuck-1)]=run0;
}
}
}*/
//}
#pragma omp critical
{
for (unsigned j=0; j<opt::nbuck; j++)
if(tVec[j] < mVec[j]) tVec[j] = mVec[j];
}
}
delete [] readBuffer;
in.close();
double pEst = 0.0, zEst = 0.0, eEst = 0.0, alpha = 0.0;
if(opt::nbuck==16)
alpha = 2*0.673;
else if (opt::nbuck == 32)
alpha = 2*0.697;
else if(opt::nbuck==64)
alpha = 2*0.709;
else
alpha = 2*0.7213/(1 + 1.079/opt::nbuck);
for (unsigned j=0; j<opt::nbuck-1; j++)
pEst += 1.0/((uint64_t)1<<tVec[j]);
zEst = 1.0/pEst;
eEst = alpha * opt::nbuck * opt::nbuck * zEst;
std::cout << (unsigned long long) eEst << "\n";
return 0;
}
<commit_msg>Parameter tuning<commit_after>#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
#include <cstdio>
#include <cstdlib>
#include <vector>
#include "nthash.hpp"
using namespace std;
namespace opt {
unsigned threads=1;
unsigned kmerLen=64;
const unsigned nhash=7;
const unsigned nbuck=512;
const unsigned nbits=9;
}
int main(int argc, const char *argv[]){
std::ifstream in(argv[1]);
opt::kmerLen = atoi(argv[2]);
uint64_t tVec[opt::nbuck];
for (unsigned j=0; j<opt::nbuck; j++)
tVec[j]=0;
size_t buffCard=0,buffSize=20000000;
//vector<string> readBuffer(buffSize);
string *readBuffer = new string [buffSize];
bool good=true;
#pragma omp parallel
{
uint64_t mVec[opt::nbuck];
for (unsigned j=0; j<opt::nbuck; j++)
mVec[j]=0;
while(good){
#pragma omp single
{
string seq, hseq;
for(buffCard=0; buffCard<buffSize; buffCard++) {
good = getline(in, hseq);
good = getline(in, seq);
good = getline(in, hseq);
good = getline(in, hseq);
if(good) readBuffer[buffCard]=seq;
else break;
}
//std::cerr << buffCard << "\t";
}
int rInd;
#pragma omp for
for(rInd=0; rInd<buffCard; rInd++) {
string seq = readBuffer[rInd];
string kmer = seq.substr(0, opt::kmerLen);
uint64_t hVal = NTP64(kmer.c_str(), opt::kmerLen);
if(hVal>>opt::nbits) {
int run0 = __builtin_clzll(hVal&(~(uint64_t)opt::nbuck-1));
if(run0 > mVec[hVal&(opt::nbuck-1)]) mVec[hVal&(opt::nbuck-1)]=run0;
}
for (size_t i = 0; i < seq.length() - opt::kmerLen; i++) {
hVal = NTP64(hVal, seq[i], seq[i+opt::kmerLen], opt::kmerLen);
if(hVal&(~(uint64_t)opt::nbuck-1)) {
int run0 = __builtin_clzll(hVal&(~(uint64_t)opt::nbuck-1));;
if(run0 > mVec[hVal&(opt::nbuck-1)]) mVec[hVal&(opt::nbuck-1)]=run0;
}
}
}
}
//bool good = true;
/*for(string seq, hseq; good;) {
#pragma omp critical(in)
{
good = getline(in, hseq);
good = getline(in, seq);
good = getline(in, hseq);
good = getline(in, hseq);
}*/
/*if(good) {
string kmer = seq.substr(0, opt::kmerLen);
uint64_t hVal = NTP64(kmer.c_str(), opt::kmerLen);
if(hVal>>opt::nbits) {
int run0 = __builtin_clzll(hVal&(~(uint64_t)opt::nbuck-1));
if(run0 > mVec[hVal&(opt::nbuck-1)]) mVec[hVal&(opt::nbuck-1)]=run0;
}
for (size_t i = 0; i < seq.length() - opt::kmerLen; i++) {
hVal = NTP64(hVal, seq[i], seq[i+opt::kmerLen], opt::kmerLen);
if(hVal&(~(uint64_t)opt::nbuck-1)) {
int run0 = __builtin_clzll(hVal&(~(uint64_t)opt::nbuck-1));;
if(run0 > mVec[hVal&(opt::nbuck-1)]) mVec[hVal&(opt::nbuck-1)]=run0;
}
}
}*/
//}
#pragma omp critical
{
for (unsigned j=0; j<opt::nbuck; j++)
if(tVec[j] < mVec[j]) tVec[j] = mVec[j];
}
}
delete [] readBuffer;
in.close();
double pEst = 0.0, zEst = 0.0, eEst = 0.0, alpha = 0.0;
if(opt::nbuck==16)
alpha = 2*0.673;
else if (opt::nbuck == 32)
alpha = 2*0.697;
else if(opt::nbuck==64)
alpha = 2*0.709;
else
alpha = 2*0.7213/(1 + 1.079/opt::nbuck);
for (unsigned j=0; j<opt::nbuck-1; j++)
pEst += 1.0/((uint64_t)1<<tVec[j]);
zEst = 1.0/pEst;
eEst = alpha * opt::nbuck * opt::nbuck * zEst;
std::cout << (unsigned long long) eEst << "\n";
return 0;
}
<|endoftext|> |
<commit_before>/*
* mesh2pcd.cpp
*
* Created on: Aug 23, 2011
* Author: aitor
*/
#include <pcl/visualization/pcl_visualizer.h>
#include <pcl/io/pcd_io.h>
#include <pcl/registration/transforms.h>
#include "vtkSmartPointer.h"
#include "vtkPLYReader.h"
#include "vtkPolyData.h"
#include <pcl/filters/voxel_grid.h>
int
main (int argc, char** argv) {
vtkSmartPointer < vtkPLYReader > readerQuery = vtkSmartPointer<vtkPLYReader>::New ();
readerQuery->SetFileName (argv[1]);
vtkSmartPointer < vtkPolyData > polydata1 = readerQuery->GetOutput ();
polydata1->Update ();
int tesselated_sphere_level = atoi(argv[2]);
int resolution = atoi(argv[3]);
double leaf_size = atof(argv[4]);
bool INTER_VIS = false;
pcl::visualization::PCLVisualizer vis;
vis.addModelFromPolyData (polydata1, "mesh1", 0);
vis.setRepresentationToSurfaceForAllActors ();
std::vector < pcl::PointCloud<pcl::PointXYZ>, Eigen::aligned_allocator<pcl::PointCloud<pcl::PointXYZ> > > views_xyz;
std::vector < Eigen::Matrix4f, Eigen::aligned_allocator<Eigen::Matrix4f> > poses;
std::vector<float> enthropies;
vis.renderViewTesselatedSphere (resolution, resolution, views_xyz, poses, enthropies, tesselated_sphere_level);
//take views and fuse them together
Eigen::Matrix4f first_pose;
first_pose = poses[0];
std::vector < pcl::PointCloud<pcl::PointXYZ>::Ptr > aligned_clouds;
for(size_t i=0; i < views_xyz.size(); i++) {
pcl::PointCloud < pcl::PointXYZ >::Ptr cloud(new pcl::PointCloud < pcl::PointXYZ >());
Eigen::Matrix4f pose_inverse;
pose_inverse = poses[i].inverse();
pcl::transformPointCloud(views_xyz[i], *cloud, pose_inverse);
aligned_clouds.push_back(cloud);
}
if(INTER_VIS) {
pcl::visualization::PCLVisualizer vis2("visualize");
for(size_t i=0; i < aligned_clouds.size(); i++) {
std::stringstream name;
name << "cloud_" << i;
vis2.addPointCloud(aligned_clouds[i],name.str());
vis2.spin();
}
}
//fuse clouds
pcl::PointCloud < pcl::PointXYZ >::Ptr big_boy(new pcl::PointCloud < pcl::PointXYZ >());
for(size_t i=0; i < aligned_clouds.size(); i++) {
*big_boy += *aligned_clouds[i];
}
{
pcl::visualization::PCLVisualizer vis2("visualize");
vis2.addPointCloud(big_boy);
vis2.spin();
}
//voxelgrid
pcl::VoxelGrid<pcl::PointXYZ> grid_;
grid_.setInputCloud (big_boy);
grid_.setLeafSize (leaf_size, leaf_size, leaf_size);
grid_.filter (*big_boy);
{
pcl::visualization::PCLVisualizer vis2("visualize");
vis2.addPointCloud(big_boy);
vis2.spin();
}
//save
pcl::io::savePCDFileASCII("out.pcd",*big_boy);
}
<commit_msg>working on the mesh2pcd tool<commit_after>/*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2010-2011, Willow Garage, Inc.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <pcl/visualization/pcl_visualizer.h>
#include <pcl/io/pcd_io.h>
#include <pcl/registration/transforms.h>
#include <vtkPLYReader.h>
#include <vtkOBJReader.h>
#include <pcl/filters/voxel_grid.h>
#include <pcl/console/print.h>
#include <pcl/console/parse.h>
using namespace pcl;
using namespace pcl::io;
using namespace pcl::console;
int default_tesselated_sphere_level = 2;
int default_resolution = 100;
float default_leaf_size = 0.01;
void
printHelp (int argc, char **argv)
{
print_error ("Syntax is: %s input.{ply,obj} output.pcd <options>\n", argv[0]);
print_info (" where options are:\n");
print_info (" -level X = tesselated sphere level (default: ");
print_value ("%d", default_tesselated_sphere_level); print_info (")\n");
print_info (" -resolution X = the sphere resolution in angle increments (default: ");
print_value ("%d", default_resolution); print_info (" deg)\n");
print_info (" -leaf_size X = the XYZ leaf size for the VoxelGrid -- for data reduction (default: ");
print_value ("%f", default_leaf_size); print_info (" m)\n");
}
/* ---[ */
int
main (int argc, char **argv)
{
print_info ("Convert a CAD model to a point cloud using ray tracing operations. For more information, use: %s -h\n",
argv[0]);
if (argc < 3)
{
printHelp (argc, argv);
return (-1);
}
// Parse command line arguments
int tesselated_sphere_level = default_tesselated_sphere_level;
parse_argument (argc, argv, "-level", tesselated_sphere_level);
int resolution = default_resolution;
parse_argument (argc, argv, "-resolution", resolution);
double leaf_size = default_leaf_size;
parse_argument (argc, argv, "-leaf_size", leaf_size);
// Parse the command line arguments for .ply and PCD files
std::vector<int> pcd_file_indices = parse_file_extension_argument (argc, argv, ".pcd");
if (pcd_file_indices.size () != 1)
{
print_error ("Need a single output PCD file to continue.\n");
return (-1);
}
std::vector<int> ply_file_indices = parse_file_extension_argument (argc, argv, ".ply");
std::vector<int> obj_file_indices = parse_file_extension_argument (argc, argv, ".obj");
if (ply_file_indices.size () != 1 && obj_file_indices.size () != 1)
{
print_error ("Need a single input PLY/OBJ file to continue.\n");
return (-1);
}
vtkSmartPointer <vtkPolyData> polydata1;
if (ply_file_indices.size () == 1)
{
vtkSmartPointer<vtkPLYReader> readerQuery = vtkSmartPointer<vtkPLYReader>::New ();
readerQuery->SetFileName (argv[ply_file_indices[0]]);
polydata1 = readerQuery->GetOutput ();
polydata1->Update ();
}
else if (obj_file_indices.size () == 1)
{
vtkSmartPointer<vtkOBJReader> readerQuery = vtkSmartPointer<vtkOBJReader>::New ();
readerQuery->SetFileName (argv[obj_file_indices[0]]);
polydata1 = readerQuery->GetOutput ();
polydata1->Update ();
}
bool INTER_VIS = false;
visualization::PCLVisualizer vis;
vis.addModelFromPolyData (polydata1, "mesh1", 0);
vis.setRepresentationToSurfaceForAllActors ();
std::vector<PointCloud<PointXYZ>, Eigen::aligned_allocator<PointCloud<PointXYZ> > > views_xyz;
std::vector<Eigen::Matrix4f, Eigen::aligned_allocator<Eigen::Matrix4f> > poses;
std::vector<float> enthropies;
vis.renderViewTesselatedSphere (resolution, resolution, views_xyz, poses, enthropies, tesselated_sphere_level);
//take views and fuse them together
Eigen::Matrix4f first_pose;
first_pose = poses[0];
std::vector<PointCloud<PointXYZ>::Ptr> aligned_clouds;
for (size_t i = 0; i < views_xyz.size (); i++)
{
PointCloud <PointXYZ>::Ptr cloud (new PointCloud <PointXYZ> ());
Eigen::Matrix4f pose_inverse;
pose_inverse = poses[i].inverse ();
transformPointCloud (views_xyz[i], *cloud, pose_inverse);
aligned_clouds.push_back (cloud);
}
if (INTER_VIS)
{
visualization::PCLVisualizer vis2 ("visualize");
for (size_t i=0; i < aligned_clouds.size (); i++)
{
std::stringstream name;
name << "cloud_" << i;
vis2.addPointCloud (aligned_clouds[i],name.str ());
vis2.spin ();
}
}
// Fuse clouds
PointCloud <PointXYZ>::Ptr big_boy (new PointCloud <PointXYZ> ());
for (size_t i=0; i < aligned_clouds.size (); i++)
*big_boy += *aligned_clouds[i];
visualization::PCLVisualizer vis2 ("visualize");
vis2.addPointCloud (big_boy);
vis2.spin ();
// Voxelgrid
VoxelGrid<PointXYZ> grid_;
grid_.setInputCloud (big_boy);
grid_.setLeafSize (leaf_size, leaf_size, leaf_size);
grid_.filter (*big_boy);
visualization::PCLVisualizer vis3 ("visualize");
vis3.addPointCloud (big_boy);
vis3.spin ();
savePCDFileASCII (argv[pcd_file_indices[0]], *big_boy);
}
<|endoftext|> |
<commit_before>/*
Copyright (C) 1998-2000 by Jorrit Tyberghein
Copyright (C) 2001 by W.C.A. Wijngaards
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "cssysdef.h"
#include "cssys/system.h"
#include "apps/isotest/isotest.h"
#include "ivideo/graph2d.h"
#include "ivideo/graph3d.h"
#include "ivideo/txtmgr.h"
#include "ivideo/fontserv.h"
#include "ivaria/iso.h"
#include "isomater.h"
#include "imap/parser.h"
#include "igraphic/loader.h"
IsoTest::IsoTest ()
{
engine = NULL;
view = NULL;
world = NULL;
font = NULL;
light = NULL;
}
IsoTest::~IsoTest ()
{
if(view) view->DecRef();
if(world) world->DecRef();
if(engine) engine->DecRef();
if(font) font->DecRef();
if(light) light->DecRef();
}
void cleanup ()
{
System->console_out ("Cleaning up...\n");
delete System;
}
/// helper texture loader
static iMaterialHandle* LoadTexture(iSystem *sys, iTextureManager *txtmgr,
iVFS *VFS, char *name)
{
iImageLoader *imgloader = QUERY_PLUGIN(sys, iImageLoader);
iDataBuffer *buf = VFS->ReadFile (name);
if(!buf) printf("Could not read file %s\n", name);
iImage *image = imgloader->Load(buf->GetUint8 (), buf->GetSize (),
txtmgr->GetTextureFormat ());
if(!image) printf("Could not load image %s\n", name);
iTextureHandle *handle = txtmgr->RegisterTexture(image, CS_TEXTURE_2D |
CS_TEXTURE_3D);
if(!handle) printf("Could not register texture %s\n", name);
csIsoMaterial *material = new csIsoMaterial(handle);
iMaterialHandle *math = txtmgr->RegisterMaterial(material);
buf->DecRef();
imgloader->DecRef();
return math;
}
/// helper grid change callback for the player sprite - to move the light
static void PlayerGridChange(iIsoSprite *sprite, void *mydata)
{
IsoTest* app = (IsoTest*)mydata;
if(app->GetLight())
app->GetLight()->SetGrid(sprite->GetGrid());
}
bool IsoTest::Initialize (int argc, const char* const argv[],
const char *iConfigName)
{
if (!superclass::Initialize (argc, argv, iConfigName))
return false;
// Find the pointer to engine plugin
engine = QUERY_PLUGIN (this, iIsoEngine);
if (!engine)
{
Printf (MSG_FATAL_ERROR, "No IsoEngine plugin!\n");
abort ();
}
// Open the main system. This will open all the previously loaded plug-ins.
if (!Open ("IsoTest Crystal Space Application"))
{
Printf (MSG_FATAL_ERROR, "Error opening system!\n");
cleanup ();
exit (1);
}
iFontServer *fsvr = QUERY_PLUGIN(this, iFontServer);
font = fsvr->LoadFont(CSFONT_LARGE);
fsvr->DecRef();
// Setup the texture manager
iTextureManager* txtmgr = G3D->GetTextureManager ();
txtmgr->SetVerbose (true);
// Initialize the texture manager
txtmgr->ResetPalette ();
// Allocate a uniformly distributed in R,G,B space palette for console
// The console will crash on some platforms if this isn't initialize properly
int r,g,b;
for (r = 0; r < 8; r++)
for (g = 0; g < 8; g++)
for (b = 0; b < 4; b++)
txtmgr->ReserveColor (r * 32, g * 32, b * 64);
txtmgr->SetPalette ();
// Some commercials...
Printf (MSG_INITIALIZATION,
"IsoTest Crystal Space Application version 0.1.\n");
// Create our world.
Printf (MSG_INITIALIZATION, "Creating world!...\n");
Printf (MSG_INITIALIZATION, "--------------------------------------\n");
// create our world to play in, and a view on it.
world = engine->CreateWorld();
view = engine->CreateView(world);
iMaterialHandle *math1 = LoadTexture(this, txtmgr, VFS,
"/lib/std/stone4.gif");
iMaterialHandle *math2 = LoadTexture(this, txtmgr, VFS,
"/lib/std/mystone2.gif");
iMaterialHandle *snow = LoadTexture(this, txtmgr, VFS,
"/lib/std/snow.jpg");
// create a rectangular grid in the world
// the grid is 10 units wide (from 0..10 in the +z direction)
// the grid is 20 units tall (from 0..20 in the +x direction)
iIsoGrid *grid = world->CreateGrid(10, 20);
grid->SetSpace(0, 0, -1.0, +10.0);
int multx = 2, multy = 2;
grid->SetGroundMult(multx, multy);
iIsoSprite *sprite = NULL;
int x,y, mx,my;
for(y=0; y<20; y++)
for(x=0; x<10; x++)
{
// put tiles on the floor
sprite = engine->CreateFloorSprite(csVector3(y,0,x), 1.0, 1.0);
if((x+y)&1)
sprite->SetMaterialHandle(math1);
else sprite->SetMaterialHandle(math2);
world->AddSprite(sprite);
for(my=0; my<multy; my++)
for(mx=0; mx<multx; mx++)
grid->SetGroundValue(x, y, mx, my, 0.0);
}
// add the player sprite to the world
csVector3 startpos(10,0,5);
player = engine->CreateFrontSprite(startpos, 1.0, 4.0);
player->SetMaterialHandle(snow);
world->AddSprite(player);
player->SetGridChangeCallback(PlayerGridChange, (void*)this);
// add a light to the scene.
iIsoLight *scenelight = engine->CreateLight();
scenelight->SetPosition(csVector3(3,3,3));
scenelight->SetGrid(grid);
scenelight->SetRadius(4.0);
scenelight->SetColor(csColor(0.0, 0.4, 1.0));
// add a light for the player, above players head.
light = engine->CreateLight();
light->SetPosition(startpos+csVector3(0,5,0));
light->SetGrid(grid);
light->SetRadius(5.0);
light->SetColor(csColor(1.0, 0.4, 0.2));
// make a bump to cast shadows
for(my=0; my<multy; my++)
for(mx=0; mx<multx; mx++)
grid->SetGroundValue(5, 15, mx, my, 4.0);
sprite = engine->CreateFloorSprite(csVector3(15,4,5), 1.0, 1.0);
sprite->SetMaterialHandle(math2);
world->AddSprite(sprite);
for(my=0; my<4; my++)
{
sprite = engine->CreateXWallSprite(csVector3(15,my,5), 1.0, 1.0);
sprite->SetMaterialHandle(math2);
world->AddSprite(sprite);
sprite = engine->CreateZWallSprite(csVector3(16,my,5), 1.0, 1.0);
sprite->SetMaterialHandle(math2);
world->AddSprite(sprite);
}
//bool res = grid->GroundHitBeam(csVector3(10,1,5), csVector3(15,-2,8));
//printf("Hitbeam gave %d\n", (int)res);
//res = grid->GroundHitBeam(csVector3(10,1,5), csVector3(20,0,10));
//printf("Hitbeam gave %d\n", (int)res);
txtmgr->PrepareTextures ();
txtmgr->PrepareMaterials ();
txtmgr->SetPalette ();
// scroll view to show player position at center of screen
view->SetScroll(startpos, csVector2(G3D->GetWidth()/2, G3D->GetHeight()/2));
return true;
}
void IsoTest::NextFrame ()
{
iTextureManager* txtmgr = G3D->GetTextureManager ();
SysSystemDriver::NextFrame ();
cs_time elapsed_time, current_time;
GetElapsedTime (elapsed_time, current_time);
// keep track of fps.
static bool fpsstarted = false;
static int numframes = 0;
static int numtime = 0;
static float fps = 0.0;
if(!fpsstarted && (elapsed_time > 0))
{fpsstarted = true; fps = 1. / (float(elapsed_time)*.001);}
numtime += elapsed_time;
numframes ++;
if(numtime >= 1000)
{
fps = float(numframes) / (float(numtime)*.001);
numtime = 0;
numframes = 0;
}
// move the player and scroll the view to keep the player centered
// according to keyboard state
float speed = (elapsed_time / 1000.) * (0.10 * 20);
csVector3 playermotion(0,0,0);
if (GetKeyState (CSKEY_RIGHT)) playermotion += csVector3(0,0,speed);
if (GetKeyState (CSKEY_LEFT)) playermotion += csVector3(0,0,-speed);
if (GetKeyState (CSKEY_PGUP)) playermotion += csVector3(0,speed,0);
if (GetKeyState (CSKEY_PGDN)) playermotion += csVector3(0,-speed,0);
if (GetKeyState (CSKEY_UP)) playermotion += csVector3(speed,0,0);
if (GetKeyState (CSKEY_DOWN)) playermotion += csVector3(-speed,0,0);
if(!playermotion.IsZero())
{
player->MovePosition(playermotion);
view->MoveScroll(playermotion);
light->SetPosition(player->GetPosition()+csVector3(0,5,0));
}
// Tell 3D driver we're going to display 3D things.
if (!G3D->BeginDraw (engine->GetBeginDrawFlags () | CSDRAW_3DGRAPHICS
| CSDRAW_CLEARSCREEN ))
return;
view->Draw ();
// Start drawing 2D graphics.
if (!G3D->BeginDraw (CSDRAW_2DGRAPHICS)) return;
char buf[255];
sprintf(buf, "FPS: %g loc(%g,%g,%g)", fps, player->GetPosition().x,
player->GetPosition().y, player->GetPosition().z);
G2D->Write(font, 10, G2D->GetHeight() - 20, txtmgr->FindRGB(255,255,255),
-1, buf);
// Drawing code ends here.
G3D->FinishDraw ();
// Print the final output.
G3D->Print (NULL);
}
bool IsoTest::HandleEvent (iEvent &Event)
{
if (superclass::HandleEvent (Event))
return true;
if ((Event.Type == csevKeyDown) && (Event.Key.Code == CSKEY_ESC))
{
Shutdown = true;
return true;
}
if ((Event.Type == csevKeyDown) && (Event.Key.Code == '\t'))
{
static float settings[][5] = {
// scale should be *displayheight.
//xscale, yscale, zscale, zskew, xskew
{1./16., 1./16., 1./16., 1.0, 1.0},
{1./16., 1./16., 1./16., 0.6, 0.6},
{1./16., 1./16., 1./16., 0.5, 0.5},
{1./40., 1./40., 1./40., 0.5, 0.5},
{1./8., 1./8., 1./8., 0.5, 0.5},
};
static int nrsettings = 5;
static int setting = 0;
setting = (setting+1)%nrsettings;
float h = engine->GetG3D()->GetHeight();
view->SetAxes( h*settings[setting][0], h*settings[setting][1],
h*settings[setting][2], settings[setting][3], settings[setting][4]);
view->SetScroll(player->GetPosition(),
csVector2(G3D->GetWidth()/2, G3D->GetHeight()/2));
return true;
}
return false;
}
/*---------------------------------------------------------------------*
* Main function
*---------------------------------------------------------------------*/
int main (int argc, char* argv[])
{
srand (time (NULL));
// Create our main class.
System = new IsoTest ();
// We want at least the minimal set of plugins
System->RequestPlugin ("crystalspace.kernel.vfs:VFS");
System->RequestPlugin ("crystalspace.font.server.default:FontServer");
System->RequestPlugin ("crystalspace.image.loader:ImageLoader");
System->RequestPlugin ("crystalspace.graphics3d.software:VideoDriver");
System->RequestPlugin ("crystalspace.console.output.standard:Console.Output");
System->RequestPlugin ("crystalspace.engine.iso:Engine.Iso");
// Initialize the main system. This will load all needed plug-ins
// (3D, 2D, network, sound, ...) and initialize them.
if (!System->Initialize (argc, argv, NULL))
{
System->Printf (MSG_FATAL_ERROR, "Error initializing system!\n");
cleanup ();
exit (1);
}
// Main loop.
System->Loop ();
// Cleanup.
cleanup ();
return 0;
}
<commit_msg>Added a nice doorway to show off lighting<commit_after>/*
Copyright (C) 1998-2000 by Jorrit Tyberghein
Copyright (C) 2001 by W.C.A. Wijngaards
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "cssysdef.h"
#include "cssys/system.h"
#include "apps/isotest/isotest.h"
#include "ivideo/graph2d.h"
#include "ivideo/graph3d.h"
#include "ivideo/txtmgr.h"
#include "ivideo/fontserv.h"
#include "ivaria/iso.h"
#include "isomater.h"
#include "imap/parser.h"
#include "igraphic/loader.h"
IsoTest::IsoTest ()
{
engine = NULL;
view = NULL;
world = NULL;
font = NULL;
light = NULL;
}
IsoTest::~IsoTest ()
{
if(view) view->DecRef();
if(world) world->DecRef();
if(engine) engine->DecRef();
if(font) font->DecRef();
if(light) light->DecRef();
}
void cleanup ()
{
System->console_out ("Cleaning up...\n");
delete System;
}
/// helper texture loader
static iMaterialHandle* LoadTexture(iSystem *sys, iTextureManager *txtmgr,
iVFS *VFS, char *name)
{
iImageLoader *imgloader = QUERY_PLUGIN(sys, iImageLoader);
iDataBuffer *buf = VFS->ReadFile (name);
if(!buf) printf("Could not read file %s\n", name);
iImage *image = imgloader->Load(buf->GetUint8 (), buf->GetSize (),
txtmgr->GetTextureFormat ());
if(!image) printf("Could not load image %s\n", name);
iTextureHandle *handle = txtmgr->RegisterTexture(image, CS_TEXTURE_2D |
CS_TEXTURE_3D);
if(!handle) printf("Could not register texture %s\n", name);
csIsoMaterial *material = new csIsoMaterial(handle);
iMaterialHandle *math = txtmgr->RegisterMaterial(material);
buf->DecRef();
imgloader->DecRef();
return math;
}
/// helper grid change callback for the player sprite - to move the light
static void PlayerGridChange(iIsoSprite *sprite, void *mydata)
{
IsoTest* app = (IsoTest*)mydata;
if(app->GetLight())
app->GetLight()->SetGrid(sprite->GetGrid());
}
bool IsoTest::Initialize (int argc, const char* const argv[],
const char *iConfigName)
{
if (!superclass::Initialize (argc, argv, iConfigName))
return false;
// Find the pointer to engine plugin
engine = QUERY_PLUGIN (this, iIsoEngine);
if (!engine)
{
Printf (MSG_FATAL_ERROR, "No IsoEngine plugin!\n");
abort ();
}
// Open the main system. This will open all the previously loaded plug-ins.
if (!Open ("IsoTest Crystal Space Application"))
{
Printf (MSG_FATAL_ERROR, "Error opening system!\n");
cleanup ();
exit (1);
}
iFontServer *fsvr = QUERY_PLUGIN(this, iFontServer);
font = fsvr->LoadFont(CSFONT_LARGE);
fsvr->DecRef();
// Setup the texture manager
iTextureManager* txtmgr = G3D->GetTextureManager ();
txtmgr->SetVerbose (true);
// Initialize the texture manager
txtmgr->ResetPalette ();
// Allocate a uniformly distributed in R,G,B space palette for console
// The console will crash on some platforms if this isn't initialize properly
int r,g,b;
for (r = 0; r < 8; r++)
for (g = 0; g < 8; g++)
for (b = 0; b < 4; b++)
txtmgr->ReserveColor (r * 32, g * 32, b * 64);
txtmgr->SetPalette ();
// Some commercials...
Printf (MSG_INITIALIZATION,
"IsoTest Crystal Space Application version 0.1.\n");
// Create our world.
Printf (MSG_INITIALIZATION, "Creating world!...\n");
Printf (MSG_INITIALIZATION, "--------------------------------------\n");
// create our world to play in, and a view on it.
world = engine->CreateWorld();
view = engine->CreateView(world);
iMaterialHandle *math1 = LoadTexture(this, txtmgr, VFS,
"/lib/std/stone4.gif");
iMaterialHandle *math2 = LoadTexture(this, txtmgr, VFS,
"/lib/std/mystone2.gif");
iMaterialHandle *snow = LoadTexture(this, txtmgr, VFS,
"/lib/std/snow.jpg");
// create a rectangular grid in the world
// the grid is 10 units wide (from 0..10 in the +z direction)
// the grid is 20 units tall (from 0..20 in the +x direction)
iIsoGrid *grid = world->CreateGrid(10, 20);
grid->SetSpace(0, 0, -1.0, +10.0);
int multx = 2, multy = 2;
grid->SetGroundMult(multx, multy);
iIsoSprite *sprite = NULL;
int x,y, mx,my;
for(y=0; y<20; y++)
for(x=0; x<10; x++)
{
// put tiles on the floor
sprite = engine->CreateFloorSprite(csVector3(y,0,x), 1.0, 1.0);
if((x+y)&1)
sprite->SetMaterialHandle(math1);
else sprite->SetMaterialHandle(math2);
world->AddSprite(sprite);
for(my=0; my<multy; my++)
for(mx=0; mx<multx; mx++)
grid->SetGroundValue(x, y, mx, my, 0.0);
}
// add the player sprite to the world
csVector3 startpos(10,0,5);
player = engine->CreateFrontSprite(startpos, 1.0, 4.0);
player->SetMaterialHandle(snow);
world->AddSprite(player);
player->SetGridChangeCallback(PlayerGridChange, (void*)this);
// add a light to the scene.
iIsoLight *scenelight = engine->CreateLight();
scenelight->SetPosition(csVector3(3,3,6));
scenelight->SetGrid(grid);
scenelight->SetRadius(4.0);
scenelight->SetColor(csColor(0.0, 0.4, 1.0));
// add a light for the player, above players head.
light = engine->CreateLight();
light->SetPosition(startpos+csVector3(0,5,0));
light->SetGrid(grid);
light->SetRadius(5.0);
light->SetColor(csColor(1.0, 0.4, 0.2));
// make a bump to cast shadows
for(my=0; my<multy; my++)
for(mx=0; mx<multx; mx++)
grid->SetGroundValue(5, 15, mx, my, 4.0);
sprite = engine->CreateFloorSprite(csVector3(15,4,5), 1.0, 1.0);
sprite->SetMaterialHandle(math1);
world->AddSprite(sprite);
for(my=0; my<4; my++)
{
sprite = engine->CreateXWallSprite(csVector3(15,my,5), 1.0, 1.0);
sprite->SetMaterialHandle(math1);
world->AddSprite(sprite);
sprite = engine->CreateZWallSprite(csVector3(16,my,5), 1.0, 1.0);
sprite->SetMaterialHandle(math1);
world->AddSprite(sprite);
}
for(mx=0; mx<8; mx++)
{
sprite = engine->CreateFloorSprite(csVector3(5,4,2+mx), 1.0, 1.0);
sprite->SetMaterialHandle(math1);
world->AddSprite(sprite);
}
for(my=0; my<4; my++)
{
sprite = engine->CreateXWallSprite(csVector3(5,my,2), 1.0, 1.0);
sprite->SetMaterialHandle(math1);
world->AddSprite(sprite);
sprite = engine->CreateXWallSprite(csVector3(5,my,7), 1.0, 1.0);
sprite->SetMaterialHandle(math2);
world->AddSprite(sprite);
for(mx=0; mx<3; mx++)
{
sprite = engine->CreateZWallSprite(csVector3(6,my,2+mx), 1.0, 1.0);
sprite->SetMaterialHandle(math1);
world->AddSprite(sprite);
sprite = engine->CreateZWallSprite(csVector3(6,my,7+mx), 1.0, 1.0);
sprite->SetMaterialHandle(math1);
world->AddSprite(sprite);
}
}
sprite = engine->CreateZWallSprite(csVector3(6,3,5), 1.0, 1.0);
sprite->SetMaterialHandle(math1);
world->AddSprite(sprite);
sprite = engine->CreateZWallSprite(csVector3(6,3,6), 1.0, 1.0);
sprite->SetMaterialHandle(math1);
world->AddSprite(sprite);
for(x=0; x<3; x++)
for(my=0; my<multy; my++)
for(mx=0; mx<multx; mx++)
{
grid->SetGroundValue(2+x, 5, mx, my, 4.0);
grid->SetGroundValue(7+x, 5, mx, my, 4.0);
}
//bool res = grid->GroundHitBeam(csVector3(10,1,5), csVector3(15,-2,8));
//printf("Hitbeam gave %d\n", (int)res);
//res = grid->GroundHitBeam(csVector3(10,1,5), csVector3(20,0,10));
//printf("Hitbeam gave %d\n", (int)res);
txtmgr->PrepareTextures ();
txtmgr->PrepareMaterials ();
txtmgr->SetPalette ();
// scroll view to show player position at center of screen
view->SetScroll(startpos, csVector2(G3D->GetWidth()/2, G3D->GetHeight()/2));
return true;
}
void IsoTest::NextFrame ()
{
iTextureManager* txtmgr = G3D->GetTextureManager ();
SysSystemDriver::NextFrame ();
cs_time elapsed_time, current_time;
GetElapsedTime (elapsed_time, current_time);
// keep track of fps.
static bool fpsstarted = false;
static int numframes = 0;
static int numtime = 0;
static float fps = 0.0;
if(!fpsstarted && (elapsed_time > 0))
{fpsstarted = true; fps = 1. / (float(elapsed_time)*.001);}
numtime += elapsed_time;
numframes ++;
if(numtime >= 1000)
{
fps = float(numframes) / (float(numtime)*.001);
numtime = 0;
numframes = 0;
}
// move the player and scroll the view to keep the player centered
// according to keyboard state
float speed = (elapsed_time / 1000.) * (0.10 * 20);
csVector3 playermotion(0,0,0);
if (GetKeyState (CSKEY_RIGHT)) playermotion += csVector3(0,0,speed);
if (GetKeyState (CSKEY_LEFT)) playermotion += csVector3(0,0,-speed);
if (GetKeyState (CSKEY_PGUP)) playermotion += csVector3(0,speed,0);
if (GetKeyState (CSKEY_PGDN)) playermotion += csVector3(0,-speed,0);
if (GetKeyState (CSKEY_UP)) playermotion += csVector3(speed,0,0);
if (GetKeyState (CSKEY_DOWN)) playermotion += csVector3(-speed,0,0);
if(!playermotion.IsZero())
{
player->MovePosition(playermotion);
view->MoveScroll(playermotion);
light->SetPosition(player->GetPosition()+csVector3(0,5,0));
}
// Tell 3D driver we're going to display 3D things.
if (!G3D->BeginDraw (engine->GetBeginDrawFlags () | CSDRAW_3DGRAPHICS
| CSDRAW_CLEARSCREEN ))
return;
view->Draw ();
// Start drawing 2D graphics.
if (!G3D->BeginDraw (CSDRAW_2DGRAPHICS)) return;
char buf[255];
sprintf(buf, "FPS: %g loc(%g,%g,%g)", fps, player->GetPosition().x,
player->GetPosition().y, player->GetPosition().z);
G2D->Write(font, 10, G2D->GetHeight() - 20, txtmgr->FindRGB(255,255,255),
-1, buf);
// Drawing code ends here.
G3D->FinishDraw ();
// Print the final output.
G3D->Print (NULL);
}
bool IsoTest::HandleEvent (iEvent &Event)
{
if (superclass::HandleEvent (Event))
return true;
if ((Event.Type == csevKeyDown) && (Event.Key.Code == CSKEY_ESC))
{
Shutdown = true;
return true;
}
if ((Event.Type == csevKeyDown) && (Event.Key.Code == '\t'))
{
static float settings[][5] = {
// scale should be *displayheight.
//xscale, yscale, zscale, zskew, xskew
{1./16., 1./16., 1./16., 1.0, 1.0},
{1./16., 1./16., 1./16., 0.6, 0.6},
{1./16., 1./16., 1./16., 0.5, 0.5},
{1./40., 1./40., 1./40., 0.5, 0.5},
{1./8., 1./8., 1./8., 0.5, 0.5},
};
static int nrsettings = 5;
static int setting = 0;
setting = (setting+1)%nrsettings;
float h = engine->GetG3D()->GetHeight();
view->SetAxes( h*settings[setting][0], h*settings[setting][1],
h*settings[setting][2], settings[setting][3], settings[setting][4]);
view->SetScroll(player->GetPosition(),
csVector2(G3D->GetWidth()/2, G3D->GetHeight()/2));
return true;
}
return false;
}
/*---------------------------------------------------------------------*
* Main function
*---------------------------------------------------------------------*/
int main (int argc, char* argv[])
{
srand (time (NULL));
// Create our main class.
System = new IsoTest ();
// We want at least the minimal set of plugins
System->RequestPlugin ("crystalspace.kernel.vfs:VFS");
System->RequestPlugin ("crystalspace.font.server.default:FontServer");
System->RequestPlugin ("crystalspace.image.loader:ImageLoader");
System->RequestPlugin ("crystalspace.graphics3d.software:VideoDriver");
System->RequestPlugin ("crystalspace.console.output.standard:Console.Output");
System->RequestPlugin ("crystalspace.engine.iso:Engine.Iso");
// Initialize the main system. This will load all needed plug-ins
// (3D, 2D, network, sound, ...) and initialize them.
if (!System->Initialize (argc, argv, NULL))
{
System->Printf (MSG_FATAL_ERROR, "Error initializing system!\n");
cleanup ();
exit (1);
}
// Main loop.
System->Loop ();
// Cleanup.
cleanup ();
return 0;
}
<|endoftext|> |
<commit_before>#ifndef OPENGL_HPP
#define OPENGL_HPP
#include <fstream> // ifstream
#include <iostream> // cerr
#include <unordered_map>
#include <X11/Xlib.h>
#include <GL/gl.h>
#include <GL/glx.h>
namespace x {
namespace gl {
class api {
public:
api(void)
{
glXBindTexImageEXT = (PFNGLXBINDTEXIMAGEEXTPROC)
glXGetProcAddress((const GLubyte *)"glXBindTexImageEXT");
glXReleaseTexImageEXT = (PFNGLXRELEASETEXIMAGEEXTPROC)
glXGetProcAddress((const GLubyte *)"glXReleaseTexImageEXT");
glXGetFBConfigs = (PFNGLXGETFBCONFIGSPROC)
glXGetProcAddress((const GLubyte *)"glXGetFBConfigs");
glCreateShader = (PFNGLCREATESHADERPROC)
glXGetProcAddress((const GLubyte *)"glCreateShader");
glDeleteShader = (PFNGLDELETESHADERPROC)
glXGetProcAddress((const GLubyte *)"glDeleteShader");
glShaderSource = (PFNGLSHADERSOURCEPROC)
glXGetProcAddress((const GLubyte *)"glShaderSource");
glCompileShader = (PFNGLCOMPILESHADERPROC)
glXGetProcAddress((const GLubyte *)"glCompileShader");
glCreateProgram = (PFNGLCREATEPROGRAMPROC)
glXGetProcAddress((const GLubyte *)"glCreateProgram");
glDeleteProgram = (PFNGLDELETEPROGRAMPROC)
glXGetProcAddress((const GLubyte *)"glDeleteProgram");
glAttachShader = (PFNGLATTACHSHADERPROC)
glXGetProcAddress((const GLubyte *)"glAttachShader");
glDetachShader = (PFNGLDETACHSHADERPROC)
glXGetProcAddress((const GLubyte *)"glDetachShader");
glLinkProgram = (PFNGLLINKPROGRAMPROC)
glXGetProcAddress((const GLubyte *)"glLinkProgram");
glUseProgram = (PFNGLUSEPROGRAMPROC)
glXGetProcAddress((const GLubyte *)"glUseProgram");
glGetProgramInfoLog = (PFNGLGETPROGRAMINFOLOGPROC)
glXGetProcAddress((const GLubyte *)"glGetProgramInfoLog");
glGetShaderInfoLog = (PFNGLGETSHADERINFOLOGPROC)
glXGetProcAddress((const GLubyte *)"glGetShaderInfoLog");
glGenerateMipmapEXT = (PFNGLGENERATEMIPMAPEXTPROC)
glXGetProcAddress((const GLubyte *)"glGenerateMipmapEXT");
glActiveTextureEXT = (PFNGLACTIVETEXTUREPROC)
glXGetProcAddress((const GLubyte *)"glActiveTexture");
glBlendFuncSeparate = (PFNGLBLENDFUNCSEPARATEPROC)
glXGetProcAddress((const GLubyte *)"glBlendFuncSeparate");
glGenSamplers = (PFNGLGENSAMPLERSPROC)
glXGetProcAddress((const GLubyte *)"glGenSamplers");
glDeleteSamplers = (PFNGLDELETESAMPLERSPROC)
glXGetProcAddressARB((const GLubyte *)"glDeleteSamplers");
glBindSampler = (PFNGLBINDSAMPLERPROC)
glXGetProcAddressARB((const GLubyte *)"glBindSampler");
glUniform1fEXT = (PFNGLUNIFORM1FPROC)
glXGetProcAddress((const GLubyte *)"glUniform1f");
glUniform2fEXT = (PFNGLUNIFORM2FPROC)
glXGetProcAddress((const GLubyte *)"glUniform2f");
glUniform3fEXT = (PFNGLUNIFORM3FPROC)
glXGetProcAddress((const GLubyte *)"glUniform3f");
glUniform4fEXT = (PFNGLUNIFORM4FPROC)
glXGetProcAddress((const GLubyte *)"glUniform4f");
glUniform1iEXT = (PFNGLUNIFORM1IPROC)
glXGetProcAddress((const GLubyte *)"glUniform1i");
glUniform2iEXT = (PFNGLUNIFORM2IPROC)
glXGetProcAddress((const GLubyte *)"glUniform2i");
glUniform3iEXT = (PFNGLUNIFORM3IPROC)
glXGetProcAddress((const GLubyte *)"glUniform3i");
glUniform4iEXT = (PFNGLUNIFORM4IPROC)
glXGetProcAddress((const GLubyte *)"glUniform4i");
glGetUniformLocationEXT = (PFNGLGETUNIFORMLOCATIONPROC)
glXGetProcAddress((const GLubyte *)"glGetUniformLocation");
glGetUniformBlockIndex = (PFNGLGETUNIFORMBLOCKINDEXPROC)
glXGetProcAddress((const GLubyte *)"glGetUniformBlockIndex");
glUniformBlockBinding = (PFNGLUNIFORMBLOCKBINDINGPROC)
glXGetProcAddress((const GLubyte *)"glUniformBlockBinding");
}
PFNGLXBINDTEXIMAGEEXTPROC glXBindTexImageEXT = 0;
PFNGLXRELEASETEXIMAGEEXTPROC glXReleaseTexImageEXT = 0;
PFNGLXGETFBCONFIGSPROC glXGetFBConfigs = 0;
PFNGLCREATESHADERPROC glCreateShader = 0;
PFNGLDELETESHADERPROC glDeleteShader = 0;
PFNGLSHADERSOURCEPROC glShaderSource = 0;
PFNGLCOMPILESHADERPROC glCompileShader = 0;
PFNGLCREATEPROGRAMPROC glCreateProgram = 0;
PFNGLDELETEPROGRAMPROC glDeleteProgram = 0;
PFNGLATTACHSHADERPROC glAttachShader = 0;
PFNGLDETACHSHADERPROC glDetachShader = 0;
PFNGLLINKPROGRAMPROC glLinkProgram = 0;
PFNGLUSEPROGRAMPROC glUseProgram = 0;
PFNGLGETPROGRAMINFOLOGPROC glGetProgramInfoLog = 0;
PFNGLGETSHADERINFOLOGPROC glGetShaderInfoLog = 0;
PFNGLGENERATEMIPMAPEXTPROC glGenerateMipmapEXT = 0;
PFNGLACTIVETEXTUREPROC glActiveTextureEXT = 0;
PFNGLBLENDFUNCSEPARATEPROC glBlendFuncSeparate = 0;
PFNGLGENSAMPLERSPROC glGenSamplers = 0;
PFNGLDELETESAMPLERSPROC glDeleteSamplers = 0;
PFNGLBINDSAMPLERPROC glBindSampler = 0;
PFNGLUNIFORM1FPROC glUniform1fEXT = 0;
PFNGLUNIFORM2FPROC glUniform2fEXT = 0;
PFNGLUNIFORM3FPROC glUniform3fEXT = 0;
PFNGLUNIFORM4FPROC glUniform4fEXT = 0;
PFNGLUNIFORM1IPROC glUniform1iEXT = 0;
PFNGLUNIFORM2IPROC glUniform2iEXT = 0;
PFNGLUNIFORM3IPROC glUniform3iEXT = 0;
PFNGLUNIFORM4IPROC glUniform4iEXT = 0;
PFNGLGETUNIFORMLOCATIONPROC glGetUniformLocationEXT = 0;
PFNGLGETUNIFORMBLOCKINDEXPROC glGetUniformBlockIndex = 0;
PFNGLUNIFORMBLOCKBINDINGPROC glUniformBlockBinding = 0;
}; // class api
class context {
public:
context(const api & api, Display * const dpy, int screen = None)
: m_api(api), m_dpy(dpy)
{
if (screen == None) screen = DefaultScreen(dpy);
m_xfb_configs =
glXChooseFBConfig(m_dpy, screen, m_pixmap_config, &m_xfb_nconfigs);
GLint gl_vi_attr[] = {
GLX_RGBA, GLX_DEPTH_SIZE, 24, GLX_DOUBLEBUFFER, None };
XVisualInfo * vi = glXChooseVisual(m_dpy, screen, gl_vi_attr);
m_context = glXCreateContext(m_dpy, vi, NULL, GL_TRUE);
delete vi;
}
~context(void)
{
glXDestroyContext(m_dpy, m_context);
if (m_xfb_configs != NULL) {
delete m_xfb_configs;
}
}
const Drawable & drawable(void)
{
return m_drawable;
}
void drawable(const Drawable & drawable)
{
m_drawable = drawable;
}
const GLuint & program(const std::string & name)
{
return m_programs.at(name).first;
}
const GLuint & texture(unsigned int id)
{
return m_textures.at(id);
}
const GLXPixmap & pixmap(unsigned int id)
{
return m_pixmaps.at(id);
}
context & active_texture(unsigned int id)
{
glActiveTexture(GL_TEXTURE0 + id);
glEnable(GL_TEXTURE_2D);
try {
glBindTexture(GL_TEXTURE_2D, m_textures.at(id));
} catch (...) {}
return *this;
}
template<typename ... FS>
context & texture(unsigned int id, FS ... fs)
{
glActiveTexture(GL_TEXTURE0 + id);
glEnable(GL_TEXTURE_2D);
try {
glBindTexture(GL_TEXTURE_2D, m_textures.at(id));
// specialise unfold here or object copies!
unfold<const GLuint &, FS ...>(m_textures.at(id), fs ...);
} catch (...) {}
glBindTexture(GL_TEXTURE_2D, 0);
glDisable(GL_TEXTURE_2D);
glActiveTexture(GL_TEXTURE0);
return *this;
}
template<typename ... FS>
context & pixmap(unsigned int id, FS ... fs)
{
try {
// specialise unfold here or object copies!
unfold<const GLXPixmap &, FS ...>(m_pixmaps.at(id), fs ...);
} catch (...) {}
return *this;
}
template<typename ... FS>
context & run(FS ... fs)
{
if (m_drawable != None) {
glXMakeCurrent(m_dpy, m_drawable, m_context);
// specialise unfold here or object copies!
unfold<context &, FS ...>(*this, fs ...);
glXMakeCurrent(m_dpy, None, NULL);
}
return *this;
}
// load shader
context & load(const std::string & filename, const std::string & name)
{
std::ifstream file(filename);
std::string shader_source_str((std::istreambuf_iterator<char>(file)),
std::istreambuf_iterator<char>());
file.close();
const GLchar * shader_source[] = { shader_source_str.c_str() };
const GLint shader_source_len[] = { (GLint)(shader_source_str.length()) };
GLsizei log_length = 0, max_len = 1024;
GLchar log_buffer[max_len];
shader_t s = m_api.glCreateShader(GL_FRAGMENT_SHADER);
m_api.glShaderSource(s, 1, shader_source, shader_source_len);
m_api.glCompileShader(s);
m_api.glGetShaderInfoLog(s, max_len, &log_length, log_buffer);
if (log_length > 0) {
std::cerr << "Shader compilation for " << name << " failed:" << std::endl
<< log_buffer << std::endl;
}
program_t p = m_api.glCreateProgram();
m_api.glAttachShader(p, s);
m_api.glLinkProgram(p);
m_api.glGetProgramInfoLog(p, max_len, &log_length, log_buffer);
if (log_length > 0) {
std::cerr << "p creation for " << name << " failed:" << std::endl
<< log_buffer << std::endl;
}
m_programs[name] = { p, s };
return *this;
}
// load texture
context & load(unsigned int id, const Pixmap & pixmap, int depth)
{
try {
m_api.glXReleaseTexImageEXT(m_dpy, m_pixmaps.at(id), GLX_FRONT_EXT);
glXDestroyGLXPixmap(m_dpy, m_pixmaps.at(id));
m_pixmaps.erase(id);
glDeleteTextures(1, &m_textures.at(id));
m_textures.erase(id);
} catch (...) {}
if (pixmap == None || m_xfb_nconfigs == 0) {
return *this;
}
auto format = [&](void)
{
switch (depth) {
case 24: return GLX_TEXTURE_FORMAT_RGB_EXT;
case 32: return GLX_TEXTURE_FORMAT_RGBA_EXT;
default: return GLX_TEXTURE_FORMAT_NONE_EXT;
}
};
const int attr[] = {
GLX_TEXTURE_TARGET_EXT, GLX_TEXTURE_2D_EXT,
GLX_TEXTURE_FORMAT_EXT, format(),
None
};
glGenTextures(1, &m_textures[id]);
m_pixmaps[id] = glXCreatePixmap(m_dpy, m_xfb_configs[0], pixmap, attr);
texture(id, [&, this](const GLuint &)
{
m_api.glXBindTexImageEXT(m_dpy, m_pixmaps[id], GLX_FRONT_EXT, NULL);
});
return *this;
}
private:
typedef GLuint shader_t;
typedef GLuint program_t;
const api & m_api;
Display * m_dpy;
Drawable m_drawable;
const int m_pixmap_config[3] = { GLX_BIND_TO_TEXTURE_RGBA_EXT, True, None };
int m_xfb_nconfigs = 0;
GLXFBConfig * m_xfb_configs = NULL;
GLXContext m_context = None;
std::unordered_map<unsigned int, GLuint> m_textures;
std::unordered_map<unsigned int, GLXPixmap> m_pixmaps;
std::unordered_map<std::string, std::pair<program_t, shader_t>> m_programs;
// private, to disallow copies
context(const context & ctx) : m_api(ctx.m_api) {}
context & operator=(const context &) { return *this; }
// careful! A a can cause object copies!
template<typename A, typename F, typename ... FS>
void unfold(A a, F f, FS ... fs)
{
f(a);
unfold(a, fs ...);
}
template<typename A, typename F>
void unfold(A a, F f)
{
f(a);
}
}; // class context
}; // namespace gl
}; // namespace x
#endif // OPENGL_HPP
<commit_msg>Hooray for =delete!<commit_after>#ifndef OPENGL_HPP
#define OPENGL_HPP
#include <fstream> // ifstream
#include <iostream> // cerr
#include <unordered_map>
#include <X11/Xlib.h>
#include <GL/gl.h>
#include <GL/glx.h>
namespace x {
namespace gl {
class api {
public:
api(void)
{
glXBindTexImageEXT = (PFNGLXBINDTEXIMAGEEXTPROC)
glXGetProcAddress((const GLubyte *)"glXBindTexImageEXT");
glXReleaseTexImageEXT = (PFNGLXRELEASETEXIMAGEEXTPROC)
glXGetProcAddress((const GLubyte *)"glXReleaseTexImageEXT");
glXGetFBConfigs = (PFNGLXGETFBCONFIGSPROC)
glXGetProcAddress((const GLubyte *)"glXGetFBConfigs");
glCreateShader = (PFNGLCREATESHADERPROC)
glXGetProcAddress((const GLubyte *)"glCreateShader");
glDeleteShader = (PFNGLDELETESHADERPROC)
glXGetProcAddress((const GLubyte *)"glDeleteShader");
glShaderSource = (PFNGLSHADERSOURCEPROC)
glXGetProcAddress((const GLubyte *)"glShaderSource");
glCompileShader = (PFNGLCOMPILESHADERPROC)
glXGetProcAddress((const GLubyte *)"glCompileShader");
glCreateProgram = (PFNGLCREATEPROGRAMPROC)
glXGetProcAddress((const GLubyte *)"glCreateProgram");
glDeleteProgram = (PFNGLDELETEPROGRAMPROC)
glXGetProcAddress((const GLubyte *)"glDeleteProgram");
glAttachShader = (PFNGLATTACHSHADERPROC)
glXGetProcAddress((const GLubyte *)"glAttachShader");
glDetachShader = (PFNGLDETACHSHADERPROC)
glXGetProcAddress((const GLubyte *)"glDetachShader");
glLinkProgram = (PFNGLLINKPROGRAMPROC)
glXGetProcAddress((const GLubyte *)"glLinkProgram");
glUseProgram = (PFNGLUSEPROGRAMPROC)
glXGetProcAddress((const GLubyte *)"glUseProgram");
glGetProgramInfoLog = (PFNGLGETPROGRAMINFOLOGPROC)
glXGetProcAddress((const GLubyte *)"glGetProgramInfoLog");
glGetShaderInfoLog = (PFNGLGETSHADERINFOLOGPROC)
glXGetProcAddress((const GLubyte *)"glGetShaderInfoLog");
glGenerateMipmapEXT = (PFNGLGENERATEMIPMAPEXTPROC)
glXGetProcAddress((const GLubyte *)"glGenerateMipmapEXT");
glActiveTextureEXT = (PFNGLACTIVETEXTUREPROC)
glXGetProcAddress((const GLubyte *)"glActiveTexture");
glBlendFuncSeparate = (PFNGLBLENDFUNCSEPARATEPROC)
glXGetProcAddress((const GLubyte *)"glBlendFuncSeparate");
glGenSamplers = (PFNGLGENSAMPLERSPROC)
glXGetProcAddress((const GLubyte *)"glGenSamplers");
glDeleteSamplers = (PFNGLDELETESAMPLERSPROC)
glXGetProcAddressARB((const GLubyte *)"glDeleteSamplers");
glBindSampler = (PFNGLBINDSAMPLERPROC)
glXGetProcAddressARB((const GLubyte *)"glBindSampler");
glUniform1fEXT = (PFNGLUNIFORM1FPROC)
glXGetProcAddress((const GLubyte *)"glUniform1f");
glUniform2fEXT = (PFNGLUNIFORM2FPROC)
glXGetProcAddress((const GLubyte *)"glUniform2f");
glUniform3fEXT = (PFNGLUNIFORM3FPROC)
glXGetProcAddress((const GLubyte *)"glUniform3f");
glUniform4fEXT = (PFNGLUNIFORM4FPROC)
glXGetProcAddress((const GLubyte *)"glUniform4f");
glUniform1iEXT = (PFNGLUNIFORM1IPROC)
glXGetProcAddress((const GLubyte *)"glUniform1i");
glUniform2iEXT = (PFNGLUNIFORM2IPROC)
glXGetProcAddress((const GLubyte *)"glUniform2i");
glUniform3iEXT = (PFNGLUNIFORM3IPROC)
glXGetProcAddress((const GLubyte *)"glUniform3i");
glUniform4iEXT = (PFNGLUNIFORM4IPROC)
glXGetProcAddress((const GLubyte *)"glUniform4i");
glGetUniformLocationEXT = (PFNGLGETUNIFORMLOCATIONPROC)
glXGetProcAddress((const GLubyte *)"glGetUniformLocation");
glGetUniformBlockIndex = (PFNGLGETUNIFORMBLOCKINDEXPROC)
glXGetProcAddress((const GLubyte *)"glGetUniformBlockIndex");
glUniformBlockBinding = (PFNGLUNIFORMBLOCKBINDINGPROC)
glXGetProcAddress((const GLubyte *)"glUniformBlockBinding");
}
PFNGLXBINDTEXIMAGEEXTPROC glXBindTexImageEXT = 0;
PFNGLXRELEASETEXIMAGEEXTPROC glXReleaseTexImageEXT = 0;
PFNGLXGETFBCONFIGSPROC glXGetFBConfigs = 0;
PFNGLCREATESHADERPROC glCreateShader = 0;
PFNGLDELETESHADERPROC glDeleteShader = 0;
PFNGLSHADERSOURCEPROC glShaderSource = 0;
PFNGLCOMPILESHADERPROC glCompileShader = 0;
PFNGLCREATEPROGRAMPROC glCreateProgram = 0;
PFNGLDELETEPROGRAMPROC glDeleteProgram = 0;
PFNGLATTACHSHADERPROC glAttachShader = 0;
PFNGLDETACHSHADERPROC glDetachShader = 0;
PFNGLLINKPROGRAMPROC glLinkProgram = 0;
PFNGLUSEPROGRAMPROC glUseProgram = 0;
PFNGLGETPROGRAMINFOLOGPROC glGetProgramInfoLog = 0;
PFNGLGETSHADERINFOLOGPROC glGetShaderInfoLog = 0;
PFNGLGENERATEMIPMAPEXTPROC glGenerateMipmapEXT = 0;
PFNGLACTIVETEXTUREPROC glActiveTextureEXT = 0;
PFNGLBLENDFUNCSEPARATEPROC glBlendFuncSeparate = 0;
PFNGLGENSAMPLERSPROC glGenSamplers = 0;
PFNGLDELETESAMPLERSPROC glDeleteSamplers = 0;
PFNGLBINDSAMPLERPROC glBindSampler = 0;
PFNGLUNIFORM1FPROC glUniform1fEXT = 0;
PFNGLUNIFORM2FPROC glUniform2fEXT = 0;
PFNGLUNIFORM3FPROC glUniform3fEXT = 0;
PFNGLUNIFORM4FPROC glUniform4fEXT = 0;
PFNGLUNIFORM1IPROC glUniform1iEXT = 0;
PFNGLUNIFORM2IPROC glUniform2iEXT = 0;
PFNGLUNIFORM3IPROC glUniform3iEXT = 0;
PFNGLUNIFORM4IPROC glUniform4iEXT = 0;
PFNGLGETUNIFORMLOCATIONPROC glGetUniformLocationEXT = 0;
PFNGLGETUNIFORMBLOCKINDEXPROC glGetUniformBlockIndex = 0;
PFNGLUNIFORMBLOCKBINDINGPROC glUniformBlockBinding = 0;
}; // class api
class context {
public:
context(const api & api, Display * const dpy, int screen = None)
: m_api(api), m_dpy(dpy)
{
if (screen == None) screen = DefaultScreen(dpy);
m_xfb_configs =
glXChooseFBConfig(m_dpy, screen, m_pixmap_config, &m_xfb_nconfigs);
GLint gl_vi_attr[] = {
GLX_RGBA, GLX_DEPTH_SIZE, 24, GLX_DOUBLEBUFFER, None };
XVisualInfo * vi = glXChooseVisual(m_dpy, screen, gl_vi_attr);
m_context = glXCreateContext(m_dpy, vi, NULL, GL_TRUE);
delete vi;
}
~context(void)
{
glXDestroyContext(m_dpy, m_context);
if (m_xfb_configs != NULL) {
delete m_xfb_configs;
}
}
context(const context & ctx) = delete;
context & operator=(const context &) = delete;
const Drawable & drawable(void)
{
return m_drawable;
}
void drawable(const Drawable & drawable)
{
m_drawable = drawable;
}
const GLuint & program(const std::string & name)
{
return m_programs.at(name).first;
}
const GLuint & texture(unsigned int id)
{
return m_textures.at(id);
}
const GLXPixmap & pixmap(unsigned int id)
{
return m_pixmaps.at(id);
}
context & active_texture(unsigned int id)
{
glActiveTexture(GL_TEXTURE0 + id);
glEnable(GL_TEXTURE_2D);
try {
glBindTexture(GL_TEXTURE_2D, m_textures.at(id));
} catch (...) {}
return *this;
}
template<typename ... FS>
context & texture(unsigned int id, FS ... fs)
{
glActiveTexture(GL_TEXTURE0 + id);
glEnable(GL_TEXTURE_2D);
try {
glBindTexture(GL_TEXTURE_2D, m_textures.at(id));
// specialise unfold here or object copies!
unfold<const GLuint &, FS ...>(m_textures.at(id), fs ...);
} catch (...) {}
glBindTexture(GL_TEXTURE_2D, 0);
glDisable(GL_TEXTURE_2D);
glActiveTexture(GL_TEXTURE0);
return *this;
}
template<typename ... FS>
context & pixmap(unsigned int id, FS ... fs)
{
try {
// specialise unfold here or object copies!
unfold<const GLXPixmap &, FS ...>(m_pixmaps.at(id), fs ...);
} catch (...) {}
return *this;
}
template<typename ... FS>
context & run(FS ... fs)
{
if (m_drawable != None) {
glXMakeCurrent(m_dpy, m_drawable, m_context);
// specialise unfold here or object copies!
unfold<context &, FS ...>(*this, fs ...);
glXMakeCurrent(m_dpy, None, NULL);
}
return *this;
}
// load shader
context & load(const std::string & filename, const std::string & name)
{
std::ifstream file(filename);
std::string shader_source_str((std::istreambuf_iterator<char>(file)),
std::istreambuf_iterator<char>());
file.close();
const GLchar * shader_source[] = { shader_source_str.c_str() };
const GLint shader_source_len[] = { (GLint)(shader_source_str.length()) };
GLsizei log_length = 0, max_len = 1024;
GLchar log_buffer[max_len];
shader_t s = m_api.glCreateShader(GL_FRAGMENT_SHADER);
m_api.glShaderSource(s, 1, shader_source, shader_source_len);
m_api.glCompileShader(s);
m_api.glGetShaderInfoLog(s, max_len, &log_length, log_buffer);
if (log_length > 0) {
std::cerr << "Shader compilation for " << name << " failed:" << std::endl
<< log_buffer << std::endl;
}
program_t p = m_api.glCreateProgram();
m_api.glAttachShader(p, s);
m_api.glLinkProgram(p);
m_api.glGetProgramInfoLog(p, max_len, &log_length, log_buffer);
if (log_length > 0) {
std::cerr << "p creation for " << name << " failed:" << std::endl
<< log_buffer << std::endl;
}
m_programs[name] = { p, s };
return *this;
}
// load texture
context & load(unsigned int id, const Pixmap & pixmap, int depth)
{
try {
m_api.glXReleaseTexImageEXT(m_dpy, m_pixmaps.at(id), GLX_FRONT_EXT);
glXDestroyGLXPixmap(m_dpy, m_pixmaps.at(id));
m_pixmaps.erase(id);
glDeleteTextures(1, &m_textures.at(id));
m_textures.erase(id);
} catch (...) {}
if (pixmap == None || m_xfb_nconfigs == 0) {
return *this;
}
auto format = [&](void)
{
switch (depth) {
case 24: return GLX_TEXTURE_FORMAT_RGB_EXT;
case 32: return GLX_TEXTURE_FORMAT_RGBA_EXT;
default: return GLX_TEXTURE_FORMAT_NONE_EXT;
}
};
const int attr[] = {
GLX_TEXTURE_TARGET_EXT, GLX_TEXTURE_2D_EXT,
GLX_TEXTURE_FORMAT_EXT, format(),
None
};
glGenTextures(1, &m_textures[id]);
m_pixmaps[id] = glXCreatePixmap(m_dpy, m_xfb_configs[0], pixmap, attr);
texture(id, [&, this](const GLuint &)
{
m_api.glXBindTexImageEXT(m_dpy, m_pixmaps[id], GLX_FRONT_EXT, NULL);
});
return *this;
}
private:
typedef GLuint shader_t;
typedef GLuint program_t;
const api & m_api;
Display * m_dpy;
Drawable m_drawable;
const int m_pixmap_config[3] = { GLX_BIND_TO_TEXTURE_RGBA_EXT, True, None };
int m_xfb_nconfigs = 0;
GLXFBConfig * m_xfb_configs = NULL;
GLXContext m_context = None;
std::unordered_map<unsigned int, GLuint> m_textures;
std::unordered_map<unsigned int, GLXPixmap> m_pixmaps;
std::unordered_map<std::string, std::pair<program_t, shader_t>> m_programs;
// careful! A a can cause object copies!
template<typename A, typename F, typename ... FS>
void unfold(A a, F f, FS ... fs)
{
f(a);
unfold(a, fs ...);
}
template<typename A, typename F>
void unfold(A a, F f)
{
f(a);
}
}; // class context
}; // namespace gl
}; // namespace x
#endif // OPENGL_HPP
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.