text stringlengths 54 60.6k |
|---|
<commit_before><commit_msg>Add the answer to the fifth question of Chapter 2<commit_after><|endoftext|> |
<commit_before>/**************************************************************************
*
* Copyright 2014 Valve Software. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*************************************************************************/
extern "C" {
#include "glv_trace_packet_utils.h"
#include "glvtrace_xgl_packet_id.h"
}
#include "glvdebug_xgl_settings.h"
#include "glvdebug_xgl_qcontroller.h"
#include <assert.h>
#include <QFileInfo>
#include <QWidget>
#include <QToolButton>
#include <QCoreApplication>
#include <QProcess>
#include "glvdebug_view.h"
#include "glvreplay_seq.h"
glvdebug_xgl_QController::glvdebug_xgl_QController()
: m_pSvgDiagram(NULL),
m_pSvgDiagramTabIndex(-1),
m_pReplayWidget(NULL),
m_pTraceFileModel(NULL)
{
initialize_default_settings();
glv_SettingGroup_reset_defaults(&g_xglDebugSettingGroup);
}
glvdebug_xgl_QController::~glvdebug_xgl_QController()
{
}
glv_trace_packet_header* glvdebug_xgl_QController::InterpretTracePacket(glv_trace_packet_header* pHeader)
{
// Attempt to interpret the packet as an XGL packet
glv_trace_packet_header* pInterpretedHeader = interpret_trace_packet_xgl(pHeader);
if (pInterpretedHeader == NULL)
{
glv_LogWarn("Unrecognized XGL packet_id: %u\n", pHeader->packet_id);
}
return pInterpretedHeader;
}
bool glvdebug_xgl_QController::LoadTraceFile(glvdebug_trace_file_info* pTraceFileInfo, glvdebug_view* pView)
{
assert(pTraceFileInfo != NULL);
assert(pView != NULL);
setView(pView);
m_pTraceFileInfo = pTraceFileInfo;
m_pReplayWidget = new glvdebug_QReplayWidget(this);
if (m_pReplayWidget != NULL)
{
// load available replayers
if (!load_replayers(pTraceFileInfo, m_pReplayWidget->GetReplayWindow()))
{
m_pView->output_error("Failed to load necessary replayers.");
delete m_pReplayWidget;
m_pReplayWidget = NULL;
}
else
{
m_pView->add_custom_state_viewer(m_pReplayWidget, "Replayer", true);
m_pReplayWidget->setEnabled(true);
connect(m_pReplayWidget, SIGNAL(ReplayStarted()), this, SLOT(onReplayStarted()));
connect(m_pReplayWidget, SIGNAL(ReplayPaused(uint64_t)), this, SLOT(onReplayPaused(uint64_t)));
connect(m_pReplayWidget, SIGNAL(ReplayContinued()), this, SLOT(onReplayContinued()));
connect(m_pReplayWidget, SIGNAL(ReplayStopped(uint64_t)), this, SLOT(onReplayStopped(uint64_t)));
connect(m_pReplayWidget, SIGNAL(ReplayFinished()), this, SLOT(onReplayFinished()));
}
}
m_pTraceFileModel = new glvdebug_xgl_QFileModel(NULL, pTraceFileInfo);
updateCallTreeBasedOnSettings();
return true;
}
void glvdebug_xgl_QController::updateCallTreeBasedOnSettings()
{
if (m_pTraceFileModel == NULL)
{
return;
}
if (g_xglDebugSettings.groupByFrame)
{
m_groupByFramesProxy.setSourceModel(m_pTraceFileModel);
m_pView->set_calltree_model(m_pTraceFileModel, &m_groupByFramesProxy);
}
else if (g_xglDebugSettings.groupByThread)
{
m_groupByThreadsProxy.setSourceModel(m_pTraceFileModel);
m_pView->set_calltree_model(m_pTraceFileModel, &m_groupByThreadsProxy);
}
else
{
m_pView->set_calltree_model(m_pTraceFileModel, NULL);
}
}
void glvdebug_xgl_QController::setStateWidgetsEnabled(bool bEnabled)
{
if(m_pSvgDiagram != NULL)
{
if(bEnabled)
{
m_pSvgDiagramTabIndex = m_pView->add_custom_state_viewer(m_pSvgDiagram, tr("SVG Diagram"), false);
}
else
{
m_pView->remove_custom_state_viewer(m_pSvgDiagramTabIndex);
m_pSvgDiagramTabIndex = -1;
}
}
}
void glvdebug_xgl_QController::onReplayStarted()
{
setStateWidgetsEnabled(false);
}
void glvdebug_xgl_QController::onReplayPaused(uint64_t packetIndex)
{
if(m_pSvgDiagram == NULL)
{
m_pSvgDiagram = new glvdebug_qsvgviewer;
if(m_pSvgDiagram != NULL)
{
setStateWidgetsEnabled(false);
}
}
if(m_pSvgDiagram != NULL)
{
// Check if DOT is available.
#if defined(PLATFORM_LINUX)
QFileInfo fileInfo(tr("/usr/bin/dot"));
#elif defined(WIN32)
// TODO: Windows path to DOT?
QFileInfo fileInfo(tr(""));
#endif
if(!fileInfo.exists() || !fileInfo.isFile())
{
m_pView->output_error("DOT not found.");
}
else
{
QProcess process;
process.start("/usr/bin/dot pipeline_dump.dot -Tsvg -o pipeline_dump.svg");
process.waitForFinished(-1);
}
if(m_pSvgDiagram->load(tr("pipeline_dump.svg")))
{
setStateWidgetsEnabled(true);
}
}
}
void glvdebug_xgl_QController::onReplayContinued()
{
setStateWidgetsEnabled(false);
}
void glvdebug_xgl_QController::onReplayStopped(uint64_t packetIndex)
{
}
void glvdebug_xgl_QController::onReplayFinished()
{
}
BOOL glvdebug_xgl_QController::PrintReplayInfoMsgs()
{
return g_xglDebugSettings.printReplayInfoMsgs;
}
BOOL glvdebug_xgl_QController::PrintReplayWarningMsgs()
{
return g_xglDebugSettings.printReplayWarningMsgs;
}
BOOL glvdebug_xgl_QController::PrintReplayErrorMsgs()
{
return g_xglDebugSettings.printReplayErrorMsgs;
}
BOOL glvdebug_xgl_QController::PauseOnReplayInfoMsg()
{
return g_xglDebugSettings.pauseOnReplayInfo;
}
BOOL glvdebug_xgl_QController::PauseOnReplayWarningMsg()
{
return g_xglDebugSettings.pauseOnReplayWarning;
}
BOOL glvdebug_xgl_QController::PauseOnReplayErrorMsg()
{
return g_xglDebugSettings.pauseOnReplayError;
}
void glvdebug_xgl_QController::onSettingsUpdated(glv_SettingGroup *pGroups, unsigned int numGroups)
{
glv_SettingGroup_Apply_Overrides(&g_xglDebugSettingGroup, pGroups, numGroups);
if (m_pReplayWidget != NULL)
{
m_pReplayWidget->OnSettingsUpdated(pGroups, numGroups);
}
updateCallTreeBasedOnSettings();
}
void glvdebug_xgl_QController::UnloadTraceFile(void)
{
if (m_pView != NULL)
{
m_pView->set_calltree_model(NULL, NULL);
m_pView = NULL;
}
if (m_pTraceFileModel != NULL)
{
delete m_pTraceFileModel;
m_pTraceFileModel = NULL;
}
if (m_pReplayWidget != NULL)
{
delete m_pReplayWidget;
m_pReplayWidget = NULL;
}
if (m_pSvgDiagram != NULL)
{
delete m_pSvgDiagram;
m_pSvgDiagram = NULL;
m_pSvgDiagramTabIndex = -1;
}
// Clean up replayers
if (m_pReplayers != NULL)
{
for (int i = 0; i < GLV_MAX_TRACER_ID_ARRAY_SIZE; i++)
{
if (m_pReplayers[i] != NULL)
{
m_pReplayers[i]->Deinitialize();
m_replayerFactory.Destroy(&m_pReplayers[i]);
}
}
}
}
<commit_msg>glvdebug: Fixed label for draw state diagram.<commit_after>/**************************************************************************
*
* Copyright 2014 Valve Software. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*************************************************************************/
extern "C" {
#include "glv_trace_packet_utils.h"
#include "glvtrace_xgl_packet_id.h"
}
#include "glvdebug_xgl_settings.h"
#include "glvdebug_xgl_qcontroller.h"
#include <assert.h>
#include <QFileInfo>
#include <QWidget>
#include <QToolButton>
#include <QCoreApplication>
#include <QProcess>
#include "glvdebug_view.h"
#include "glvreplay_seq.h"
glvdebug_xgl_QController::glvdebug_xgl_QController()
: m_pSvgDiagram(NULL),
m_pSvgDiagramTabIndex(-1),
m_pReplayWidget(NULL),
m_pTraceFileModel(NULL)
{
initialize_default_settings();
glv_SettingGroup_reset_defaults(&g_xglDebugSettingGroup);
}
glvdebug_xgl_QController::~glvdebug_xgl_QController()
{
}
glv_trace_packet_header* glvdebug_xgl_QController::InterpretTracePacket(glv_trace_packet_header* pHeader)
{
// Attempt to interpret the packet as an XGL packet
glv_trace_packet_header* pInterpretedHeader = interpret_trace_packet_xgl(pHeader);
if (pInterpretedHeader == NULL)
{
glv_LogWarn("Unrecognized XGL packet_id: %u\n", pHeader->packet_id);
}
return pInterpretedHeader;
}
bool glvdebug_xgl_QController::LoadTraceFile(glvdebug_trace_file_info* pTraceFileInfo, glvdebug_view* pView)
{
assert(pTraceFileInfo != NULL);
assert(pView != NULL);
setView(pView);
m_pTraceFileInfo = pTraceFileInfo;
m_pReplayWidget = new glvdebug_QReplayWidget(this);
if (m_pReplayWidget != NULL)
{
// load available replayers
if (!load_replayers(pTraceFileInfo, m_pReplayWidget->GetReplayWindow()))
{
m_pView->output_error("Failed to load necessary replayers.");
delete m_pReplayWidget;
m_pReplayWidget = NULL;
}
else
{
m_pView->add_custom_state_viewer(m_pReplayWidget, "Replayer", true);
m_pReplayWidget->setEnabled(true);
connect(m_pReplayWidget, SIGNAL(ReplayStarted()), this, SLOT(onReplayStarted()));
connect(m_pReplayWidget, SIGNAL(ReplayPaused(uint64_t)), this, SLOT(onReplayPaused(uint64_t)));
connect(m_pReplayWidget, SIGNAL(ReplayContinued()), this, SLOT(onReplayContinued()));
connect(m_pReplayWidget, SIGNAL(ReplayStopped(uint64_t)), this, SLOT(onReplayStopped(uint64_t)));
connect(m_pReplayWidget, SIGNAL(ReplayFinished()), this, SLOT(onReplayFinished()));
}
}
m_pTraceFileModel = new glvdebug_xgl_QFileModel(NULL, pTraceFileInfo);
updateCallTreeBasedOnSettings();
return true;
}
void glvdebug_xgl_QController::updateCallTreeBasedOnSettings()
{
if (m_pTraceFileModel == NULL)
{
return;
}
if (g_xglDebugSettings.groupByFrame)
{
m_groupByFramesProxy.setSourceModel(m_pTraceFileModel);
m_pView->set_calltree_model(m_pTraceFileModel, &m_groupByFramesProxy);
}
else if (g_xglDebugSettings.groupByThread)
{
m_groupByThreadsProxy.setSourceModel(m_pTraceFileModel);
m_pView->set_calltree_model(m_pTraceFileModel, &m_groupByThreadsProxy);
}
else
{
m_pView->set_calltree_model(m_pTraceFileModel, NULL);
}
}
void glvdebug_xgl_QController::setStateWidgetsEnabled(bool bEnabled)
{
if(m_pSvgDiagram != NULL)
{
if(bEnabled)
{
m_pSvgDiagramTabIndex = m_pView->add_custom_state_viewer(m_pSvgDiagram, tr("Draw State Diagram"), false);
}
else
{
m_pView->remove_custom_state_viewer(m_pSvgDiagramTabIndex);
m_pSvgDiagramTabIndex = -1;
}
}
}
void glvdebug_xgl_QController::onReplayStarted()
{
setStateWidgetsEnabled(false);
}
void glvdebug_xgl_QController::onReplayPaused(uint64_t packetIndex)
{
if(m_pSvgDiagram == NULL)
{
m_pSvgDiagram = new glvdebug_qsvgviewer;
if(m_pSvgDiagram != NULL)
{
setStateWidgetsEnabled(false);
}
}
if(m_pSvgDiagram != NULL)
{
// Check if DOT is available.
#if defined(PLATFORM_LINUX)
QFileInfo fileInfo(tr("/usr/bin/dot"));
#elif defined(WIN32)
// TODO: Windows path to DOT?
QFileInfo fileInfo(tr(""));
#endif
if(!fileInfo.exists() || !fileInfo.isFile())
{
m_pView->output_error("DOT not found.");
}
else
{
QProcess process;
process.start("/usr/bin/dot pipeline_dump.dot -Tsvg -o pipeline_dump.svg");
process.waitForFinished(-1);
}
if(m_pSvgDiagram->load(tr("pipeline_dump.svg")))
{
setStateWidgetsEnabled(true);
}
}
}
void glvdebug_xgl_QController::onReplayContinued()
{
setStateWidgetsEnabled(false);
}
void glvdebug_xgl_QController::onReplayStopped(uint64_t packetIndex)
{
}
void glvdebug_xgl_QController::onReplayFinished()
{
}
BOOL glvdebug_xgl_QController::PrintReplayInfoMsgs()
{
return g_xglDebugSettings.printReplayInfoMsgs;
}
BOOL glvdebug_xgl_QController::PrintReplayWarningMsgs()
{
return g_xglDebugSettings.printReplayWarningMsgs;
}
BOOL glvdebug_xgl_QController::PrintReplayErrorMsgs()
{
return g_xglDebugSettings.printReplayErrorMsgs;
}
BOOL glvdebug_xgl_QController::PauseOnReplayInfoMsg()
{
return g_xglDebugSettings.pauseOnReplayInfo;
}
BOOL glvdebug_xgl_QController::PauseOnReplayWarningMsg()
{
return g_xglDebugSettings.pauseOnReplayWarning;
}
BOOL glvdebug_xgl_QController::PauseOnReplayErrorMsg()
{
return g_xglDebugSettings.pauseOnReplayError;
}
void glvdebug_xgl_QController::onSettingsUpdated(glv_SettingGroup *pGroups, unsigned int numGroups)
{
glv_SettingGroup_Apply_Overrides(&g_xglDebugSettingGroup, pGroups, numGroups);
if (m_pReplayWidget != NULL)
{
m_pReplayWidget->OnSettingsUpdated(pGroups, numGroups);
}
updateCallTreeBasedOnSettings();
}
void glvdebug_xgl_QController::UnloadTraceFile(void)
{
if (m_pView != NULL)
{
m_pView->set_calltree_model(NULL, NULL);
m_pView = NULL;
}
if (m_pTraceFileModel != NULL)
{
delete m_pTraceFileModel;
m_pTraceFileModel = NULL;
}
if (m_pReplayWidget != NULL)
{
delete m_pReplayWidget;
m_pReplayWidget = NULL;
}
if (m_pSvgDiagram != NULL)
{
delete m_pSvgDiagram;
m_pSvgDiagram = NULL;
m_pSvgDiagramTabIndex = -1;
}
// Clean up replayers
if (m_pReplayers != NULL)
{
for (int i = 0; i < GLV_MAX_TRACER_ID_ARRAY_SIZE; i++)
{
if (m_pReplayers[i] != NULL)
{
m_pReplayers[i]->Deinitialize();
m_replayerFactory.Destroy(&m_pReplayers[i]);
}
}
}
}
<|endoftext|> |
<commit_before>// @(#)root/main:$Name: $:$Id: pmain.cxx,v 1.13 2007/01/23 11:31:33 rdm Exp $
// Author: Fons Rademakers 15/02/97
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// PMain //
// //
// Main program used to create PROOF server application. //
// //
//////////////////////////////////////////////////////////////////////////
#include <stdio.h>
#include <errno.h>
#ifdef WIN32
#include <io.h>
#endif
#include <stdio.h>
#include <errno.h>
#ifdef R__HAVE_CONFIG
#include "RConfigure.h"
#endif
#ifdef R__AFS
#include "TAFS.h"
#endif
#include "TApplication.h"
#include "TInterpreter.h"
#include "TROOT.h"
#include "TSystem.h"
// Special type for the hook to the TXProofServ constructor, needed to avoid
// using the plugin manager
typedef TApplication *(*TProofServ_t)(Int_t *argc, char **argv, FILE *flog);
#ifdef R__AFS
// Special type for the hook to the TAFS constructor, needed to avoid
// using the plugin manager
typedef TAFS *(*TAFS_t)(const char *, const char *, Int_t);
// Instance of the AFS token class
static TAFS *gAFS = 0;
#endif
//______________________________________________________________________________
static FILE *RedirectOutput(const char *logfile, const char *loc)
{
// Redirect stdout to 'logfile'. This log file will be flushed to the
// client or master after each command.
// On success return a pointer to the open log file. Return 0 on failure.
if (loc)
fprintf(stderr,"%s: RedirectOutput: enter: %s\n", loc, logfile);
if (!logfile || strlen(logfile) <= 0) {
fprintf(stderr,"%s: RedirectOutput: logfile path undefined\n", loc);
return 0;
}
if (loc)
fprintf(stderr,"%s: RedirectOutput: reopen %s\n", loc, logfile);
FILE *flog = freopen(logfile, "w", stdout);
if (!flog) {
fprintf(stderr,"%s: RedirectOutput: could not freopen stdout\n", loc);
return 0;
}
if (loc)
fprintf(stderr,"%s: RedirectOutput: dup2 ...\n", loc);
if ((dup2(fileno(stdout), fileno(stderr))) < 0) {
fprintf(stderr,"%s: RedirectOutput: could not redirect stderr\n", loc);
return 0;
}
if (loc)
fprintf(stderr,"%s: RedirectOutput: read open ...\n", loc);
FILE *fLog = fopen(logfile, "r");
if (!fLog) {
fprintf(stderr,"%s: RedirectOutput: could not open logfile %s\n", loc, logfile);
return 0;
}
if (loc)
fprintf(stderr,"%s: RedirectOutput: done!\n", loc);
// We are done
return fLog;
}
#ifdef R__AFS
//______________________________________________________________________________
static Int_t InitAFS(const char *fileafs, const char *loc)
{
// Init AFS token using credentials at fileafs
TString getter("GetTAFS");
char *p = 0;
TString afslib = "libAFSAuth";
if ((p = gSystem->DynamicPathName(afslib, kTRUE))) {
delete[] p;
if (gSystem->Load(afslib) == -1) {
if (loc)
fprintf(stderr,"%s: can't load %s\n", loc, afslib.Data());
return -1;
}
} else {
if (loc)
fprintf(stderr,"%s: can't locate %s\n", loc, afslib.Data());
return -1;
}
// Locate constructor
Func_t f = gSystem->DynFindSymbol(afslib, getter);
if (f) {
gAFS = (*((TAFS_t)f))(fileafs, 0, -1);
if (!gAFS) {
if (loc)
fprintf(stderr,"%s: could not initialize a valid TAFS\n", loc);
return -1;
}
} else {
if (loc)
fprintf(stderr,"%s: can't find %s\n", loc, getter.Data());
return -1;
}
// Done
return 0;
}
#endif
//______________________________________________________________________________
int main(int argc, char **argv)
{
// PROOF server main program.
#ifdef R__DEBUG
int debug = 1;
while (debug)
;
#endif
int loglevel = -1;
if (getenv("ROOTPROOFLOGLEVEL"))
loglevel = atoi(getenv("ROOTPROOFLOGLEVEL"));
if (loglevel > 0)
fprintf(stderr,"%s: starting %s\n", argv[1], argv[0]);
// Redirect the output
FILE *fLog = 0;
char *logfile = 0;
char *loc = 0;
const char *sessdir = getenv("ROOTPROOFSESSDIR");
if (sessdir && !getenv("ROOTPROOFDONOTREDIR")) {
logfile = new char[strlen(sessdir) + 5];
sprintf(logfile, "%s.log", sessdir);
loc = (loglevel > 0) ? argv[1] : 0;
if (loglevel > 0)
fprintf(stderr,"%s: redirecting output to %s\n", argv[1], logfile);
if (!(fLog = RedirectOutput(logfile, loc))) {
fprintf(stderr,"%s: problems redirecting output to file %s\n", argv[1], logfile);
exit(1);
}
}
if (loglevel > 0)
fprintf(stderr,"%s: output redirected to: %s\n",
argv[1], (logfile ? logfile : "+++not redirected+++"));
#ifdef R__AFS
// Init AFS, if required
if (getenv("ROOTPROOFAFSCREDS")) {
if (InitAFS(getenv("ROOTPROOFAFSCREDS"), loc) != 0) {
fprintf(stderr,"%s: unable to initialize the AFS token\n", argv[1]);
} else {
if (loglevel > 0)
fprintf(stderr,"%s: AFS token initialized\n", argv[1]);
}
}
#endif
gROOT->SetBatch();
TApplication *theApp = 0;
// Enable autoloading
gInterpreter->EnableAutoLoading();
TString getter("GetTProofServ");
TString prooflib = "libProof";
if (argc > 2) {
// XPD: additionally load the appropriate library
prooflib = "libProofx";
getter = "GetTXProofServ";
}
char *p = 0;
if ((p = gSystem->DynamicPathName(prooflib, kTRUE))) {
delete[] p;
if (gSystem->Load(prooflib) == -1) {
fprintf(stderr,"%s: can't load %s\n", argv[1], prooflib.Data());
exit(1);
}
} else {
fprintf(stderr,"%s: can't locate %s\n", argv[1], prooflib.Data());
exit(1);
}
// Locate constructor
Func_t f = gSystem->DynFindSymbol(prooflib, getter);
if (f) {
theApp = (TApplication *) (*((TProofServ_t)f))(&argc, argv, fLog);
} else {
fprintf(stderr,"%s: can't find %s\n", argv[1], getter.Data());
exit(1);
}
// Ready to run
if (loglevel > 0)
fprintf(stderr,"%s: running the TProofServ application\n", argv[1]);
theApp->Run();
#ifdef R__AFS
// Cleanup
if (gAFS)
delete gAFS;
#endif
// We can exit now
gSystem->Exit(0);
}
<commit_msg>From Gerri: - Take loglevel from argc #5 - Use logfile path generated by XrdProofdProtocol.cxx<commit_after>// @(#)root/main:$Name: $:$Id: pmain.cxx,v 1.14 2007/06/08 09:17:25 rdm Exp $
// Author: Fons Rademakers 15/02/97
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// PMain //
// //
// Main program used to create PROOF server application. //
// //
//////////////////////////////////////////////////////////////////////////
#include <stdio.h>
#include <errno.h>
#ifdef WIN32
#include <io.h>
#endif
#include <stdio.h>
#include <errno.h>
#ifdef R__HAVE_CONFIG
#include "RConfigure.h"
#endif
#ifdef R__AFS
#include "TAFS.h"
#endif
#include "TApplication.h"
#include "TInterpreter.h"
#include "TROOT.h"
#include "TSystem.h"
// Special type for the hook to the TXProofServ constructor, needed to avoid
// using the plugin manager
typedef TApplication *(*TProofServ_t)(Int_t *argc, char **argv, FILE *flog);
#ifdef R__AFS
// Special type for the hook to the TAFS constructor, needed to avoid
// using the plugin manager
typedef TAFS *(*TAFS_t)(const char *, const char *, Int_t);
// Instance of the AFS token class
static TAFS *gAFS = 0;
#endif
//______________________________________________________________________________
static FILE *RedirectOutput(const char *logfile, const char *loc)
{
// Redirect stdout to 'logfile'. This log file will be flushed to the
// client or master after each command.
// On success return a pointer to the open log file. Return 0 on failure.
if (loc)
fprintf(stderr,"%s: RedirectOutput: enter: %s\n", loc, logfile);
if (!logfile || strlen(logfile) <= 0) {
fprintf(stderr,"%s: RedirectOutput: logfile path undefined\n", loc);
return 0;
}
if (loc)
fprintf(stderr,"%s: RedirectOutput: reopen %s\n", loc, logfile);
FILE *flog = freopen(logfile, "w", stdout);
if (!flog) {
fprintf(stderr,"%s: RedirectOutput: could not freopen stdout\n", loc);
return 0;
}
if (loc)
fprintf(stderr,"%s: RedirectOutput: dup2 ...\n", loc);
if ((dup2(fileno(stdout), fileno(stderr))) < 0) {
fprintf(stderr,"%s: RedirectOutput: could not redirect stderr\n", loc);
return 0;
}
if (loc)
fprintf(stderr,"%s: RedirectOutput: read open ...\n", loc);
FILE *fLog = fopen(logfile, "r");
if (!fLog) {
fprintf(stderr,"%s: RedirectOutput: could not open logfile %s\n", loc, logfile);
return 0;
}
if (loc)
fprintf(stderr,"%s: RedirectOutput: done!\n", loc);
// We are done
return fLog;
}
#ifdef R__AFS
//______________________________________________________________________________
static Int_t InitAFS(const char *fileafs, const char *loc)
{
// Init AFS token using credentials at fileafs
TString getter("GetTAFS");
char *p = 0;
TString afslib = "libAFSAuth";
if ((p = gSystem->DynamicPathName(afslib, kTRUE))) {
delete[] p;
if (gSystem->Load(afslib) == -1) {
if (loc)
fprintf(stderr,"%s: can't load %s\n", loc, afslib.Data());
return -1;
}
} else {
if (loc)
fprintf(stderr,"%s: can't locate %s\n", loc, afslib.Data());
return -1;
}
// Locate constructor
Func_t f = gSystem->DynFindSymbol(afslib, getter);
if (f) {
gAFS = (*((TAFS_t)f))(fileafs, 0, -1);
if (!gAFS) {
if (loc)
fprintf(stderr,"%s: could not initialize a valid TAFS\n", loc);
return -1;
}
} else {
if (loc)
fprintf(stderr,"%s: can't find %s\n", loc, getter.Data());
return -1;
}
// Done
return 0;
}
#endif
//______________________________________________________________________________
int main(int argc, char **argv)
{
// PROOF server main program.
#ifdef R__DEBUG
int debug = 1;
while (debug)
;
#endif
int loglevel = (argc >= 6) ? strtol(argv[5], 0, 10) : -1;
if (loglevel < 0 && getenv("ROOTPROOFLOGLEVEL"))
loglevel = atoi(getenv("ROOTPROOFLOGLEVEL"));
if (loglevel > 0)
fprintf(stderr,"%s: starting %s\n", argv[1], argv[0]);
// Redirect the output
FILE *fLog = 0;
char *loc = 0;
char *logfile = (char *)getenv("ROOTPROOFLOGFILE");
if (logfile && !getenv("ROOTPROOFDONOTREDIR")) {
loc = (loglevel > 0) ? argv[1] : 0;
if (loglevel > 0)
fprintf(stderr,"%s: redirecting output to %s\n", argv[1], logfile);
if (!(fLog = RedirectOutput(logfile, loc))) {
fprintf(stderr,"%s: problems redirecting output to file %s\n", argv[1], logfile);
exit(1);
}
}
if (loglevel > 0)
fprintf(stderr,"%s: output redirected to: %s\n",
argv[1], (logfile ? logfile : "+++not redirected+++"));
#ifdef R__AFS
// Init AFS, if required
if (getenv("ROOTPROOFAFSCREDS")) {
if (InitAFS(getenv("ROOTPROOFAFSCREDS"), loc) != 0) {
fprintf(stderr,"%s: unable to initialize the AFS token\n", argv[1]);
} else {
if (loglevel > 0)
fprintf(stderr,"%s: AFS token initialized\n", argv[1]);
}
}
#endif
gROOT->SetBatch();
TApplication *theApp = 0;
// Enable autoloading
gInterpreter->EnableAutoLoading();
TString getter("GetTProofServ");
TString prooflib = "libProof";
if (argc > 2) {
// XPD: additionally load the appropriate library
prooflib = "libProofx";
getter = "GetTXProofServ";
}
char *p = 0;
if ((p = gSystem->DynamicPathName(prooflib, kTRUE))) {
delete[] p;
if (gSystem->Load(prooflib) == -1) {
fprintf(stderr,"%s: can't load %s\n", argv[1], prooflib.Data());
exit(1);
}
} else {
fprintf(stderr,"%s: can't locate %s\n", argv[1], prooflib.Data());
exit(1);
}
// Locate constructor
Func_t f = gSystem->DynFindSymbol(prooflib, getter);
if (f) {
theApp = (TApplication *) (*((TProofServ_t)f))(&argc, argv, fLog);
} else {
fprintf(stderr,"%s: can't find %s\n", argv[1], getter.Data());
exit(1);
}
// Ready to run
if (loglevel > 0)
fprintf(stderr,"%s: running the TProofServ application\n", argv[1]);
theApp->Run();
#ifdef R__AFS
// Cleanup
if (gAFS)
delete gAFS;
#endif
// We can exit now
gSystem->Exit(0);
}
<|endoftext|> |
<commit_before>/*
* Phusion Passenger - http://www.modrails.com/
* Copyright (c) 2010 Phusion
*
* "Phusion Passenger" is a trademark of Hongli Lai & Ninh Bui.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <oxt/system_calls.hpp>
#include <oxt/backtrace.hpp>
#include <string>
#include <vector>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/un.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>
#include <fcntl.h>
#include <cstdlib>
#include <cstring>
#include <cerrno>
#include <cmath>
#include "IOUtils.h"
#include "StrIntUtils.h"
#include "../Exceptions.h"
namespace Passenger {
using namespace std;
using namespace oxt;
// Urgh, Solaris :-(
#ifndef AF_LOCAL
#define AF_LOCAL AF_UNIX
#endif
#ifndef PF_LOCAL
#define PF_LOCAL PF_UNIX
#endif
ServerAddressType
getSocketAddressType(const StaticString &address) {
const char *data = address.c_str();
size_t len = address.size();
if (len > sizeof("unix:") - 1 && memcmp(data, "unix:", sizeof("unix:") - 1) == 0) {
return SAT_UNIX;
} else if (len > sizeof("tcp://") - 1 && memcmp(data, "tcp://", sizeof("tcp://") - 1) == 0) {
return SAT_TCP;
} else {
return SAT_UNKNOWN;
}
}
string
parseUnixSocketAddress(const StaticString &address) {
if (getSocketAddressType(address) != SAT_UNIX) {
throw ArgumentException("Not a valid Unix socket address");
}
return string(address.c_str() + sizeof("unix:") - 1, address.size() - sizeof("unix:") + 1);
}
void
parseTcpSocketAddress(const StaticString &address, string &host, unsigned short &port) {
if (getSocketAddressType(address) != SAT_TCP) {
throw ArgumentException("Not a valid TCP socket address");
}
vector<string> args;
string begin(address.c_str() + sizeof("tcp://") - 1, address.size() - sizeof("tcp://") + 1);
split(begin, ':', args);
if (args.size() != 2) {
throw ArgumentException("Not a valid TCP socket address");
} else {
host = args[0];
port = atoi(args[1].c_str());
}
}
bool
isLocalSocketAddress(const StaticString &address) {
switch (getSocketAddressType(address)) {
case SAT_UNIX:
return true;
case SAT_TCP: {
string host;
unsigned short port;
parseTcpSocketAddress(address, host, port);
return host == "127.0.0.1" || host == "::1" || host == "localhost";
}
default:
throw ArgumentException("Unsupported socket address type");
}
}
void
setNonBlocking(int fd) {
int flags, ret;
do {
flags = fcntl(fd, F_GETFL);
} while (flags == -1 && errno == EINTR);
if (flags == -1) {
int e = errno;
throw SystemException("Cannot set socket to non-blocking mode: "
"cannot get socket flags",
e);
}
do {
ret = fcntl(fd, F_SETFL, flags | O_NONBLOCK);
} while (ret == -1 && errno == EINTR);
if (ret == -1) {
int e = errno;
throw SystemException("Cannot set socket to non-blocking mode: "
"cannot set socket flags",
e);
}
}
int
createServer(const StaticString &address, unsigned int backlogSize, bool autoDelete) {
TRACE_POINT();
switch (getSocketAddressType(address)) {
case SAT_UNIX:
return createUnixServer(parseUnixSocketAddress(address),
backlogSize, autoDelete);
case SAT_TCP: {
string host;
unsigned short port;
parseTcpSocketAddress(address, host, port);
return createTcpServer(host.c_str(), port, backlogSize);
}
default:
throw ArgumentException(string("Unknown address type for '") + address + "'");
}
}
int
createUnixServer(const StaticString &filename, unsigned int backlogSize, bool autoDelete) {
struct sockaddr_un addr;
int fd, ret;
if (filename.size() > sizeof(addr.sun_path) - 1) {
string message = "Cannot create Unix socket '";
message.append(filename.toString());
message.append("': filename is too long.");
throw RuntimeException(message);
}
fd = syscalls::socket(PF_LOCAL, SOCK_STREAM, 0);
if (fd == -1) {
int e = errno;
throw SystemException("Cannot create a Unix socket file descriptor", e);
}
addr.sun_family = AF_LOCAL;
strncpy(addr.sun_path, filename.c_str(), filename.size());
addr.sun_path[filename.size()] = '\0';
if (autoDelete) {
do {
ret = unlink(filename.c_str());
} while (ret == -1 && errno == EINTR);
}
try {
ret = syscalls::bind(fd, (const struct sockaddr *) &addr, sizeof(addr));
} catch (...) {
do {
ret = close(fd);
} while (ret == -1 && errno == EINTR);
throw;
}
if (ret == -1) {
int e = errno;
string message = "Cannot bind Unix socket '";
message.append(filename.toString());
message.append("'");
do {
ret = close(fd);
} while (ret == -1 && errno == EINTR);
throw SystemException(message, e);
}
if (backlogSize == 0) {
backlogSize = 1024;
}
try {
ret = syscalls::listen(fd, backlogSize);
} catch (...) {
do {
ret = close(fd);
} while (ret == -1 && errno == EINTR);
throw;
}
if (ret == -1) {
int e = errno;
string message = "Cannot listen on Unix socket '";
message.append(filename.toString());
message.append("'");
do {
ret = close(fd);
} while (ret == -1 && errno == EINTR);
throw SystemException(message, e);
}
return fd;
}
int
createTcpServer(const char *address, unsigned short port, unsigned int backlogSize) {
struct sockaddr_in addr;
int fd, ret, optval;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
ret = inet_pton(AF_INET, address, &addr.sin_addr.s_addr);
if (ret < 0) {
int e = errno;
string message = "Cannot parse the IP address '";
message.append(address);
message.append("'");
throw SystemException(message, e);
} else if (ret == 0) {
string message = "Cannot parse the IP address '";
message.append(address);
message.append("'");
throw ArgumentException(message);
}
addr.sin_port = htons(port);
fd = syscalls::socket(PF_INET, SOCK_STREAM, 0);
if (fd == -1) {
int e = errno;
throw SystemException("Cannot create a TCP socket file descriptor", e);
}
try {
ret = syscalls::bind(fd, (const struct sockaddr *) &addr, sizeof(addr));
} catch (...) {
do {
ret = close(fd);
} while (ret == -1 && errno == EINTR);
throw;
}
if (ret == -1) {
int e = errno;
string message = "Cannot bind a TCP socket on address '";
message.append(address);
message.append("' port ");
message.append(toString(port));
do {
ret = close(fd);
} while (ret == -1 && errno == EINTR);
throw SystemException(message, e);
}
optval = 1;
try {
if (syscalls::setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
&optval, sizeof(optval)) == -1) {
printf("so_reuseaddr failed: %s\n", strerror(errno));
}
} catch (...) {
do {
ret = close(fd);
} while (ret == -1 && errno == EINTR);
throw;
}
// Ignore SO_REUSEPORT error, it's not fatal.
if (backlogSize == 0) {
backlogSize = 1024;
}
try {
ret = syscalls::listen(fd, backlogSize);
} catch (...) {
do {
ret = close(fd);
} while (ret == -1 && errno == EINTR);
throw;
}
if (ret == -1) {
int e = errno;
string message = "Cannot listen on TCP socket '";
message.append(address);
message.append("' port ");
message.append(toString(port));
do {
ret = close(fd);
} while (ret == -1 && errno == EINTR);
throw SystemException(message, e);
}
return fd;
}
int
connectToServer(const StaticString &address) {
TRACE_POINT();
switch (getSocketAddressType(address)) {
case SAT_UNIX:
return connectToUnixServer(parseUnixSocketAddress(address));
case SAT_TCP: {
string host;
unsigned short port;
parseTcpSocketAddress(address, host, port);
return connectToTcpServer(host, port);
}
default:
throw ArgumentException(string("Unknown address type for '") + address + "'");
}
}
int
connectToUnixServer(const StaticString &filename) {
int fd, ret;
struct sockaddr_un addr;
if (filename.size() > sizeof(addr.sun_path) - 1) {
string message = "Cannot connect to Unix socket '";
message.append(filename.toString());
message.append("': filename is too long.");
throw RuntimeException(message);
}
fd = syscalls::socket(PF_UNIX, SOCK_STREAM, 0);
if (fd == -1) {
int e = errno;
throw SystemException("Cannot create a Unix socket file descriptor", e);
}
addr.sun_family = AF_UNIX;
memcpy(addr.sun_path, filename.c_str(), filename.size());
addr.sun_path[filename.size()] = '\0';
bool retry = true;
int counter = 0;
while (retry) {
try {
ret = syscalls::connect(fd, (const sockaddr *) &addr, sizeof(addr));
} catch (...) {
do {
ret = close(fd);
} while (ret == -1 && errno == EINTR);
throw;
}
if (ret == -1) {
#if defined(sun) || defined(__sun)
/* Solaris has this nice kernel bug where connecting to
* a newly created Unix socket which is obviously
* connectable can cause an ECONNREFUSED. So we retry
* in a loop.
*/
retry = errno == ECONNREFUSED;
#else
retry = false;
#endif
retry = retry && counter < 9;
if (retry) {
counter++;
syscalls::usleep((useconds_t) (10000 * pow((double) 2, (double) counter)));
} else {
int e = errno;
string message("Cannot connect to Unix socket '");
message.append(filename.toString());
message.append("'");
do {
ret = close(fd);
} while (ret == -1 && errno == EINTR);
throw SystemException(message, e);
}
} else {
return fd;
}
}
}
int
connectToTcpServer(const StaticString &hostname, unsigned int port) {
struct addrinfo hints, *res;
int ret, e, fd;
memset(&hints, 0, sizeof(hints));
hints.ai_family = PF_INET;
hints.ai_socktype = SOCK_STREAM;
ret = getaddrinfo(hostname.c_str(), toString(port).c_str(), &hints, &res);
if (ret != 0) {
string message = "Cannot resolve IP address '";
message.append(hostname.toString());
message.append(":");
message.append(toString(port));
message.append("': ");
message.append(gai_strerror(ret));
throw IOException(message);
}
try {
fd = syscalls::socket(PF_INET, SOCK_STREAM, 0);
} catch (...) {
freeaddrinfo(res);
throw;
}
if (fd == -1) {
e = errno;
freeaddrinfo(res);
throw SystemException("Cannot create a TCP socket file descriptor", e);
}
try {
ret = syscalls::connect(fd, res->ai_addr, res->ai_addrlen);
} catch (...) {
freeaddrinfo(res);
do {
ret = close(fd);
} while (ret == -1 && errno == EINTR);
throw;
}
e = errno;
freeaddrinfo(res);
if (ret == -1) {
string message = "Cannot connect to TCP socket '";
message.append(hostname.toString());
message.append(":");
message.append(toString(port));
message.append("'");
do {
ret = close(fd);
} while (ret == -1 && errno == EINTR);
throw SystemException(message, e);
}
return fd;
}
} // namespace Passenger
<commit_msg>Fix connectToUnixServer()'s sleep retry calculation and fix a compilation warning.<commit_after>/*
* Phusion Passenger - http://www.modrails.com/
* Copyright (c) 2010 Phusion
*
* "Phusion Passenger" is a trademark of Hongli Lai & Ninh Bui.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <oxt/system_calls.hpp>
#include <oxt/backtrace.hpp>
#include <string>
#include <vector>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/un.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>
#include <fcntl.h>
#include <cstdlib>
#include <cstring>
#include <cerrno>
#include <cmath>
#include "IOUtils.h"
#include "StrIntUtils.h"
#include "../Exceptions.h"
namespace Passenger {
using namespace std;
using namespace oxt;
// Urgh, Solaris :-(
#ifndef AF_LOCAL
#define AF_LOCAL AF_UNIX
#endif
#ifndef PF_LOCAL
#define PF_LOCAL PF_UNIX
#endif
ServerAddressType
getSocketAddressType(const StaticString &address) {
const char *data = address.c_str();
size_t len = address.size();
if (len > sizeof("unix:") - 1 && memcmp(data, "unix:", sizeof("unix:") - 1) == 0) {
return SAT_UNIX;
} else if (len > sizeof("tcp://") - 1 && memcmp(data, "tcp://", sizeof("tcp://") - 1) == 0) {
return SAT_TCP;
} else {
return SAT_UNKNOWN;
}
}
string
parseUnixSocketAddress(const StaticString &address) {
if (getSocketAddressType(address) != SAT_UNIX) {
throw ArgumentException("Not a valid Unix socket address");
}
return string(address.c_str() + sizeof("unix:") - 1, address.size() - sizeof("unix:") + 1);
}
void
parseTcpSocketAddress(const StaticString &address, string &host, unsigned short &port) {
if (getSocketAddressType(address) != SAT_TCP) {
throw ArgumentException("Not a valid TCP socket address");
}
vector<string> args;
string begin(address.c_str() + sizeof("tcp://") - 1, address.size() - sizeof("tcp://") + 1);
split(begin, ':', args);
if (args.size() != 2) {
throw ArgumentException("Not a valid TCP socket address");
} else {
host = args[0];
port = atoi(args[1].c_str());
}
}
bool
isLocalSocketAddress(const StaticString &address) {
switch (getSocketAddressType(address)) {
case SAT_UNIX:
return true;
case SAT_TCP: {
string host;
unsigned short port;
parseTcpSocketAddress(address, host, port);
return host == "127.0.0.1" || host == "::1" || host == "localhost";
}
default:
throw ArgumentException("Unsupported socket address type");
}
}
void
setNonBlocking(int fd) {
int flags, ret;
do {
flags = fcntl(fd, F_GETFL);
} while (flags == -1 && errno == EINTR);
if (flags == -1) {
int e = errno;
throw SystemException("Cannot set socket to non-blocking mode: "
"cannot get socket flags",
e);
}
do {
ret = fcntl(fd, F_SETFL, flags | O_NONBLOCK);
} while (ret == -1 && errno == EINTR);
if (ret == -1) {
int e = errno;
throw SystemException("Cannot set socket to non-blocking mode: "
"cannot set socket flags",
e);
}
}
int
createServer(const StaticString &address, unsigned int backlogSize, bool autoDelete) {
TRACE_POINT();
switch (getSocketAddressType(address)) {
case SAT_UNIX:
return createUnixServer(parseUnixSocketAddress(address),
backlogSize, autoDelete);
case SAT_TCP: {
string host;
unsigned short port;
parseTcpSocketAddress(address, host, port);
return createTcpServer(host.c_str(), port, backlogSize);
}
default:
throw ArgumentException(string("Unknown address type for '") + address + "'");
}
}
int
createUnixServer(const StaticString &filename, unsigned int backlogSize, bool autoDelete) {
struct sockaddr_un addr;
int fd, ret;
if (filename.size() > sizeof(addr.sun_path) - 1) {
string message = "Cannot create Unix socket '";
message.append(filename.toString());
message.append("': filename is too long.");
throw RuntimeException(message);
}
fd = syscalls::socket(PF_LOCAL, SOCK_STREAM, 0);
if (fd == -1) {
int e = errno;
throw SystemException("Cannot create a Unix socket file descriptor", e);
}
addr.sun_family = AF_LOCAL;
strncpy(addr.sun_path, filename.c_str(), filename.size());
addr.sun_path[filename.size()] = '\0';
if (autoDelete) {
do {
ret = unlink(filename.c_str());
} while (ret == -1 && errno == EINTR);
}
try {
ret = syscalls::bind(fd, (const struct sockaddr *) &addr, sizeof(addr));
} catch (...) {
do {
ret = close(fd);
} while (ret == -1 && errno == EINTR);
throw;
}
if (ret == -1) {
int e = errno;
string message = "Cannot bind Unix socket '";
message.append(filename.toString());
message.append("'");
do {
ret = close(fd);
} while (ret == -1 && errno == EINTR);
throw SystemException(message, e);
}
if (backlogSize == 0) {
backlogSize = 1024;
}
try {
ret = syscalls::listen(fd, backlogSize);
} catch (...) {
do {
ret = close(fd);
} while (ret == -1 && errno == EINTR);
throw;
}
if (ret == -1) {
int e = errno;
string message = "Cannot listen on Unix socket '";
message.append(filename.toString());
message.append("'");
do {
ret = close(fd);
} while (ret == -1 && errno == EINTR);
throw SystemException(message, e);
}
return fd;
}
int
createTcpServer(const char *address, unsigned short port, unsigned int backlogSize) {
struct sockaddr_in addr;
int fd, ret, optval;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
ret = inet_pton(AF_INET, address, &addr.sin_addr.s_addr);
if (ret < 0) {
int e = errno;
string message = "Cannot parse the IP address '";
message.append(address);
message.append("'");
throw SystemException(message, e);
} else if (ret == 0) {
string message = "Cannot parse the IP address '";
message.append(address);
message.append("'");
throw ArgumentException(message);
}
addr.sin_port = htons(port);
fd = syscalls::socket(PF_INET, SOCK_STREAM, 0);
if (fd == -1) {
int e = errno;
throw SystemException("Cannot create a TCP socket file descriptor", e);
}
try {
ret = syscalls::bind(fd, (const struct sockaddr *) &addr, sizeof(addr));
} catch (...) {
do {
ret = close(fd);
} while (ret == -1 && errno == EINTR);
throw;
}
if (ret == -1) {
int e = errno;
string message = "Cannot bind a TCP socket on address '";
message.append(address);
message.append("' port ");
message.append(toString(port));
do {
ret = close(fd);
} while (ret == -1 && errno == EINTR);
throw SystemException(message, e);
}
optval = 1;
try {
if (syscalls::setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
&optval, sizeof(optval)) == -1) {
printf("so_reuseaddr failed: %s\n", strerror(errno));
}
} catch (...) {
do {
ret = close(fd);
} while (ret == -1 && errno == EINTR);
throw;
}
// Ignore SO_REUSEPORT error, it's not fatal.
if (backlogSize == 0) {
backlogSize = 1024;
}
try {
ret = syscalls::listen(fd, backlogSize);
} catch (...) {
do {
ret = close(fd);
} while (ret == -1 && errno == EINTR);
throw;
}
if (ret == -1) {
int e = errno;
string message = "Cannot listen on TCP socket '";
message.append(address);
message.append("' port ");
message.append(toString(port));
do {
ret = close(fd);
} while (ret == -1 && errno == EINTR);
throw SystemException(message, e);
}
return fd;
}
int
connectToServer(const StaticString &address) {
TRACE_POINT();
switch (getSocketAddressType(address)) {
case SAT_UNIX:
return connectToUnixServer(parseUnixSocketAddress(address));
case SAT_TCP: {
string host;
unsigned short port;
parseTcpSocketAddress(address, host, port);
return connectToTcpServer(host, port);
}
default:
throw ArgumentException(string("Unknown address type for '") + address + "'");
}
}
int
connectToUnixServer(const StaticString &filename) {
int fd, ret;
struct sockaddr_un addr;
if (filename.size() > sizeof(addr.sun_path) - 1) {
string message = "Cannot connect to Unix socket '";
message.append(filename.toString());
message.append("': filename is too long.");
throw RuntimeException(message);
}
fd = syscalls::socket(PF_UNIX, SOCK_STREAM, 0);
if (fd == -1) {
int e = errno;
throw SystemException("Cannot create a Unix socket file descriptor", e);
}
addr.sun_family = AF_UNIX;
memcpy(addr.sun_path, filename.c_str(), filename.size());
addr.sun_path[filename.size()] = '\0';
bool retry = true;
int counter = 0;
while (retry) {
try {
ret = syscalls::connect(fd, (const sockaddr *) &addr, sizeof(addr));
} catch (...) {
do {
ret = close(fd);
} while (ret == -1 && errno == EINTR);
throw;
}
if (ret == -1) {
#if defined(sun) || defined(__sun)
/* Solaris has this nice kernel bug where connecting to
* a newly created Unix socket which is obviously
* connectable can cause an ECONNREFUSED. So we retry
* in a loop.
*/
retry = errno == ECONNREFUSED;
#else
retry = false;
#endif
retry = retry && counter < 9;
if (retry) {
syscalls::usleep((useconds_t) (10000 * pow((double) 2, (double) counter)));
counter++;
} else {
int e = errno;
string message("Cannot connect to Unix socket '");
message.append(filename.toString());
message.append("'");
do {
ret = close(fd);
} while (ret == -1 && errno == EINTR);
throw SystemException(message, e);
}
} else {
return fd;
}
}
abort(); // Never reached.
return -1; // Shut up compiler warning.
}
int
connectToTcpServer(const StaticString &hostname, unsigned int port) {
struct addrinfo hints, *res;
int ret, e, fd;
memset(&hints, 0, sizeof(hints));
hints.ai_family = PF_INET;
hints.ai_socktype = SOCK_STREAM;
ret = getaddrinfo(hostname.c_str(), toString(port).c_str(), &hints, &res);
if (ret != 0) {
string message = "Cannot resolve IP address '";
message.append(hostname.toString());
message.append(":");
message.append(toString(port));
message.append("': ");
message.append(gai_strerror(ret));
throw IOException(message);
}
try {
fd = syscalls::socket(PF_INET, SOCK_STREAM, 0);
} catch (...) {
freeaddrinfo(res);
throw;
}
if (fd == -1) {
e = errno;
freeaddrinfo(res);
throw SystemException("Cannot create a TCP socket file descriptor", e);
}
try {
ret = syscalls::connect(fd, res->ai_addr, res->ai_addrlen);
} catch (...) {
freeaddrinfo(res);
do {
ret = close(fd);
} while (ret == -1 && errno == EINTR);
throw;
}
e = errno;
freeaddrinfo(res);
if (ret == -1) {
string message = "Cannot connect to TCP socket '";
message.append(hostname.toString());
message.append(":");
message.append(toString(port));
message.append("'");
do {
ret = close(fd);
} while (ret == -1 && errno == EINTR);
throw SystemException(message, e);
}
return fd;
}
} // namespace Passenger
<|endoftext|> |
<commit_before>/* t-various.cpp
This file is part of qgpgme, the Qt API binding for gpgme
Copyright (c) 2017 Intevation GmbH
QGpgME 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.
QGpgME is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
In addition, as a special exception, the copyright holders give
permission to link the code of this program with any edition of
the Qt library by Trolltech AS, Norway (or with modified versions
of Qt that use the same license as Qt), and distribute linked
combinations including the two. You must obey the GNU General
Public License in all respects for all of the code used other than
Qt. If you modify this file, you may extend this exception to
your version of the file, but you are not obligated to do so. If
you do not wish to do so, delete this exception statement from
your version.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <QDebug>
#include <QTest>
#include <QSignalSpy>
#include <QTemporaryDir>
#include "keylistjob.h"
#include "protocol.h"
#include "keylistresult.h"
#include "context.h"
#include "engineinfo.h"
#include "t-support.h"
using namespace QGpgME;
using namespace GpgME;
class TestVarious: public QGpgMETest
{
Q_OBJECT
Q_SIGNALS:
void asyncDone();
private Q_SLOTS:
void testQuickUid()
{
if (GpgME::engineInfo(GpgME::GpgEngine).engineVersion() < "2.1.13") {
return;
}
KeyListJob *job = openpgp()->keyListJob(false, true, true);
std::vector<GpgME::Key> keys;
GpgME::KeyListResult result = job->exec(QStringList() << QStringLiteral("alfa@example.net"),
false, keys);
delete job;
QVERIFY (!result.error());
QVERIFY (keys.size() == 1);
Key key = keys.front();
QVERIFY (key.numUserIDs() == 3);
const char uid[] = "Foo Bar (with comment) <foo@bar.baz>";
auto ctx = Context::createForProtocol(key.protocol());
QVERIFY (ctx);
TestPassphraseProvider provider;
ctx->setPassphraseProvider(&provider);
ctx->setPinentryMode(Context::PinentryLoopback);
QVERIFY(!ctx->addUid(key, uid));
delete ctx;
key.update();
QVERIFY (key.numUserIDs() == 4);
bool id_found = false;;
for (const auto &u: key.userIDs()) {
if (!strcmp (u.id(), uid)) {
QVERIFY (!u.isRevoked());
id_found = true;
break;
}
}
QVERIFY (id_found);
ctx = Context::createForProtocol(key.protocol());
QVERIFY (!ctx->revUid(key, uid));
delete ctx;
key.update();
bool id_revoked = false;;
for (const auto &u: key.userIDs()) {
if (!strcmp (u.id(), uid)) {
id_revoked = true;
break;
}
}
QVERIFY(id_revoked);
}
void initTestCase()
{
QGpgMETest::initTestCase();
const QString gpgHome = qgetenv("GNUPGHOME");
QVERIFY(copyKeyrings(gpgHome, mDir.path()));
qputenv("GNUPGHOME", mDir.path().toUtf8());
}
private:
QTemporaryDir mDir;
};
QTEST_MAIN(TestVarious)
#include "t-various.moc"
<commit_msg>qt: Add test for DN parser<commit_after>/* t-various.cpp
This file is part of qgpgme, the Qt API binding for gpgme
Copyright (c) 2017 Intevation GmbH
QGpgME 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.
QGpgME is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
In addition, as a special exception, the copyright holders give
permission to link the code of this program with any edition of
the Qt library by Trolltech AS, Norway (or with modified versions
of Qt that use the same license as Qt), and distribute linked
combinations including the two. You must obey the GNU General
Public License in all respects for all of the code used other than
Qt. If you modify this file, you may extend this exception to
your version of the file, but you are not obligated to do so. If
you do not wish to do so, delete this exception statement from
your version.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <QDebug>
#include <QTest>
#include <QSignalSpy>
#include <QTemporaryDir>
#include "keylistjob.h"
#include "protocol.h"
#include "keylistresult.h"
#include "context.h"
#include "engineinfo.h"
#include "dn.h"
#include "t-support.h"
using namespace QGpgME;
using namespace GpgME;
class TestVarious: public QGpgMETest
{
Q_OBJECT
Q_SIGNALS:
void asyncDone();
private Q_SLOTS:
void testDN()
{
DN dn(QStringLiteral("CN=Before\\0DAfter,OU=Test,DC=North America,DC=Fabrikam,DC=COM"));
QVERIFY(dn.dn() == QStringLiteral("CN=Before\rAfter,OU=Test,DC=North America,DC=Fabrikam,DC=COM"));
QStringList attrOrder;
attrOrder << QStringLiteral("DC") << QStringLiteral("OU") << QStringLiteral("CN");
dn.setAttributeOrder(attrOrder);
QVERIFY(dn.prettyDN() == QStringLiteral("DC=North America,DC=Fabrikam,DC=COM,OU=Test,CN=Before\rAfter"));
}
void testQuickUid()
{
if (GpgME::engineInfo(GpgME::GpgEngine).engineVersion() < "2.1.13") {
return;
}
KeyListJob *job = openpgp()->keyListJob(false, true, true);
std::vector<GpgME::Key> keys;
GpgME::KeyListResult result = job->exec(QStringList() << QStringLiteral("alfa@example.net"),
false, keys);
delete job;
QVERIFY (!result.error());
QVERIFY (keys.size() == 1);
Key key = keys.front();
QVERIFY (key.numUserIDs() == 3);
const char uid[] = "Foo Bar (with comment) <foo@bar.baz>";
auto ctx = Context::createForProtocol(key.protocol());
QVERIFY (ctx);
TestPassphraseProvider provider;
ctx->setPassphraseProvider(&provider);
ctx->setPinentryMode(Context::PinentryLoopback);
QVERIFY(!ctx->addUid(key, uid));
delete ctx;
key.update();
QVERIFY (key.numUserIDs() == 4);
bool id_found = false;;
for (const auto &u: key.userIDs()) {
if (!strcmp (u.id(), uid)) {
QVERIFY (!u.isRevoked());
id_found = true;
break;
}
}
QVERIFY (id_found);
ctx = Context::createForProtocol(key.protocol());
QVERIFY (!ctx->revUid(key, uid));
delete ctx;
key.update();
bool id_revoked = false;;
for (const auto &u: key.userIDs()) {
if (!strcmp (u.id(), uid)) {
id_revoked = true;
break;
}
}
QVERIFY(id_revoked);
}
void initTestCase()
{
QGpgMETest::initTestCase();
const QString gpgHome = qgetenv("GNUPGHOME");
QVERIFY(copyKeyrings(gpgHome, mDir.path()));
qputenv("GNUPGHOME", mDir.path().toUtf8());
}
private:
QTemporaryDir mDir;
};
QTEST_MAIN(TestVarious)
#include "t-various.moc"
<|endoftext|> |
<commit_before>/**
* @file ProcessManagerTest.cpp
* @brief ProcessManager class tester.
* @author zer0
* @date 2017-07-29
*/
#include <gtest/gtest.h>
#include <libtbag/log/Log.hpp>
#include <libtbag/uvpp/Loop.hpp>
#include <libtbag/process/ProcessManager.hpp>
#include <libtbag/filesystem/Path.hpp>
using namespace libtbag;
using namespace libtbag::process;
using namespace libtbag::uvpp;
TEST(ProcessManagerTest, Default)
{
log::SeverityGuard guard;
std::string const EXE_NAME = "tbproc";
std::string const TEST_OUT = "test_output_string";
using Path = filesystem::Path;
Path const PATH = Path::getExeDir() / filesystem::getExecutableName(EXE_NAME);
int const TEST_COUNT = 10;
int on_read = 0;
int on_error = 0;
int on_exit = 0;
ProcessManager pm;
pm.out_read_cb = [&](int pid, char const * buffer, std::size_t size){
++on_read;
};
pm.err_read_cb = [&](int pid, char const * buffer, std::size_t size){
++on_error;
};
pm.exit_cb = [&](int pid, int64_t exit_status, int term_signal){
++on_exit;
};
for (int i = 0; i < TEST_COUNT; ++i) {
ASSERT_NE(0, pm.exec(PATH.toString(), {"out"}, {}, std::string(), TEST_OUT));
}
pm.join();
ASSERT_EQ(TEST_COUNT, pm.size());
ASSERT_FALSE(pm.empty());
auto list = pm.list();
ASSERT_EQ(TEST_COUNT, list.size());
for (auto & proc : list) {
auto shared = pm.get(proc.pid).lock();
ASSERT_EQ(0, shared->getExitStatus());
ASSERT_EQ(0, shared->getTermSignal());
}
ASSERT_EQ(TEST_COUNT, on_read);
ASSERT_EQ(0, on_error);
ASSERT_EQ(TEST_COUNT, on_exit);
}
<commit_msg>Fixed bug in ProcessManagerTest.Default tester.<commit_after>/**
* @file ProcessManagerTest.cpp
* @brief ProcessManager class tester.
* @author zer0
* @date 2017-07-29
*/
#include <gtest/gtest.h>
#include <libtbag/log/Log.hpp>
#include <libtbag/uvpp/Loop.hpp>
#include <libtbag/process/ProcessManager.hpp>
#include <libtbag/filesystem/Path.hpp>
#include <atomic>
using namespace libtbag;
using namespace libtbag::process;
using namespace libtbag::uvpp;
TEST(ProcessManagerTest, Default)
{
log::SeverityGuard guard;
std::string const EXE_NAME = "tbproc";
std::string const TEST_OUT = "test_output_string";
using Path = filesystem::Path;
Path const PATH = Path::getExeDir() / filesystem::getExecutableName(EXE_NAME);
int const TEST_COUNT = 10;
std::atomic_int on_read(0);
std::atomic_int on_error(0);
std::atomic_int on_exit(0);
ProcessManager pm;
pm.out_read_cb = [&](int pid, char const * buffer, std::size_t size){
++on_read;
};
pm.err_read_cb = [&](int pid, char const * buffer, std::size_t size){
++on_error;
};
pm.exit_cb = [&](int pid, int64_t exit_status, int term_signal){
++on_exit;
};
for (int i = 0; i < TEST_COUNT; ++i) {
ASSERT_NE(0, pm.exec(PATH.toString(), {"out"}, {}, std::string(), TEST_OUT));
}
pm.join();
ASSERT_EQ(TEST_COUNT, pm.size());
ASSERT_FALSE(pm.empty());
auto list = pm.list();
ASSERT_EQ(TEST_COUNT, list.size());
for (auto & proc : list) {
auto shared = pm.get(proc.pid).lock();
ASSERT_EQ(0, shared->getExitStatus());
ASSERT_EQ(0, shared->getTermSignal());
}
ASSERT_EQ(TEST_COUNT, on_read);
ASSERT_EQ(0, on_error);
ASSERT_EQ(TEST_COUNT, on_exit);
}
<|endoftext|> |
<commit_before>/* opendatacon
*
* Copyright (c) 2014:
*
* DCrip3fJguWgVCLrZFfA7sIGgvx1Ou3fHfCxnrz4svAi
* yxeOtDhDCXf1Z4ApgXvX5ahqQmzRfJ2DoX8S05SqHA==
*
* 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 <opendatacon/asio.h>
#include <thread>
#include <catch.hpp>
#include "PortLoader.h"
#define SUITE(name) "DNP3PortEndToEndTestSuite - " name
TEST_CASE(SUITE("TCP link"))
{
//Load the library
InitLibaryLoading();
auto portlib = LoadModule(GetLibFileName("DNP3Port"));
REQUIRE(portlib);
{
auto ios = std::make_shared<asio::io_service>();
auto work = std::make_unique<asio::io_service::work>(*ios);
std::thread t([&](){ios->run();});
//make an outstation port
newptr newOutstation = GetPortCreator(portlib, "DNP3Outstation");
REQUIRE(newOutstation);
delptr delOutstation = GetPortDestroyer(portlib, "DNP3Outstation");
REQUIRE(delOutstation);
Json::Value Oconf;
Oconf["IP"] = "0.0.0.0";
auto OPUT = std::shared_ptr<DataPort>(newOutstation("OutstationUnderTest", "", Oconf), delOutstation);
REQUIRE(OPUT);
//make a master port
newptr newMaster = GetPortCreator(portlib, "DNP3Master");
REQUIRE(newMaster);
delptr delMaster = GetPortDestroyer(portlib, "DNP3Master");
REQUIRE(delMaster);
Json::Value Mconf;
Mconf["ServerType"] = "PERSISTENT";
auto MPUT = std::unique_ptr<DataPort,delptr>(newMaster("MasterUnderTest", "", Mconf), delMaster);
REQUIRE(MPUT);
//get them to build themselves using their configs
OPUT->Build();
MPUT->Build();
//turn them on
OPUT->SetIOS(ios);
MPUT->SetIOS(ios);
OPUT->Enable();
MPUT->Enable();
//TODO: write a better way to wait for GetStatus
unsigned int count = 0;
while((MPUT->GetStatus()["Result"].asString() == "Port enabled - link down" || OPUT->GetStatus()["Result"].asString() == "Port enabled - link down") && count < 20000)
{
std::this_thread::sleep_for(std::chrono::milliseconds(1));
count++;
}
REQUIRE(MPUT->GetStatus()["Result"].asString() == "Port enabled - link up (unreset)");
REQUIRE(OPUT->GetStatus()["Result"].asString() == "Port enabled - link up (unreset)");
//turn outstation off
OPUT->Disable();
count = 0;
while(MPUT->GetStatus()["Result"].asString() == "Port enabled - link up (unreset)" && count < 20000)
{
std::this_thread::sleep_for(std::chrono::milliseconds(1));
count++;
}
REQUIRE(MPUT->GetStatus()["Result"].asString() == "Port enabled - link down");
REQUIRE(OPUT->GetStatus()["Result"].asString() == "Port disabled");
work.reset();
t.join();
ios.reset();
}
//Unload the library
UnLoadModule(portlib);
}
TEST_CASE(SUITE("Serial link"))
{
if(system("socat -h > /dev/null"))
{
WARN("Failed to execute socat (for virtual serial ports) - skipping test");
}
else
{
//Load the library
InitLibaryLoading();
auto portlib = LoadModule(GetLibFileName("DNP3Port"));
REQUIRE(portlib);
{
auto ios = std::make_shared<asio::io_service>();
auto work = std::make_unique<asio::io_service::work>(*ios);
std::thread t([&](){ios->run();});
system("socat pty,raw,echo=0,link=SerialEndpoint1 pty,raw,echo=0,link=SerialEndpoint2 &");
//make an outstation port
newptr newOutstation = GetPortCreator(portlib, "DNP3Outstation");
REQUIRE(newOutstation);
delptr delOutstation = GetPortDestroyer(portlib, "DNP3Outstation");
REQUIRE(delOutstation);
Json::Value Oconf;
Oconf["SerialDevice"] = "SerialEndpoint1";
auto OPUT = std::shared_ptr<DataPort>(newOutstation("OutstationUnderTest", "", Oconf), delOutstation);
REQUIRE(OPUT);
//make a master port
newptr newMaster = GetPortCreator(portlib, "DNP3Master");
REQUIRE(newMaster);
delptr delMaster = GetPortDestroyer(portlib, "DNP3Master");
REQUIRE(delMaster);
Json::Value Mconf;
Mconf["ServerType"] = "PERSISTENT";
Mconf["SerialDevice"] = "SerialEndpoint2";
Mconf["LinkKeepAlivems"] = 200;
Mconf["LinkTimeoutms"] = 100;
auto MPUT = std::unique_ptr<DataPort,delptr>(newMaster("MasterUnderTest", "", Mconf), delMaster);
REQUIRE(MPUT);
//get them to build themselves using their configs
OPUT->Build();
MPUT->Build();
//turn them on
OPUT->SetIOS(ios);
MPUT->SetIOS(ios);
OPUT->Enable();
MPUT->Enable();
//TODO: write a better way to wait for GetStatus
unsigned int count = 0;
while((MPUT->GetStatus()["Result"].asString() == "Port enabled - link down" || OPUT->GetStatus()["Result"].asString() == "Port enabled - link down") && count < 20000)
{
std::this_thread::sleep_for(std::chrono::milliseconds(1));
count++;
}
REQUIRE(MPUT->GetStatus()["Result"].asString() == "Port enabled - link up (unreset)");
REQUIRE(OPUT->GetStatus()["Result"].asString() == "Port enabled - link up (unreset)");
//turn outstation off
OPUT->Disable();
count = 0;
while(MPUT->GetStatus()["Result"].asString() == "Port enabled - link up (unreset)" && count < 20000)
{
std::this_thread::sleep_for(std::chrono::milliseconds(1));
count++;
}
REQUIRE(MPUT->GetStatus()["Result"].asString() == "Port enabled - link down");
REQUIRE(OPUT->GetStatus()["Result"].asString() == "Port disabled");
system("killall socat");
work.reset();
t.join();
ios.reset();
}
//Unload the library
UnLoadModule(portlib);
}
}
<commit_msg>commented out serial port DNP3 test<commit_after>/* opendatacon
*
* Copyright (c) 2014:
*
* DCrip3fJguWgVCLrZFfA7sIGgvx1Ou3fHfCxnrz4svAi
* yxeOtDhDCXf1Z4ApgXvX5ahqQmzRfJ2DoX8S05SqHA==
*
* 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 <opendatacon/asio.h>
#include <thread>
#include <catch.hpp>
#include "PortLoader.h"
#define SUITE(name) "DNP3PortEndToEndTestSuite - " name
TEST_CASE(SUITE("TCP link"))
{
//Load the library
InitLibaryLoading();
auto portlib = LoadModule(GetLibFileName("DNP3Port"));
REQUIRE(portlib);
{
auto ios = std::make_shared<asio::io_service>();
auto work = std::make_unique<asio::io_service::work>(*ios);
std::thread t([&](){ios->run();});
//make an outstation port
newptr newOutstation = GetPortCreator(portlib, "DNP3Outstation");
REQUIRE(newOutstation);
delptr delOutstation = GetPortDestroyer(portlib, "DNP3Outstation");
REQUIRE(delOutstation);
Json::Value Oconf;
Oconf["IP"] = "0.0.0.0";
auto OPUT = std::shared_ptr<DataPort>(newOutstation("OutstationUnderTest", "", Oconf), delOutstation);
REQUIRE(OPUT);
//make a master port
newptr newMaster = GetPortCreator(portlib, "DNP3Master");
REQUIRE(newMaster);
delptr delMaster = GetPortDestroyer(portlib, "DNP3Master");
REQUIRE(delMaster);
Json::Value Mconf;
Mconf["ServerType"] = "PERSISTENT";
auto MPUT = std::unique_ptr<DataPort,delptr>(newMaster("MasterUnderTest", "", Mconf), delMaster);
REQUIRE(MPUT);
//get them to build themselves using their configs
OPUT->Build();
MPUT->Build();
//turn them on
OPUT->SetIOS(ios);
MPUT->SetIOS(ios);
OPUT->Enable();
MPUT->Enable();
//TODO: write a better way to wait for GetStatus
unsigned int count = 0;
while((MPUT->GetStatus()["Result"].asString() == "Port enabled - link down" || OPUT->GetStatus()["Result"].asString() == "Port enabled - link down") && count < 20000)
{
std::this_thread::sleep_for(std::chrono::milliseconds(1));
count++;
}
REQUIRE(MPUT->GetStatus()["Result"].asString() == "Port enabled - link up (unreset)");
REQUIRE(OPUT->GetStatus()["Result"].asString() == "Port enabled - link up (unreset)");
//turn outstation off
OPUT->Disable();
count = 0;
while(MPUT->GetStatus()["Result"].asString() == "Port enabled - link up (unreset)" && count < 20000)
{
std::this_thread::sleep_for(std::chrono::milliseconds(1));
count++;
}
REQUIRE(MPUT->GetStatus()["Result"].asString() == "Port enabled - link down");
REQUIRE(OPUT->GetStatus()["Result"].asString() == "Port disabled");
work.reset();
t.join();
ios.reset();
}
//Unload the library
UnLoadModule(portlib);
}
//TEST_CASE(SUITE("Serial link"))
//{
// if(system("socat -h > /dev/null"))
// {
// WARN("Failed to execute socat (for virtual serial ports) - skipping test");
// }
// else
// {
// //Load the library
// InitLibaryLoading();
// auto portlib = LoadModule(GetLibFileName("DNP3Port"));
// REQUIRE(portlib);
// {
// auto ios = std::make_shared<asio::io_service>();
// auto work = std::make_unique<asio::io_service::work>(*ios);
// std::thread t([&](){ios->run();});
// system("socat pty,raw,echo=0,link=SerialEndpoint1 pty,raw,echo=0,link=SerialEndpoint2 &");
// //make an outstation port
// newptr newOutstation = GetPortCreator(portlib, "DNP3Outstation");
// REQUIRE(newOutstation);
// delptr delOutstation = GetPortDestroyer(portlib, "DNP3Outstation");
// REQUIRE(delOutstation);
// Json::Value Oconf;
// Oconf["SerialDevice"] = "SerialEndpoint1";
// auto OPUT = std::shared_ptr<DataPort>(newOutstation("OutstationUnderTest", "", Oconf), delOutstation);
// REQUIRE(OPUT);
// //make a master port
// newptr newMaster = GetPortCreator(portlib, "DNP3Master");
// REQUIRE(newMaster);
// delptr delMaster = GetPortDestroyer(portlib, "DNP3Master");
// REQUIRE(delMaster);
// Json::Value Mconf;
// Mconf["ServerType"] = "PERSISTENT";
// Mconf["SerialDevice"] = "SerialEndpoint2";
// Mconf["LinkKeepAlivems"] = 200;
// Mconf["LinkTimeoutms"] = 100;
// auto MPUT = std::unique_ptr<DataPort,delptr>(newMaster("MasterUnderTest", "", Mconf), delMaster);
// REQUIRE(MPUT);
// //get them to build themselves using their configs
// OPUT->Build();
// MPUT->Build();
// //turn them on
// OPUT->SetIOS(ios);
// MPUT->SetIOS(ios);
// OPUT->Enable();
// MPUT->Enable();
// //TODO: write a better way to wait for GetStatus
// unsigned int count = 0;
// while((MPUT->GetStatus()["Result"].asString() == "Port enabled - link down" || OPUT->GetStatus()["Result"].asString() == "Port enabled - link down") && count < 20000)
// {
// std::this_thread::sleep_for(std::chrono::milliseconds(1));
// count++;
// }
// REQUIRE(MPUT->GetStatus()["Result"].asString() == "Port enabled - link up (unreset)");
// REQUIRE(OPUT->GetStatus()["Result"].asString() == "Port enabled - link up (unreset)");
// //turn outstation off
// OPUT->Disable();
// count = 0;
// while(MPUT->GetStatus()["Result"].asString() == "Port enabled - link up (unreset)" && count < 20000)
// {
// std::this_thread::sleep_for(std::chrono::milliseconds(1));
// count++;
// }
// REQUIRE(MPUT->GetStatus()["Result"].asString() == "Port enabled - link down");
// REQUIRE(OPUT->GetStatus()["Result"].asString() == "Port disabled");
// system("killall socat");
// work.reset();
// t.join();
// ios.reset();
// }
// //Unload the library
// UnLoadModule(portlib);
// }
//}
<|endoftext|> |
<commit_before>// ---------------------------------------------------------------------
// $Id$
//
// Copyright (C) 2004 - 2013 by the deal.II authors
//
// This file is part of the deal.II library.
//
// The deal.II library is free software; you can use it, 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.
// The full text of the license can be found in the file LICENSE at
// the top level of the deal.II distribution.
//
// ---------------------------------------------------------------------
#include <deal.II/lac/petsc_parallel_vector.h>
#ifdef DEAL_II_WITH_PETSC
# include <deal.II/lac/petsc_vector.h>
# include <cmath>
# include <algorithm>
DEAL_II_NAMESPACE_OPEN
namespace PETScWrappers
{
namespace MPI
{
Vector::Vector ()
{
// this is an invalid empty vector, so we
// can just as well create a sequential
// one to avoid all the overhead incurred
// by parallelism
const int n = 0;
const int ierr
= VecCreateSeq (PETSC_COMM_SELF, n, &vector);
AssertThrow (ierr == 0, ExcPETScError(ierr));
ghosted = false;
}
Vector::Vector (const MPI_Comm &communicator,
const size_type n,
const size_type local_size)
:
communicator (communicator)
{
Vector::create_vector (n, local_size);
}
Vector::Vector (const MPI_Comm &communicator,
const VectorBase &v,
const size_type local_size)
:
communicator (communicator)
{
Vector::create_vector (v.size(), local_size);
VectorBase::operator = (v);
}
Vector::Vector (const MPI_Comm &communicator,
const IndexSet &local,
const IndexSet &ghost)
:
communicator (communicator)
{
Assert(local.is_contiguous(), ExcNotImplemented());
IndexSet ghost_set = ghost;
ghost_set.subtract_set(local);
Vector::create_vector(local.size(), local.n_elements(), ghost_set);
}
Vector::Vector (const IndexSet &local,
const IndexSet &ghost,
const MPI_Comm &communicator)
:
communicator (communicator)
{
Assert(local.is_contiguous(), ExcNotImplemented());
IndexSet ghost_set = ghost;
ghost_set.subtract_set(local);
Vector::create_vector(local.size(), local.n_elements(), ghost_set);
}
Vector::Vector (const IndexSet &local,
const MPI_Comm &communicator)
:
communicator (communicator)
{
Assert(local.is_contiguous(), ExcNotImplemented());
Vector::create_vector(local.size(), local.n_elements());
}
Vector::Vector (const MPI_Comm &communicator,
const IndexSet &local)
:
communicator (communicator)
{
Assert(local.is_contiguous(), ExcNotImplemented());
Vector::create_vector(local.size(), local.n_elements());
}
void
Vector::reinit (const MPI_Comm &comm,
const size_type n,
const size_type local_sz,
const bool fast)
{
communicator = comm;
// only do something if the sizes
// mismatch (may not be true for every proc)
int k_global, k = ((size() != n) || (local_size() != local_sz));
MPI_Allreduce (&k, &k_global, 1,
MPI_INT, MPI_LOR, communicator);
if (k_global)
{
// FIXME: I'd like to use this here,
// but somehow it leads to odd errors
// somewhere down the line in some of
// the tests:
// const int ierr = VecSetSizes (vector, n, n);
// AssertThrow (ierr == 0, ExcPETScError(ierr));
// so let's go the slow way:
int ierr;
#if DEAL_II_PETSC_VERSION_LT(3,2,0)
ierr = VecDestroy (vector);
#else
ierr = VecDestroy (&vector);
#endif
AssertThrow (ierr == 0, ExcPETScError(ierr));
create_vector (n, local_sz);
}
// finally clear the new vector if so
// desired
if (fast == false)
*this = 0;
}
void
Vector::reinit (const Vector &v,
const bool fast)
{
if (v.has_ghost_elements())
{
reinit (v.locally_owned_elements(), v.ghost_indices, v.communicator);
if (!fast)
{
int ierr = VecSet(vector, 0.0);
AssertThrow (ierr == 0, ExcPETScError(ierr));
}
}
else
reinit (communicator, v.size(), v.local_size(), fast);
}
void
Vector::reinit (const MPI_Comm &comm,
const IndexSet &local,
const IndexSet &ghost)
{
reinit(local, ghost, comm);
}
void
Vector::reinit (const IndexSet &local,
const IndexSet &ghost,
const MPI_Comm &comm)
{
communicator = comm;
Assert(local.is_contiguous(), ExcNotImplemented());
IndexSet ghost_set = ghost;
ghost_set.subtract_set(local);
create_vector(local.size(), local.n_elements(), ghost_set);
}
void
Vector::reinit (const MPI_Comm &comm,
const IndexSet &local)
{
reinit(local, comm);
}
void
Vector::reinit (const IndexSet &local,
const MPI_Comm &comm)
{
communicator = comm;
Assert(local.is_contiguous(), ExcNotImplemented());
Assert(local.size()>0, ExcMessage("can not create vector of size 0."));
create_vector(local.size(), local.n_elements());
}
Vector &
Vector::operator = (const PETScWrappers::Vector &v)
{
Assert(last_action==VectorOperation::unknown,
ExcMessage("Call to compress() required before calling operator=."));
//TODO [TH]: can not access v.last_action here. Implement is_compressed()?
//Assert(v.last_action==VectorOperation::unknown,
// ExcMessage("Call to compress() required before calling operator=."));
int ierr;
// get a pointer to the local memory of
// this vector
PetscScalar *dest_array;
ierr = VecGetArray (vector, &dest_array);
AssertThrow (ierr == 0, ExcPETScError(ierr));
// then also a pointer to the source
// vector
PetscScalar *src_array;
ierr = VecGetArray (static_cast<const Vec &>(v), &src_array);
AssertThrow (ierr == 0, ExcPETScError(ierr));
// then copy:
const std::pair<size_type, size_type>
local_elements = local_range ();
std::copy (src_array + local_elements.first,
src_array + local_elements.second,
dest_array);
// finally restore the arrays
ierr = VecRestoreArray (vector, &dest_array);
AssertThrow (ierr == 0, ExcPETScError(ierr));
ierr = VecRestoreArray (static_cast<const Vec &>(v), &src_array);
AssertThrow (ierr == 0, ExcPETScError(ierr));
if (has_ghost_elements())
update_ghost_values();
return *this;
}
void
Vector::create_vector (const size_type n,
const size_type local_size)
{
Assert (local_size <= n, ExcIndexRange (local_size, 0, n));
ghosted = false;
const int ierr
= VecCreateMPI (communicator, local_size, PETSC_DETERMINE,
&vector);
AssertThrow (ierr == 0, ExcPETScError(ierr));
Assert (size() == n,
ExcDimensionMismatch (size(), n));
}
void
Vector::create_vector (const size_type n,
const size_type local_size,
const IndexSet &ghostnodes)
{
Assert (local_size <= n, ExcIndexRange (local_size, 0, n));
ghosted = true;
ghost_indices = ghostnodes;
std::vector<size_type> ghostindices;
ghostnodes.fill_index_vector(ghostindices);
const PetscInt *ptr
= (ghostindices.size() > 0
?
(const PetscInt *)(&(ghostindices[0]))
:
0);
int ierr
= VecCreateGhost(communicator,
local_size,
PETSC_DETERMINE,
ghostindices.size(),
ptr,
&vector);
AssertThrow (ierr == 0, ExcPETScError(ierr));
Assert (size() == n,
ExcDimensionMismatch (size(), n));
#if DEBUG
// test ghost allocation in debug mode
PetscInt begin, end;
ierr = VecGetOwnershipRange (vector, &begin, &end);
Assert(local_size==(size_type)(end-begin), ExcInternalError());
Vec l;
ierr = VecGhostGetLocalForm(vector, &l);
AssertThrow (ierr == 0, ExcPETScError(ierr));
PetscInt lsize;
ierr = VecGetSize(l, &lsize);
AssertThrow (ierr == 0, ExcPETScError(ierr));
ierr = VecGhostRestoreLocalForm(vector, &l);
AssertThrow (ierr == 0, ExcPETScError(ierr));
Assert( lsize==end-begin+(PetscInt)ghost_indices.n_elements() ,ExcInternalError());
#endif
}
void
Vector::print (std::ostream &out,
const unsigned int precision,
const bool scientific,
const bool across) const
{
AssertThrow (out, ExcIO());
// get a representation of the vector and
// loop over all the elements
PetscScalar *val;
PetscInt nlocal, istart, iend;
int ierr = VecGetArray (vector, &val);
AssertThrow (ierr == 0, ExcPETScError(ierr));
ierr = VecGetLocalSize (vector, &nlocal);
AssertThrow (ierr == 0, ExcPETScError(ierr));
ierr = VecGetOwnershipRange (vector, &istart, &iend);
AssertThrow (ierr == 0, ExcPETScError(ierr));
// save the state of out stream
std::ios::fmtflags old_flags = out.flags();
unsigned int old_precision = out.precision (precision);
out.precision (precision);
if (scientific)
out.setf (std::ios::scientific, std::ios::floatfield);
else
out.setf (std::ios::fixed, std::ios::floatfield);
for ( unsigned int i = 0;
i < Utilities::MPI::n_mpi_processes(communicator);
i++)
{
// This is slow, but most likely only used to debug.
MPI_Barrier(communicator);
if (i == Utilities::MPI::this_mpi_process(communicator))
{
if (across)
{
out << "[Proc" << i << " " << istart << "-" << iend-1 << "]" << ' ';
for (PetscInt i=0; i<nlocal; ++i)
out << val[i] << ' ';
}
else
{
out << "[Proc " << i << " " << istart << "-" << iend-1 << "]" << std::endl;
for (PetscInt i=0; i<nlocal; ++i)
out << val[i] << std::endl;
}
out << std::endl;
}
}
// reset output format
out.flags (old_flags);
out.precision(old_precision);
// restore the representation of the
// vector
ierr = VecRestoreArray (vector, &val);
AssertThrow (ierr == 0, ExcPETScError(ierr));
AssertThrow (out, ExcIO());
}
}
}
DEAL_II_NAMESPACE_CLOSE
#endif // DEAL_II_WITH_PETSC
<commit_msg>more PETSc reinit() fixes<commit_after>// ---------------------------------------------------------------------
// $Id$
//
// Copyright (C) 2004 - 2013 by the deal.II authors
//
// This file is part of the deal.II library.
//
// The deal.II library is free software; you can use it, 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.
// The full text of the license can be found in the file LICENSE at
// the top level of the deal.II distribution.
//
// ---------------------------------------------------------------------
#include <deal.II/lac/petsc_parallel_vector.h>
#ifdef DEAL_II_WITH_PETSC
# include <deal.II/lac/petsc_vector.h>
# include <cmath>
# include <algorithm>
DEAL_II_NAMESPACE_OPEN
namespace PETScWrappers
{
namespace MPI
{
Vector::Vector ()
{
// this is an invalid empty vector, so we
// can just as well create a sequential
// one to avoid all the overhead incurred
// by parallelism
const int n = 0;
const int ierr
= VecCreateSeq (PETSC_COMM_SELF, n, &vector);
AssertThrow (ierr == 0, ExcPETScError(ierr));
ghosted = false;
}
Vector::Vector (const MPI_Comm &communicator,
const size_type n,
const size_type local_size)
:
communicator (communicator)
{
Vector::create_vector (n, local_size);
}
Vector::Vector (const MPI_Comm &communicator,
const VectorBase &v,
const size_type local_size)
:
communicator (communicator)
{
Vector::create_vector (v.size(), local_size);
VectorBase::operator = (v);
}
Vector::Vector (const MPI_Comm &communicator,
const IndexSet &local,
const IndexSet &ghost)
:
communicator (communicator)
{
Assert(local.is_contiguous(), ExcNotImplemented());
IndexSet ghost_set = ghost;
ghost_set.subtract_set(local);
Vector::create_vector(local.size(), local.n_elements(), ghost_set);
}
Vector::Vector (const IndexSet &local,
const IndexSet &ghost,
const MPI_Comm &communicator)
:
communicator (communicator)
{
Assert(local.is_contiguous(), ExcNotImplemented());
IndexSet ghost_set = ghost;
ghost_set.subtract_set(local);
Vector::create_vector(local.size(), local.n_elements(), ghost_set);
}
Vector::Vector (const IndexSet &local,
const MPI_Comm &communicator)
:
communicator (communicator)
{
Assert(local.is_contiguous(), ExcNotImplemented());
Vector::create_vector(local.size(), local.n_elements());
}
Vector::Vector (const MPI_Comm &communicator,
const IndexSet &local)
:
communicator (communicator)
{
Assert(local.is_contiguous(), ExcNotImplemented());
Vector::create_vector(local.size(), local.n_elements());
}
void
Vector::reinit (const MPI_Comm &comm,
const size_type n,
const size_type local_sz,
const bool fast)
{
communicator = comm;
// only do something if the sizes
// mismatch (may not be true for every proc)
int k_global, k = ((size() != n) || (local_size() != local_sz));
MPI_Allreduce (&k, &k_global, 1,
MPI_INT, MPI_LOR, communicator);
if (k_global || has_ghost_elements())
{
// FIXME: I'd like to use this here,
// but somehow it leads to odd errors
// somewhere down the line in some of
// the tests:
// const int ierr = VecSetSizes (vector, n, n);
// AssertThrow (ierr == 0, ExcPETScError(ierr));
// so let's go the slow way:
int ierr;
#if DEAL_II_PETSC_VERSION_LT(3,2,0)
ierr = VecDestroy (vector);
#else
ierr = VecDestroy (&vector);
#endif
AssertThrow (ierr == 0, ExcPETScError(ierr));
create_vector (n, local_sz);
}
// finally clear the new vector if so
// desired
if (fast == false)
*this = 0;
}
void
Vector::reinit (const Vector &v,
const bool fast)
{
if (v.has_ghost_elements())
{
reinit (v.locally_owned_elements(), v.ghost_indices, v.communicator);
if (!fast)
{
int ierr = VecSet(vector, 0.0);
AssertThrow (ierr == 0, ExcPETScError(ierr));
}
}
else
reinit (v.communicator, v.size(), v.local_size(), fast);
}
void
Vector::reinit (const MPI_Comm &comm,
const IndexSet &local,
const IndexSet &ghost)
{
reinit(local, ghost, comm);
}
void
Vector::reinit (const IndexSet &local,
const IndexSet &ghost,
const MPI_Comm &comm)
{
communicator = comm;
Assert(local.is_contiguous(), ExcNotImplemented());
IndexSet ghost_set = ghost;
ghost_set.subtract_set(local);
create_vector(local.size(), local.n_elements(), ghost_set);
}
void
Vector::reinit (const MPI_Comm &comm,
const IndexSet &local)
{
reinit(local, comm);
}
void
Vector::reinit (const IndexSet &local,
const MPI_Comm &comm)
{
communicator = comm;
Assert(local.is_contiguous(), ExcNotImplemented());
Assert(local.size()>0, ExcMessage("can not create vector of size 0."));
create_vector(local.size(), local.n_elements());
}
Vector &
Vector::operator = (const PETScWrappers::Vector &v)
{
Assert(last_action==VectorOperation::unknown,
ExcMessage("Call to compress() required before calling operator=."));
//TODO [TH]: can not access v.last_action here. Implement is_compressed()?
//Assert(v.last_action==VectorOperation::unknown,
// ExcMessage("Call to compress() required before calling operator=."));
int ierr;
// get a pointer to the local memory of
// this vector
PetscScalar *dest_array;
ierr = VecGetArray (vector, &dest_array);
AssertThrow (ierr == 0, ExcPETScError(ierr));
// then also a pointer to the source
// vector
PetscScalar *src_array;
ierr = VecGetArray (static_cast<const Vec &>(v), &src_array);
AssertThrow (ierr == 0, ExcPETScError(ierr));
// then copy:
const std::pair<size_type, size_type>
local_elements = local_range ();
std::copy (src_array + local_elements.first,
src_array + local_elements.second,
dest_array);
// finally restore the arrays
ierr = VecRestoreArray (vector, &dest_array);
AssertThrow (ierr == 0, ExcPETScError(ierr));
ierr = VecRestoreArray (static_cast<const Vec &>(v), &src_array);
AssertThrow (ierr == 0, ExcPETScError(ierr));
if (has_ghost_elements())
update_ghost_values();
return *this;
}
void
Vector::create_vector (const size_type n,
const size_type local_size)
{
Assert (local_size <= n, ExcIndexRange (local_size, 0, n));
ghosted = false;
const int ierr
= VecCreateMPI (communicator, local_size, PETSC_DETERMINE,
&vector);
AssertThrow (ierr == 0, ExcPETScError(ierr));
Assert (size() == n,
ExcDimensionMismatch (size(), n));
}
void
Vector::create_vector (const size_type n,
const size_type local_size,
const IndexSet &ghostnodes)
{
Assert (local_size <= n, ExcIndexRange (local_size, 0, n));
ghosted = true;
ghost_indices = ghostnodes;
std::vector<size_type> ghostindices;
ghostnodes.fill_index_vector(ghostindices);
const PetscInt *ptr
= (ghostindices.size() > 0
?
(const PetscInt *)(&(ghostindices[0]))
:
0);
int ierr
= VecCreateGhost(communicator,
local_size,
PETSC_DETERMINE,
ghostindices.size(),
ptr,
&vector);
AssertThrow (ierr == 0, ExcPETScError(ierr));
Assert (size() == n,
ExcDimensionMismatch (size(), n));
#if DEBUG
// test ghost allocation in debug mode
PetscInt begin, end;
ierr = VecGetOwnershipRange (vector, &begin, &end);
Assert(local_size==(size_type)(end-begin), ExcInternalError());
Vec l;
ierr = VecGhostGetLocalForm(vector, &l);
AssertThrow (ierr == 0, ExcPETScError(ierr));
PetscInt lsize;
ierr = VecGetSize(l, &lsize);
AssertThrow (ierr == 0, ExcPETScError(ierr));
ierr = VecGhostRestoreLocalForm(vector, &l);
AssertThrow (ierr == 0, ExcPETScError(ierr));
Assert( lsize==end-begin+(PetscInt)ghost_indices.n_elements() ,ExcInternalError());
#endif
}
void
Vector::print (std::ostream &out,
const unsigned int precision,
const bool scientific,
const bool across) const
{
AssertThrow (out, ExcIO());
// get a representation of the vector and
// loop over all the elements
PetscScalar *val;
PetscInt nlocal, istart, iend;
int ierr = VecGetArray (vector, &val);
AssertThrow (ierr == 0, ExcPETScError(ierr));
ierr = VecGetLocalSize (vector, &nlocal);
AssertThrow (ierr == 0, ExcPETScError(ierr));
ierr = VecGetOwnershipRange (vector, &istart, &iend);
AssertThrow (ierr == 0, ExcPETScError(ierr));
// save the state of out stream
std::ios::fmtflags old_flags = out.flags();
unsigned int old_precision = out.precision (precision);
out.precision (precision);
if (scientific)
out.setf (std::ios::scientific, std::ios::floatfield);
else
out.setf (std::ios::fixed, std::ios::floatfield);
for ( unsigned int i = 0;
i < Utilities::MPI::n_mpi_processes(communicator);
i++)
{
// This is slow, but most likely only used to debug.
MPI_Barrier(communicator);
if (i == Utilities::MPI::this_mpi_process(communicator))
{
if (across)
{
out << "[Proc" << i << " " << istart << "-" << iend-1 << "]" << ' ';
for (PetscInt i=0; i<nlocal; ++i)
out << val[i] << ' ';
}
else
{
out << "[Proc " << i << " " << istart << "-" << iend-1 << "]" << std::endl;
for (PetscInt i=0; i<nlocal; ++i)
out << val[i] << std::endl;
}
out << std::endl;
}
}
// reset output format
out.flags (old_flags);
out.precision(old_precision);
// restore the representation of the
// vector
ierr = VecRestoreArray (vector, &val);
AssertThrow (ierr == 0, ExcPETScError(ierr));
AssertThrow (out, ExcIO());
}
}
}
DEAL_II_NAMESPACE_CLOSE
#endif // DEAL_II_WITH_PETSC
<|endoftext|> |
<commit_before>#ifndef JOINT_CPP_STRING_HPP
#define JOINT_CPP_STRING_HPP
#include <algorithm>
#include <joint.cpp/BytesView.hpp>
#include <joint.cpp/detail/Iterator.hpp>
namespace joint
{
class Utf32View
{
typedef char Byte;
typedef uint32_t value_type;
public:
class iterator : public detail::IteratorOps<iterator, value_type, value_type>
{
friend class Utf32View;
friend class detail::IteratorOps<iterator, value_type, value_type>;
private:
const Byte* _begin;
const Byte* _end;
const Byte* _ptr;
public:
iterator() { }
protected:
iterator(const Byte* begin, const Byte* end, const Byte* ptr)
: _begin(begin), _end(end), _ptr(ptr)
{ }
bool Equals(iterator other) const
{ return _ptr == other._ptr; }
value_type Dereference() const
{
Byte firstByte = *_ptr;
value_type valueMask = 0x7F;
size_t len = 0;
for (; len < 4; ++len)
{
if ((firstByte & ~valueMask) != ~valueMask)
break;
valueMask >>= 1;
}
len = std::min(len, size_t(_end - _ptr));
value_type result = firstByte & valueMask;
for (size_t i = 1; i < len; ++i)
result = (result << 6) | (*(_ptr + i) & 0x3F);
return result;
}
void Increment()
{
while (_ptr < _end && (*(++_ptr) & 0xC0) == 0x80)
{ }
}
void Decrement()
{
while (_ptr > _begin && (*(--_ptr) & 0xC0) == 0x80)
{ }
}
};
typedef iterator const_iterator;
private:
BytesView _bytes;
public:
explicit Utf32View(BytesView bytes)
: _bytes(bytes)
{ }
const_iterator begin() const { return const_iterator(_bytes.begin(), _bytes.end(), _bytes.begin()); }
const_iterator end() const { return const_iterator(_bytes.begin(), _bytes.end(), _bytes.end()); }
};
Utf32View::const_iterator begin(const Utf32View& v) { return v.begin(); }
Utf32View::const_iterator end(const Utf32View& v) { return v.end(); }
namespace detail
{
template < typename String_ >
class StringImpl
{
public:
BytesView Utf8Bytes() const { return BytesView(Self().Data(), Self().Size()); }
joint::Utf32View Utf32View() const { return joint::Utf32View(Utf8Bytes()); }
protected:
~StringImpl() { }
private:
const String_& Self() const { return static_cast<const String_&>(*this); }
};
}
class StringRef : public detail::StringImpl<StringRef>
{
friend class detail::StringImpl<StringRef>;
private:
const char* _data;
size_t _size;
public:
StringRef(const char* data) // TODO: is this ok?
: _data(data), _size(strlen(data) + 1)
{ }
StringRef(const char* data, size_t size)
: _data(data), _size(size)
{ }
protected:
const char* Data() const { return _data; }
size_t Size() const { return _size; }
};
class String : public detail::StringImpl<String>
{
friend class detail::StringImpl<String>;
private:
std::string _storage;
public:
String()
{ }
String(const char* value) // TODO: is this ok?
: _storage(value)
{ }
explicit String(StringRef stringRef)
: _storage(stringRef.Utf8Bytes().data(), stringRef.Utf8Bytes().size())
{ }
explicit String(const std::string& storage)
: _storage(storage)
{ }
std::string& Storage() { return _storage; }
const std::string& Storage() const { return _storage; }
operator StringRef() const
{ return StringRef(Utf8Bytes().data(), Utf8Bytes().size()); }
protected:
const char* Data() const { return _storage.c_str(); }
size_t Size() const { return _storage.size() + 1; }
};
template < typename String1_, typename String2_ >
String operator+(const detail::StringImpl<String1_>& l, const detail::StringImpl<String2_>& r)
{
String result(l.Utf8Bytes().data()); // TODO: reimplement
result.Storage() += r.Utf8Bytes().data();
return result;
}
template < typename String1_, typename String2_ >
bool operator==(const detail::StringImpl<String1_>& l, const detail::StringImpl<String2_>& r)
{
BytesView lb = l.Utf8Bytes();
BytesView rb = r.Utf8Bytes();
return strncmp(lb.data(), rb.data(), std::min(lb.size(), rb.size())) == 0;
}
template < typename String1_, typename String2_ >
bool operator!=(const detail::StringImpl<String1_>& l, const detail::StringImpl<String2_>& r)
{ return !(l == r); }
}
#endif
<commit_msg>Fix build<commit_after>#ifndef JOINT_CPP_STRING_HPP
#define JOINT_CPP_STRING_HPP
#include <algorithm>
#include <joint.cpp/BytesView.hpp>
#include <joint.cpp/detail/Iterator.hpp>
namespace joint
{
class Utf32View
{
typedef char Byte;
typedef uint32_t value_type;
public:
class iterator : public detail::IteratorOps<iterator, value_type, value_type>
{
friend class Utf32View;
friend class detail::IteratorOps<iterator, value_type, value_type>;
private:
const Byte* _begin;
const Byte* _end;
const Byte* _ptr;
public:
iterator() { }
protected:
iterator(const Byte* begin, const Byte* end, const Byte* ptr)
: _begin(begin), _end(end), _ptr(ptr)
{ }
bool Equals(iterator other) const
{ return _ptr == other._ptr; }
value_type Dereference() const
{
Byte firstByte = *_ptr;
value_type valueMask = 0x7F;
size_t len = 0;
for (; len < 4; ++len)
{
if ((firstByte & ~valueMask) != ~valueMask)
break;
valueMask >>= 1;
}
len = std::min(len, size_t(_end - _ptr));
value_type result = firstByte & valueMask;
for (size_t i = 1; i < len; ++i)
result = (result << 6) | (*(_ptr + i) & 0x3F);
return result;
}
void Increment()
{
while (_ptr < _end && (*(++_ptr) & 0xC0) == 0x80)
{ }
}
void Decrement()
{
while (_ptr > _begin && (*(--_ptr) & 0xC0) == 0x80)
{ }
}
};
typedef iterator const_iterator;
private:
BytesView _bytes;
public:
explicit Utf32View(BytesView bytes)
: _bytes(bytes)
{ }
const_iterator begin() const { return const_iterator(_bytes.begin(), _bytes.end(), _bytes.begin()); }
const_iterator end() const { return const_iterator(_bytes.begin(), _bytes.end(), _bytes.end()); }
};
Utf32View::const_iterator begin(const Utf32View& v) { return v.begin(); }
Utf32View::const_iterator end(const Utf32View& v) { return v.end(); }
namespace detail
{
template < typename String_ >
class StringImpl
{
public:
BytesView Utf8Bytes() const { return BytesView(Self().Data(), Self().Size()); }
joint::Utf32View Utf32View() const { return joint::Utf32View(Utf8Bytes()); }
protected:
~StringImpl() { }
private:
const String_& Self() const { return static_cast<const String_&>(*this); }
};
}
class StringRef : public detail::StringImpl<StringRef>
{
friend class detail::StringImpl<StringRef>;
private:
const char* _data;
size_t _size;
public:
StringRef(const char* data) // TODO: is this ok?
: _data(data), _size(strlen(data) + 1)
{ }
StringRef(const char* data, size_t size)
: _data(data), _size(size)
{ }
protected:
const char* Data() const { return _data; }
size_t Size() const { return _size; }
};
class String : public detail::StringImpl<String>
{
friend class detail::StringImpl<String>;
private:
std::string _storage;
public:
String()
{ }
String(const char* value) // TODO: is this ok?
: _storage(value)
{ }
explicit String(StringRef stringRef)
: _storage(stringRef.Utf8Bytes().data(), stringRef.Utf8Bytes().size())
{ }
explicit String(const std::string& storage)
: _storage(storage)
{ }
std::string& Storage() { return _storage; }
const std::string& Storage() const { return _storage; }
operator StringRef() const
{ return StringRef(Utf8Bytes().data(), Utf8Bytes().size()); }
protected:
const char* Data() const { return _storage.c_str(); }
size_t Size() const { return _storage.size() + 1; }
};
inline std::ostream& operator<<(std::ostream& s, const String& str)
{ return s << str.Utf8Bytes().data(); }
template < typename String1_, typename String2_ >
String operator+(const detail::StringImpl<String1_>& l, const detail::StringImpl<String2_>& r)
{
String result(l.Utf8Bytes().data()); // TODO: reimplement
result.Storage() += r.Utf8Bytes().data();
return result;
}
template < typename String1_, typename String2_ >
bool operator==(const detail::StringImpl<String1_>& l, const detail::StringImpl<String2_>& r)
{
BytesView lb = l.Utf8Bytes();
BytesView rb = r.Utf8Bytes();
return strncmp(lb.data(), rb.data(), std::min(lb.size(), rb.size())) == 0;
}
template < typename String1_, typename String2_ >
bool operator!=(const detail::StringImpl<String1_>& l, const detail::StringImpl<String2_>& r)
{ return !(l == r); }
}
#endif
<|endoftext|> |
<commit_before>//===------- MicrosoftCXXABI.cpp - AST support for the Microsoft C++ ABI --===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This provides C++ AST support targeting the Microsoft Visual C++
// ABI.
//
//===----------------------------------------------------------------------===//
#include "CXXABI.h"
#include "clang/AST/Attr.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/RecordLayout.h"
#include "clang/AST/Type.h"
#include "clang/Basic/TargetInfo.h"
using namespace clang;
namespace {
class MicrosoftCXXABI : public CXXABI {
ASTContext &Context;
public:
MicrosoftCXXABI(ASTContext &Ctx) : Context(Ctx) { }
std::pair<uint64_t, unsigned>
getMemberPointerWidthAndAlign(const MemberPointerType *MPT) const;
CallingConv getDefaultMethodCallConv(bool isVariadic) const {
if (!isVariadic && Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
return CC_X86ThisCall;
else
return CC_C;
}
bool isNearlyEmpty(const CXXRecordDecl *RD) const {
// FIXME: Audit the corners
if (!RD->isDynamicClass())
return false;
const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
// In the Microsoft ABI, classes can have one or two vtable pointers.
CharUnits PointerSize =
Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
return Layout.getNonVirtualSize() == PointerSize ||
Layout.getNonVirtualSize() == PointerSize * 2;
}
};
}
// getNumBases() seems to only give us the number of direct bases, and not the
// total. This function tells us if we inherit from anybody that uses MI, or if
// we have a non-primary base class, which uses the multiple inheritance model.
bool usesMultipleInheritanceModel(const CXXRecordDecl *RD) {
while (RD->getNumBases() > 0) {
if (RD->getNumBases() > 1)
return true;
assert(RD->getNumBases() == 1);
const CXXRecordDecl *Base = RD->bases_begin()->getType()->getAsCXXRecordDecl();
if (RD->isPolymorphic() && !Base->isPolymorphic())
return true;
RD = Base;
}
return false;
}
MSInheritanceModel MSInheritanceAttrToModel(attr::Kind Kind) {
switch (Kind) {
default: llvm_unreachable("expected MS inheritance attribute");
case attr::SingleInheritance: return MSIM_Single;
case attr::MultipleInheritance: return MSIM_Multiple;
case attr::VirtualInheritance: return MSIM_Virtual;
case attr::UnspecifiedInheritance: return MSIM_Unspecified;
}
}
MSInheritanceModel CXXRecordDecl::getMSInheritanceModel() const {
Attr *IA = this->getAttr<MSInheritanceAttr>();
if (IA)
return MSInheritanceAttrToModel(IA->getKind());
// If there was no explicit attribute, the record must be defined already, and
// we can figure out the inheritance model from its other properties.
if (this->getNumVBases() > 0)
return MSIM_Virtual;
if (usesMultipleInheritanceModel(this))
return MSIM_Multiple;
return MSIM_Single;
}
// Returns the number of pointer and integer slots used to represent a member
// pointer in the MS C++ ABI.
//
// Member function pointers have the following general form; however, fields
// are dropped as permitted (under the MSVC interpretation) by the inheritance
// model of the actual class.
//
// struct {
// // A pointer to the member function to call. If the member function is
// // virtual, this will be a thunk that forwards to the appropriate vftable
// // slot.
// void *FunctionPointerOrVirtualThunk;
//
// // An offset to add to the address of the vbtable pointer after (possibly)
// // selecting the virtual base but before resolving and calling the function.
// // Only needed if the class has any virtual bases or bases at a non-zero
// // offset.
// int NonVirtualBaseAdjustment;
//
// // An offset within the vb-table that selects the virtual base containing
// // the member. Loading from this offset produces a new offset that is
// // added to the address of the vb-table pointer to produce the base.
// int VirtualBaseAdjustmentOffset;
//
// // The offset of the vb-table pointer within the object. Only needed for
// // incomplete types.
// int VBTableOffset;
// };
std::pair<unsigned, unsigned> MemberPointerType::getMSMemberPointerSlots() const {
const CXXRecordDecl *RD = this->getClass()->getAsCXXRecordDecl();
MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
unsigned Ptrs;
unsigned Ints = 0;
if (this->isMemberFunctionPointer()) {
// Member function pointers are a struct of a function pointer followed by a
// variable number of ints depending on the inheritance model used. The
// function pointer is a real function if it is non-virtual and a vftable
// slot thunk if it is virtual. The ints select the object base passed for
// the 'this' pointer.
Ptrs = 1; // First slot is always a function pointer.
switch (Inheritance) {
case MSIM_Unspecified: ++Ints; // VBTableOffset
case MSIM_Virtual: ++Ints; // VirtualBaseAdjustmentOffset
case MSIM_Multiple: ++Ints; // NonVirtualBaseAdjustment
case MSIM_Single: break; // Nothing
}
} else {
// Data pointers are an aggregate of ints. The first int is an offset
// followed by vbtable-related offsets.
Ptrs = 0;
switch (Inheritance) {
case MSIM_Unspecified: ++Ints; // VBTableOffset
case MSIM_Virtual: ++Ints; // VirtualBaseAdjustmentOffset
case MSIM_Multiple: // Nothing
case MSIM_Single: ++Ints; // Field offset
}
}
return std::make_pair(Ptrs, Ints);
}
std::pair<uint64_t, unsigned>
MicrosoftCXXABI::getMemberPointerWidthAndAlign(const MemberPointerType *MPT) const {
const TargetInfo &Target = Context.getTargetInfo();
assert(Target.getTriple().getArch() == llvm::Triple::x86 ||
Target.getTriple().getArch() == llvm::Triple::x86_64);
unsigned Ptrs, Ints;
llvm::tie(Ptrs, Ints) = MPT->getMSMemberPointerSlots();
// The nominal struct is laid out with pointers followed by ints and aligned
// to a pointer width if any are present and an int width otherwise.
unsigned PtrSize = Target.getPointerWidth(0);
unsigned IntSize = Target.getIntWidth();
uint64_t Width = Ptrs * PtrSize + Ints * IntSize;
unsigned Align = Ptrs > 0 ? Target.getPointerAlign(0) : Target.getIntAlign();
Width = llvm::RoundUpToAlignment(Width, Align);
return std::make_pair(Width, Align);
}
CXXABI *clang::CreateMicrosoftCXXABI(ASTContext &Ctx) {
return new MicrosoftCXXABI(Ctx);
}
<commit_msg>Make helpers static & 80 cols.<commit_after>//===------- MicrosoftCXXABI.cpp - AST support for the Microsoft C++ ABI --===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This provides C++ AST support targeting the Microsoft Visual C++
// ABI.
//
//===----------------------------------------------------------------------===//
#include "CXXABI.h"
#include "clang/AST/Attr.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/RecordLayout.h"
#include "clang/AST/Type.h"
#include "clang/Basic/TargetInfo.h"
using namespace clang;
namespace {
class MicrosoftCXXABI : public CXXABI {
ASTContext &Context;
public:
MicrosoftCXXABI(ASTContext &Ctx) : Context(Ctx) { }
std::pair<uint64_t, unsigned>
getMemberPointerWidthAndAlign(const MemberPointerType *MPT) const;
CallingConv getDefaultMethodCallConv(bool isVariadic) const {
if (!isVariadic &&
Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
return CC_X86ThisCall;
return CC_C;
}
bool isNearlyEmpty(const CXXRecordDecl *RD) const {
// FIXME: Audit the corners
if (!RD->isDynamicClass())
return false;
const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
// In the Microsoft ABI, classes can have one or two vtable pointers.
CharUnits PointerSize =
Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
return Layout.getNonVirtualSize() == PointerSize ||
Layout.getNonVirtualSize() == PointerSize * 2;
}
};
}
// getNumBases() seems to only give us the number of direct bases, and not the
// total. This function tells us if we inherit from anybody that uses MI, or if
// we have a non-primary base class, which uses the multiple inheritance model.
static bool usesMultipleInheritanceModel(const CXXRecordDecl *RD) {
while (RD->getNumBases() > 0) {
if (RD->getNumBases() > 1)
return true;
assert(RD->getNumBases() == 1);
const CXXRecordDecl *Base =
RD->bases_begin()->getType()->getAsCXXRecordDecl();
if (RD->isPolymorphic() && !Base->isPolymorphic())
return true;
RD = Base;
}
return false;
}
static MSInheritanceModel MSInheritanceAttrToModel(attr::Kind Kind) {
switch (Kind) {
default: llvm_unreachable("expected MS inheritance attribute");
case attr::SingleInheritance: return MSIM_Single;
case attr::MultipleInheritance: return MSIM_Multiple;
case attr::VirtualInheritance: return MSIM_Virtual;
case attr::UnspecifiedInheritance: return MSIM_Unspecified;
}
}
MSInheritanceModel CXXRecordDecl::getMSInheritanceModel() const {
if (Attr *IA = this->getAttr<MSInheritanceAttr>())
return MSInheritanceAttrToModel(IA->getKind());
// If there was no explicit attribute, the record must be defined already, and
// we can figure out the inheritance model from its other properties.
if (this->getNumVBases() > 0)
return MSIM_Virtual;
if (usesMultipleInheritanceModel(this))
return MSIM_Multiple;
return MSIM_Single;
}
// Returns the number of pointer and integer slots used to represent a member
// pointer in the MS C++ ABI.
//
// Member function pointers have the following general form; however, fields
// are dropped as permitted (under the MSVC interpretation) by the inheritance
// model of the actual class.
//
// struct {
// // A pointer to the member function to call. If the member function is
// // virtual, this will be a thunk that forwards to the appropriate vftable
// // slot.
// void *FunctionPointerOrVirtualThunk;
//
// // An offset to add to the address of the vbtable pointer after (possibly)
// // selecting the virtual base but before resolving and calling the function.
// // Only needed if the class has any virtual bases or bases at a non-zero
// // offset.
// int NonVirtualBaseAdjustment;
//
// // An offset within the vb-table that selects the virtual base containing
// // the member. Loading from this offset produces a new offset that is
// // added to the address of the vb-table pointer to produce the base.
// int VirtualBaseAdjustmentOffset;
//
// // The offset of the vb-table pointer within the object. Only needed for
// // incomplete types.
// int VBTableOffset;
// };
std::pair<unsigned, unsigned>
MemberPointerType::getMSMemberPointerSlots() const {
const CXXRecordDecl *RD = this->getClass()->getAsCXXRecordDecl();
MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
unsigned Ptrs;
unsigned Ints = 0;
if (this->isMemberFunctionPointer()) {
// Member function pointers are a struct of a function pointer followed by a
// variable number of ints depending on the inheritance model used. The
// function pointer is a real function if it is non-virtual and a vftable
// slot thunk if it is virtual. The ints select the object base passed for
// the 'this' pointer.
Ptrs = 1; // First slot is always a function pointer.
switch (Inheritance) {
case MSIM_Unspecified: ++Ints; // VBTableOffset
case MSIM_Virtual: ++Ints; // VirtualBaseAdjustmentOffset
case MSIM_Multiple: ++Ints; // NonVirtualBaseAdjustment
case MSIM_Single: break; // Nothing
}
} else {
// Data pointers are an aggregate of ints. The first int is an offset
// followed by vbtable-related offsets.
Ptrs = 0;
switch (Inheritance) {
case MSIM_Unspecified: ++Ints; // VBTableOffset
case MSIM_Virtual: ++Ints; // VirtualBaseAdjustmentOffset
case MSIM_Multiple: // Nothing
case MSIM_Single: ++Ints; // Field offset
}
}
return std::make_pair(Ptrs, Ints);
}
std::pair<uint64_t, unsigned> MicrosoftCXXABI::getMemberPointerWidthAndAlign(
const MemberPointerType *MPT) const {
const TargetInfo &Target = Context.getTargetInfo();
assert(Target.getTriple().getArch() == llvm::Triple::x86 ||
Target.getTriple().getArch() == llvm::Triple::x86_64);
unsigned Ptrs, Ints;
llvm::tie(Ptrs, Ints) = MPT->getMSMemberPointerSlots();
// The nominal struct is laid out with pointers followed by ints and aligned
// to a pointer width if any are present and an int width otherwise.
unsigned PtrSize = Target.getPointerWidth(0);
unsigned IntSize = Target.getIntWidth();
uint64_t Width = Ptrs * PtrSize + Ints * IntSize;
unsigned Align = Ptrs > 0 ? Target.getPointerAlign(0) : Target.getIntAlign();
Width = llvm::RoundUpToAlignment(Width, Align);
return std::make_pair(Width, Align);
}
CXXABI *clang::CreateMicrosoftCXXABI(ASTContext &Ctx) {
return new MicrosoftCXXABI(Ctx);
}
<|endoftext|> |
<commit_before>//===- lib/Linker/LinkArchives.cpp - Link LLVM objects and libraries ------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains routines to handle linking together LLVM bitcode files,
// and to handle annoying things like static libraries.
//
//===----------------------------------------------------------------------===//
#include "llvm/Linker.h"
#include "llvm/Module.h"
#include "llvm/ModuleProvider.h"
#include "llvm/ADT/SetOperations.h"
#include "llvm/Bitcode/Archive.h"
#include "llvm/Config/config.h"
#include <memory>
#include <set>
using namespace llvm;
/// GetAllUndefinedSymbols - calculates the set of undefined symbols that still
/// exist in an LLVM module. This is a bit tricky because there may be two
/// symbols with the same name but different LLVM types that will be resolved to
/// each other but aren't currently (thus we need to treat it as resolved).
///
/// Inputs:
/// M - The module in which to find undefined symbols.
///
/// Outputs:
/// UndefinedSymbols - A set of C++ strings containing the name of all
/// undefined symbols.
///
static void
GetAllUndefinedSymbols(Module *M, std::set<std::string> &UndefinedSymbols) {
std::set<std::string> DefinedSymbols;
UndefinedSymbols.clear();
// If the program doesn't define a main, try pulling one in from a .a file.
// This is needed for programs where the main function is defined in an
// archive, such f2c'd programs.
Function *Main = M->getFunction("main");
if (Main == 0 || Main->isDeclaration())
UndefinedSymbols.insert("main");
for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
if (I->hasName()) {
if (I->isDeclaration())
UndefinedSymbols.insert(I->getName());
else if (!I->hasInternalLinkage()) {
assert(!I->hasDLLImportLinkage()
&& "Found dllimported non-external symbol!");
DefinedSymbols.insert(I->getName());
}
}
for (Module::global_iterator I = M->global_begin(), E = M->global_end();
I != E; ++I)
if (I->hasName()) {
if (I->isDeclaration())
UndefinedSymbols.insert(I->getName());
else if (!I->hasInternalLinkage()) {
assert(!I->hasDLLImportLinkage()
&& "Found dllimported non-external symbol!");
DefinedSymbols.insert(I->getName());
}
}
// Prune out any defined symbols from the undefined symbols set...
for (std::set<std::string>::iterator I = UndefinedSymbols.begin();
I != UndefinedSymbols.end(); )
if (DefinedSymbols.count(*I))
UndefinedSymbols.erase(I++); // This symbol really is defined!
else
++I; // Keep this symbol in the undefined symbols list
}
/// LinkInArchive - opens an archive library and link in all objects which
/// provide symbols that are currently undefined.
///
/// Inputs:
/// Filename - The pathname of the archive.
///
/// Return Value:
/// TRUE - An error occurred.
/// FALSE - No errors.
bool
Linker::LinkInArchive(const sys::Path &Filename, bool &is_native) {
// Make sure this is an archive file we're dealing with
if (!Filename.isArchive())
return error("File '" + Filename.toString() + "' is not an archive.");
// Open the archive file
verbose("Linking archive file '" + Filename.toString() + "'");
// Find all of the symbols currently undefined in the bitcode program.
// If all the symbols are defined, the program is complete, and there is
// no reason to link in any archive files.
std::set<std::string> UndefinedSymbols;
GetAllUndefinedSymbols(Composite, UndefinedSymbols);
if (UndefinedSymbols.empty()) {
verbose("No symbols undefined, skipping library '" +
Filename.toString() + "'");
return false; // No need to link anything in!
}
std::string ErrMsg;
std::auto_ptr<Archive> AutoArch (
Archive::OpenAndLoadSymbols(Filename,&ErrMsg));
Archive* arch = AutoArch.get();
if (!arch)
return error("Cannot read archive '" + Filename.toString() +
"': " + ErrMsg);
if (!arch->isBitcodeArchive()) {
is_native = true;
return false;
}
is_native = false;
// Save a set of symbols that are not defined by the archive. Since we're
// entering a loop, there's no point searching for these multiple times. This
// variable is used to "set_subtract" from the set of undefined symbols.
std::set<std::string> NotDefinedByArchive;
// Save the current set of undefined symbols, because we may have to make
// multiple passes over the archive:
std::set<std::string> CurrentlyUndefinedSymbols;
do {
CurrentlyUndefinedSymbols = UndefinedSymbols;
// Find the modules we need to link into the target module
std::set<ModuleProvider*> Modules;
if (!arch->findModulesDefiningSymbols(UndefinedSymbols, Modules, &ErrMsg))
return error("Cannot find symbols in '" + Filename.toString() +
"': " + ErrMsg);
// If we didn't find any more modules to link this time, we are done
// searching this archive.
if (Modules.empty())
break;
// Any symbols remaining in UndefinedSymbols after
// findModulesDefiningSymbols are ones that the archive does not define. So
// we add them to the NotDefinedByArchive variable now.
NotDefinedByArchive.insert(UndefinedSymbols.begin(),
UndefinedSymbols.end());
// Loop over all the ModuleProviders that we got back from the archive
for (std::set<ModuleProvider*>::iterator I=Modules.begin(), E=Modules.end();
I != E; ++I) {
// Get the module we must link in.
std::string moduleErrorMsg;
std::auto_ptr<Module> AutoModule((*I)->releaseModule( &moduleErrorMsg ));
Module* aModule = AutoModule.get();
if (aModule != NULL) {
verbose(" Linking in module: " + aModule->getModuleIdentifier());
// Link it in
if (LinkInModule(aModule, &moduleErrorMsg)) {
return error("Cannot link in module '" +
aModule->getModuleIdentifier() + "': " + moduleErrorMsg);
}
}
}
// Get the undefined symbols from the aggregate module. This recomputes the
// symbols we still need after the new modules have been linked in.
GetAllUndefinedSymbols(Composite, UndefinedSymbols);
// At this point we have two sets of undefined symbols: UndefinedSymbols
// which holds the undefined symbols from all the modules, and
// NotDefinedByArchive which holds symbols we know the archive doesn't
// define. There's no point searching for symbols that we won't find in the
// archive so we subtract these sets.
set_subtract(UndefinedSymbols, NotDefinedByArchive);
// If there's no symbols left, no point in continuing to search the
// archive.
if (UndefinedSymbols.empty())
break;
} while (CurrentlyUndefinedSymbols != UndefinedSymbols);
return false;
}
<commit_msg>Report an error if one occurs in releaseModule.<commit_after>//===- lib/Linker/LinkArchives.cpp - Link LLVM objects and libraries ------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains routines to handle linking together LLVM bitcode files,
// and to handle annoying things like static libraries.
//
//===----------------------------------------------------------------------===//
#include "llvm/Linker.h"
#include "llvm/Module.h"
#include "llvm/ModuleProvider.h"
#include "llvm/ADT/SetOperations.h"
#include "llvm/Bitcode/Archive.h"
#include "llvm/Config/config.h"
#include <memory>
#include <set>
using namespace llvm;
/// GetAllUndefinedSymbols - calculates the set of undefined symbols that still
/// exist in an LLVM module. This is a bit tricky because there may be two
/// symbols with the same name but different LLVM types that will be resolved to
/// each other but aren't currently (thus we need to treat it as resolved).
///
/// Inputs:
/// M - The module in which to find undefined symbols.
///
/// Outputs:
/// UndefinedSymbols - A set of C++ strings containing the name of all
/// undefined symbols.
///
static void
GetAllUndefinedSymbols(Module *M, std::set<std::string> &UndefinedSymbols) {
std::set<std::string> DefinedSymbols;
UndefinedSymbols.clear();
// If the program doesn't define a main, try pulling one in from a .a file.
// This is needed for programs where the main function is defined in an
// archive, such f2c'd programs.
Function *Main = M->getFunction("main");
if (Main == 0 || Main->isDeclaration())
UndefinedSymbols.insert("main");
for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
if (I->hasName()) {
if (I->isDeclaration())
UndefinedSymbols.insert(I->getName());
else if (!I->hasInternalLinkage()) {
assert(!I->hasDLLImportLinkage()
&& "Found dllimported non-external symbol!");
DefinedSymbols.insert(I->getName());
}
}
for (Module::global_iterator I = M->global_begin(), E = M->global_end();
I != E; ++I)
if (I->hasName()) {
if (I->isDeclaration())
UndefinedSymbols.insert(I->getName());
else if (!I->hasInternalLinkage()) {
assert(!I->hasDLLImportLinkage()
&& "Found dllimported non-external symbol!");
DefinedSymbols.insert(I->getName());
}
}
// Prune out any defined symbols from the undefined symbols set...
for (std::set<std::string>::iterator I = UndefinedSymbols.begin();
I != UndefinedSymbols.end(); )
if (DefinedSymbols.count(*I))
UndefinedSymbols.erase(I++); // This symbol really is defined!
else
++I; // Keep this symbol in the undefined symbols list
}
/// LinkInArchive - opens an archive library and link in all objects which
/// provide symbols that are currently undefined.
///
/// Inputs:
/// Filename - The pathname of the archive.
///
/// Return Value:
/// TRUE - An error occurred.
/// FALSE - No errors.
bool
Linker::LinkInArchive(const sys::Path &Filename, bool &is_native) {
// Make sure this is an archive file we're dealing with
if (!Filename.isArchive())
return error("File '" + Filename.toString() + "' is not an archive.");
// Open the archive file
verbose("Linking archive file '" + Filename.toString() + "'");
// Find all of the symbols currently undefined in the bitcode program.
// If all the symbols are defined, the program is complete, and there is
// no reason to link in any archive files.
std::set<std::string> UndefinedSymbols;
GetAllUndefinedSymbols(Composite, UndefinedSymbols);
if (UndefinedSymbols.empty()) {
verbose("No symbols undefined, skipping library '" +
Filename.toString() + "'");
return false; // No need to link anything in!
}
std::string ErrMsg;
std::auto_ptr<Archive> AutoArch (
Archive::OpenAndLoadSymbols(Filename,&ErrMsg));
Archive* arch = AutoArch.get();
if (!arch)
return error("Cannot read archive '" + Filename.toString() +
"': " + ErrMsg);
if (!arch->isBitcodeArchive()) {
is_native = true;
return false;
}
is_native = false;
// Save a set of symbols that are not defined by the archive. Since we're
// entering a loop, there's no point searching for these multiple times. This
// variable is used to "set_subtract" from the set of undefined symbols.
std::set<std::string> NotDefinedByArchive;
// Save the current set of undefined symbols, because we may have to make
// multiple passes over the archive:
std::set<std::string> CurrentlyUndefinedSymbols;
do {
CurrentlyUndefinedSymbols = UndefinedSymbols;
// Find the modules we need to link into the target module
std::set<ModuleProvider*> Modules;
if (!arch->findModulesDefiningSymbols(UndefinedSymbols, Modules, &ErrMsg))
return error("Cannot find symbols in '" + Filename.toString() +
"': " + ErrMsg);
// If we didn't find any more modules to link this time, we are done
// searching this archive.
if (Modules.empty())
break;
// Any symbols remaining in UndefinedSymbols after
// findModulesDefiningSymbols are ones that the archive does not define. So
// we add them to the NotDefinedByArchive variable now.
NotDefinedByArchive.insert(UndefinedSymbols.begin(),
UndefinedSymbols.end());
// Loop over all the ModuleProviders that we got back from the archive
for (std::set<ModuleProvider*>::iterator I=Modules.begin(), E=Modules.end();
I != E; ++I) {
// Get the module we must link in.
std::string moduleErrorMsg;
std::auto_ptr<Module> AutoModule((*I)->releaseModule( &moduleErrorMsg ));
if (!moduleErrorMsg.empty())
return error("Could not load a module: " + moduleErrorMsg);
Module* aModule = AutoModule.get();
if (aModule != NULL) {
verbose(" Linking in module: " + aModule->getModuleIdentifier());
// Link it in
if (LinkInModule(aModule, &moduleErrorMsg)) {
return error("Cannot link in module '" +
aModule->getModuleIdentifier() + "': " + moduleErrorMsg);
}
}
}
// Get the undefined symbols from the aggregate module. This recomputes the
// symbols we still need after the new modules have been linked in.
GetAllUndefinedSymbols(Composite, UndefinedSymbols);
// At this point we have two sets of undefined symbols: UndefinedSymbols
// which holds the undefined symbols from all the modules, and
// NotDefinedByArchive which holds symbols we know the archive doesn't
// define. There's no point searching for symbols that we won't find in the
// archive so we subtract these sets.
set_subtract(UndefinedSymbols, NotDefinedByArchive);
// If there's no symbols left, no point in continuing to search the
// archive.
if (UndefinedSymbols.empty())
break;
} while (CurrentlyUndefinedSymbols != UndefinedSymbols);
return false;
}
<|endoftext|> |
<commit_before><commit_msg>loplugin:cstylecast<commit_after><|endoftext|> |
<commit_before>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
// this file defines the otbCommonTest for the test driver
// and all it expects is that you have a function called RegisterTests
#include "otbTestMain.h"
void RegisterTests()
{
REGISTER_TEST(otbStreamingImageFileWriterTestCalculateNumberOfDivisions);
REGISTER_TEST(otbStreamingImageFileWriterWithFilterTest);
REGISTER_TEST(otbStreamingWithImageFileWriterTestCalculateNumberOfDivisions);
}
<commit_msg>COMP: Fixing error in massive tests renaming<commit_after>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
// this file defines the otbCommonTest for the test driver
// and all it expects is that you have a function called RegisterTests
#include "otbTestMain.h"
void RegisterTests()
{
REGISTER_TEST(otbImageFileWriterTestCalculateNumberOfDivisions);
REGISTER_TEST(otbImageFileWriterWithFilterTest);
REGISTER_TEST(otbStreamingWithImageFileWriterTestCalculateNumberOfDivisions);
}
<|endoftext|> |
<commit_before>//=======================================================================
// Copyright (c) 2014-2015 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#ifndef CPP_UTILS_PARALLEL_HPP
#define CPP_UTILS_PARALLEL_HPP
#include "parallel.hpp"
namespace cpp {
template<bool Parallel>
struct thread_pool {
//Does not do anything by default
};
template<>
struct thread_pool<true> : default_thread_pool<> {
//Simply inherits from default thread pool
};
//parallel versions
template<typename Container, typename Functor>
void maybe_parallel_foreach(thread_pool<true>& thread_pool, const Container& container, Functor&& fun){
parallel_foreach(thread_pool, container, std::forward<Functor>(fun));
}
template<typename Iterator, typename Functor>
void maybe_parallel_foreach(thread_pool<true>& thread_pool, Iterator first, Iterator last, Functor&& fun){
parallel_foreach(thread_pool, first, last, std::forward<Functor>(fun));
}
template<typename Container, typename Functor>
void maybe_parallel_foreach_i(thread_pool<true>& thread_pool, const Container& container, Functor&& fun){
parallel_foreach_i(thread_pool, container, std::forward<Functor>(fun));
}
template<typename Iterator, typename Functor>
void maybe_parallel_foreach_i(thread_pool<true>& thread_pool, Iterator it, Iterator end, Functor&& fun){
parallel_foreach_i(thread_pool, it, end, std::forward<Functor>(fun));
}
template<typename Iterator, typename Iterator2, typename Functor>
void maybe_parallel_foreach_pair_i(thread_pool<true>& thread_pool, Iterator it, Iterator end, Iterator2 iit, Iterator2 ilast, Functor&& fun){
parallel_foreach_pair_i(thread_pool, it, end, iit, ilast, std::forward<Functor>(fun));
}
template<typename Functor>
void maybe_parallel_foreach_n(thread_pool<true>& thread_pool, std::size_t first, std::size_t last, Functor&& fun){
parallel_foreach_n(thread_pool, first, last, std::forward<Functor>(fun));
}
//non-parallel versions
template<typename Container, typename Functor>
void maybe_parallel_foreach(thread_pool<false>& /*thread_pool*/, const Container& container, Functor&& fun){
foreach(container, fun);
}
template<typename Iterator, typename Functor>
void maybe_parallel_foreach(thread_pool<false>& /*thread_pool*/, Iterator first, Iterator last, Functor&& fun){
foreach(first, last, fun);
}
template<typename Container, typename Functor>
void maybe_parallel_foreach_i(thread_pool<false>& /*thread_pool*/, const Container& container, Functor&& fun){
foreach_i(container, fun);
}
template<typename Iterator, typename Functor>
void maybe_parallel_foreach_i(thread_pool<false>& /*thread_pool*/, Iterator it, Iterator end, Functor&& fun){
foreach_i(it, end);
}
template<typename Iterator, typename Iterator2, typename Functor>
void maybe_parallel_foreach_pair_i(thread_pool<false>& /*thread_pool*/, Iterator it, Iterator end, Iterator2 iit, Iterator2 ilast, Functor&& fun){
cpp_unused(ilast);
for(std::size_t i = 0; it != end; ++it, ++iit, ++i){
fun(*it, *iit, i);
}
}
template<typename functor>
void maybe_parallel_foreach_n(thread_pool<false>& /*thread_pool*/, std::size_t first, std::size_t last, functor&& fun){
foreach_n(first, last, fun);
}
} //end of dll namespace
#endif
<commit_msg>Fix include guard<commit_after>//=======================================================================
// Copyright (c) 2014-2015 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#ifndef CPP_UTILS_MAYBE_PARALLEL_HPP
#define CPP_UTILS_MAYBE_PARALLEL_HPP
#include "parallel.hpp"
namespace cpp {
template<bool Parallel>
struct thread_pool {
//Does not do anything by default
};
template<>
struct thread_pool<true> : default_thread_pool<> {
//Simply inherits from default thread pool
};
//parallel versions
template<typename Container, typename Functor>
void maybe_parallel_foreach(thread_pool<true>& thread_pool, const Container& container, Functor&& fun){
parallel_foreach(thread_pool, container, std::forward<Functor>(fun));
}
template<typename Iterator, typename Functor>
void maybe_parallel_foreach(thread_pool<true>& thread_pool, Iterator first, Iterator last, Functor&& fun){
parallel_foreach(thread_pool, first, last, std::forward<Functor>(fun));
}
template<typename Container, typename Functor>
void maybe_parallel_foreach_i(thread_pool<true>& thread_pool, const Container& container, Functor&& fun){
parallel_foreach_i(thread_pool, container, std::forward<Functor>(fun));
}
template<typename Iterator, typename Functor>
void maybe_parallel_foreach_i(thread_pool<true>& thread_pool, Iterator it, Iterator end, Functor&& fun){
parallel_foreach_i(thread_pool, it, end, std::forward<Functor>(fun));
}
template<typename Iterator, typename Iterator2, typename Functor>
void maybe_parallel_foreach_pair_i(thread_pool<true>& thread_pool, Iterator it, Iterator end, Iterator2 iit, Iterator2 ilast, Functor&& fun){
parallel_foreach_pair_i(thread_pool, it, end, iit, ilast, std::forward<Functor>(fun));
}
template<typename Functor>
void maybe_parallel_foreach_n(thread_pool<true>& thread_pool, std::size_t first, std::size_t last, Functor&& fun){
parallel_foreach_n(thread_pool, first, last, std::forward<Functor>(fun));
}
//non-parallel versions
template<typename Container, typename Functor>
void maybe_parallel_foreach(thread_pool<false>& /*thread_pool*/, const Container& container, Functor&& fun){
foreach(container, fun);
}
template<typename Iterator, typename Functor>
void maybe_parallel_foreach(thread_pool<false>& /*thread_pool*/, Iterator first, Iterator last, Functor&& fun){
foreach(first, last, fun);
}
template<typename Container, typename Functor>
void maybe_parallel_foreach_i(thread_pool<false>& /*thread_pool*/, const Container& container, Functor&& fun){
foreach_i(container, fun);
}
template<typename Iterator, typename Functor>
void maybe_parallel_foreach_i(thread_pool<false>& /*thread_pool*/, Iterator it, Iterator end, Functor&& fun){
foreach_i(it, end);
}
template<typename Iterator, typename Iterator2, typename Functor>
void maybe_parallel_foreach_pair_i(thread_pool<false>& /*thread_pool*/, Iterator it, Iterator end, Iterator2 iit, Iterator2 ilast, Functor&& fun){
cpp_unused(ilast);
for(std::size_t i = 0; it != end; ++it, ++iit, ++i){
fun(*it, *iit, i);
}
}
template<typename functor>
void maybe_parallel_foreach_n(thread_pool<false>& /*thread_pool*/, std::size_t first, std::size_t last, functor&& fun){
foreach_n(first, last, fun);
}
} //end of dll namespace
#endif
<|endoftext|> |
<commit_before>/***********************************************************************
filename: CEGUIPCRERegexMatcher.cpp
created: Mon Jul 27 2009
author: Paul D Turner <paul@cegui.org.uk>
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2009 Paul D Turner & The CEGUI Development Team
*
* 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 BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#include "CEGUI/PCRERegexMatcher.h"
#include "CEGUI/Exceptions.h"
#include "CEGUI/PropertyHelper.h"
// Start of CEGUI namespace section
namespace CEGUI
{
//----------------------------------------------------------------------------//
PCRERegexMatcher::PCRERegexMatcher() :
d_regex(0)
{
}
//----------------------------------------------------------------------------//
PCRERegexMatcher::~PCRERegexMatcher()
{
release();
}
//----------------------------------------------------------------------------//
void PCRERegexMatcher::setRegexString(const String& regex)
{
// release old regex string.
release();
d_string.clear();
// try to compile this new regex string
const char* prce_error;
int pcre_erroff;
d_regex = pcre_compile(regex.c_str(), PCRE_UTF8,
&prce_error, &pcre_erroff, 0);
// handle failure
if (!d_regex)
CEGUI_THROW(InvalidRequestException(
"Bad RegEx set: '" + regex + "'. Additional Information: " +
prce_error));
// set this last so that upon failure object is in consistant state.
d_string = regex;
}
//----------------------------------------------------------------------------//
const String& PCRERegexMatcher::getRegexString() const
{
return d_string;
}
//----------------------------------------------------------------------------//
RegexMatcher::MatchState PCRERegexMatcher::getMatchStateOfString(
const String& str) const
{
// if the regex is not valid, then an exception is thrown
if (!d_regex)
CEGUI_THROW(InvalidRequestException(
"Attempt to use invalid RegEx '" + d_string + "'."));
int match[3];
const char* utf8_str = str.c_str();
const int len = static_cast<int>(strlen(utf8_str));
const int result = pcre_exec(d_regex, 0, utf8_str, len, 0,
PCRE_PARTIAL_SOFT | PCRE_ANCHORED, match, 3);
if (result == PCRE_ERROR_PARTIAL)
return MS_PARTIAL;
// a match must be for the entire string
if (result >= 0)
return (match[1] - match[0] == len) ? MS_VALID : MS_INVALID;
// no match found or if test string or regex is 0
if (result == PCRE_ERROR_NOMATCH || result == PCRE_ERROR_NULL)
return MS_INVALID;
// anything else is an error
CEGUI_THROW(InvalidRequestException(
"PCRE Error: " + PropertyHelper<int>::toString(result) +
" occurred while attempting to match the RegEx '" +
d_string + "'."));
}
//----------------------------------------------------------------------------//
void PCRERegexMatcher::release()
{
if (d_regex)
{
pcre_free(d_regex);
d_regex = 0;
}
}
} // End of CEGUI namespace section
<commit_msg>Support pcre < 8.0 with the backwards compatible PCRE_PARTIAL option<commit_after>/***********************************************************************
filename: CEGUIPCRERegexMatcher.cpp
created: Mon Jul 27 2009
author: Paul D Turner <paul@cegui.org.uk>
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2009 Paul D Turner & The CEGUI Development Team
*
* 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 BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#include "CEGUI/PCRERegexMatcher.h"
#include "CEGUI/Exceptions.h"
#include "CEGUI/PropertyHelper.h"
// Start of CEGUI namespace section
namespace CEGUI
{
//----------------------------------------------------------------------------//
PCRERegexMatcher::PCRERegexMatcher() :
d_regex(0)
{
}
//----------------------------------------------------------------------------//
PCRERegexMatcher::~PCRERegexMatcher()
{
release();
}
//----------------------------------------------------------------------------//
void PCRERegexMatcher::setRegexString(const String& regex)
{
// release old regex string.
release();
d_string.clear();
// try to compile this new regex string
const char* prce_error;
int pcre_erroff;
d_regex = pcre_compile(regex.c_str(), PCRE_UTF8,
&prce_error, &pcre_erroff, 0);
// handle failure
if (!d_regex)
CEGUI_THROW(InvalidRequestException(
"Bad RegEx set: '" + regex + "'. Additional Information: " +
prce_error));
// set this last so that upon failure object is in consistant state.
d_string = regex;
}
//----------------------------------------------------------------------------//
const String& PCRERegexMatcher::getRegexString() const
{
return d_string;
}
//----------------------------------------------------------------------------//
RegexMatcher::MatchState PCRERegexMatcher::getMatchStateOfString(
const String& str) const
{
// if the regex is not valid, then an exception is thrown
if (!d_regex)
CEGUI_THROW(InvalidRequestException(
"Attempt to use invalid RegEx '" + d_string + "'."));
int match[3];
const char* utf8_str = str.c_str();
const int len = static_cast<int>(strlen(utf8_str));
// PCRE_PARTIAL is a backwards compatible synonym for PCRE_PARTIAL_SOFT
// using it is a requirement if we want to support pcre < 8.0
const int result = pcre_exec(d_regex, 0, utf8_str, len, 0,
PCRE_PARTIAL | PCRE_ANCHORED, match, 3);
if (result == PCRE_ERROR_PARTIAL)
return MS_PARTIAL;
// a match must be for the entire string
if (result >= 0)
return (match[1] - match[0] == len) ? MS_VALID : MS_INVALID;
// no match found or if test string or regex is 0
if (result == PCRE_ERROR_NOMATCH || result == PCRE_ERROR_NULL)
return MS_INVALID;
// anything else is an error
CEGUI_THROW(InvalidRequestException(
"PCRE Error: " + PropertyHelper<int>::toString(result) +
" occurred while attempting to match the RegEx '" +
d_string + "'."));
}
//----------------------------------------------------------------------------//
void PCRERegexMatcher::release()
{
if (d_regex)
{
pcre_free(d_regex);
d_regex = 0;
}
}
} // End of CEGUI namespace section
<|endoftext|> |
<commit_before>/**************************************************************************
*
* Copyright 2014 VMware, Inc
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
**************************************************************************/
#include "d3d9state.hpp"
#include <assert.h>
#include <stdint.h>
#include "image.hpp"
#include "halffloat.hpp"
#ifdef HAVE_DXGI
#include "dxgistate.hpp"
#endif
std::ostream &
operator << (std::ostream &os, D3DFORMAT Format) {
if (Format >= 0 && Format < 256) {
return os << (unsigned)Format;
} else {
char ch0 = Format;
char ch1 = Format >> 8;
char ch2 = Format >> 16;
char ch3 = Format >> 24;
return os << "'" << ch0 << ch1 << ch2 << ch3 << "'";
}
return os;
}
namespace d3dstate {
#ifdef HAVE_DXGI
/**
* http://msdn.microsoft.com/en-us/library/windows/desktop/cc308051.aspx
*/
static DXGI_FORMAT
convertFormatDXGI(D3DFORMAT Format)
{
switch ((int)Format) {
case D3DFMT_UNKNOWN:
return DXGI_FORMAT_UNKNOWN;
case D3DFMT_A8R8G8B8:
return DXGI_FORMAT_B8G8R8A8_UNORM;
case D3DFMT_X8R8G8B8:
return DXGI_FORMAT_B8G8R8X8_UNORM;
case D3DFMT_R5G6B5:
return DXGI_FORMAT_B5G6R5_UNORM;
case D3DFMT_A1R5G5B5:
return DXGI_FORMAT_B5G5R5A1_UNORM;
case D3DFMT_A4R4G4B4:
return DXGI_FORMAT_B4G4R4A4_UNORM;
case D3DFMT_A8:
return DXGI_FORMAT_A8_UNORM;
case D3DFMT_A2B10G10R10:
return DXGI_FORMAT_R10G10B10A2_UNORM;
case D3DFMT_A8B8G8R8:
return DXGI_FORMAT_R8G8B8A8_UNORM;
case D3DFMT_G16R16:
return DXGI_FORMAT_R16G16_UNORM;
case D3DFMT_A16B16G16R16:
return DXGI_FORMAT_R16G16B16A16_UNORM;
case D3DFMT_L8:
return DXGI_FORMAT_R8_UNORM;
case D3DFMT_V8U8:
return DXGI_FORMAT_R8G8_SNORM;
case D3DFMT_Q8W8V8U8:
return DXGI_FORMAT_R8G8B8A8_SNORM;
case D3DFMT_V16U16:
return DXGI_FORMAT_R16G16_SNORM;
case D3DFMT_R8G8_B8G8:
return DXGI_FORMAT_G8R8_G8B8_UNORM;
case D3DFMT_G8R8_G8B8:
return DXGI_FORMAT_R8G8_B8G8_UNORM;
case D3DFMT_DXT1:
return DXGI_FORMAT_BC1_UNORM;
case D3DFMT_DXT2:
return DXGI_FORMAT_BC2_UNORM;
case D3DFMT_DXT3:
return DXGI_FORMAT_BC2_UNORM;
case D3DFMT_DXT4:
return DXGI_FORMAT_BC3_UNORM;
case D3DFMT_DXT5:
return DXGI_FORMAT_BC3_UNORM;
case D3DFMT_D16:
case D3DFMT_D16_LOCKABLE:
return DXGI_FORMAT_D16_UNORM;
case D3DFMT_D32F_LOCKABLE:
return DXGI_FORMAT_D32_FLOAT;
case D3DFMT_D24S8:
return DXGI_FORMAT_D24_UNORM_S8_UINT;
case D3DFMT_L16:
return DXGI_FORMAT_R16_UNORM;
case D3DFMT_INDEX16:
return DXGI_FORMAT_R16_UINT;
case D3DFMT_INDEX32:
return DXGI_FORMAT_R32_UINT;
case D3DFMT_Q16W16V16U16:
return DXGI_FORMAT_R16G16B16A16_SNORM;
case D3DFMT_R16F:
return DXGI_FORMAT_R16_FLOAT;
case D3DFMT_G16R16F:
return DXGI_FORMAT_R16G16_FLOAT;
case D3DFMT_A16B16G16R16F:
return DXGI_FORMAT_R16G16B16A16_FLOAT;
case D3DFMT_R32F:
return DXGI_FORMAT_R32_FLOAT;
case D3DFMT_G32R32F:
return DXGI_FORMAT_R32G32_FLOAT;
case D3DFMT_A32B32G32R32F:
return DXGI_FORMAT_R32G32B32A32_FLOAT;
case D3DFMT_ATI1N:
return DXGI_FORMAT_BC4_UNORM;
case D3DFMT_ATI2N:
return DXGI_FORMAT_BC5_UNORM;
default:
return DXGI_FORMAT_UNKNOWN;
}
}
image::Image *
ConvertImageDXGI(D3DFORMAT SrcFormat,
void *SrcData,
INT SrcPitch,
UINT Width, UINT Height)
{
DXGI_FORMAT Format = convertFormatDXGI(SrcFormat);
if (Format == DXGI_FORMAT_UNKNOWN) {
return NULL;
}
assert(SrcPitch >= 0);
return ConvertImage(Format, SrcData, SrcPitch, Width, Height);
}
#endif /* HAVE_DXGI */
image::Image *
ConvertImage(D3DFORMAT SrcFormat,
void *SrcData,
INT SrcPitch,
UINT Width, UINT Height)
{
image::Image *image;
unsigned numChannels;
image::ChannelType channelType;
switch (SrcFormat) {
case D3DFMT_A8R8G8B8:
case D3DFMT_A8B8G8R8:
numChannels = 4;
channelType = image::TYPE_UNORM8;
break;
case D3DFMT_A32B32G32R32F:
case D3DFMT_A16B16G16R16F:
numChannels = 4;
channelType = image::TYPE_FLOAT;
break;
case D3DFMT_X8R8G8B8:
case D3DFMT_R5G6B5:
numChannels = 3;
channelType = image::TYPE_UNORM8;
break;
case D3DFMT_G32R32F:
case D3DFMT_G16R16F:
numChannels = 2;
channelType = image::TYPE_FLOAT;
break;
case D3DFMT_R32F:
case D3DFMT_R16F:
case D3DFMT_D16:
case D3DFMT_D16_LOCKABLE:
case D3DFMT_D24S8:
case D3DFMT_D24X8:
case D3DFMT_D32F_LOCKABLE:
case D3DFMT_DF16:
case D3DFMT_DF24:
case D3DFMT_INTZ:
numChannels = 1;
channelType = image::TYPE_FLOAT;
break;
default:
#ifdef HAVE_DXGI
image = ConvertImageDXGI(SrcFormat, SrcData, SrcPitch, Width, Height);
if (image) {
return image;
}
#endif
std::cerr << "warning: unsupported D3DFORMAT " << SrcFormat << "\n";
return NULL;
}
image = new image::Image(Width, Height, numChannels, true, channelType);
if (!image) {
return NULL;
}
const unsigned char *src;
unsigned char *dst;
dst = image->start();
src = (const unsigned char *)SrcData;
for (unsigned y = 0; y < Height; ++y) {
switch (SrcFormat) {
case D3DFMT_A8R8G8B8:
for (unsigned x = 0; x < Width; ++x) {
dst[4*x + 0] = src[4*x + 2];
dst[4*x + 1] = src[4*x + 1];
dst[4*x + 2] = src[4*x + 0];
dst[4*x + 3] = src[4*x + 3];
}
break;
case D3DFMT_A8B8G8R8:
for (unsigned x = 0; x < Width; ++x) {
dst[4*x + 0] = src[4*x + 0];
dst[4*x + 1] = src[4*x + 1];
dst[4*x + 2] = src[4*x + 2];
dst[4*x + 3] = src[4*x + 3];
}
break;
case D3DFMT_R5G6B5:
for (unsigned x = 0; x < Width; ++x) {
uint32_t pixel = ((const uint16_t *)src)[x];
dst[3*x + 0] = (( pixel & 0x1f) * (2*0xff) + 0x1f) / (2*0x1f);
dst[3*x + 1] = (((pixel >> 5) & 0x3f) * (2*0xff) + 0x3f) / (2*0x3f);
dst[3*x + 2] = (( pixel >> 11 ) * (2*0xff) + 0x1f) / (2*0x1f);
}
break;
case D3DFMT_X8R8G8B8:
for (unsigned x = 0; x < Width; ++x) {
dst[3*x + 0] = src[4*x + 2];
dst[3*x + 1] = src[4*x + 1];
dst[3*x + 2] = src[4*x + 0];
}
break;
case D3DFMT_A32B32G32R32F:
for (unsigned x = 0; x < Width; ++x) {
((float *)dst)[4*x + 0] = ((const float *)src)[4*x + 0];
((float *)dst)[4*x + 1] = ((const float *)src)[4*x + 1];
((float *)dst)[4*x + 2] = ((const float *)src)[4*x + 2];
((float *)dst)[4*x + 3] = ((const float *)src)[4*x + 3];
}
break;
case D3DFMT_A16B16G16R16F:
for (unsigned x = 0; x < Width; ++x) {
((float *)dst)[4*x + 0] = util_half_to_float(((const uint16_t *)src)[4*x + 0]);
((float *)dst)[4*x + 1] = util_half_to_float(((const uint16_t *)src)[4*x + 1]);
((float *)dst)[4*x + 2] = util_half_to_float(((const uint16_t *)src)[4*x + 2]);
((float *)dst)[4*x + 3] = util_half_to_float(((const uint16_t *)src)[4*x + 3]);
}
break;
case D3DFMT_G32R32F:
for (unsigned x = 0; x < Width; ++x) {
((float *)dst)[2*x + 0] = ((const float *)src)[2*x + 0];
((float *)dst)[2*x + 1] = ((const float *)src)[2*x + 1];
}
break;
case D3DFMT_G16R16F:
for (unsigned x = 0; x < Width; ++x) {
((float *)dst)[2*x + 0] = util_half_to_float(((const uint16_t *)src)[2*x + 0]);
((float *)dst)[2*x + 1] = util_half_to_float(((const uint16_t *)src)[2*x + 1]);
}
break;
case D3DFMT_D16:
case D3DFMT_D16_LOCKABLE:
case D3DFMT_DF16:
for (unsigned x = 0; x < Width; ++x) {
((float *)dst)[x] = ((const uint16_t *)src)[x] * (1.0f / 0xffff);
}
break;
case D3DFMT_D24S8:
case D3DFMT_D24X8:
case D3DFMT_DF24:
case D3DFMT_INTZ:
for (unsigned x = 0; x < Width; ++x) {
((float *)dst)[x] = ((const uint32_t *)src)[x] * (1.0 / 0xffffff);
}
break;
case D3DFMT_D32F_LOCKABLE:
case D3DFMT_R32F:
memcpy(dst, src, Width * sizeof(float));
break;
case D3DFMT_R16F:
for (unsigned x = 0; x < Width; ++x) {
((float *)dst)[x] = util_half_to_float(((const uint16_t *)src)[x]);
}
break;
default:
assert(0);
break;
}
src += SrcPitch;
dst += image->stride();
}
return image;
}
} /* namespace d3dstate */
<commit_msg>d3dretrace: Add support for D3DFMT_X8B8G8R8<commit_after>/**************************************************************************
*
* Copyright 2014 VMware, Inc
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
**************************************************************************/
#include "d3d9state.hpp"
#include <assert.h>
#include <stdint.h>
#include "image.hpp"
#include "halffloat.hpp"
#ifdef HAVE_DXGI
#include "dxgistate.hpp"
#endif
std::ostream &
operator << (std::ostream &os, D3DFORMAT Format) {
if (Format >= 0 && Format < 256) {
return os << (unsigned)Format;
} else {
char ch0 = Format;
char ch1 = Format >> 8;
char ch2 = Format >> 16;
char ch3 = Format >> 24;
return os << "'" << ch0 << ch1 << ch2 << ch3 << "'";
}
return os;
}
namespace d3dstate {
#ifdef HAVE_DXGI
/**
* http://msdn.microsoft.com/en-us/library/windows/desktop/cc308051.aspx
*/
static DXGI_FORMAT
convertFormatDXGI(D3DFORMAT Format)
{
switch ((int)Format) {
case D3DFMT_UNKNOWN:
return DXGI_FORMAT_UNKNOWN;
case D3DFMT_A8R8G8B8:
return DXGI_FORMAT_B8G8R8A8_UNORM;
case D3DFMT_X8R8G8B8:
return DXGI_FORMAT_B8G8R8X8_UNORM;
case D3DFMT_R5G6B5:
return DXGI_FORMAT_B5G6R5_UNORM;
case D3DFMT_A1R5G5B5:
return DXGI_FORMAT_B5G5R5A1_UNORM;
case D3DFMT_A4R4G4B4:
return DXGI_FORMAT_B4G4R4A4_UNORM;
case D3DFMT_A8:
return DXGI_FORMAT_A8_UNORM;
case D3DFMT_A2B10G10R10:
return DXGI_FORMAT_R10G10B10A2_UNORM;
case D3DFMT_A8B8G8R8:
return DXGI_FORMAT_R8G8B8A8_UNORM;
case D3DFMT_G16R16:
return DXGI_FORMAT_R16G16_UNORM;
case D3DFMT_A16B16G16R16:
return DXGI_FORMAT_R16G16B16A16_UNORM;
case D3DFMT_L8:
return DXGI_FORMAT_R8_UNORM;
case D3DFMT_V8U8:
return DXGI_FORMAT_R8G8_SNORM;
case D3DFMT_Q8W8V8U8:
return DXGI_FORMAT_R8G8B8A8_SNORM;
case D3DFMT_V16U16:
return DXGI_FORMAT_R16G16_SNORM;
case D3DFMT_R8G8_B8G8:
return DXGI_FORMAT_G8R8_G8B8_UNORM;
case D3DFMT_G8R8_G8B8:
return DXGI_FORMAT_R8G8_B8G8_UNORM;
case D3DFMT_DXT1:
return DXGI_FORMAT_BC1_UNORM;
case D3DFMT_DXT2:
return DXGI_FORMAT_BC2_UNORM;
case D3DFMT_DXT3:
return DXGI_FORMAT_BC2_UNORM;
case D3DFMT_DXT4:
return DXGI_FORMAT_BC3_UNORM;
case D3DFMT_DXT5:
return DXGI_FORMAT_BC3_UNORM;
case D3DFMT_D16:
case D3DFMT_D16_LOCKABLE:
return DXGI_FORMAT_D16_UNORM;
case D3DFMT_D32F_LOCKABLE:
return DXGI_FORMAT_D32_FLOAT;
case D3DFMT_D24S8:
return DXGI_FORMAT_D24_UNORM_S8_UINT;
case D3DFMT_L16:
return DXGI_FORMAT_R16_UNORM;
case D3DFMT_INDEX16:
return DXGI_FORMAT_R16_UINT;
case D3DFMT_INDEX32:
return DXGI_FORMAT_R32_UINT;
case D3DFMT_Q16W16V16U16:
return DXGI_FORMAT_R16G16B16A16_SNORM;
case D3DFMT_R16F:
return DXGI_FORMAT_R16_FLOAT;
case D3DFMT_G16R16F:
return DXGI_FORMAT_R16G16_FLOAT;
case D3DFMT_A16B16G16R16F:
return DXGI_FORMAT_R16G16B16A16_FLOAT;
case D3DFMT_R32F:
return DXGI_FORMAT_R32_FLOAT;
case D3DFMT_G32R32F:
return DXGI_FORMAT_R32G32_FLOAT;
case D3DFMT_A32B32G32R32F:
return DXGI_FORMAT_R32G32B32A32_FLOAT;
case D3DFMT_ATI1N:
return DXGI_FORMAT_BC4_UNORM;
case D3DFMT_ATI2N:
return DXGI_FORMAT_BC5_UNORM;
default:
return DXGI_FORMAT_UNKNOWN;
}
}
image::Image *
ConvertImageDXGI(D3DFORMAT SrcFormat,
void *SrcData,
INT SrcPitch,
UINT Width, UINT Height)
{
DXGI_FORMAT Format = convertFormatDXGI(SrcFormat);
if (Format == DXGI_FORMAT_UNKNOWN) {
return NULL;
}
assert(SrcPitch >= 0);
return ConvertImage(Format, SrcData, SrcPitch, Width, Height);
}
#endif /* HAVE_DXGI */
image::Image *
ConvertImage(D3DFORMAT SrcFormat,
void *SrcData,
INT SrcPitch,
UINT Width, UINT Height)
{
image::Image *image;
unsigned numChannels;
image::ChannelType channelType;
switch (SrcFormat) {
case D3DFMT_A8R8G8B8:
case D3DFMT_A8B8G8R8:
numChannels = 4;
channelType = image::TYPE_UNORM8;
break;
case D3DFMT_A32B32G32R32F:
case D3DFMT_A16B16G16R16F:
numChannels = 4;
channelType = image::TYPE_FLOAT;
break;
case D3DFMT_X8R8G8B8:
case D3DFMT_X8B8G8R8:
case D3DFMT_R5G6B5:
numChannels = 3;
channelType = image::TYPE_UNORM8;
break;
case D3DFMT_G32R32F:
case D3DFMT_G16R16F:
numChannels = 2;
channelType = image::TYPE_FLOAT;
break;
case D3DFMT_R32F:
case D3DFMT_R16F:
case D3DFMT_D16:
case D3DFMT_D16_LOCKABLE:
case D3DFMT_D24S8:
case D3DFMT_D24X8:
case D3DFMT_D32F_LOCKABLE:
case D3DFMT_DF16:
case D3DFMT_DF24:
case D3DFMT_INTZ:
numChannels = 1;
channelType = image::TYPE_FLOAT;
break;
default:
#ifdef HAVE_DXGI
image = ConvertImageDXGI(SrcFormat, SrcData, SrcPitch, Width, Height);
if (image) {
return image;
}
#endif
std::cerr << "warning: unsupported D3DFORMAT " << SrcFormat << "\n";
return NULL;
}
image = new image::Image(Width, Height, numChannels, true, channelType);
if (!image) {
return NULL;
}
const unsigned char *src;
unsigned char *dst;
dst = image->start();
src = (const unsigned char *)SrcData;
for (unsigned y = 0; y < Height; ++y) {
switch (SrcFormat) {
case D3DFMT_A8R8G8B8:
for (unsigned x = 0; x < Width; ++x) {
dst[4*x + 0] = src[4*x + 2];
dst[4*x + 1] = src[4*x + 1];
dst[4*x + 2] = src[4*x + 0];
dst[4*x + 3] = src[4*x + 3];
}
break;
case D3DFMT_A8B8G8R8:
for (unsigned x = 0; x < Width; ++x) {
dst[4*x + 0] = src[4*x + 0];
dst[4*x + 1] = src[4*x + 1];
dst[4*x + 2] = src[4*x + 2];
dst[4*x + 3] = src[4*x + 3];
}
break;
case D3DFMT_R5G6B5:
for (unsigned x = 0; x < Width; ++x) {
uint32_t pixel = ((const uint16_t *)src)[x];
dst[3*x + 0] = (( pixel & 0x1f) * (2*0xff) + 0x1f) / (2*0x1f);
dst[3*x + 1] = (((pixel >> 5) & 0x3f) * (2*0xff) + 0x3f) / (2*0x3f);
dst[3*x + 2] = (( pixel >> 11 ) * (2*0xff) + 0x1f) / (2*0x1f);
}
break;
case D3DFMT_X8R8G8B8:
for (unsigned x = 0; x < Width; ++x) {
dst[3*x + 0] = src[4*x + 2];
dst[3*x + 1] = src[4*x + 1];
dst[3*x + 2] = src[4*x + 0];
}
break;
case D3DFMT_X8B8G8R8:
for (unsigned x = 0; x < Width; ++x) {
dst[3*x + 0] = src[4*x + 0];
dst[3*x + 1] = src[4*x + 1];
dst[3*x + 2] = src[4*x + 2];
}
break;
case D3DFMT_A32B32G32R32F:
for (unsigned x = 0; x < Width; ++x) {
((float *)dst)[4*x + 0] = ((const float *)src)[4*x + 0];
((float *)dst)[4*x + 1] = ((const float *)src)[4*x + 1];
((float *)dst)[4*x + 2] = ((const float *)src)[4*x + 2];
((float *)dst)[4*x + 3] = ((const float *)src)[4*x + 3];
}
break;
case D3DFMT_A16B16G16R16F:
for (unsigned x = 0; x < Width; ++x) {
((float *)dst)[4*x + 0] = util_half_to_float(((const uint16_t *)src)[4*x + 0]);
((float *)dst)[4*x + 1] = util_half_to_float(((const uint16_t *)src)[4*x + 1]);
((float *)dst)[4*x + 2] = util_half_to_float(((const uint16_t *)src)[4*x + 2]);
((float *)dst)[4*x + 3] = util_half_to_float(((const uint16_t *)src)[4*x + 3]);
}
break;
case D3DFMT_G32R32F:
for (unsigned x = 0; x < Width; ++x) {
((float *)dst)[2*x + 0] = ((const float *)src)[2*x + 0];
((float *)dst)[2*x + 1] = ((const float *)src)[2*x + 1];
}
break;
case D3DFMT_G16R16F:
for (unsigned x = 0; x < Width; ++x) {
((float *)dst)[2*x + 0] = util_half_to_float(((const uint16_t *)src)[2*x + 0]);
((float *)dst)[2*x + 1] = util_half_to_float(((const uint16_t *)src)[2*x + 1]);
}
break;
case D3DFMT_D16:
case D3DFMT_D16_LOCKABLE:
case D3DFMT_DF16:
for (unsigned x = 0; x < Width; ++x) {
((float *)dst)[x] = ((const uint16_t *)src)[x] * (1.0f / 0xffff);
}
break;
case D3DFMT_D24S8:
case D3DFMT_D24X8:
case D3DFMT_DF24:
case D3DFMT_INTZ:
for (unsigned x = 0; x < Width; ++x) {
((float *)dst)[x] = ((const uint32_t *)src)[x] * (1.0 / 0xffffff);
}
break;
case D3DFMT_D32F_LOCKABLE:
case D3DFMT_R32F:
memcpy(dst, src, Width * sizeof(float));
break;
case D3DFMT_R16F:
for (unsigned x = 0; x < Width; ++x) {
((float *)dst)[x] = util_half_to_float(((const uint16_t *)src)[x]);
}
break;
default:
assert(0);
break;
}
src += SrcPitch;
dst += image->stride();
}
return image;
}
} /* namespace d3dstate */
<|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 <functional>
#include <iostream>
#include <vector>
#include "lexer.hh"
#include "value.hh"
#include "chunk.hh"
#include "vm.hh"
#include "compiler.hh"
namespace tadpole {
enum class Precedence {
NONE,
ASSIGN, // =
TERM, // - +
FACTOR, // / *
CALL, // ()
PRIMARY,
};
template <typename T> inline Precedence operator+(Precedence a, T b) noexcept {
return as_type<Precedence>(as_type<int>(a) + as_type<int>(b));
}
struct ParseRule {
using ParseFn = std::function<void (GlobalParser&, bool)>;
ParseFn prefix;
ParseFn infix;
Precedence precedence;
};
struct LocalVar {
Token name;
int depth{};
bool is_upvalue{};
LocalVar(const Token& arg_name, int arg_depth = -1, bool arg_upvalue = false) noexcept
: name(arg_name), depth(arg_depth), is_upvalue(arg_upvalue) {
}
};
struct Upvalue {
u8_t index{};
bool is_local{};
Upvalue(u8_t arg_index = 0, bool arg_local = false) noexcept
: index(arg_index), is_local(arg_local) {
}
inline bool operator==(Upvalue r) const noexcept {
return index == r.index && is_local == r.is_local;
}
inline bool operator!=(Upvalue r) const noexcept {
return !(*this == r);
}
inline bool is_equal(u8_t arg_index, bool arg_local) const noexcept {
return index == arg_index && is_local == arg_local;
}
};
enum class FunType {
FUNCTION,
TOPLEVEL,
};
class Compiler final : private UnCopyable {
using ErrorFn = std::function<void (const str_t&)>;
Compiler* enclosing_{};
FunctionObject* fn_{};
FunType fn_type_{};
int scope_depth_{};
std::vector<LocalVar> locals_;
std::vector<Upvalue> upvalues_;
public:
Compiler() noexcept {}
Compiler(Compiler* enclosing,
FunctionObject* fn, FunType fn_type, int scope_depth = 0) noexcept
: enclosing_(enclosing), fn_(fn), fn_type_(fn_type), scope_depth_(scope_depth) {
}
inline void set_compiler(Compiler* enclosing,
FunctionObject* fn, FunType fn_type, int scope_depth = 0) noexcept {
enclosing_ = enclosing;
fn_ = fn;
fn_type_ = fn_type;
scope_depth_ = scope_depth;
}
inline Compiler* enclosing() const noexcept { return enclosing_; }
inline FunctionObject* fn() const noexcept { return fn_; }
inline FunType fn_type() const noexcept { return fn_type_; }
inline int scope_depth() const noexcept { return scope_depth_; }
inline void set_scope_depth(int depth) noexcept { scope_depth_ = depth; }
inline int locals_count() const noexcept { return as_type<int>(locals_.size()); }
inline LocalVar& get_local(sz_t i) noexcept { return locals_[i]; }
inline const LocalVar& get_local(sz_t i) const noexcept { return locals_[i]; }
inline LocalVar& peek_local() noexcept { return locals_.back(); }
inline const LocalVar& peek_local() const noexcept { return locals_.back(); }
inline void append_local(const LocalVar& var) noexcept { return locals_.push_back(var); }
inline Upvalue& get_upvalue(sz_t i) noexcept { return upvalues_[i]; }
inline const Upvalue& get_upvalue(sz_t i) const noexcept { return upvalues_[i]; }
inline void append_upvalue(const Upvalue& u) noexcept { upvalues_.push_back(u); }
void enter_scope() noexcept { ++scope_depth_; }
template <typename Fn> void leave_scope(Fn&& visitor) {
--scope_depth_;
while (!locals_.empty() && peek_local().depth > scope_depth_) {
visitor(peek_local());
locals_.pop_back();
}
}
int resolve_local(const Token& name, const ErrorFn& errfn) {
for (int i = locals_count() - 1; i >= 0; --i) {
auto& local = locals_[i];
if (local.name == name) {
if (local.depth == -1)
errfn(from_fmt("cannot load local variable `%s` in its own initializer", name.as_cstring()));
return i;
}
}
return -1;
}
int add_upvalue(u8_t index, bool is_local) {
for (int i = 0; i < fn_->upvalues_count(); ++i) {
if (upvalues_[i].is_equal(index, is_local))
return i;
}
upvalues_.push_back(Upvalue(index, is_local));
return as_type<int>(fn_->inc_upvalues_count());
}
int resolve_upvalue(const Token& name, const ErrorFn& errfn) {
if (enclosing_ == nullptr)
return -1;
if (int local = enclosing_->resolve_local(name, errfn); local != -1) {
enclosing_->locals_[local].is_upvalue = true;
return add_upvalue(as_type<u8_t>(local), true);
}
if (int Upvalue = enclosing_->resolve_upvalue(name, errfn); Upvalue != -1)
return add_upvalue(as_type<u8_t>(Upvalue), false);
return -1;
}
void declare_localvar(const Token& name, const ErrorFn& errfn) {
if (scope_depth_ == 0)
return;
for (auto it = locals_.rbegin(); it != locals_.rend(); ++it) {
if (it->depth != -1 && it->depth < scope_depth_)
break;
if (it->name == name)
errfn(from_fmt("name `%s` is redefined", name.as_cstring()));
}
locals_.push_back(LocalVar(name, -1, false));
}
};
class GlobalParser final : private UnCopyable {
static constexpr int kMaxArgs = 8;
VM& vm_;
Lexer& lex_;
Token prev_;
Token curr_;
bool had_error_{};
bool panic_mode_{};
Compiler* curr_compiler_{};
void error_at(const Token& tok, const str_t& msg) noexcept {
if (panic_mode_)
return;
panic_mode_ = true;
std::cerr
<< "SyntaxError:" << std::endl
<< " [LINE: " << tok.lineno() << "] ERROR ";
if (tok.kind() == TokenKind::TK_EOF)
std::cerr << "at end ";
else if (tok.kind() == TokenKind::TK_ERR)
(void)0;
else
std::cerr << "at `" << tok.literal() << "` ";
std::cerr << ": " << msg << std::endl;
had_error_ = true;
}
inline void error_at_current(const str_t& msg) noexcept { error_at(curr_, msg); }
inline void error(const str_t& msg) noexcept { error_at(prev_, msg); }
inline Chunk* curr_chunk() const noexcept { return curr_compiler_->fn()->chunk(); }
inline bool check(TokenKind kind) const noexcept { return curr_.kind() == kind; }
void advance() {
prev_ = curr_;
for (;;) {
curr_ = lex_.next_token();
if (!check(TokenKind::TK_ERR))
break;
error_at_current(curr_.as_string());
}
}
void consume(TokenKind kind, const str_t& msg) {
if (check(kind))
advance();
else
error_at_current(msg);
}
bool match(TokenKind kind) {
if (check(kind)) {
advance();
return true;
}
return false;
}
template <typename T> inline void emit_byte(T byte) noexcept {
curr_chunk()->write(byte, prev_.lineno());
}
template <typename T, typename U> inline void emit_bytes(T b1, U b2) noexcept {
emit_byte(b1);
emit_byte(b2);
}
inline void emit_return() noexcept { return emit_bytes(Code::NIL, Code::RETURN); }
inline void emit_constant(const Value& v) noexcept {
emit_bytes(Code::CONSTANT, curr_chunk()->add_constant(v));
}
void init_compiler(Compiler* compiler, int scope_depth, FunType fn_type) {
StringObject* func_name{};
if (fn_type == FunType::FUNCTION)
func_name = StringObject::create(vm_, prev_.as_string());
compiler->set_compiler(
curr_compiler_,
FunctionObject::create(vm_, func_name),
fn_type,
scope_depth);
curr_compiler_ = compiler;
curr_compiler_->append_local(LocalVar(Token::make(""), curr_compiler_->scope_depth(), false));
}
FunctionObject* finish_compiler() {
emit_return();
FunctionObject* fn = curr_compiler_->fn();
#if defined(_TADPOLE_DEBUG_VM)
if (!had_error_)
curr_chunk()->dis(fn->name_asstr());
#endif
curr_compiler_ = curr_compiler_->enclosing();
return fn;
}
inline void enter_scope() {
curr_compiler_->enter_scope();
}
inline void leave_scope() {
curr_compiler_->leave_scope([this](const LocalVar& var) {
emit_byte(var.is_upvalue ? Code::CLOSE_UPVALUE : Code::POP);
});
}
inline u8_t identifier_constant(const Token& name) noexcept {
return curr_chunk()->add_constant(StringObject::create(vm_, name.as_string()));
}
u8_t parse_variable(const str_t& msg) {
consume(TokenKind::TK_IDENTIFIER, msg);
curr_compiler_->declare_localvar(prev_, [this](const str_t& m) { error(m); });
if (curr_compiler_->scope_depth() > 0)
return 0;
return identifier_constant(prev_);
}
void mark_initialized() {
if (curr_compiler_->scope_depth() == 0)
return;
curr_compiler_->peek_local().depth = curr_compiler_->scope_depth();
}
void define_global(u8_t global) {
if (curr_compiler_->scope_depth() > 0) {
mark_initialized();
return;
}
emit_bytes(Code::DEF_GLOBAL, global);
}
u8_t arguments() {
u8_t argc = 0;
if (!check(TokenKind::TK_RPAREN)) {
do {
expression();
++argc;
if (argc > kMaxArgs)
error(from_fmt("cannot have more than `%d` arguments", kMaxArgs));
} while (match(TokenKind::TK_COMMA));
}
consume(TokenKind::TK_RPAREN, "expect `;` after function arguments");
return argc;
}
void named_variable(const Token& name, bool can_assign) {
auto errfn = [this](const str_t& msg) { error(msg); };
Code getop, setop;
int arg = curr_compiler_->resolve_local(name, errfn);
if (arg != -1) {
getop = Code::GET_LOCAL;
setop = Code::SET_LOCAL;
}
else if (arg = curr_compiler_->resolve_upvalue(name, errfn); arg != -1) {
getop = Code::GET_UPVALUE;
setop = Code::SET_UPVALUE;
}
else {
arg = identifier_constant(name);
getop = Code::GET_GLOBAL;
setop = Code::SET_GLOBAL;
}
if (can_assign && match(TokenKind::TK_EQ)) {
expression();
emit_bytes(setop, arg);
}
else {
emit_bytes(getop, arg);
}
}
void expression() {}
};
FunctionObject* GlobalCompiler::compile(VM& vm, const str_t& source_bytes) {
return nullptr;
}
void GlobalCompiler::mark_compiler() {
}
}
<commit_msg>:construction: chore(rule): add getting rule structure<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 <functional>
#include <iostream>
#include <vector>
#include "lexer.hh"
#include "value.hh"
#include "chunk.hh"
#include "vm.hh"
#include "compiler.hh"
namespace tadpole {
enum class Precedence {
NONE,
ASSIGN, // =
TERM, // - +
FACTOR, // / *
CALL, // ()
PRIMARY,
};
template <typename T> inline Precedence operator+(Precedence a, T b) noexcept {
return as_type<Precedence>(as_type<int>(a) + as_type<int>(b));
}
struct ParseRule {
using ParseFn = std::function<void (GlobalParser&, bool)>;
ParseFn prefix;
ParseFn infix;
Precedence precedence;
};
struct LocalVar {
Token name;
int depth{};
bool is_upvalue{};
LocalVar(const Token& arg_name, int arg_depth = -1, bool arg_upvalue = false) noexcept
: name(arg_name), depth(arg_depth), is_upvalue(arg_upvalue) {
}
};
struct Upvalue {
u8_t index{};
bool is_local{};
Upvalue(u8_t arg_index = 0, bool arg_local = false) noexcept
: index(arg_index), is_local(arg_local) {
}
inline bool operator==(Upvalue r) const noexcept {
return index == r.index && is_local == r.is_local;
}
inline bool operator!=(Upvalue r) const noexcept {
return !(*this == r);
}
inline bool is_equal(u8_t arg_index, bool arg_local) const noexcept {
return index == arg_index && is_local == arg_local;
}
};
enum class FunType {
FUNCTION,
TOPLEVEL,
};
class Compiler final : private UnCopyable {
using ErrorFn = std::function<void (const str_t&)>;
Compiler* enclosing_{};
FunctionObject* fn_{};
FunType fn_type_{};
int scope_depth_{};
std::vector<LocalVar> locals_;
std::vector<Upvalue> upvalues_;
public:
Compiler() noexcept {}
Compiler(Compiler* enclosing,
FunctionObject* fn, FunType fn_type, int scope_depth = 0) noexcept
: enclosing_(enclosing), fn_(fn), fn_type_(fn_type), scope_depth_(scope_depth) {
}
inline void set_compiler(Compiler* enclosing,
FunctionObject* fn, FunType fn_type, int scope_depth = 0) noexcept {
enclosing_ = enclosing;
fn_ = fn;
fn_type_ = fn_type;
scope_depth_ = scope_depth;
}
inline Compiler* enclosing() const noexcept { return enclosing_; }
inline FunctionObject* fn() const noexcept { return fn_; }
inline FunType fn_type() const noexcept { return fn_type_; }
inline int scope_depth() const noexcept { return scope_depth_; }
inline void set_scope_depth(int depth) noexcept { scope_depth_ = depth; }
inline int locals_count() const noexcept { return as_type<int>(locals_.size()); }
inline LocalVar& get_local(sz_t i) noexcept { return locals_[i]; }
inline const LocalVar& get_local(sz_t i) const noexcept { return locals_[i]; }
inline LocalVar& peek_local() noexcept { return locals_.back(); }
inline const LocalVar& peek_local() const noexcept { return locals_.back(); }
inline void append_local(const LocalVar& var) noexcept { return locals_.push_back(var); }
inline Upvalue& get_upvalue(sz_t i) noexcept { return upvalues_[i]; }
inline const Upvalue& get_upvalue(sz_t i) const noexcept { return upvalues_[i]; }
inline void append_upvalue(const Upvalue& u) noexcept { upvalues_.push_back(u); }
void enter_scope() noexcept { ++scope_depth_; }
template <typename Fn> void leave_scope(Fn&& visitor) {
--scope_depth_;
while (!locals_.empty() && peek_local().depth > scope_depth_) {
visitor(peek_local());
locals_.pop_back();
}
}
int resolve_local(const Token& name, const ErrorFn& errfn) {
for (int i = locals_count() - 1; i >= 0; --i) {
auto& local = locals_[i];
if (local.name == name) {
if (local.depth == -1)
errfn(from_fmt("cannot load local variable `%s` in its own initializer", name.as_cstring()));
return i;
}
}
return -1;
}
int add_upvalue(u8_t index, bool is_local) {
for (int i = 0; i < fn_->upvalues_count(); ++i) {
if (upvalues_[i].is_equal(index, is_local))
return i;
}
upvalues_.push_back(Upvalue(index, is_local));
return as_type<int>(fn_->inc_upvalues_count());
}
int resolve_upvalue(const Token& name, const ErrorFn& errfn) {
if (enclosing_ == nullptr)
return -1;
if (int local = enclosing_->resolve_local(name, errfn); local != -1) {
enclosing_->locals_[local].is_upvalue = true;
return add_upvalue(as_type<u8_t>(local), true);
}
if (int Upvalue = enclosing_->resolve_upvalue(name, errfn); Upvalue != -1)
return add_upvalue(as_type<u8_t>(Upvalue), false);
return -1;
}
void declare_localvar(const Token& name, const ErrorFn& errfn) {
if (scope_depth_ == 0)
return;
for (auto it = locals_.rbegin(); it != locals_.rend(); ++it) {
if (it->depth != -1 && it->depth < scope_depth_)
break;
if (it->name == name)
errfn(from_fmt("name `%s` is redefined", name.as_cstring()));
}
locals_.push_back(LocalVar(name, -1, false));
}
};
class GlobalParser final : private UnCopyable {
static constexpr int kMaxArgs = 8;
VM& vm_;
Lexer& lex_;
Token prev_;
Token curr_;
bool had_error_{};
bool panic_mode_{};
Compiler* curr_compiler_{};
void error_at(const Token& tok, const str_t& msg) noexcept {
if (panic_mode_)
return;
panic_mode_ = true;
std::cerr
<< "SyntaxError:" << std::endl
<< " [LINE: " << tok.lineno() << "] ERROR ";
if (tok.kind() == TokenKind::TK_EOF)
std::cerr << "at end ";
else if (tok.kind() == TokenKind::TK_ERR)
(void)0;
else
std::cerr << "at `" << tok.literal() << "` ";
std::cerr << ": " << msg << std::endl;
had_error_ = true;
}
inline void error_at_current(const str_t& msg) noexcept { error_at(curr_, msg); }
inline void error(const str_t& msg) noexcept { error_at(prev_, msg); }
inline Chunk* curr_chunk() const noexcept { return curr_compiler_->fn()->chunk(); }
inline bool check(TokenKind kind) const noexcept { return curr_.kind() == kind; }
void advance() {
prev_ = curr_;
for (;;) {
curr_ = lex_.next_token();
if (!check(TokenKind::TK_ERR))
break;
error_at_current(curr_.as_string());
}
}
void consume(TokenKind kind, const str_t& msg) {
if (check(kind))
advance();
else
error_at_current(msg);
}
bool match(TokenKind kind) {
if (check(kind)) {
advance();
return true;
}
return false;
}
template <typename T> inline void emit_byte(T byte) noexcept {
curr_chunk()->write(byte, prev_.lineno());
}
template <typename T, typename U> inline void emit_bytes(T b1, U b2) noexcept {
emit_byte(b1);
emit_byte(b2);
}
inline void emit_return() noexcept { return emit_bytes(Code::NIL, Code::RETURN); }
inline void emit_constant(const Value& v) noexcept {
emit_bytes(Code::CONSTANT, curr_chunk()->add_constant(v));
}
void init_compiler(Compiler* compiler, int scope_depth, FunType fn_type) {
StringObject* func_name{};
if (fn_type == FunType::FUNCTION)
func_name = StringObject::create(vm_, prev_.as_string());
compiler->set_compiler(
curr_compiler_,
FunctionObject::create(vm_, func_name),
fn_type,
scope_depth);
curr_compiler_ = compiler;
curr_compiler_->append_local(LocalVar(Token::make(""), curr_compiler_->scope_depth(), false));
}
FunctionObject* finish_compiler() {
emit_return();
FunctionObject* fn = curr_compiler_->fn();
#if defined(_TADPOLE_DEBUG_VM)
if (!had_error_)
curr_chunk()->dis(fn->name_asstr());
#endif
curr_compiler_ = curr_compiler_->enclosing();
return fn;
}
inline void enter_scope() {
curr_compiler_->enter_scope();
}
inline void leave_scope() {
curr_compiler_->leave_scope([this](const LocalVar& var) {
emit_byte(var.is_upvalue ? Code::CLOSE_UPVALUE : Code::POP);
});
}
inline u8_t identifier_constant(const Token& name) noexcept {
return curr_chunk()->add_constant(StringObject::create(vm_, name.as_string()));
}
u8_t parse_variable(const str_t& msg) {
consume(TokenKind::TK_IDENTIFIER, msg);
curr_compiler_->declare_localvar(prev_, [this](const str_t& m) { error(m); });
if (curr_compiler_->scope_depth() > 0)
return 0;
return identifier_constant(prev_);
}
void mark_initialized() {
if (curr_compiler_->scope_depth() == 0)
return;
curr_compiler_->peek_local().depth = curr_compiler_->scope_depth();
}
void define_global(u8_t global) {
if (curr_compiler_->scope_depth() > 0) {
mark_initialized();
return;
}
emit_bytes(Code::DEF_GLOBAL, global);
}
u8_t arguments() {
u8_t argc = 0;
if (!check(TokenKind::TK_RPAREN)) {
do {
expression();
++argc;
if (argc > kMaxArgs)
error(from_fmt("cannot have more than `%d` arguments", kMaxArgs));
} while (match(TokenKind::TK_COMMA));
}
consume(TokenKind::TK_RPAREN, "expect `;` after function arguments");
return argc;
}
void named_variable(const Token& name, bool can_assign) {
auto errfn = [this](const str_t& msg) { error(msg); };
Code getop, setop;
int arg = curr_compiler_->resolve_local(name, errfn);
if (arg != -1) {
getop = Code::GET_LOCAL;
setop = Code::SET_LOCAL;
}
else if (arg = curr_compiler_->resolve_upvalue(name, errfn); arg != -1) {
getop = Code::GET_UPVALUE;
setop = Code::SET_UPVALUE;
}
else {
arg = identifier_constant(name);
getop = Code::GET_GLOBAL;
setop = Code::SET_GLOBAL;
}
if (can_assign && match(TokenKind::TK_EQ)) {
expression();
emit_bytes(setop, arg);
}
else {
emit_bytes(getop, arg);
}
}
const ParseRule& get_rule(TokenKind kind) const noexcept {
#define _RULE(fn) [](GlobalParser& p, bool b) { p.fn(b); }
static const ParseRule _rules[] = {
{nullptr, nullptr, Precedence::NONE}, // PUNCTUATOR(LPAREN, "(")
{nullptr, nullptr, Precedence::NONE}, // PUNCTUATOR(RPAREN, ")")
{nullptr, nullptr, Precedence::NONE}, // PUNCTUATOR(LBRACE, "{")
{nullptr, nullptr, Precedence::NONE}, // PUNCTUATOR(RBRACE, "}")
{nullptr, nullptr, Precedence::NONE}, // PUNCTUATOR(COMMA, ",")
{nullptr, nullptr, Precedence::NONE}, // PUNCTUATOR(MINUS, "-")
{nullptr, nullptr, Precedence::NONE}, // PUNCTUATOR(PLUS, "+")
{nullptr, nullptr, Precedence::NONE}, // PUNCTUATOR(SEMI, ";")
{nullptr, nullptr, Precedence::NONE}, // PUNCTUATOR(SLASH, "/")
{nullptr, nullptr, Precedence::NONE}, // PUNCTUATOR(STAR, "*")
{nullptr, nullptr, Precedence::NONE}, // PUNCTUATOR(EQ, "=")
{nullptr, nullptr, Precedence::NONE}, // TOKEN(IDENTIFIER, "Identifier")
{nullptr, nullptr, Precedence::NONE}, // TOKEN(NUMERIC, "Numeric")
{nullptr, nullptr, Precedence::NONE}, // TOKEN(STRING, "String")
{nullptr, nullptr, Precedence::NONE}, // KEYWORD(FALSE, "false")
{nullptr, nullptr, Precedence::NONE}, // KEYWORD(FN, "fn")
{nullptr, nullptr, Precedence::NONE}, // KEYWORD(NIL, "nil")
{nullptr, nullptr, Precedence::NONE}, // KEYWORD(TRUE, "true")
{nullptr, nullptr, Precedence::NONE}, // KEYWORD(VAR, "var")
{nullptr, nullptr, Precedence::NONE}, // TOKEN(EOF, "Eof")
{nullptr, nullptr, Precedence::NONE}, // TOKEN(ERR, "Error")
};
#undef _RULE
return _rules[as_type<int>(kind)];
}
void expression() {}
};
FunctionObject* GlobalCompiler::compile(VM& vm, const str_t& source_bytes) {
return nullptr;
}
void GlobalCompiler::mark_compiler() {
}
}
<|endoftext|> |
<commit_before>/*
* MIT License
*
* Copyright (c) 2017 Richard Hartmann
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "cplxfnc.hpp"
#include <complex>
#include <iostream>
#include <iomanip>
#include <stdexcept>
int check_values(){
std::cout << "check values ... ";
std::complex<double> res, s, a, res_check;
double d;
double tol = 1e-16;
const std::complex<double> I(0, 1);
unsigned int limit = 1;
try {
res = zeta(2., 1 - I*1234., tol, limit, true);
} catch (const std::runtime_error& e) {
std::cout << "\nI guess you have arb version prior to 2.9. installed" <<
"\nupdating yields a slight efficiency improvement!\n";
limit = 2;
}
double data [18][6] = { {2. , 0., 1., 0. , M_PI*M_PI/6, 0},
{2. , 0., 1., 1. , 4.63000096622763786e-1, -7.94233542759318865e-1},
{2. , 0., 0., 1. , -5.36999903377236213e-1, -7.94233542759318865e-1},
{2. , 0., 1., 10. , 4.99999999999999999e-3, -9.98329975849301549e-2},
{2. , 0., 1.,-1234. , 3.28352014373937781e-7, 8.10372682779022825e-4},
{1.2, 0., 1., 0. , 5.59158244117775188 , 0},
{1.2, 0., 1., 1. , 4.79688290618251932 , -1.04259444248270157},
{1.2, 0., 0., 1. , 4.48786591180757196 , -1.99365095877785516},
{1.2, 0., 1., 10. , 3.00952851308319147 , -9.44683699633929863e-1},
{1.2, 0., 1.,-1234. , 1.14531441635402694 , 3.72032603245348282e-1},
{1.2, 1., 1., 0. , 7.89008276053315959e-1, -8.904382488200783911e-1},
{1.2, 1., 1., 1. , -3.74965169663485969e-1, -2.732104072569482620},
{1.2, 1., 0., 1. , -1.86148443143806753 , -7.307139932227024369},
{1.2, 1., 1., 10. , -1.89011737420273344 , 2.105544806767073391},
{1.2, 1., 1.,-1234. , -1.56061472179186142e-2, -4.656891594125561926e-2},
{1.2, 0., 1., 1.e6 , 3.00038056734908233e-1, -9.748824108122723291e-2},
{1.2, 0., 1., 1.e12 , 1.89311209369371249e-2, -6.151094064175929217e-3},
{1.2, 0., 1., 1.e24 , 7.53661499160987508e-5, -2.448794653698247891e-5} };
for (int i = 0; i < 18; i++){
s = data[i][0] + I*data[i][1];
a = data[i][2] + I*data[i][3];
res_check = data[i][4] + I*data[i][5];
res = zeta(s, a, tol, 1, true);
d = fabs(res.real() - res_check.real());
if (d > tol){
std::cout << "\nERROR (real part)\n" <<
std::scientific << std::setprecision(2) <<
"diff real part: " << d << " < tol (" << tol << ")\n" <<
std::setprecision(1) << std::fixed <<
"zeta(s, a) with s=" << s << " and a=" << a << std::endl << std::scientific << std::setprecision(16) <<
"returned : " << res.real() << std::endl <<
"but should be : " << res_check.real() << std::endl;
return -1;
}
d = fabs(res.imag() - res_check.imag());
if (d > tol){
std::cout << "\nERROR (imag part)\n" <<
std::scientific << std::setprecision(2) <<
"diff imag part: " << d << " < tol (" << tol << ")\n" <<
std::setprecision(1) << std::fixed <<
"zeta(s, a) with s=" << s << " and a=" << a << std::endl << std::scientific << std::setprecision(16) <<
"returned : " << res.imag() << std::endl <<
"but should be : " << res_check.imag() << std::endl;
return -1;
}
}
std::cout << "done\n";
return 0;
}
int check_call_error()
{
std::cout << "check call err ... ";
std::complex<double> res, s, a, res_check;
double tol = 1e-16;
const std::complex<double> I(0, 1);
s = 1.00000004 + I*10.;
a = 1.e6 + I*1.e6;
int status = zeta(s, a, &res, tol, 1, false);
if (status == 0) {
std::cout << "\nERROR (limit should have been reached)\n" <<
"expect zeta to return other than 0 return code!" << std::endl;
return -1;
}
bool got_exception = false;
try {
res = zeta(s, a, tol, 1, false);
} catch (const std::runtime_error& e) {
got_exception = true;
}
if (got_exception == false) {
std::cout << "\nERROR (limit should have been reached)\n" <<
"expect zeta to raise runtime_error exception!" << std::endl;
return -1;
}
std::cout << "done\n";
return 0;
}
int check_call_overloads()
{
std::cout << "check call overloads ... ";
std::complex<double> res;
zeta(2, 1, &res, 1e-16, 1, false);
zeta(2, 1, 1e-16, 1, false);
zeta(2, 1);
std::cout << "done\n";
return 0;
}
int main(){
std::cout << "\nrun tests for cplxfnc library\n";
if (check_values()) return -1;
if (check_call_error()) return -1;
if (check_call_overloads()) return -1;
return 0;
}
<commit_msg>fixed type error<commit_after>/*
* MIT License
*
* Copyright (c) 2017 Richard Hartmann
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "cplxfnc.hpp"
#include <complex>
#include <iostream>
#include <iomanip>
#include <stdexcept>
int check_values(){
std::cout << "check values ... ";
std::complex<double> res, s, a, res_check;
double d;
double tol = 1e-16;
const std::complex<double> I(0, 1);
unsigned int limit = 1;
try {
res = zeta(2., 1. - I*1234., tol, limit, true);
} catch (const std::runtime_error& e) {
std::cout << "\nI guess you have arb version prior to 2.9. installed" <<
"\nupdating yields a slight efficiency improvement!\n";
limit = 2;
}
double data [18][6] = { {2. , 0., 1., 0. , M_PI*M_PI/6, 0},
{2. , 0., 1., 1. , 4.63000096622763786e-1, -7.94233542759318865e-1},
{2. , 0., 0., 1. , -5.36999903377236213e-1, -7.94233542759318865e-1},
{2. , 0., 1., 10. , 4.99999999999999999e-3, -9.98329975849301549e-2},
{2. , 0., 1.,-1234. , 3.28352014373937781e-7, 8.10372682779022825e-4},
{1.2, 0., 1., 0. , 5.59158244117775188 , 0},
{1.2, 0., 1., 1. , 4.79688290618251932 , -1.04259444248270157},
{1.2, 0., 0., 1. , 4.48786591180757196 , -1.99365095877785516},
{1.2, 0., 1., 10. , 3.00952851308319147 , -9.44683699633929863e-1},
{1.2, 0., 1.,-1234. , 1.14531441635402694 , 3.72032603245348282e-1},
{1.2, 1., 1., 0. , 7.89008276053315959e-1, -8.904382488200783911e-1},
{1.2, 1., 1., 1. , -3.74965169663485969e-1, -2.732104072569482620},
{1.2, 1., 0., 1. , -1.86148443143806753 , -7.307139932227024369},
{1.2, 1., 1., 10. , -1.89011737420273344 , 2.105544806767073391},
{1.2, 1., 1.,-1234. , -1.56061472179186142e-2, -4.656891594125561926e-2},
{1.2, 0., 1., 1.e6 , 3.00038056734908233e-1, -9.748824108122723291e-2},
{1.2, 0., 1., 1.e12 , 1.89311209369371249e-2, -6.151094064175929217e-3},
{1.2, 0., 1., 1.e24 , 7.53661499160987508e-5, -2.448794653698247891e-5} };
for (int i = 0; i < 18; i++){
s = data[i][0] + I*data[i][1];
a = data[i][2] + I*data[i][3];
res_check = data[i][4] + I*data[i][5];
res = zeta(s, a, tol, 1, true);
d = fabs(res.real() - res_check.real());
if (d > tol){
std::cout << "\nERROR (real part)\n" <<
std::scientific << std::setprecision(2) <<
"diff real part: " << d << " < tol (" << tol << ")\n" <<
std::setprecision(1) << std::fixed <<
"zeta(s, a) with s=" << s << " and a=" << a << std::endl << std::scientific << std::setprecision(16) <<
"returned : " << res.real() << std::endl <<
"but should be : " << res_check.real() << std::endl;
return -1;
}
d = fabs(res.imag() - res_check.imag());
if (d > tol){
std::cout << "\nERROR (imag part)\n" <<
std::scientific << std::setprecision(2) <<
"diff imag part: " << d << " < tol (" << tol << ")\n" <<
std::setprecision(1) << std::fixed <<
"zeta(s, a) with s=" << s << " and a=" << a << std::endl << std::scientific << std::setprecision(16) <<
"returned : " << res.imag() << std::endl <<
"but should be : " << res_check.imag() << std::endl;
return -1;
}
}
std::cout << "done\n";
return 0;
}
int check_call_error()
{
std::cout << "check call err ... ";
std::complex<double> res, s, a, res_check;
double tol = 1e-16;
const std::complex<double> I(0, 1);
s = 1.00000004 + I*10.;
a = 1.e6 + I*1.e6;
int status = zeta(s, a, &res, tol, 1, false);
if (status == 0) {
std::cout << "\nERROR (limit should have been reached)\n" <<
"expect zeta to return other than 0 return code!" << std::endl;
return -1;
}
bool got_exception = false;
try {
res = zeta(s, a, tol, 1, false);
} catch (const std::runtime_error& e) {
got_exception = true;
}
if (got_exception == false) {
std::cout << "\nERROR (limit should have been reached)\n" <<
"expect zeta to raise runtime_error exception!" << std::endl;
return -1;
}
std::cout << "done\n";
return 0;
}
int check_call_overloads()
{
std::cout << "check call overloads ... ";
std::complex<double> res;
zeta(2, 1, &res, 1e-16, 1, false);
zeta(2, 1, 1e-16, 1, false);
zeta(2, 1);
std::cout << "done\n";
return 0;
}
int main(){
std::cout << "\nrun tests for cplxfnc library\n";
if (check_values()) return -1;
if (check_call_error()) return -1;
if (check_call_overloads()) return -1;
return 0;
}
<|endoftext|> |
<commit_before>#include <stdarg.h>
#include <stdint.h>
#define WEAK __attribute__((weak))
extern "C" {
extern void __android_log_vprint(int, const char *, const char *, va_list);
extern uint32_t fwrite(void *, uint32_t, uint32_t, void *);
extern void *fopen(const char *, const char *);
extern void fclose(void *);
WEAK int halide_printf(const char * fmt, ...) {
va_list args;
va_start(args,fmt);
__android_log_vprint(7, "halide", fmt, args);
va_end(args);
return 0;
}
static bool write_stub(const void *bytes, size_t size, void *f) {
return fwrite(const_cast<void *>(bytes), size, 1, f) == 1;
}
WEAK int32_t halide_debug_to_file(const char *filename, uint8_t *data,
int32_t s0, int32_t s1, int32_t s2, int32_t s3,
int32_t type_code, int32_t bytes_per_element) {
void *f = fopen(filename, "wb");
if (!f) return -1;
int result = halide_write_debug_image(filename, data, s0, s1, s2, s3,
type_code, bytes_per_element, write_stub, (void *)f);
fclose(f);
return result;
}
}
<commit_msg>Indentation fix.<commit_after>#include <stdarg.h>
#include <stdint.h>
#define WEAK __attribute__((weak))
extern "C" {
extern void __android_log_vprint(int, const char *, const char *, va_list);
extern uint32_t fwrite(void *, uint32_t, uint32_t, void *);
extern void *fopen(const char *, const char *);
extern void fclose(void *);
WEAK int halide_printf(const char * fmt, ...) {
va_list args;
va_start(args,fmt);
__android_log_vprint(7, "halide", fmt, args);
va_end(args);
return 0;
}
static bool write_stub(const void *bytes, size_t size, void *f) {
return fwrite(const_cast<void *>(bytes), size, 1, f) == 1;
}
WEAK int32_t halide_debug_to_file(const char *filename, uint8_t *data,
int32_t s0, int32_t s1, int32_t s2, int32_t s3,
int32_t type_code, int32_t bytes_per_element) {
void *f = fopen(filename, "wb");
if (!f) return -1;
int result = halide_write_debug_image(filename, data, s0, s1, s2, s3,
type_code, bytes_per_element, write_stub, (void *)f);
fclose(f);
return result;
}
}
<|endoftext|> |
<commit_before>#pragma once
#include "greens/Greens.hpp"
#include "numeric/sparse.hpp"
#include "compute/lanczos.hpp"
#include "detail/macros.hpp"
namespace tbm { namespace kpm {
/**
Computes and stores the KPM scaling parameters `a` and `b` based on the energy
bounds (min and max eigenvalue) of the Hamiltonian. The bounds are determined
automatically with the Lanczos procedure, or set manually by the user.
Note: `compute` must be called before `a` and `b` are used. This is slightly awkward
but necessary because the computation is relatively expensive and should not be done
at construction time.
*/
template<class scalar_t>
class Scale {
using real_t = num::get_real_t<scalar_t>;
static constexpr auto scaling_tolerance = 0.01f; ///< the eigenvalue bounds are not precise
public:
Scale() = default;
/// Set the energy bounds manually, therefore skipping the Lanczos procedure at `compute` time
Scale(real_t min_energy, real_t max_energy) : bounds{min_energy, max_energy, 0} {}
// Compute the scaling params of the Hamiltonian `matrix` using the Lanczos procedure
void compute(SparseMatrixX<scalar_t> const& matrix, real_t lanczos_tolerance);
public:
real_t a = 0;
real_t b = 0;
compute::LanczosBounds<real_t> bounds = {0, 0, 0};
};
/**
Indices of the Green's function matrix that will be computed
A single KPM calculation will compute an entire `row` of the Green's matrix,
however only some column indices are required to be saved, as indicated by `cols`.
*/
struct Indices {
int row = -1;
ArrayXi cols;
Indices() = default;
Indices(int row, int col) : row(row), cols(1) { cols[0] = col; }
Indices(int row, ArrayXi const& cols) : row(row), cols(cols) {}
Indices(int row, std::vector<int> const& cols) : row(row), cols(eigen_cast<ArrayX>(cols)) {}
friend bool operator==(Indices const& l, Indices const& r) {
return l.row == r.row && all_of(l.cols == r.cols);
}
};
/**
Stores a scaled Hamiltonian `(H - b)/a` which limits it to (-1, 1) boundaries required for KPM.
In addition, two optimisations are applied:
1) The matrix is multiplied by 2. This benefits most calculations (e.g. `x = 2*H*x - y`),
because the 2x multiplication is done only once, but it will need to be divided by 2
when the original element values are needed (very rarely).
2) Reorder the elements so that the index pair (i, j) is at the start of the matrix.
This produces the `optimized_sizes` vector which may be used to reduce calculation
time by skipping sparse matrix-vector multiplication of zero values.
*/
template<class scalar_t>
class OptimizedHamiltonian {
using real_t = num::get_real_t<scalar_t>;
public:
/// Create the optimized Hamiltonian from `H` targeting index pair `idx`
void create(SparseMatrixX<scalar_t> const& H, Indices const& idx,
Scale<scalar_t> scale, bool use_reordering);
/// Return an index into `optimized_sizes`, indicating the optimal system size
/// for the calculation of KPM moment number `n` out of total `num_moments`
int optimized_size_index(int n, int num_moments) const {
assert(n < num_moments);
assert(!optimized_sizes.empty());
auto const max_index = std::min(
static_cast<int>(optimized_sizes.size()) - 1,
num_moments / 2
);
if (n < max_index) {
return n; // size grows in the beginning
} else { // constant in the middle and shrinking near the end as reverse `n`
return std::min(max_index, num_moments - 1 - n + size_index_offset);
}
}
/// Return the optimized system size for KPM moment number `n` out of total `num_moments`
int optimized_size(int n, int num_moments) const {
if (!optimized_sizes.empty()) {
return optimized_sizes[optimized_size_index(n, num_moments)];
} else {
return H2.rows();
}
}
/// The unoptimized compute area is H2.nonZeros() * num_moments
double optimized_area(int num_moments) const;
public:
SparseMatrixX<scalar_t> H2; ///< the optimized matrix
Indices original_idx; ///< indices from the original `H` matrix
Indices optimized_idx; ///< reordered indices in the `H2` matrix
std::vector<int> optimized_sizes; ///< optimal matrix size "steps" for the KPM calculation
int size_index_offset = 0; ///< needed to correctly compute off-diagonal elements (i != j)
private:
/// Fill H2 with scaled Hamiltonian: H2 = (H - I*b) * (2/a)
void create_scaled(SparseMatrixX<scalar_t> const& H, Indices const& idx,
Scale<scalar_t> scale);
/// Scale and reorder the Hamiltonian so that idx is at the start of the H2 matrix
void create_reordered(SparseMatrixX<scalar_t> const& H, Indices const& idx,
Scale<scalar_t> scale);
static Indices reorder_indices(Indices const& original_idx,
std::vector<int> const& reorder_map);
static int compute_index_offset(Indices const& optimized_idx,
std::vector<int> const& optimized_sizes);
};
namespace detail {
/// Put the kernel in *Kernel* polynomial method
template<class scalar_t, class real_t>
void apply_lorentz_kernel(ArrayX<scalar_t>& moments, real_t lambda) {
auto const N = moments.size();
auto lorentz_kernel = [=](real_t n) { // n is real_t to get proper fp division
using std::sinh;
return sinh(lambda * (1 - n / N)) / sinh(lambda);
};
for (auto n = 0u; n < N; ++n) {
moments[n] *= lorentz_kernel(static_cast<real_t>(n));
}
}
/// Calculate the final Green's function for `scaled_energy` using the KPM `moments`
template<class scalar_t, class real_t, class complex_t = num::get_complex_t<scalar_t>>
ArrayX<complex_t> calculate_greens(ArrayX<real_t> const& scaled_energy,
ArrayX<scalar_t> const& moments) {
// Note that this integer array has real type values
auto ns = ArrayX<real_t>(moments.size());
for (auto n = 0; n < ns.size(); ++n) {
ns[n] = static_cast<real_t>(n);
}
// G = -2*i / sqrt(1 - E^2) * sum( moments * exp(-i*ns*acos(E)) )
auto greens = ArrayX<complex_t>(scaled_energy.size());
transform(scaled_energy, greens, [&](real_t E) {
using std::acos;
using constant::i1;
auto const norm = -real_t{2} * complex_t{i1} / sqrt(1 - E*E);
return norm * sum(moments * exp(-complex_t{i1} * ns * acos(E)));
});
return greens;
}
} // namespace detail
/**
Stores KPM moments (size `num_moments`) computed for each index (size of `indices`)
*/
template<class scalar_t>
class MomentMatrix {
using real_t = num::get_real_t<scalar_t>;
ArrayXi indices;
std::vector<ArrayX<scalar_t>> data;
public:
MomentMatrix(int num_moments, ArrayXi const& indices)
: indices(indices), data(indices.size()) {
for (auto& moments : data) {
moments.resize(num_moments);
}
}
/// Collect the first 2 moments which are computer outside the main KPM loop
void collect_initial(VectorX<scalar_t> const& r0, VectorX<scalar_t> const& r1) {
for (auto i = 0u; i < indices.size(); ++i) {
auto const idx = indices[i];
data[i][0] = r0[idx] * real_t{0.5}; // 0.5 is special for the moment zero
data[i][1] = r1[idx];
}
}
/// Collect moment `n` from result vector `r` for each index. Expects `n >= 2`.
void collect(int n, VectorX<scalar_t> const& r) {
assert(n >= 2 && n < data[0].size());
for (auto i = 0u; i < indices.size(); ++i) {
auto const idx = indices[i];
data[i][n] = r[idx];
}
}
/// Put the kernel in *Kernel* polynomial method
void apply_lorentz_kernel(real_t lambda) {
for (auto& moments : data) {
detail::apply_lorentz_kernel(moments, lambda);
}
}
/// Calculate the final Green's function at all indices for `scaled_energy`
std::vector<ArrayXcd> calc_greens(ArrayX<real_t> const& scaled_energy) const {
auto greens = std::vector<ArrayXcd>();
greens.reserve(indices.size());
for (auto const& moments : data) {
auto const g = detail::calculate_greens(scaled_energy, moments);
greens.push_back(g.template cast<std::complex<double>>());
}
return greens;
}
};
/**
Stats of the KPM calculation
*/
class Stats {
public:
std::string report(bool shortform) const;
template<class real_t>
void lanczos(compute::LanczosBounds<real_t> const& bounds, Chrono const& time);
template<class scalar_t>
void reordering(OptimizedHamiltonian<scalar_t> const& oh, int num_moments, Chrono const& time);
template<class scalar_t>
void kpm(OptimizedHamiltonian<scalar_t> const& oh, int num_moments, Chrono const& time);
void greens(Chrono const& time);
private:
void append(std::string short_str, std::string long_str, Chrono const& time);
private:
char const* short_line = "{:s} [{}] ";
char const* long_line = "- {:<80s} | {}\n";
std::string short_report;
std::string long_report;
};
} // namespace kpm
struct KPMConfig {
float lambda = 4.0f; ///< controls the accuracy of the kernel polynomial method
float min_energy = 0.0f; ///< lowest eigenvalue of the Hamiltonian
float max_energy = 0.0f; ///< highest eigenvalue of the Hamiltonian
int optimization_level = 2; ///< 0 to 2, higher levels apply more complex optimizations
float lanczos_precision = 0.002f; ///< how precise should the min/max energy estimation be
};
/**
Kernel polynomial method for calculating Green's function
*/
template<class scalar_t>
class KPM : public GreensStrategy {
using real_t = num::get_real_t<scalar_t>;
using complex_t = num::get_complex_t<scalar_t>;
public:
using Config = KPMConfig;
explicit KPM(SparseMatrixRC<scalar_t> hamiltonian, Config const& config = {});
bool change_hamiltonian(Hamiltonian const& h) override;
ArrayXcd calc(int i, int j, ArrayXd const& energy, double broadening) override;
std::vector<ArrayXcd> calc_vector(int row, std::vector<int> const& cols,
ArrayXd const& energy, double broadening) override;
std::string report(bool shortform) const override;
private:
/// Calculate the KPM Green's function moments
static kpm::MomentMatrix<scalar_t> calc_moments(kpm::OptimizedHamiltonian<scalar_t> const& oh,
int num_moments);
/// Optimized `calc_moments`: lower memory bandwidth requirements
static kpm::MomentMatrix<scalar_t> calc_moments2(kpm::OptimizedHamiltonian<scalar_t> const& oh,
int num_moments);
private:
SparseMatrixRC<scalar_t> hamiltonian;
Config const config;
kpm::Scale<scalar_t> scale;
kpm::OptimizedHamiltonian<scalar_t> optimized_hamiltonian;
kpm::Stats stats;
};
TBM_EXTERN_TEMPLATE_CLASS(KPM)
TBM_EXTERN_TEMPLATE_CLASS(kpm::Scale)
TBM_EXTERN_TEMPLATE_CLASS(kpm::OptimizedHamiltonian)
TBM_EXTERN_TEMPLATE_CLASS(kpm::MomentMatrix)
} // namespace tbm
<commit_msg>Fix signed/unsigned mismatch warning<commit_after>#pragma once
#include "greens/Greens.hpp"
#include "numeric/sparse.hpp"
#include "compute/lanczos.hpp"
#include "detail/macros.hpp"
namespace tbm { namespace kpm {
/**
Computes and stores the KPM scaling parameters `a` and `b` based on the energy
bounds (min and max eigenvalue) of the Hamiltonian. The bounds are determined
automatically with the Lanczos procedure, or set manually by the user.
Note: `compute` must be called before `a` and `b` are used. This is slightly awkward
but necessary because the computation is relatively expensive and should not be done
at construction time.
*/
template<class scalar_t>
class Scale {
using real_t = num::get_real_t<scalar_t>;
static constexpr auto scaling_tolerance = 0.01f; ///< the eigenvalue bounds are not precise
public:
Scale() = default;
/// Set the energy bounds manually, therefore skipping the Lanczos procedure at `compute` time
Scale(real_t min_energy, real_t max_energy) : bounds{min_energy, max_energy, 0} {}
// Compute the scaling params of the Hamiltonian `matrix` using the Lanczos procedure
void compute(SparseMatrixX<scalar_t> const& matrix, real_t lanczos_tolerance);
public:
real_t a = 0;
real_t b = 0;
compute::LanczosBounds<real_t> bounds = {0, 0, 0};
};
/**
Indices of the Green's function matrix that will be computed
A single KPM calculation will compute an entire `row` of the Green's matrix,
however only some column indices are required to be saved, as indicated by `cols`.
*/
struct Indices {
int row = -1;
ArrayXi cols;
Indices() = default;
Indices(int row, int col) : row(row), cols(1) { cols[0] = col; }
Indices(int row, ArrayXi const& cols) : row(row), cols(cols) {}
Indices(int row, std::vector<int> const& cols) : row(row), cols(eigen_cast<ArrayX>(cols)) {}
friend bool operator==(Indices const& l, Indices const& r) {
return l.row == r.row && all_of(l.cols == r.cols);
}
};
/**
Stores a scaled Hamiltonian `(H - b)/a` which limits it to (-1, 1) boundaries required for KPM.
In addition, two optimisations are applied:
1) The matrix is multiplied by 2. This benefits most calculations (e.g. `x = 2*H*x - y`),
because the 2x multiplication is done only once, but it will need to be divided by 2
when the original element values are needed (very rarely).
2) Reorder the elements so that the index pair (i, j) is at the start of the matrix.
This produces the `optimized_sizes` vector which may be used to reduce calculation
time by skipping sparse matrix-vector multiplication of zero values.
*/
template<class scalar_t>
class OptimizedHamiltonian {
using real_t = num::get_real_t<scalar_t>;
public:
/// Create the optimized Hamiltonian from `H` targeting index pair `idx`
void create(SparseMatrixX<scalar_t> const& H, Indices const& idx,
Scale<scalar_t> scale, bool use_reordering);
/// Return an index into `optimized_sizes`, indicating the optimal system size
/// for the calculation of KPM moment number `n` out of total `num_moments`
int optimized_size_index(int n, int num_moments) const {
assert(n < num_moments);
assert(!optimized_sizes.empty());
auto const max_index = std::min(
static_cast<int>(optimized_sizes.size()) - 1,
num_moments / 2
);
if (n < max_index) {
return n; // size grows in the beginning
} else { // constant in the middle and shrinking near the end as reverse `n`
return std::min(max_index, num_moments - 1 - n + size_index_offset);
}
}
/// Return the optimized system size for KPM moment number `n` out of total `num_moments`
int optimized_size(int n, int num_moments) const {
if (!optimized_sizes.empty()) {
return optimized_sizes[optimized_size_index(n, num_moments)];
} else {
return H2.rows();
}
}
/// The unoptimized compute area is H2.nonZeros() * num_moments
double optimized_area(int num_moments) const;
public:
SparseMatrixX<scalar_t> H2; ///< the optimized matrix
Indices original_idx; ///< indices from the original `H` matrix
Indices optimized_idx; ///< reordered indices in the `H2` matrix
std::vector<int> optimized_sizes; ///< optimal matrix size "steps" for the KPM calculation
int size_index_offset = 0; ///< needed to correctly compute off-diagonal elements (i != j)
private:
/// Fill H2 with scaled Hamiltonian: H2 = (H - I*b) * (2/a)
void create_scaled(SparseMatrixX<scalar_t> const& H, Indices const& idx,
Scale<scalar_t> scale);
/// Scale and reorder the Hamiltonian so that idx is at the start of the H2 matrix
void create_reordered(SparseMatrixX<scalar_t> const& H, Indices const& idx,
Scale<scalar_t> scale);
static Indices reorder_indices(Indices const& original_idx,
std::vector<int> const& reorder_map);
static int compute_index_offset(Indices const& optimized_idx,
std::vector<int> const& optimized_sizes);
};
namespace detail {
/// Put the kernel in *Kernel* polynomial method
template<class scalar_t, class real_t>
void apply_lorentz_kernel(ArrayX<scalar_t>& moments, real_t lambda) {
auto const N = moments.size();
auto lorentz_kernel = [=](real_t n) { // n is real_t to get proper fp division
using std::sinh;
return sinh(lambda * (1 - n / N)) / sinh(lambda);
};
for (auto n = 0; n < N; ++n) {
moments[n] *= lorentz_kernel(static_cast<real_t>(n));
}
}
/// Calculate the final Green's function for `scaled_energy` using the KPM `moments`
template<class scalar_t, class real_t, class complex_t = num::get_complex_t<scalar_t>>
ArrayX<complex_t> calculate_greens(ArrayX<real_t> const& scaled_energy,
ArrayX<scalar_t> const& moments) {
// Note that this integer array has real type values
auto ns = ArrayX<real_t>(moments.size());
for (auto n = 0; n < ns.size(); ++n) {
ns[n] = static_cast<real_t>(n);
}
// G = -2*i / sqrt(1 - E^2) * sum( moments * exp(-i*ns*acos(E)) )
auto greens = ArrayX<complex_t>(scaled_energy.size());
transform(scaled_energy, greens, [&](real_t E) {
using std::acos;
using constant::i1;
auto const norm = -real_t{2} * complex_t{i1} / sqrt(1 - E*E);
return norm * sum(moments * exp(-complex_t{i1} * ns * acos(E)));
});
return greens;
}
} // namespace detail
/**
Stores KPM moments (size `num_moments`) computed for each index (size of `indices`)
*/
template<class scalar_t>
class MomentMatrix {
using real_t = num::get_real_t<scalar_t>;
ArrayXi indices;
std::vector<ArrayX<scalar_t>> data;
public:
MomentMatrix(int num_moments, ArrayXi const& indices)
: indices(indices), data(indices.size()) {
for (auto& moments : data) {
moments.resize(num_moments);
}
}
/// Collect the first 2 moments which are computer outside the main KPM loop
void collect_initial(VectorX<scalar_t> const& r0, VectorX<scalar_t> const& r1) {
for (auto i = 0; i < indices.size(); ++i) {
auto const idx = indices[i];
data[i][0] = r0[idx] * real_t{0.5}; // 0.5 is special for the moment zero
data[i][1] = r1[idx];
}
}
/// Collect moment `n` from result vector `r` for each index. Expects `n >= 2`.
void collect(int n, VectorX<scalar_t> const& r) {
assert(n >= 2 && n < data[0].size());
for (auto i = 0; i < indices.size(); ++i) {
auto const idx = indices[i];
data[i][n] = r[idx];
}
}
/// Put the kernel in *Kernel* polynomial method
void apply_lorentz_kernel(real_t lambda) {
for (auto& moments : data) {
detail::apply_lorentz_kernel(moments, lambda);
}
}
/// Calculate the final Green's function at all indices for `scaled_energy`
std::vector<ArrayXcd> calc_greens(ArrayX<real_t> const& scaled_energy) const {
auto greens = std::vector<ArrayXcd>();
greens.reserve(indices.size());
for (auto const& moments : data) {
auto const g = detail::calculate_greens(scaled_energy, moments);
greens.push_back(g.template cast<std::complex<double>>());
}
return greens;
}
};
/**
Stats of the KPM calculation
*/
class Stats {
public:
std::string report(bool shortform) const;
template<class real_t>
void lanczos(compute::LanczosBounds<real_t> const& bounds, Chrono const& time);
template<class scalar_t>
void reordering(OptimizedHamiltonian<scalar_t> const& oh, int num_moments, Chrono const& time);
template<class scalar_t>
void kpm(OptimizedHamiltonian<scalar_t> const& oh, int num_moments, Chrono const& time);
void greens(Chrono const& time);
private:
void append(std::string short_str, std::string long_str, Chrono const& time);
private:
char const* short_line = "{:s} [{}] ";
char const* long_line = "- {:<80s} | {}\n";
std::string short_report;
std::string long_report;
};
} // namespace kpm
struct KPMConfig {
float lambda = 4.0f; ///< controls the accuracy of the kernel polynomial method
float min_energy = 0.0f; ///< lowest eigenvalue of the Hamiltonian
float max_energy = 0.0f; ///< highest eigenvalue of the Hamiltonian
int optimization_level = 2; ///< 0 to 2, higher levels apply more complex optimizations
float lanczos_precision = 0.002f; ///< how precise should the min/max energy estimation be
};
/**
Kernel polynomial method for calculating Green's function
*/
template<class scalar_t>
class KPM : public GreensStrategy {
using real_t = num::get_real_t<scalar_t>;
using complex_t = num::get_complex_t<scalar_t>;
public:
using Config = KPMConfig;
explicit KPM(SparseMatrixRC<scalar_t> hamiltonian, Config const& config = {});
bool change_hamiltonian(Hamiltonian const& h) override;
ArrayXcd calc(int i, int j, ArrayXd const& energy, double broadening) override;
std::vector<ArrayXcd> calc_vector(int row, std::vector<int> const& cols,
ArrayXd const& energy, double broadening) override;
std::string report(bool shortform) const override;
private:
/// Calculate the KPM Green's function moments
static kpm::MomentMatrix<scalar_t> calc_moments(kpm::OptimizedHamiltonian<scalar_t> const& oh,
int num_moments);
/// Optimized `calc_moments`: lower memory bandwidth requirements
static kpm::MomentMatrix<scalar_t> calc_moments2(kpm::OptimizedHamiltonian<scalar_t> const& oh,
int num_moments);
private:
SparseMatrixRC<scalar_t> hamiltonian;
Config const config;
kpm::Scale<scalar_t> scale;
kpm::OptimizedHamiltonian<scalar_t> optimized_hamiltonian;
kpm::Stats stats;
};
TBM_EXTERN_TEMPLATE_CLASS(KPM)
TBM_EXTERN_TEMPLATE_CLASS(kpm::Scale)
TBM_EXTERN_TEMPLATE_CLASS(kpm::OptimizedHamiltonian)
TBM_EXTERN_TEMPLATE_CLASS(kpm::MomentMatrix)
} // namespace tbm
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include <stdlib.h>
#include <stdio.h>
#include <tools/rcid.h>
#include <rschash.hxx>
#include <rscerror.h>
#include <rscall.h>
#include <rscdb.hxx>
#include <rscpar.hxx>
#include "rsclex.hxx"
ERRTYPE& ERRTYPE::operator = ( const ERRTYPE & rError )
{
if( !IsError() ){
if( rError.IsError() || !IsWarning() )
nError = rError.nError;
}
return *this;
}
void RscError::StdOut( const char * pStr, const RscVerbosity _verbosityLevel )
{
if ( m_verbosity >= _verbosityLevel )
{
if( pStr ){
printf( "%s", pStr );
fflush( stdout );
}
}
}
void RscError::StdErr( const char * pStr )
{
if( pStr )
fprintf( stderr, "%s", pStr );
}
void RscError::LstOut( const char * pStr ){
if( fListing && pStr )
fprintf( fListing, "%s", pStr );
}
void RscError::StdLstOut( const char * pStr ){
StdOut( pStr );
LstOut( pStr );
}
void RscError::StdLstErr( const char * pStr ){
StdErr( pStr );
LstOut( pStr );
}
void RscError::WriteError( const ERRTYPE& rError, const char * pMessage )
{
switch( rError )
{
case ERR_ERROR: {
StdLstErr( "!! " );
if( 1 == nErrors )
StdLstErr(OString::number(nErrors).getStr());
else
StdLstErr(OString::number(nErrors -1).getStr());
StdLstErr( " Error" );
StdLstErr( " found!!" );
}
break;
case ERR_UNKNOWN_METHOD:
StdLstErr( "The used type is not allowed." );
break;
case ERR_OPENFILE:
StdLstErr( "This file <" );
StdLstErr( pMessage );
StdLstErr( "> cannot be opened." );
break;
case ERR_RENAMEFILE:
StdLstErr( "rename <" );
StdLstErr( pMessage );
StdLstErr( "> s not possible." );
break;
case ERR_FILESIZE:
StdLstErr( "Wrong file <" );
StdLstErr( pMessage );
StdLstErr( "> length." );
break;
case ERR_FILEFORMAT:
StdLstErr( "Wrong file type <" );
StdLstErr( pMessage );
StdLstErr( ">." );
break;
case ERR_NOCHAR:
StdLstErr( "Character: '\\xxx'; The value xxx is greater than 255.");
break;
case ERR_NORSCINST:
StdLstErr( "Internal error, instance invalid.");
break;
case ERR_NOINPUT:
StdLstErr( "Input file was not specified.\n");
case ERR_USAGE:
StdLstOut( "Copyright (C) 2000 - 2012 LibreOffice contributors.\n" );
{
char buf[40];
StdLstOut( "DataVersion: " );
sprintf( buf, "%d.%d\n\n",
RSCVERSION_ID / 100, RSCVERSION_ID % 100 );
StdLstOut( buf );
}
StdLstOut( "Command line: rsc [Switches] <Source File(s)>\n" );
StdLstOut( "Command line: rsc @<Command File>\n" );
StdLstOut( "-h shows this help.\n" );
StdLstOut( "-p No preprocessor.\n" );
StdLstOut( "-s Syntax analysis, creates .srs file\n");
StdLstOut( "-l Linker, links files created with rsc -s,\n" );
StdLstOut( " creates .rc file and .res file.\n" );
StdLstOut( "-r Prevents .res file.\n" );
StdLstOut( "-d Symbol definitions for the Preprocessor.\n" );
StdLstOut( "-i Include directives for the Preprocessor.\n" );
StdLstOut( "-presponse Use response file for Preprocessor.\n" );
StdLstOut( "-lg<language> Use a different language.\n" );
StdLstOut( "-fs=<filename> Name of the .res file.\n" );
StdLstOut( "-lip=<path> additional search path for system dependent files\n" );
StdLstOut( "-fp=<filename> Renaming of the .srs file.\n" );
StdLstOut( "-oil=<dir> Output directory for image list files\n" );
StdLstOut( "-sub<ENV>=<path> replace <path> by <ENV> in image list files\n" );
StdLstOut( "-BIGENDIAN Format of number values.\n" );
StdLstOut( "-LITTLEENDIAN Format of number values.\n" );
StdLstOut( "-SrsDefault Only write one language to srs file.\n" );
StdLstOut( "\nwhen creating multiple .res files in one pass, please give these\n" );
StdLstOut( "options in consecutive blocks:\n" );
StdLstOut( "-lg<language> -fs<filename> [-lip<path> [-lip<path>] ]\n" );
StdLstOut( "a new block begins when either -lg or -fs is used again.\n" );
break;
case ERR_UNKNOWNSW:
StdLstErr( "Unknown switch <" );
StdLstErr( pMessage );
StdLstErr( ">." );
break;
case ERR_REFTODEEP:
StdLstErr( "Too many reference levels have been used (see Switch -RefDeep)." );
break;
case ERR_CONT_INVALIDPOS:
StdLstErr( "Internal error, Container class: invalid position." );
break;
case ERR_CONT_INVALIDTYPE:
StdLstErr( "Invalid type <" );
StdLstErr( pMessage );
StdLstErr( ">." );
break;
case ERR_ARRAY_INVALIDINDEX:
StdLstErr( "Internal error, Array class: invalid index." );
break;
case ERR_RSCINST_NOVARNAME:
StdLstErr( "Internal error, invalid name of variable." );
break;
case ERR_YACC:
StdLstErr( pMessage );
break;
case ERR_DOUBLEID:
StdLstErr( "Two global resources have the same identifier." );
break;
case ERR_FALSETYPE:
StdLstErr( "Wrong type <" );
StdLstErr( pMessage );
StdLstErr( ">." );
break;
case ERR_NOVARIABLENAME:
StdLstErr( "The variable <" );
StdLstErr( pMessage );
StdLstErr( "> must not be used here." );
break;
case ERR_RSCRANGE_OUTDEFSET:
StdLstErr( "The used value is not in the expected domain." );
break;
case ERR_USHORTRANGE:
StdLstErr( "Value is <" );
StdLstErr( pMessage );
StdLstErr( "> the allowed domain is from 0 up to 65535." );
break;
case ERR_IDRANGE:
StdLstErr( "Value is <" );
StdLstErr( pMessage );
StdLstErr( "> the allowed domain is from 1 up to 32767." );
break;
case ERR_NOCOPYOBJ:
StdLstErr( "Default resource <" );
StdLstErr( pMessage );
StdLstErr( "> not found." );
break;
case ERR_REFNOTALLOWED:
StdLstErr( "The use of a reference is not allowed." );
break;
case ERR_COPYNOTALLOWED:
StdLstErr( "The use of a default resource is not allowed." );
break;
case ERR_IDEXPECTED:
StdLstErr( "An identifier needs to be specified." );
break;
case ERR_DOUBLEDEFINE:
StdLstErr( "The symbol <" );
StdLstErr( pMessage );
StdLstErr( "> is defined twice." );
break;
case ERR_RSCINST_RESERVEDNAME:
StdLstErr( "The symbol <" );
StdLstErr( pMessage );
StdLstErr( "> is a reserved name." );
break;
case ERR_ZERODIVISION:
StdLstErr( "Attempt to divide by zero." );
break;
case ERR_PRAGMA:
StdLstErr( "Error in a #pragma statement." );
break;
case ERR_DECLAREDEFINE:
StdLstErr( "Error in the declaration part of the macro." );
break;
case ERR_NOTYPE:
StdLstErr( "type expected." );
break;
case ERR_NOIMAGE:
StdLstErr( "The image(s) <" );
StdLstErr( pMessage );
StdLstErr( "> could not be found." );
break;
case WRN_LOCALID:
StdLstErr( "Sub resources should have an identifier < 256." );
break;
case WRN_GLOBALID:
StdLstErr( "Global resources should have an identifier >= 256." );
break;
case WRN_SUBINMEMBER:
StdLstErr( "Sub resources are ignored." );
break;
case WRN_CONT_NOID:
StdLstErr( "Resources without name are ignored." );
break;
case WRN_CONT_DOUBLEID:
StdLstErr( "Two local resources have the same identifier." );
break;
case WRN_STR_REFNOTFOUND:
StdLstErr( "String reference <" );
StdLstErr( pMessage );
StdLstErr( " > could not be resolved." );
break;
case WRN_MGR_REFNOTFOUND:
StdLstErr( "Reference <" );
StdLstErr( pMessage );
StdLstErr( " > could not be resolved." );
break;
default:
if( pMessage ){
StdLstErr( "\nMessage: " );
StdLstErr( pMessage );
};
break;
}
}
void RscError::ErrorFormat( const ERRTYPE& rError, RscTop * pClass,
const RscId & aId ){
char buf[ 10 ];
sal_uInt32 i;
if( pFI )
{
pFI->SetError( rError );
StdErr( "\n" );
StdErr( pFI->GetLine() );
StdErr( "\n" );
// Fehlerposition anzeigen
for( i = 0; (i +1) < pFI->GetScanPos(); i++ )
StdLstErr( " " );
LstOut( " ^" ); //Zeilennummern beachten
StdErr( "^" );
StdLstErr( "\n" );
}
StdLstErr( "f" );
sprintf( buf, "%u", (unsigned int)rError );
StdLstErr( buf );
if( pFI && pTC ){
StdLstErr( ": \"" );
StdLstErr( pTC->aFileTab.Get( pFI->GetFileIndex() )->aFileName.getStr() );
StdLstErr( "\", line " );
sprintf( buf, "%u", (unsigned int)pFI->GetLineNo() );
StdLstErr( buf );
}
if( rError.IsError() )
StdLstErr( ": Error" );
else
StdLstErr( ": Warning" );
if( pClass || aId.IsId() )
{
StdLstErr( " in the object (" );
if( pClass )
{
StdLstErr( "Type: " );
StdLstErr( pHS->getString( pClass->GetId() ).getStr() );
if( aId.IsId() )
StdLstErr( ", " );
}
if( aId.IsId() )
StdLstErr( aId.GetName().getStr() );
StdLstErr( "):\n" );
}
else
StdLstErr( ": " );
}
void RscError::Error( const ERRTYPE& rError, RscTop * pClass,
const RscId & aId, const char * pMessage )
{
if( WRN_LOCALID == rError ) // Keine Warning erzeugen
return;
if( rError.IsError() )
nErrors++;
if( rError.IsError() || rError.IsWarning() ){
ErrorFormat( rError, pClass, aId );
WriteError( rError, pMessage );
StdLstErr( "\n" );
}
}
void RscError::FatalError( const ERRTYPE& rError, const RscId &aId,
const char * pMessage )
{
if( ERR_USAGE != rError ){
nErrors++;
ErrorFormat( rError, NULL, aId );
WriteError( rError, pMessage );
StdLstErr( "\nTerminating compiler\n" );
}
else
WriteError( rError, pMessage );
exit( 1 );
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>coverity#705195 Missing break in switch<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include <stdlib.h>
#include <stdio.h>
#include <tools/rcid.h>
#include <rschash.hxx>
#include <rscerror.h>
#include <rscall.h>
#include <rscdb.hxx>
#include <rscpar.hxx>
#include "rsclex.hxx"
ERRTYPE& ERRTYPE::operator = ( const ERRTYPE & rError )
{
if( !IsError() ){
if( rError.IsError() || !IsWarning() )
nError = rError.nError;
}
return *this;
}
void RscError::StdOut( const char * pStr, const RscVerbosity _verbosityLevel )
{
if ( m_verbosity >= _verbosityLevel )
{
if( pStr ){
printf( "%s", pStr );
fflush( stdout );
}
}
}
void RscError::StdErr( const char * pStr )
{
if( pStr )
fprintf( stderr, "%s", pStr );
}
void RscError::LstOut( const char * pStr ){
if( fListing && pStr )
fprintf( fListing, "%s", pStr );
}
void RscError::StdLstOut( const char * pStr ){
StdOut( pStr );
LstOut( pStr );
}
void RscError::StdLstErr( const char * pStr ){
StdErr( pStr );
LstOut( pStr );
}
void RscError::WriteError( const ERRTYPE& rError, const char * pMessage )
{
switch( rError )
{
case ERR_ERROR: {
StdLstErr( "!! " );
if( 1 == nErrors )
StdLstErr(OString::number(nErrors).getStr());
else
StdLstErr(OString::number(nErrors -1).getStr());
StdLstErr( " Error" );
StdLstErr( " found!!" );
}
break;
case ERR_UNKNOWN_METHOD:
StdLstErr( "The used type is not allowed." );
break;
case ERR_OPENFILE:
StdLstErr( "This file <" );
StdLstErr( pMessage );
StdLstErr( "> cannot be opened." );
break;
case ERR_RENAMEFILE:
StdLstErr( "rename <" );
StdLstErr( pMessage );
StdLstErr( "> s not possible." );
break;
case ERR_FILESIZE:
StdLstErr( "Wrong file <" );
StdLstErr( pMessage );
StdLstErr( "> length." );
break;
case ERR_FILEFORMAT:
StdLstErr( "Wrong file type <" );
StdLstErr( pMessage );
StdLstErr( ">." );
break;
case ERR_NOCHAR:
StdLstErr( "Character: '\\xxx'; The value xxx is greater than 255.");
break;
case ERR_NORSCINST:
StdLstErr( "Internal error, instance invalid.");
break;
case ERR_NOINPUT:
StdLstErr( "Input file was not specified.\n");
//fall-through
case ERR_USAGE:
StdLstOut( "Copyright (C) 2000 - 2012 LibreOffice contributors.\n" );
{
char buf[40];
StdLstOut( "DataVersion: " );
sprintf( buf, "%d.%d\n\n",
RSCVERSION_ID / 100, RSCVERSION_ID % 100 );
StdLstOut( buf );
}
StdLstOut( "Command line: rsc [Switches] <Source File(s)>\n" );
StdLstOut( "Command line: rsc @<Command File>\n" );
StdLstOut( "-h shows this help.\n" );
StdLstOut( "-p No preprocessor.\n" );
StdLstOut( "-s Syntax analysis, creates .srs file\n");
StdLstOut( "-l Linker, links files created with rsc -s,\n" );
StdLstOut( " creates .rc file and .res file.\n" );
StdLstOut( "-r Prevents .res file.\n" );
StdLstOut( "-d Symbol definitions for the Preprocessor.\n" );
StdLstOut( "-i Include directives for the Preprocessor.\n" );
StdLstOut( "-presponse Use response file for Preprocessor.\n" );
StdLstOut( "-lg<language> Use a different language.\n" );
StdLstOut( "-fs=<filename> Name of the .res file.\n" );
StdLstOut( "-lip=<path> additional search path for system dependent files\n" );
StdLstOut( "-fp=<filename> Renaming of the .srs file.\n" );
StdLstOut( "-oil=<dir> Output directory for image list files\n" );
StdLstOut( "-sub<ENV>=<path> replace <path> by <ENV> in image list files\n" );
StdLstOut( "-BIGENDIAN Format of number values.\n" );
StdLstOut( "-LITTLEENDIAN Format of number values.\n" );
StdLstOut( "-SrsDefault Only write one language to srs file.\n" );
StdLstOut( "\nwhen creating multiple .res files in one pass, please give these\n" );
StdLstOut( "options in consecutive blocks:\n" );
StdLstOut( "-lg<language> -fs<filename> [-lip<path> [-lip<path>] ]\n" );
StdLstOut( "a new block begins when either -lg or -fs is used again.\n" );
break;
case ERR_UNKNOWNSW:
StdLstErr( "Unknown switch <" );
StdLstErr( pMessage );
StdLstErr( ">." );
break;
case ERR_REFTODEEP:
StdLstErr( "Too many reference levels have been used (see Switch -RefDeep)." );
break;
case ERR_CONT_INVALIDPOS:
StdLstErr( "Internal error, Container class: invalid position." );
break;
case ERR_CONT_INVALIDTYPE:
StdLstErr( "Invalid type <" );
StdLstErr( pMessage );
StdLstErr( ">." );
break;
case ERR_ARRAY_INVALIDINDEX:
StdLstErr( "Internal error, Array class: invalid index." );
break;
case ERR_RSCINST_NOVARNAME:
StdLstErr( "Internal error, invalid name of variable." );
break;
case ERR_YACC:
StdLstErr( pMessage );
break;
case ERR_DOUBLEID:
StdLstErr( "Two global resources have the same identifier." );
break;
case ERR_FALSETYPE:
StdLstErr( "Wrong type <" );
StdLstErr( pMessage );
StdLstErr( ">." );
break;
case ERR_NOVARIABLENAME:
StdLstErr( "The variable <" );
StdLstErr( pMessage );
StdLstErr( "> must not be used here." );
break;
case ERR_RSCRANGE_OUTDEFSET:
StdLstErr( "The used value is not in the expected domain." );
break;
case ERR_USHORTRANGE:
StdLstErr( "Value is <" );
StdLstErr( pMessage );
StdLstErr( "> the allowed domain is from 0 up to 65535." );
break;
case ERR_IDRANGE:
StdLstErr( "Value is <" );
StdLstErr( pMessage );
StdLstErr( "> the allowed domain is from 1 up to 32767." );
break;
case ERR_NOCOPYOBJ:
StdLstErr( "Default resource <" );
StdLstErr( pMessage );
StdLstErr( "> not found." );
break;
case ERR_REFNOTALLOWED:
StdLstErr( "The use of a reference is not allowed." );
break;
case ERR_COPYNOTALLOWED:
StdLstErr( "The use of a default resource is not allowed." );
break;
case ERR_IDEXPECTED:
StdLstErr( "An identifier needs to be specified." );
break;
case ERR_DOUBLEDEFINE:
StdLstErr( "The symbol <" );
StdLstErr( pMessage );
StdLstErr( "> is defined twice." );
break;
case ERR_RSCINST_RESERVEDNAME:
StdLstErr( "The symbol <" );
StdLstErr( pMessage );
StdLstErr( "> is a reserved name." );
break;
case ERR_ZERODIVISION:
StdLstErr( "Attempt to divide by zero." );
break;
case ERR_PRAGMA:
StdLstErr( "Error in a #pragma statement." );
break;
case ERR_DECLAREDEFINE:
StdLstErr( "Error in the declaration part of the macro." );
break;
case ERR_NOTYPE:
StdLstErr( "type expected." );
break;
case ERR_NOIMAGE:
StdLstErr( "The image(s) <" );
StdLstErr( pMessage );
StdLstErr( "> could not be found." );
break;
case WRN_LOCALID:
StdLstErr( "Sub resources should have an identifier < 256." );
break;
case WRN_GLOBALID:
StdLstErr( "Global resources should have an identifier >= 256." );
break;
case WRN_SUBINMEMBER:
StdLstErr( "Sub resources are ignored." );
break;
case WRN_CONT_NOID:
StdLstErr( "Resources without name are ignored." );
break;
case WRN_CONT_DOUBLEID:
StdLstErr( "Two local resources have the same identifier." );
break;
case WRN_STR_REFNOTFOUND:
StdLstErr( "String reference <" );
StdLstErr( pMessage );
StdLstErr( " > could not be resolved." );
break;
case WRN_MGR_REFNOTFOUND:
StdLstErr( "Reference <" );
StdLstErr( pMessage );
StdLstErr( " > could not be resolved." );
break;
default:
if( pMessage ){
StdLstErr( "\nMessage: " );
StdLstErr( pMessage );
};
break;
}
}
void RscError::ErrorFormat( const ERRTYPE& rError, RscTop * pClass,
const RscId & aId ){
char buf[ 10 ];
sal_uInt32 i;
if( pFI )
{
pFI->SetError( rError );
StdErr( "\n" );
StdErr( pFI->GetLine() );
StdErr( "\n" );
// Fehlerposition anzeigen
for( i = 0; (i +1) < pFI->GetScanPos(); i++ )
StdLstErr( " " );
LstOut( " ^" ); //Zeilennummern beachten
StdErr( "^" );
StdLstErr( "\n" );
}
StdLstErr( "f" );
sprintf( buf, "%u", (unsigned int)rError );
StdLstErr( buf );
if( pFI && pTC ){
StdLstErr( ": \"" );
StdLstErr( pTC->aFileTab.Get( pFI->GetFileIndex() )->aFileName.getStr() );
StdLstErr( "\", line " );
sprintf( buf, "%u", (unsigned int)pFI->GetLineNo() );
StdLstErr( buf );
}
if( rError.IsError() )
StdLstErr( ": Error" );
else
StdLstErr( ": Warning" );
if( pClass || aId.IsId() )
{
StdLstErr( " in the object (" );
if( pClass )
{
StdLstErr( "Type: " );
StdLstErr( pHS->getString( pClass->GetId() ).getStr() );
if( aId.IsId() )
StdLstErr( ", " );
}
if( aId.IsId() )
StdLstErr( aId.GetName().getStr() );
StdLstErr( "):\n" );
}
else
StdLstErr( ": " );
}
void RscError::Error( const ERRTYPE& rError, RscTop * pClass,
const RscId & aId, const char * pMessage )
{
if( WRN_LOCALID == rError ) // Keine Warning erzeugen
return;
if( rError.IsError() )
nErrors++;
if( rError.IsError() || rError.IsWarning() ){
ErrorFormat( rError, pClass, aId );
WriteError( rError, pMessage );
StdLstErr( "\n" );
}
}
void RscError::FatalError( const ERRTYPE& rError, const RscId &aId,
const char * pMessage )
{
if( ERR_USAGE != rError ){
nErrors++;
ErrorFormat( rError, NULL, aId );
WriteError( rError, pMessage );
StdLstErr( "\nTerminating compiler\n" );
}
else
WriteError( rError, pMessage );
exit( 1 );
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>/*
* Copyright 2017 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <folly/portability/SysUio.h>
#include <errno.h>
#include <stdio.h>
#include <folly/ScopeGuard.h>
#include <folly/portability/SysFile.h>
#include <folly/portability/Unistd.h>
template <class F, class... Args>
static int wrapPositional(F f, int fd, off_t offset, Args... args) {
off_t origLoc = lseek(fd, 0, SEEK_CUR);
if (origLoc == off_t(-1)) {
return -1;
}
if (lseek(fd, offset, SEEK_SET) == off_t(-1)) {
return -1;
}
int res = (int)f(fd, args...);
int curErrNo = errno;
if (lseek(fd, origLoc, SEEK_SET) == off_t(-1)) {
if (res == -1) {
errno = curErrNo;
}
return -1;
}
errno = curErrNo;
return res;
}
#if !FOLLY_HAVE_PREADV
extern "C" ssize_t preadv(int fd, const iovec* iov, int count, off_t offset) {
return wrapPositional(readv, fd, offset, iov, count);
}
#endif
#if !FOLLY_HAVE_PWRITEV
extern "C" ssize_t pwritev(int fd, const iovec* iov, int count, off_t offset) {
return wrapPositional(writev, fd, offset, iov, count);
}
#endif
#ifdef _WIN32
template <bool isRead>
static ssize_t doVecOperation(int fd, const iovec* iov, int count) {
if (!count) {
return 0;
}
if (count < 0 || count > folly::kIovMax) {
errno = EINVAL;
return -1;
}
if (lockf(fd, F_LOCK, 0) == -1) {
return -1;
}
SCOPE_EXIT {
lockf(fd, F_ULOCK, 0);
};
ssize_t bytesProcessed = 0;
int curIov = 0;
void* curBase = iov[0].iov_base;
size_t curLen = iov[0].iov_len;
while (curIov < count) {
ssize_t res = 0;
if (isRead) {
res = read(fd, curBase, (unsigned int)curLen);
if (res == 0 && curLen != 0) {
break; // End of File
}
} else {
res = write(fd, curBase, (unsigned int)curLen);
// Write of zero bytes is fine.
}
if (res == -1) {
return -1;
}
if (size_t(res) == curLen) {
curIov++;
if (curIov < count) {
curBase = iov[curIov].iov_base;
curLen = iov[curIov].iov_len;
}
} else {
curBase = (void*)((char*)curBase + res);
curLen -= res;
}
if (bytesProcessed + res < 0) {
// Overflow
errno = EINVAL;
return -1;
}
bytesProcessed += res;
}
return bytesProcessed;
}
extern "C" ssize_t readv(int fd, const iovec* iov, int count) {
return doVecOperation<true>(fd, iov, count);
}
extern "C" ssize_t writev(int fd, const iovec* iov, int count) {
return doVecOperation<false>(fd, iov, count);
}
#endif
<commit_msg>Don't attempt to lock the file descriptor in readv/writev if it's a socket<commit_after>/*
* Copyright 2017 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <folly/portability/SysUio.h>
#include <errno.h>
#include <stdio.h>
#include <folly/ScopeGuard.h>
#include <folly/portability/SysFile.h>
#include <folly/portability/Unistd.h>
template <class F, class... Args>
static int wrapPositional(F f, int fd, off_t offset, Args... args) {
off_t origLoc = lseek(fd, 0, SEEK_CUR);
if (origLoc == off_t(-1)) {
return -1;
}
if (lseek(fd, offset, SEEK_SET) == off_t(-1)) {
return -1;
}
int res = (int)f(fd, args...);
int curErrNo = errno;
if (lseek(fd, origLoc, SEEK_SET) == off_t(-1)) {
if (res == -1) {
errno = curErrNo;
}
return -1;
}
errno = curErrNo;
return res;
}
#if !FOLLY_HAVE_PREADV
extern "C" ssize_t preadv(int fd, const iovec* iov, int count, off_t offset) {
return wrapPositional(readv, fd, offset, iov, count);
}
#endif
#if !FOLLY_HAVE_PWRITEV
extern "C" ssize_t pwritev(int fd, const iovec* iov, int count, off_t offset) {
return wrapPositional(writev, fd, offset, iov, count);
}
#endif
#ifdef _WIN32
template <bool isRead>
static ssize_t doVecOperation(int fd, const iovec* iov, int count) {
if (!count) {
return 0;
}
if (count < 0 || count > folly::kIovMax) {
errno = EINVAL;
return -1;
}
// We only need to worry about locking if the file descriptor is
// not a socket. We have no way of locking sockets :(
// The correct way to do this for sockets is via sendmsg/recvmsg,
// but this is good enough for now.
bool shouldLock = !folly::portability::sockets::is_fh_socket(fd);
if (shouldLock && lockf(fd, F_LOCK, 0) == -1) {
return -1;
}
SCOPE_EXIT {
if (shouldLock) {
lockf(fd, F_ULOCK, 0);
}
};
ssize_t bytesProcessed = 0;
int curIov = 0;
void* curBase = iov[0].iov_base;
size_t curLen = iov[0].iov_len;
while (curIov < count) {
ssize_t res = 0;
if (isRead) {
res = read(fd, curBase, (unsigned int)curLen);
if (res == 0 && curLen != 0) {
break; // End of File
}
} else {
res = write(fd, curBase, (unsigned int)curLen);
// Write of zero bytes is fine.
}
if (res == -1) {
return -1;
}
if (size_t(res) == curLen) {
curIov++;
if (curIov < count) {
curBase = iov[curIov].iov_base;
curLen = iov[curIov].iov_len;
}
} else {
curBase = (void*)((char*)curBase + res);
curLen -= res;
}
if (bytesProcessed + res < 0) {
// Overflow
errno = EINVAL;
return -1;
}
bytesProcessed += res;
}
return bytesProcessed;
}
extern "C" ssize_t readv(int fd, const iovec* iov, int count) {
return doVecOperation<true>(fd, iov, count);
}
extern "C" ssize_t writev(int fd, const iovec* iov, int count) {
return doVecOperation<false>(fd, iov, count);
}
#endif
<|endoftext|> |
<commit_before>/*
* Copyright 2016 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <folly/Exception.h>
#include <cstdio>
#include <memory>
#include <glog/logging.h>
#include <gtest/gtest.h>
namespace folly { namespace test {
#define EXPECT_SYSTEM_ERROR(statement, err, msg) \
try { \
statement; \
ADD_FAILURE() << "Didn't throw"; \
} catch (const std::system_error& e) { \
std::system_error expected(err, std::system_category(), msg); \
EXPECT_STREQ(expected.what(), e.what()); \
} catch (...) { \
ADD_FAILURE() << "Threw a different type"; \
}
TEST(ExceptionTest, Simple) {
// Make sure errno isn't used when we don't want it to, set it to something
// else than what we set when we call Explicit functions
errno = ERANGE;
EXPECT_SYSTEM_ERROR({throwSystemErrorExplicit(EIO, "hello");},
EIO, "hello");
errno = ERANGE;
EXPECT_SYSTEM_ERROR({throwSystemErrorExplicit(EIO, "hello", " world");},
EIO, "hello world");
errno = ERANGE;
EXPECT_SYSTEM_ERROR({throwSystemError("hello", " world");},
ERANGE, "hello world");
EXPECT_NO_THROW({checkPosixError(0, "hello", " world");});
errno = ERANGE;
EXPECT_SYSTEM_ERROR({checkPosixError(EIO, "hello", " world");},
EIO, "hello world");
EXPECT_NO_THROW({checkKernelError(0, "hello", " world");});
EXPECT_NO_THROW({checkKernelError(EIO, "hello", " world");});
errno = ERANGE;
EXPECT_SYSTEM_ERROR({checkKernelError(-EIO, "hello", " world");},
EIO, "hello world");
EXPECT_NO_THROW({checkUnixError(0, "hello", " world");});
EXPECT_NO_THROW({checkUnixError(1, "hello", " world");});
errno = ERANGE;
EXPECT_SYSTEM_ERROR({checkUnixError(-1, "hello", " world");},
ERANGE, "hello world");
EXPECT_NO_THROW({checkUnixErrorExplicit(0, EIO, "hello", " world");});
EXPECT_NO_THROW({checkUnixErrorExplicit(1, EIO, "hello", " world");});
errno = ERANGE;
EXPECT_SYSTEM_ERROR({checkUnixErrorExplicit(-1, EIO, "hello", " world");},
EIO, "hello world");
std::shared_ptr<FILE> fp(tmpfile(), fclose);
ASSERT_TRUE(fp != nullptr);
EXPECT_NO_THROW({checkFopenError(fp.get(), "hello", " world");});
errno = ERANGE;
EXPECT_SYSTEM_ERROR({checkFopenError(nullptr, "hello", " world");},
ERANGE, "hello world");
EXPECT_NO_THROW({checkFopenErrorExplicit(fp.get(), EIO, "hello", " world");});
errno = ERANGE;
EXPECT_SYSTEM_ERROR({checkFopenErrorExplicit(nullptr, EIO,
"hello", " world");},
EIO, "hello world");
}
}} // namespaces
<commit_msg>Switch from tmpdir to TemporaryDirectory<commit_after>/*
* Copyright 2016 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <folly/Exception.h>
#include <folly/experimental/TestUtil.h>
#include <cstdio>
#include <memory>
#include <glog/logging.h>
#include <gtest/gtest.h>
namespace folly { namespace test {
#define EXPECT_SYSTEM_ERROR(statement, err, msg) \
try { \
statement; \
ADD_FAILURE() << "Didn't throw"; \
} catch (const std::system_error& e) { \
std::system_error expected(err, std::system_category(), msg); \
EXPECT_STREQ(expected.what(), e.what()); \
} catch (...) { \
ADD_FAILURE() << "Threw a different type"; \
}
TEST(ExceptionTest, Simple) {
// Make sure errno isn't used when we don't want it to, set it to something
// else than what we set when we call Explicit functions
errno = ERANGE;
EXPECT_SYSTEM_ERROR({throwSystemErrorExplicit(EIO, "hello");},
EIO, "hello");
errno = ERANGE;
EXPECT_SYSTEM_ERROR({throwSystemErrorExplicit(EIO, "hello", " world");},
EIO, "hello world");
errno = ERANGE;
EXPECT_SYSTEM_ERROR({throwSystemError("hello", " world");},
ERANGE, "hello world");
EXPECT_NO_THROW({checkPosixError(0, "hello", " world");});
errno = ERANGE;
EXPECT_SYSTEM_ERROR({checkPosixError(EIO, "hello", " world");},
EIO, "hello world");
EXPECT_NO_THROW({checkKernelError(0, "hello", " world");});
EXPECT_NO_THROW({checkKernelError(EIO, "hello", " world");});
errno = ERANGE;
EXPECT_SYSTEM_ERROR({checkKernelError(-EIO, "hello", " world");},
EIO, "hello world");
EXPECT_NO_THROW({checkUnixError(0, "hello", " world");});
EXPECT_NO_THROW({checkUnixError(1, "hello", " world");});
errno = ERANGE;
EXPECT_SYSTEM_ERROR({checkUnixError(-1, "hello", " world");},
ERANGE, "hello world");
EXPECT_NO_THROW({checkUnixErrorExplicit(0, EIO, "hello", " world");});
EXPECT_NO_THROW({checkUnixErrorExplicit(1, EIO, "hello", " world");});
errno = ERANGE;
EXPECT_SYSTEM_ERROR({checkUnixErrorExplicit(-1, EIO, "hello", " world");},
EIO, "hello world");
TemporaryDirectory tmpdir;
auto exnpath = tmpdir.path() / "ExceptionTest";
auto fp = fopen(exnpath.c_str(), "w+b");
ASSERT_TRUE(fp != nullptr);
SCOPE_EXIT { fclose(fp); };
EXPECT_NO_THROW({ checkFopenError(fp, "hello", " world"); });
errno = ERANGE;
EXPECT_SYSTEM_ERROR({checkFopenError(nullptr, "hello", " world");},
ERANGE, "hello world");
EXPECT_NO_THROW({ checkFopenErrorExplicit(fp, EIO, "hello", " world"); });
errno = ERANGE;
EXPECT_SYSTEM_ERROR({checkFopenErrorExplicit(nullptr, EIO,
"hello", " world");},
EIO, "hello world");
}
}} // namespaces
<|endoftext|> |
<commit_before>/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */
// vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4:
#ident "$Id$"
#ident "Copyright (c) 2010 Tokutek Inc. All rights reserved."
#ident "The technology is licensed by the Massachusetts Institute of Technology, Rutgers State University of New Jersey, and the Research Foundation of State University of New York at Stony Brook under United States of America Serial No. 11/760379 and to the patents and/or patent applications resulting from it."
#include "cachetable.h"
#include <inttypes.h>
/* Test for #2755. The ft_loader is using too much VM. */
bool verbose=false;
static void test_cachetable_reservation (long size) {
CACHETABLE ct;
{
int r = toku_create_cachetable(&ct, size, ZERO_LSN, NULL);
assert(r==0);
}
{
uint64_t r0 = toku_cachetable_reserve_memory(ct, 0.5);
uint64_t r0_bound = size/2 + size/16;
uint64_t r1 = toku_cachetable_reserve_memory(ct, 0.5);
uint64_t r1_bound = r0_bound/2;
uint64_t r2 = toku_cachetable_reserve_memory(ct, 0.5);
uint64_t r2_bound = r1_bound/2;
if (verbose) printf("%10ld: r0=%10" PRIu64 " r1=%10" PRIu64 " r2=%10" PRIu64 "\n", size, r0, r1, r2);
assert(r0 <= r0_bound);
assert(r1 <= r1_bound);
assert(r2 <= r2_bound);
assert(r1 <= r0);
assert(r2 <= r1);
long unreservable_part = size * 0.25;
assert(r0 <= (size - unreservable_part)*0.5);
assert(r1 <= (size - unreservable_part - r0)*0.5);
assert(r2 <= (size - unreservable_part - r0 -1)*0.5);
}
{
int r = toku_cachetable_close(&ct);
assert(r==0);
}
}
int main (int argc __attribute__((__unused__)), char *argv[] __attribute__((__unused__))) {
test_cachetable_reservation(1L<<28);
test_cachetable_reservation(1LL<<33);
test_cachetable_reservation(3L<<28);
test_cachetable_reservation((3L<<28) - 107);
return 0;
}
<commit_msg>refs #5406, remove tabs from file<commit_after>/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */
// vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4:
#ident "$Id$"
#ident "Copyright (c) 2010 Tokutek Inc. All rights reserved."
#ident "The technology is licensed by the Massachusetts Institute of Technology, Rutgers State University of New Jersey, and the Research Foundation of State University of New York at Stony Brook under United States of America Serial No. 11/760379 and to the patents and/or patent applications resulting from it."
#include "cachetable.h"
#include <inttypes.h>
/* Test for #2755. The ft_loader is using too much VM. */
bool verbose=false;
static void test_cachetable_reservation (long size) {
CACHETABLE ct;
{
int r = toku_create_cachetable(&ct, size, ZERO_LSN, NULL);
assert(r==0);
}
{
uint64_t r0 = toku_cachetable_reserve_memory(ct, 0.5);
uint64_t r0_bound = size/2 + size/16;
uint64_t r1 = toku_cachetable_reserve_memory(ct, 0.5);
uint64_t r1_bound = r0_bound/2;
uint64_t r2 = toku_cachetable_reserve_memory(ct, 0.5);
uint64_t r2_bound = r1_bound/2;
if (verbose) printf("%10ld: r0=%10" PRIu64 " r1=%10" PRIu64 " r2=%10" PRIu64 "\n", size, r0, r1, r2);
assert(r0 <= r0_bound);
assert(r1 <= r1_bound);
assert(r2 <= r2_bound);
assert(r1 <= r0);
assert(r2 <= r1);
long unreservable_part = size * 0.25;
assert(r0 <= (size - unreservable_part)*0.5);
assert(r1 <= (size - unreservable_part - r0)*0.5);
assert(r2 <= (size - unreservable_part - r0 -1)*0.5);
}
{
int r = toku_cachetable_close(&ct);
assert(r==0);
}
}
int main (int argc __attribute__((__unused__)), char *argv[] __attribute__((__unused__))) {
test_cachetable_reservation(1L<<28);
test_cachetable_reservation(1LL<<33);
test_cachetable_reservation(3L<<28);
test_cachetable_reservation((3L<<28) - 107);
return 0;
}
<|endoftext|> |
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (info@qt.nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** 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.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at info@qt.nokia.com.
**
**************************************************************************/
#include "formeditorgraphicsview.h"
#include <QWheelEvent>
#include <QApplication>
#include <QtDebug>
#include <qmlanchors.h>
namespace QmlDesigner {
FormEditorGraphicsView::FormEditorGraphicsView(QWidget *parent) :
QGraphicsView(parent)
{
setTransformationAnchor(QGraphicsView::AnchorUnderMouse);
setResizeAnchor(QGraphicsView::AnchorViewCenter);
setAlignment(Qt::AlignCenter);
setCacheMode(QGraphicsView::CacheNone);
// setCacheMode(QGraphicsView::CacheBackground);
setViewportUpdateMode(QGraphicsView::SmartViewportUpdate);
setOptimizationFlags(QGraphicsView::DontSavePainterState);
// setViewportUpdateMode(QGraphicsView::NoViewportUpdate);
setRenderHint(QPainter::Antialiasing, false);
setFrameShape(QFrame::NoFrame);
setAutoFillBackground(true);
setBackgroundRole(QPalette::Window);
const int checkerbordSize= 20;
QPixmap tilePixmap(checkerbordSize * 2, checkerbordSize * 2);
tilePixmap.fill(Qt::white);
QPainter tilePainter(&tilePixmap);
QColor color(220, 220, 220);
tilePainter.fillRect(0, 0, checkerbordSize, checkerbordSize, color);
tilePainter.fillRect(checkerbordSize, checkerbordSize, checkerbordSize, checkerbordSize, color);
tilePainter.end();
setBackgroundBrush(tilePixmap);
viewport()->setMouseTracking(true);
}
void FormEditorGraphicsView::wheelEvent(QWheelEvent *event)
{
if (event->modifiers().testFlag(Qt::ControlModifier)) {
event->ignore();
} else {
QGraphicsView::wheelEvent(event);
}
}
void FormEditorGraphicsView::mouseMoveEvent(QMouseEvent *event)
{
if (rect().contains(event->pos())) {
QGraphicsView::mouseMoveEvent(event);
} else {
QPoint position = event->pos();
QPoint topLeft = rect().topLeft();
QPoint bottomRight = rect().bottomRight();
position.rx() = qMax(topLeft.x(), qMin(position.x(), bottomRight.x()));
position.ry() = qMax(topLeft.y(), qMin(position.y(), bottomRight.y()));
QMouseEvent *mouseEvent = QMouseEvent::createExtendedMouseEvent(event->type(), position, mapToGlobal(position), event->button(), event->buttons(), event->modifiers());
QGraphicsView::mouseMoveEvent(mouseEvent);
delete mouseEvent;
}
// Keeps the feedback bubble within screen boundraries
int tx = qMin(width() - 114, qMax(16, event->pos().x() + 50));
int ty = qMin(height() - 45, qMax(10, event->pos().y() - 70));
m_feedbackOriginPoint = QPoint(tx, ty);
}
void FormEditorGraphicsView::keyPressEvent(QKeyEvent *event)
{
m_feedbackOriginPoint = QPoint();
QGraphicsView::keyPressEvent(event);
}
void FormEditorGraphicsView::setRootItemRect(const QRectF &rect)
{
m_rootItemRect = rect;
viewport()->update();
}
QRectF FormEditorGraphicsView::rootItemRect() const
{
return m_rootItemRect;
}
void FormEditorGraphicsView::mousePressEvent(QMouseEvent *mouseEvent)
{
QGraphicsView::mousePressEvent(mouseEvent);
}
void FormEditorGraphicsView::mouseReleaseEvent(QMouseEvent *event)
{
if (rect().contains(event->pos())) {
QGraphicsView::mouseReleaseEvent(event);
} else {
QPoint position = event->pos();
QPoint topLeft = rect().topLeft();
QPoint bottomRight = rect().bottomRight();
position.rx() = qMax(topLeft.x(), qMin(position.x(), bottomRight.x()));
position.ry() = qMax(topLeft.y(), qMin(position.y(), bottomRight.y()));
QMouseEvent *mouseEvent = QMouseEvent::createExtendedMouseEvent(event->type(), position, mapToGlobal(position), event->button(), event->buttons(), event->modifiers());
QGraphicsView::mouseReleaseEvent(mouseEvent);
delete mouseEvent;
}
m_feedbackOriginPoint = QPoint();
}
void FormEditorGraphicsView::leaveEvent(QEvent *event)
{
m_feedbackOriginPoint = QPoint();
QGraphicsView::leaveEvent(event);
}
static QPixmap createBubblePixmap()
{
QPixmap pixmap(124, 48);
pixmap.fill(Qt::transparent);
QPainter pmPainter(&pixmap);
pmPainter.setRenderHint(QPainter::Antialiasing);
pmPainter.setOpacity(0.85);
pmPainter.translate(0.5, 0.5);
pmPainter.setPen(Qt::NoPen);
pmPainter.setBrush(QColor(0, 0, 0, 40));
pmPainter.drawRoundedRect(QRect(0, 0, 124, 48), 8, 8);
QLinearGradient gradient(QPoint(0, 0), QPoint(0, 44));
gradient.setColorAt(0.0, QColor(70, 70, 70));
gradient.setColorAt(1.0, QColor(10, 10, 10));
pmPainter.setBrush(gradient);
pmPainter.setPen(QColor(60, 60, 60));
pmPainter.drawRoundedRect(QRect(2, 1, 120, 45), 5, 5);
pmPainter.setBrush(Qt::NoBrush);
pmPainter.setPen(QColor(255, 255, 255, 140));
pmPainter.drawRoundedRect(QRect(3, 2, 118, 43), 5, 5);
pmPainter.end();
return pixmap;
}
void FormEditorGraphicsView::drawForeground(QPainter *painter, const QRectF &/*rect*/ )
{
if (!m_feedbackNode.isValid())
return;
if (m_feedbackOriginPoint.isNull())
return;
painter->save();
painter->resetTransform();
painter->translate(m_feedbackOriginPoint);
QColor defaultColor(Qt::white);
QColor changeColor("#9999ff");
QFont font;
font.setFamily("Helvetica");
font.setPixelSize(12);
painter->setFont(font);
if (m_bubblePixmap.isNull())
m_bubblePixmap = createBubblePixmap();
painter->drawPixmap(-13, -7, m_bubblePixmap);
if (m_beginXHasExpression) {
if(m_feedbackNode.hasBindingProperty("x"))
painter->setPen(defaultColor);
else
painter->setPen(Qt::red);
} else {
if (m_beginX != m_feedbackNode.instanceValue("x"))
painter->setPen(changeColor);
else
painter->setPen(defaultColor);
}
painter->drawText(QPoint(8.0, 13.0), QString("x:"));
painter->drawText(QPoint(22.0, 13.0), m_feedbackNode.instanceValue("x").toString());
if (m_beginYHasExpression) {
if(m_feedbackNode.hasBindingProperty("y"))
painter->setPen(defaultColor);
else
painter->setPen(Qt::red);
} else {
if (m_beginY != m_feedbackNode.instanceValue("y"))
painter->setPen(changeColor);
else
painter->setPen(defaultColor);
}
painter->drawText(QPoint(60.0, 13.0), QString("y:"));
painter->drawText(QPoint(72.0, 13.0), m_feedbackNode.instanceValue("y").toString());
if (m_beginWidthHasExpression) {
if(m_feedbackNode.hasBindingProperty("width"))
painter->setPen(defaultColor);
else
painter->setPen(Qt::red);
} else {
if (m_beginWidth != m_feedbackNode.instanceValue("width"))
painter->setPen(changeColor);
else
painter->setPen(defaultColor);
}
painter->drawText(QPoint(8.0, 29.0), QString("w:"));
painter->drawText(QPoint(22.0, 29.0), m_feedbackNode.instanceValue("width").toString());
if (m_beginHeightHasExpression) {
if(m_feedbackNode.hasBindingProperty("height"))
painter->setPen(defaultColor);
else
painter->setPen(Qt::red);
} else {
if (m_beginHeight != m_feedbackNode.instanceValue("height"))
painter->setPen(changeColor);
else
painter->setPen(defaultColor);
}
painter->drawText(QPoint(60.0, 29.0), QString("h:"));
painter->drawText(QPoint(72.0, 29.0), m_feedbackNode.instanceValue("height").toString());
if (m_parentNode != m_feedbackNode.instanceParent()) {
painter->setPen(changeColor);
painter->drawText(QPoint(2.0, 39.0), QString("Parent changed"));
}
painter->restore();
}
void FormEditorGraphicsView::setFeedbackNode(const QmlItemNode &node)
{
if (node == m_feedbackNode)
return;
m_feedbackNode = node;
if (m_feedbackNode.isValid()) {
m_beginX = m_feedbackNode.instanceValue("x");
m_beginY = m_feedbackNode.instanceValue("y");
m_beginWidth = m_feedbackNode.instanceValue("width");
m_beginHeight = m_feedbackNode.instanceValue("height");
m_parentNode = m_feedbackNode.instanceParent();
m_beginLeftMargin = m_feedbackNode.instanceValue("anchors.leftMargin");
m_beginRightMargin = m_feedbackNode.instanceValue("anchors.rightMargin");
m_beginTopMargin = m_feedbackNode.instanceValue("anchors.topMargin");
m_beginBottomMargin = m_feedbackNode.instanceValue("anchors.bottomMargin");
m_beginXHasExpression = m_feedbackNode.hasBindingProperty("x");
m_beginYHasExpression = m_feedbackNode.hasBindingProperty("y");
m_beginWidthHasExpression = m_feedbackNode.hasBindingProperty("width");
m_beginHeightHasExpression = m_feedbackNode.hasBindingProperty("height");
} else {
m_beginX = QVariant();
m_beginY = QVariant();
m_beginWidth = QVariant();
m_beginHeight = QVariant();
m_parentNode = QmlObjectNode();
m_beginLeftMargin = QVariant();
m_beginRightMargin = QVariant();
m_beginTopMargin = QVariant();
m_beginBottomMargin = QVariant();
m_beginXHasExpression = false;
m_beginYHasExpression = false;
m_beginWidthHasExpression = false;
m_beginHeightHasExpression = false;
}
}
void FormEditorGraphicsView::drawBackground(QPainter *painter, const QRectF &rectangle)
{
painter->save();
painter->setBrushOrigin(0, 0);
painter->fillRect(rectangle.intersected(rootItemRect()), backgroundBrush());
// paint rect around editable area
painter->setPen(Qt::black);
painter->drawRect( rootItemRect());
painter->restore();
}
} // namespace QmlDesigner
<commit_msg>NodeInstances: Improve repaint of the form editor<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (info@qt.nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** 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.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at info@qt.nokia.com.
**
**************************************************************************/
#include "formeditorgraphicsview.h"
#include <QWheelEvent>
#include <QApplication>
#include <QtDebug>
#include <qmlanchors.h>
namespace QmlDesigner {
FormEditorGraphicsView::FormEditorGraphicsView(QWidget *parent) :
QGraphicsView(parent)
{
setTransformationAnchor(QGraphicsView::AnchorUnderMouse);
setResizeAnchor(QGraphicsView::AnchorViewCenter);
setAlignment(Qt::AlignCenter);
setCacheMode(QGraphicsView::CacheBackground);
// setCacheMode(QGraphicsView::CacheBackground);
setViewportUpdateMode(QGraphicsView::MinimalViewportUpdate);
setOptimizationFlags(QGraphicsView::DontSavePainterState);
// setViewportUpdateMode(QGraphicsView::NoViewportUpdate);
setRenderHint(QPainter::Antialiasing, false);
setFrameShape(QFrame::NoFrame);
setAutoFillBackground(true);
setBackgroundRole(QPalette::Window);
const int checkerbordSize= 20;
QPixmap tilePixmap(checkerbordSize * 2, checkerbordSize * 2);
tilePixmap.fill(Qt::white);
QPainter tilePainter(&tilePixmap);
QColor color(220, 220, 220);
tilePainter.fillRect(0, 0, checkerbordSize, checkerbordSize, color);
tilePainter.fillRect(checkerbordSize, checkerbordSize, checkerbordSize, checkerbordSize, color);
tilePainter.end();
setBackgroundBrush(tilePixmap);
viewport()->setMouseTracking(true);
}
void FormEditorGraphicsView::wheelEvent(QWheelEvent *event)
{
if (event->modifiers().testFlag(Qt::ControlModifier)) {
event->ignore();
} else {
QGraphicsView::wheelEvent(event);
}
}
void FormEditorGraphicsView::mouseMoveEvent(QMouseEvent *event)
{
if (rect().contains(event->pos())) {
QGraphicsView::mouseMoveEvent(event);
} else {
QPoint position = event->pos();
QPoint topLeft = rect().topLeft();
QPoint bottomRight = rect().bottomRight();
position.rx() = qMax(topLeft.x(), qMin(position.x(), bottomRight.x()));
position.ry() = qMax(topLeft.y(), qMin(position.y(), bottomRight.y()));
QMouseEvent *mouseEvent = QMouseEvent::createExtendedMouseEvent(event->type(), position, mapToGlobal(position), event->button(), event->buttons(), event->modifiers());
QGraphicsView::mouseMoveEvent(mouseEvent);
delete mouseEvent;
}
// Keeps the feedback bubble within screen boundraries
int tx = qMin(width() - 114, qMax(16, event->pos().x() + 50));
int ty = qMin(height() - 45, qMax(10, event->pos().y() - 70));
m_feedbackOriginPoint = QPoint(tx, ty);
}
void FormEditorGraphicsView::keyPressEvent(QKeyEvent *event)
{
m_feedbackOriginPoint = QPoint();
QGraphicsView::keyPressEvent(event);
}
void FormEditorGraphicsView::setRootItemRect(const QRectF &rect)
{
m_rootItemRect = rect;
viewport()->update();
}
QRectF FormEditorGraphicsView::rootItemRect() const
{
return m_rootItemRect;
}
void FormEditorGraphicsView::mousePressEvent(QMouseEvent *mouseEvent)
{
QGraphicsView::mousePressEvent(mouseEvent);
}
void FormEditorGraphicsView::mouseReleaseEvent(QMouseEvent *event)
{
if (rect().contains(event->pos())) {
QGraphicsView::mouseReleaseEvent(event);
} else {
QPoint position = event->pos();
QPoint topLeft = rect().topLeft();
QPoint bottomRight = rect().bottomRight();
position.rx() = qMax(topLeft.x(), qMin(position.x(), bottomRight.x()));
position.ry() = qMax(topLeft.y(), qMin(position.y(), bottomRight.y()));
QMouseEvent *mouseEvent = QMouseEvent::createExtendedMouseEvent(event->type(), position, mapToGlobal(position), event->button(), event->buttons(), event->modifiers());
QGraphicsView::mouseReleaseEvent(mouseEvent);
delete mouseEvent;
}
m_feedbackOriginPoint = QPoint();
}
void FormEditorGraphicsView::leaveEvent(QEvent *event)
{
m_feedbackOriginPoint = QPoint();
QGraphicsView::leaveEvent(event);
}
static QPixmap createBubblePixmap()
{
QPixmap pixmap(124, 48);
pixmap.fill(Qt::transparent);
QPainter pmPainter(&pixmap);
pmPainter.setRenderHint(QPainter::Antialiasing);
pmPainter.setOpacity(0.85);
pmPainter.translate(0.5, 0.5);
pmPainter.setPen(Qt::NoPen);
pmPainter.setBrush(QColor(0, 0, 0, 40));
pmPainter.drawRoundedRect(QRect(0, 0, 124, 48), 8, 8);
QLinearGradient gradient(QPoint(0, 0), QPoint(0, 44));
gradient.setColorAt(0.0, QColor(70, 70, 70));
gradient.setColorAt(1.0, QColor(10, 10, 10));
pmPainter.setBrush(gradient);
pmPainter.setPen(QColor(60, 60, 60));
pmPainter.drawRoundedRect(QRect(2, 1, 120, 45), 5, 5);
pmPainter.setBrush(Qt::NoBrush);
pmPainter.setPen(QColor(255, 255, 255, 140));
pmPainter.drawRoundedRect(QRect(3, 2, 118, 43), 5, 5);
pmPainter.end();
return pixmap;
}
void FormEditorGraphicsView::drawForeground(QPainter *painter, const QRectF &/*rect*/ )
{
if (!m_feedbackNode.isValid())
return;
if (m_feedbackOriginPoint.isNull())
return;
painter->save();
painter->resetTransform();
painter->translate(m_feedbackOriginPoint);
QColor defaultColor(Qt::white);
QColor changeColor("#9999ff");
QFont font;
font.setFamily("Helvetica");
font.setPixelSize(12);
painter->setFont(font);
if (m_bubblePixmap.isNull())
m_bubblePixmap = createBubblePixmap();
painter->drawPixmap(-13, -7, m_bubblePixmap);
if (m_beginXHasExpression) {
if(m_feedbackNode.hasBindingProperty("x"))
painter->setPen(defaultColor);
else
painter->setPen(Qt::red);
} else {
if (m_beginX != m_feedbackNode.instanceValue("x"))
painter->setPen(changeColor);
else
painter->setPen(defaultColor);
}
painter->drawText(QPoint(8.0, 13.0), QString("x:"));
painter->drawText(QPoint(22.0, 13.0), m_feedbackNode.instanceValue("x").toString());
if (m_beginYHasExpression) {
if(m_feedbackNode.hasBindingProperty("y"))
painter->setPen(defaultColor);
else
painter->setPen(Qt::red);
} else {
if (m_beginY != m_feedbackNode.instanceValue("y"))
painter->setPen(changeColor);
else
painter->setPen(defaultColor);
}
painter->drawText(QPoint(60.0, 13.0), QString("y:"));
painter->drawText(QPoint(72.0, 13.0), m_feedbackNode.instanceValue("y").toString());
if (m_beginWidthHasExpression) {
if(m_feedbackNode.hasBindingProperty("width"))
painter->setPen(defaultColor);
else
painter->setPen(Qt::red);
} else {
if (m_beginWidth != m_feedbackNode.instanceValue("width"))
painter->setPen(changeColor);
else
painter->setPen(defaultColor);
}
painter->drawText(QPoint(8.0, 29.0), QString("w:"));
painter->drawText(QPoint(22.0, 29.0), m_feedbackNode.instanceValue("width").toString());
if (m_beginHeightHasExpression) {
if(m_feedbackNode.hasBindingProperty("height"))
painter->setPen(defaultColor);
else
painter->setPen(Qt::red);
} else {
if (m_beginHeight != m_feedbackNode.instanceValue("height"))
painter->setPen(changeColor);
else
painter->setPen(defaultColor);
}
painter->drawText(QPoint(60.0, 29.0), QString("h:"));
painter->drawText(QPoint(72.0, 29.0), m_feedbackNode.instanceValue("height").toString());
if (m_parentNode != m_feedbackNode.instanceParent()) {
painter->setPen(changeColor);
painter->drawText(QPoint(2.0, 39.0), QString("Parent changed"));
}
painter->restore();
}
void FormEditorGraphicsView::setFeedbackNode(const QmlItemNode &node)
{
if (node == m_feedbackNode)
return;
m_feedbackNode = node;
if (m_feedbackNode.isValid()) {
m_beginX = m_feedbackNode.instanceValue("x");
m_beginY = m_feedbackNode.instanceValue("y");
m_beginWidth = m_feedbackNode.instanceValue("width");
m_beginHeight = m_feedbackNode.instanceValue("height");
m_parentNode = m_feedbackNode.instanceParent();
m_beginLeftMargin = m_feedbackNode.instanceValue("anchors.leftMargin");
m_beginRightMargin = m_feedbackNode.instanceValue("anchors.rightMargin");
m_beginTopMargin = m_feedbackNode.instanceValue("anchors.topMargin");
m_beginBottomMargin = m_feedbackNode.instanceValue("anchors.bottomMargin");
m_beginXHasExpression = m_feedbackNode.hasBindingProperty("x");
m_beginYHasExpression = m_feedbackNode.hasBindingProperty("y");
m_beginWidthHasExpression = m_feedbackNode.hasBindingProperty("width");
m_beginHeightHasExpression = m_feedbackNode.hasBindingProperty("height");
} else {
m_beginX = QVariant();
m_beginY = QVariant();
m_beginWidth = QVariant();
m_beginHeight = QVariant();
m_parentNode = QmlObjectNode();
m_beginLeftMargin = QVariant();
m_beginRightMargin = QVariant();
m_beginTopMargin = QVariant();
m_beginBottomMargin = QVariant();
m_beginXHasExpression = false;
m_beginYHasExpression = false;
m_beginWidthHasExpression = false;
m_beginHeightHasExpression = false;
}
}
void FormEditorGraphicsView::drawBackground(QPainter *painter, const QRectF &rectangle)
{
painter->save();
painter->setBrushOrigin(0, 0);
painter->fillRect(rectangle.intersected(rootItemRect()), backgroundBrush());
// paint rect around editable area
painter->setPen(Qt::black);
painter->drawRect( rootItemRect());
painter->restore();
}
} // namespace QmlDesigner
<|endoftext|> |
<commit_before>#include "SampleCode.h"
#include "SkView.h"
#include "SkCanvas.h"
#include "SkGradientShader.h"
#include "SkGraphics.h"
#include "SkImageDecoder.h"
#include "SkPath.h"
#include "SkRegion.h"
#include "SkShader.h"
#include "SkUtils.h"
#include "SkXfermode.h"
#include "SkComposeShader.h"
#include "SkColorPriv.h"
#include "SkColorFilter.h"
#include "SkTime.h"
#include "SkTypeface.h"
#include "SkImageRef_GlobalPool.h"
#include "SkOSFile.h"
#include "SkStream.h"
#include "SkBlurDrawLooper.h"
#include "SkColorMatrixFilter.h"
static void drawmarshmallow(SkCanvas* canvas) {
SkBitmap bitmap;
SkPaint paint;
SkRect r;
SkMatrix m;
SkImageDecoder::DecodeFile("/Users/reed/Downloads/3elfs.jpg", &bitmap);
SkShader* s = SkShader::CreateBitmapShader(bitmap,
SkShader::kRepeat_TileMode,
SkShader::kRepeat_TileMode);
paint.setShader(s)->unref();
m.setTranslate(SkIntToScalar(250), SkIntToScalar(134));
s->setLocalMatrix(m);
r.set(SkIntToScalar(250),
SkIntToScalar(134),
SkIntToScalar(250 + 449),
SkIntToScalar(134 + 701));
paint.setFlags(2);
canvas->drawRect(r, paint);
}
static void DrawRoundRect(SkCanvas& canvas) {
bool ret = false;
SkPaint paint;
SkBitmap bitmap;
SkMatrix matrix;
matrix.reset();
bitmap.setConfig(SkBitmap::kARGB_8888_Config, 1370, 812);
bitmap.allocPixels();
#if 0
SkCanvas canvas;
canvas.setBitmapDevice(bitmap);
#endif
// set up clipper
SkRect skclip;
skclip.set(SkIntToFixed(284), SkIntToFixed(40), SkIntToFixed(1370), SkIntToFixed(708));
// ret = canvas.clipRect(skclip);
// SkASSERT(ret);
matrix.set(SkMatrix::kMTransX, SkFloatToFixed(-1153.28));
matrix.set(SkMatrix::kMTransY, SkFloatToFixed(1180.50));
matrix.set(SkMatrix::kMScaleX, SkFloatToFixed(0.177171));
matrix.set(SkMatrix::kMScaleY, SkFloatToFixed(0.177043));
matrix.set(SkMatrix::kMSkewX, SkFloatToFixed(0.126968));
matrix.set(SkMatrix::kMSkewY, SkFloatToFixed(-0.126876));
matrix.set(SkMatrix::kMPersp0, SkFloatToFixed(0.0));
matrix.set(SkMatrix::kMPersp1, SkFloatToFixed(0.0));
ret = canvas.concat(matrix);
paint.setAntiAlias(true);
paint.setColor(0xb2202020);
paint.setStyle(SkPaint::kStroke_Style);
paint.setStrokeWidth(SkFloatToFixed(68.13));
SkRect r;
r.set(SkFloatToFixed(-313.714417), SkFloatToFixed(-4.826389), SkFloatToFixed(18014.447266), SkFloatToFixed(1858.154541));
canvas.drawRoundRect(r, SkFloatToFixed(91.756363), SkFloatToFixed(91.756363), paint);
}
static bool SetImageRef(SkBitmap* bitmap, SkStream* stream,
SkBitmap::Config pref, const char name[] = NULL) {
#if 0
// test buffer streams
SkStream* str = new SkBufferStream(stream, 717);
stream->unref();
stream = str;
#endif
SkImageRef* ref = new SkImageRef_GlobalPool(stream, pref, 1);
ref->setURI(name);
if (!ref->getInfo(bitmap)) {
delete ref;
return false;
}
bitmap->setPixelRef(ref)->unref();
return true;
}
//#define SPECIFIC_IMAGE "/skimages/72.jpg"
#define SPECIFIC_IMAGE "/Users/reed/Downloads/3elfs.jpg"
#define IMAGE_DIR "/skimages/"
#define IMAGE_SUFFIX ".gif"
class ImageDirView : public SkView {
public:
SkBitmap* fBitmaps;
SkString* fStrings;
int fBitmapCount;
int fCurrIndex;
SkScalar fSaturation;
SkScalar fAngle;
ImageDirView() {
SkImageRef_GlobalPool::SetRAMBudget(320 * 1024);
#ifdef SPECIFIC_IMAGE
fBitmaps = new SkBitmap[3];
fStrings = new SkString[3];
fBitmapCount = 3;
const SkBitmap::Config configs[] = {
SkBitmap::kARGB_8888_Config,
SkBitmap::kRGB_565_Config,
SkBitmap::kARGB_4444_Config
};
for (int i = 0; i < fBitmapCount; i++) {
#if 1
SkStream* stream = new SkFILEStream(SPECIFIC_IMAGE);
SetImageRef(&fBitmaps[i], stream, configs[i], SPECIFIC_IMAGE);
stream->unref();
#else
SkImageDecoder::DecodeFile(SPECIFIC_IMAGE, &fBitmaps[i]);
#endif
}
#else
int i, N = 0;
SkOSFile::Iter iter(IMAGE_DIR, IMAGE_SUFFIX);
SkString name;
while (iter.next(&name)) {
N += 1;
}
fBitmaps = new SkBitmap[N];
fStrings = new SkString[N];
iter.reset(IMAGE_DIR, IMAGE_SUFFIX);
for (i = 0; i < N; i++) {
iter.next(&name);
SkString path(IMAGE_DIR);
path.append(name);
SkStream* stream = new SkFILEStream(path.c_str());
SetImageRef(&fBitmaps[i], stream, SkBitmap::kNo_Config,
name.c_str());
stream->unref();
fStrings[i] = name;
}
fBitmapCount = N;
#endif
fCurrIndex = 0;
fDX = fDY = 0;
fSaturation = SK_Scalar1;
fAngle = 0;
fScale = SK_Scalar1;
}
virtual ~ImageDirView() {
delete[] fBitmaps;
delete[] fStrings;
SkImageRef_GlobalPool::DumpPool();
}
protected:
// overrides from SkEventSink
virtual bool onQuery(SkEvent* evt) {
if (SampleCode::TitleQ(*evt)) {
SkString str("ImageDir: ");
#ifdef SPECIFIC_IMAGE
str.append(SPECIFIC_IMAGE);
#else
str.append(IMAGE_DIR);
#endif
SampleCode::TitleR(evt, str.c_str());
return true;
}
return this->INHERITED::onQuery(evt);
}
void drawBG(SkCanvas* canvas) {
// canvas->drawColor(0xFFDDDDDD);
canvas->drawColor(SK_ColorGRAY);
canvas->drawColor(SK_ColorWHITE);
}
SkScalar fScale;
virtual void onDraw(SkCanvas* canvas) {
this->drawBG(canvas);
if (true) {
canvas->scale(SkIntToScalar(2), SkIntToScalar(2));
drawmarshmallow(canvas);
return;
}
if (false) {
SkPaint p;
p.setStyle(SkPaint::kStroke_Style);
p.setStrokeWidth(SkIntToScalar(4));
canvas->drawCircle(SkIntToScalar(100), SkIntToScalar(100), SkIntToScalar(50), p);
p.setAntiAlias(true);
canvas->drawCircle(SkIntToScalar(300), SkIntToScalar(100), SkIntToScalar(50), p);
}
if (false) {
SkScalar cx = this->width()/2;
SkScalar cy = this->height()/2;
canvas->translate(cx, cy);
canvas->scale(fScale, fScale);
canvas->translate(-cx, -cy);
DrawRoundRect(*canvas);
return;
}
canvas->translate(SkIntToScalar(10), SkIntToScalar(10));
SkScalar x = SkIntToScalar(32), y = SkIntToScalar(32);
SkPaint paint;
#if 0
for (int i = 0; i < fBitmapCount; i++) {
SkPaint p;
#if 1
const SkScalar cm[] = {
SkIntToScalar(2), 0, 0, 0, SkIntToScalar(-255),
0, SkIntToScalar(2), 0, 0, SkIntToScalar(-255),
0, 0, SkIntToScalar(2), 0, SkIntToScalar(-255),
0, 0, 0, SkIntToScalar(1), 0
};
SkColorFilter* cf = new SkColorMatrixFilter(cm);
p.setColorFilter(cf)->unref();
#endif
canvas->drawBitmap(fBitmaps[i], x, y, &p);
x += SkIntToScalar(fBitmaps[i].width() + 10);
}
return;
#endif
canvas->drawBitmap(fBitmaps[fCurrIndex], x, y, &paint);
#ifndef SPECIFIC_IMAGE
if (true) {
fCurrIndex += 1;
if (fCurrIndex >= fBitmapCount) {
fCurrIndex = 0;
}
this->inval(NULL);
}
#endif
}
virtual SkView::Click* onFindClickHandler(SkScalar x, SkScalar y) {
if (true) {
fCurrIndex += 1;
if (fCurrIndex >= fBitmapCount)
fCurrIndex = 0;
this->inval(NULL);
}
return new Click(this);
}
virtual bool onClick(Click* click) {
SkScalar center = this->width()/2;
fSaturation = SkScalarDiv(click->fCurr.fX - center, center/2);
center = this->height()/2;
fAngle = SkScalarDiv(click->fCurr.fY - center, center) * 180;
fDX += click->fCurr.fX - click->fPrev.fX;
fDY += click->fCurr.fY - click->fPrev.fY;
fScale = SkScalarDiv(click->fCurr.fX, this->width());
this->inval(NULL);
return true;
return this->INHERITED::onClick(click);
}
private:
SkScalar fDX, fDY;
typedef SkView INHERITED;
};
//////////////////////////////////////////////////////////////////////////////
static SkView* MyFactory() { return new ImageDirView; }
static SkViewRegister reg(MyFactory);
<commit_msg>notice if the bitmap failed to load<commit_after>#include "SampleCode.h"
#include "SkView.h"
#include "SkCanvas.h"
#include "SkGradientShader.h"
#include "SkGraphics.h"
#include "SkImageDecoder.h"
#include "SkPath.h"
#include "SkRegion.h"
#include "SkShader.h"
#include "SkUtils.h"
#include "SkXfermode.h"
#include "SkComposeShader.h"
#include "SkColorPriv.h"
#include "SkColorFilter.h"
#include "SkTime.h"
#include "SkTypeface.h"
#include "SkImageRef_GlobalPool.h"
#include "SkOSFile.h"
#include "SkStream.h"
#include "SkBlurDrawLooper.h"
#include "SkColorMatrixFilter.h"
static void drawmarshmallow(SkCanvas* canvas) {
SkBitmap bitmap;
SkPaint paint;
SkRect r;
SkMatrix m;
SkImageDecoder::DecodeFile("/Users/reed/Downloads/3elfs.jpg", &bitmap);
if (!bitmap.pixelRef()) {
return;
}
SkShader* s = SkShader::CreateBitmapShader(bitmap,
SkShader::kRepeat_TileMode,
SkShader::kRepeat_TileMode);
paint.setShader(s)->unref();
m.setTranslate(SkIntToScalar(250), SkIntToScalar(134));
s->setLocalMatrix(m);
r.set(SkIntToScalar(250),
SkIntToScalar(134),
SkIntToScalar(250 + 449),
SkIntToScalar(134 + 701));
paint.setFlags(2);
canvas->drawRect(r, paint);
}
static void DrawRoundRect(SkCanvas& canvas) {
bool ret = false;
SkPaint paint;
SkBitmap bitmap;
SkMatrix matrix;
matrix.reset();
bitmap.setConfig(SkBitmap::kARGB_8888_Config, 1370, 812);
bitmap.allocPixels();
#if 0
SkCanvas canvas;
canvas.setBitmapDevice(bitmap);
#endif
// set up clipper
SkRect skclip;
skclip.set(SkIntToFixed(284), SkIntToFixed(40), SkIntToFixed(1370), SkIntToFixed(708));
// ret = canvas.clipRect(skclip);
// SkASSERT(ret);
matrix.set(SkMatrix::kMTransX, SkFloatToFixed(-1153.28));
matrix.set(SkMatrix::kMTransY, SkFloatToFixed(1180.50));
matrix.set(SkMatrix::kMScaleX, SkFloatToFixed(0.177171));
matrix.set(SkMatrix::kMScaleY, SkFloatToFixed(0.177043));
matrix.set(SkMatrix::kMSkewX, SkFloatToFixed(0.126968));
matrix.set(SkMatrix::kMSkewY, SkFloatToFixed(-0.126876));
matrix.set(SkMatrix::kMPersp0, SkFloatToFixed(0.0));
matrix.set(SkMatrix::kMPersp1, SkFloatToFixed(0.0));
ret = canvas.concat(matrix);
paint.setAntiAlias(true);
paint.setColor(0xb2202020);
paint.setStyle(SkPaint::kStroke_Style);
paint.setStrokeWidth(SkFloatToFixed(68.13));
SkRect r;
r.set(SkFloatToFixed(-313.714417), SkFloatToFixed(-4.826389), SkFloatToFixed(18014.447266), SkFloatToFixed(1858.154541));
canvas.drawRoundRect(r, SkFloatToFixed(91.756363), SkFloatToFixed(91.756363), paint);
}
static bool SetImageRef(SkBitmap* bitmap, SkStream* stream,
SkBitmap::Config pref, const char name[] = NULL) {
#if 0
// test buffer streams
SkStream* str = new SkBufferStream(stream, 717);
stream->unref();
stream = str;
#endif
SkImageRef* ref = new SkImageRef_GlobalPool(stream, pref, 1);
ref->setURI(name);
if (!ref->getInfo(bitmap)) {
delete ref;
return false;
}
bitmap->setPixelRef(ref)->unref();
return true;
}
//#define SPECIFIC_IMAGE "/skimages/72.jpg"
#define SPECIFIC_IMAGE "/Users/reed/Downloads/3elfs.jpg"
#define IMAGE_DIR "/skimages/"
#define IMAGE_SUFFIX ".gif"
class ImageDirView : public SkView {
public:
SkBitmap* fBitmaps;
SkString* fStrings;
int fBitmapCount;
int fCurrIndex;
SkScalar fSaturation;
SkScalar fAngle;
ImageDirView() {
SkImageRef_GlobalPool::SetRAMBudget(320 * 1024);
#ifdef SPECIFIC_IMAGE
fBitmaps = new SkBitmap[3];
fStrings = new SkString[3];
fBitmapCount = 3;
const SkBitmap::Config configs[] = {
SkBitmap::kARGB_8888_Config,
SkBitmap::kRGB_565_Config,
SkBitmap::kARGB_4444_Config
};
for (int i = 0; i < fBitmapCount; i++) {
#if 1
SkStream* stream = new SkFILEStream(SPECIFIC_IMAGE);
SetImageRef(&fBitmaps[i], stream, configs[i], SPECIFIC_IMAGE);
stream->unref();
#else
SkImageDecoder::DecodeFile(SPECIFIC_IMAGE, &fBitmaps[i]);
#endif
}
#else
int i, N = 0;
SkOSFile::Iter iter(IMAGE_DIR, IMAGE_SUFFIX);
SkString name;
while (iter.next(&name)) {
N += 1;
}
fBitmaps = new SkBitmap[N];
fStrings = new SkString[N];
iter.reset(IMAGE_DIR, IMAGE_SUFFIX);
for (i = 0; i < N; i++) {
iter.next(&name);
SkString path(IMAGE_DIR);
path.append(name);
SkStream* stream = new SkFILEStream(path.c_str());
SetImageRef(&fBitmaps[i], stream, SkBitmap::kNo_Config,
name.c_str());
stream->unref();
fStrings[i] = name;
}
fBitmapCount = N;
#endif
fCurrIndex = 0;
fDX = fDY = 0;
fSaturation = SK_Scalar1;
fAngle = 0;
fScale = SK_Scalar1;
}
virtual ~ImageDirView() {
delete[] fBitmaps;
delete[] fStrings;
SkImageRef_GlobalPool::DumpPool();
}
protected:
// overrides from SkEventSink
virtual bool onQuery(SkEvent* evt) {
if (SampleCode::TitleQ(*evt)) {
SkString str("ImageDir: ");
#ifdef SPECIFIC_IMAGE
str.append(SPECIFIC_IMAGE);
#else
str.append(IMAGE_DIR);
#endif
SampleCode::TitleR(evt, str.c_str());
return true;
}
return this->INHERITED::onQuery(evt);
}
void drawBG(SkCanvas* canvas) {
// canvas->drawColor(0xFFDDDDDD);
canvas->drawColor(SK_ColorGRAY);
canvas->drawColor(SK_ColorWHITE);
}
SkScalar fScale;
virtual void onDraw(SkCanvas* canvas) {
this->drawBG(canvas);
if (true) {
canvas->scale(SkIntToScalar(2), SkIntToScalar(2));
drawmarshmallow(canvas);
return;
}
if (false) {
SkPaint p;
p.setStyle(SkPaint::kStroke_Style);
p.setStrokeWidth(SkIntToScalar(4));
canvas->drawCircle(SkIntToScalar(100), SkIntToScalar(100), SkIntToScalar(50), p);
p.setAntiAlias(true);
canvas->drawCircle(SkIntToScalar(300), SkIntToScalar(100), SkIntToScalar(50), p);
}
if (false) {
SkScalar cx = this->width()/2;
SkScalar cy = this->height()/2;
canvas->translate(cx, cy);
canvas->scale(fScale, fScale);
canvas->translate(-cx, -cy);
DrawRoundRect(*canvas);
return;
}
canvas->translate(SkIntToScalar(10), SkIntToScalar(10));
SkScalar x = SkIntToScalar(32), y = SkIntToScalar(32);
SkPaint paint;
#if 0
for (int i = 0; i < fBitmapCount; i++) {
SkPaint p;
#if 1
const SkScalar cm[] = {
SkIntToScalar(2), 0, 0, 0, SkIntToScalar(-255),
0, SkIntToScalar(2), 0, 0, SkIntToScalar(-255),
0, 0, SkIntToScalar(2), 0, SkIntToScalar(-255),
0, 0, 0, SkIntToScalar(1), 0
};
SkColorFilter* cf = new SkColorMatrixFilter(cm);
p.setColorFilter(cf)->unref();
#endif
canvas->drawBitmap(fBitmaps[i], x, y, &p);
x += SkIntToScalar(fBitmaps[i].width() + 10);
}
return;
#endif
canvas->drawBitmap(fBitmaps[fCurrIndex], x, y, &paint);
#ifndef SPECIFIC_IMAGE
if (true) {
fCurrIndex += 1;
if (fCurrIndex >= fBitmapCount) {
fCurrIndex = 0;
}
this->inval(NULL);
}
#endif
}
virtual SkView::Click* onFindClickHandler(SkScalar x, SkScalar y) {
if (true) {
fCurrIndex += 1;
if (fCurrIndex >= fBitmapCount)
fCurrIndex = 0;
this->inval(NULL);
}
return new Click(this);
}
virtual bool onClick(Click* click) {
SkScalar center = this->width()/2;
fSaturation = SkScalarDiv(click->fCurr.fX - center, center/2);
center = this->height()/2;
fAngle = SkScalarDiv(click->fCurr.fY - center, center) * 180;
fDX += click->fCurr.fX - click->fPrev.fX;
fDY += click->fCurr.fY - click->fPrev.fY;
fScale = SkScalarDiv(click->fCurr.fX, this->width());
this->inval(NULL);
return true;
return this->INHERITED::onClick(click);
}
private:
SkScalar fDX, fDY;
typedef SkView INHERITED;
};
//////////////////////////////////////////////////////////////////////////////
static SkView* MyFactory() { return new ImageDirView; }
static SkViewRegister reg(MyFactory);
<|endoftext|> |
<commit_before>/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SampleCode.h"
#include "SkDumpCanvas.h"
#include "SkView.h"
#include "SkCanvas.h"
#include "SkGradientShader.h"
#include "SkGraphics.h"
#include "SkImageDecoder.h"
#include "SkOSFile.h"
#include "SkPath.h"
#include "SkPicture.h"
#include "SkPictureRecorder.h"
#include "SkRandom.h"
#include "SkRegion.h"
#include "SkShader.h"
#include "SkUtils.h"
#include "SkColorPriv.h"
#include "SkColorFilter.h"
#include "SkTime.h"
#include "SkTypeface.h"
#include "SkXfermode.h"
#include "SkStream.h"
#include "SkSurface.h"
#include "SkGlyphCache.h"
#include "SkDrawFilter.h"
class SkCounterDrawFilter : public SkDrawFilter {
public:
SkCounterDrawFilter(int count) : fCount(count) {}
bool filter(SkPaint*, Type t) override {
return --fCount >= 0;
}
int fCount;
};
class PictFileView : public SampleView {
public:
PictFileView(const char name[] = nullptr)
: fFilename(name)
, fBBox(kNo_BBoxType)
, fTileSize(SkSize::Make(0, 0)) {
for (int i = 0; i < kBBoxTypeCount; ++i) {
fPictures[i] = nullptr;
}
fCount = 0;
}
virtual ~PictFileView() {
for (int i = 0; i < kBBoxTypeCount; ++i) {
SkSafeUnref(fPictures[i]);
}
}
void onTileSizeChanged(const SkSize &tileSize) override {
if (tileSize != fTileSize) {
fTileSize = tileSize;
}
}
protected:
// overrides from SkEventSink
bool onQuery(SkEvent* evt) override {
if (SampleCode::TitleQ(*evt)) {
SkString name("P:");
const char* basename = strrchr(fFilename.c_str(), SkPATH_SEPARATOR);
name.append(basename ? basename+1: fFilename.c_str());
switch (fBBox) {
case kNo_BBoxType:
// No name appended
break;
case kRTree_BBoxType:
name.append(" <bbox: R>");
break;
default:
SkASSERT(false);
break;
}
SampleCode::TitleR(evt, name.c_str());
return true;
}
SkUnichar uni;
if (SampleCode::CharQ(*evt, &uni)) {
switch (uni) {
case 'n': fCount += 1; this->inval(nullptr); return true;
case 'p': fCount -= 1; this->inval(nullptr); return true;
case 's': fCount = 0; this->inval(nullptr); return true;
default: break;
}
}
return this->INHERITED::onQuery(evt);
}
bool onEvent(const SkEvent& evt) override {
if (evt.isType("PictFileView::toggleBBox")) {
fBBox = (BBoxType)((fBBox + 1) % kBBoxTypeCount);
return true;
}
return this->INHERITED::onEvent(evt);
}
void onDrawContent(SkCanvas* canvas) override {
SkASSERT(static_cast<int>(fBBox) < kBBoxTypeCount);
SkPicture** picture = fPictures + fBBox;
#ifdef SK_GLYPHCACHE_TRACK_HASH_STATS
SkGraphics::PurgeFontCache();
#endif
if (!*picture) {
*picture = LoadPicture(fFilename.c_str(), fBBox).release();
}
if (*picture) {
SkCounterDrawFilter filter(fCount);
if (fCount > 0) {
canvas->setDrawFilter(&filter);
}
canvas->drawPicture(*picture);
canvas->setDrawFilter(nullptr);
}
#ifdef SK_GLYPHCACHE_TRACK_HASH_STATS
SkGlyphCache::Dump();
SkDebugf("\n");
#endif
}
private:
enum BBoxType {
kNo_BBoxType,
kRTree_BBoxType,
kLast_BBoxType = kRTree_BBoxType,
};
static const int kBBoxTypeCount = kLast_BBoxType + 1;
SkString fFilename;
SkPicture* fPictures[kBBoxTypeCount];
BBoxType fBBox;
SkSize fTileSize;
int fCount;
sk_sp<SkPicture> LoadPicture(const char path[], BBoxType bbox) {
sk_sp<SkPicture> pic;
SkBitmap bm;
if (SkImageDecoder::DecodeFile(path, &bm)) {
bm.setImmutable();
SkPictureRecorder recorder;
SkCanvas* can = recorder.beginRecording(SkIntToScalar(bm.width()),
SkIntToScalar(bm.height()),
nullptr, 0);
can->drawBitmap(bm, 0, 0, nullptr);
pic = recorder.finishRecordingAsPicture();
} else {
SkFILEStream stream(path);
if (stream.isValid()) {
pic = SkPicture::MakeFromStream(&stream);
} else {
SkDebugf("coun't load picture at \"path\"\n", path);
}
if (false) { // re-record
SkPictureRecorder recorder;
pic->playback(recorder.beginRecording(pic->cullRect().width(),
pic->cullRect().height(),
nullptr, 0));
sk_sp<SkPicture> p2(recorder.finishRecordingAsPicture());
SkString path2(path);
path2.append(".new.skp");
SkFILEWStream writer(path2.c_str());
p2->serialize(&writer);
}
}
if (nullptr == pic) {
return nullptr;
}
SkAutoTDelete<SkBBHFactory> factory;
switch (bbox) {
case kNo_BBoxType:
// no bbox playback necessary
return std::move(pic);
case kRTree_BBoxType:
factory.reset(new SkRTreeFactory);
break;
default:
SkASSERT(false);
}
SkPictureRecorder recorder;
pic->playback(recorder.beginRecording(pic->cullRect().width(),
pic->cullRect().height(),
factory.get(), 0));
return recorder.finishRecordingAsPicture();
}
typedef SampleView INHERITED;
};
SampleView* CreateSamplePictFileView(const char filename[]);
SampleView* CreateSamplePictFileView(const char filename[]) {
return new PictFileView(filename);
}
//////////////////////////////////////////////////////////////////////////////
#if 0
static SkView* MyFactory() { return new PictFileView; }
static SkViewRegister reg(MyFactory);
#endif
<commit_msg>Fix pessimizing move in SamplePictFile<commit_after>/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SampleCode.h"
#include "SkDumpCanvas.h"
#include "SkView.h"
#include "SkCanvas.h"
#include "SkGradientShader.h"
#include "SkGraphics.h"
#include "SkImageDecoder.h"
#include "SkOSFile.h"
#include "SkPath.h"
#include "SkPicture.h"
#include "SkPictureRecorder.h"
#include "SkRandom.h"
#include "SkRegion.h"
#include "SkShader.h"
#include "SkUtils.h"
#include "SkColorPriv.h"
#include "SkColorFilter.h"
#include "SkTime.h"
#include "SkTypeface.h"
#include "SkXfermode.h"
#include "SkStream.h"
#include "SkSurface.h"
#include "SkGlyphCache.h"
#include "SkDrawFilter.h"
class SkCounterDrawFilter : public SkDrawFilter {
public:
SkCounterDrawFilter(int count) : fCount(count) {}
bool filter(SkPaint*, Type t) override {
return --fCount >= 0;
}
int fCount;
};
class PictFileView : public SampleView {
public:
PictFileView(const char name[] = nullptr)
: fFilename(name)
, fBBox(kNo_BBoxType)
, fTileSize(SkSize::Make(0, 0)) {
for (int i = 0; i < kBBoxTypeCount; ++i) {
fPictures[i] = nullptr;
}
fCount = 0;
}
virtual ~PictFileView() {
for (int i = 0; i < kBBoxTypeCount; ++i) {
SkSafeUnref(fPictures[i]);
}
}
void onTileSizeChanged(const SkSize &tileSize) override {
if (tileSize != fTileSize) {
fTileSize = tileSize;
}
}
protected:
// overrides from SkEventSink
bool onQuery(SkEvent* evt) override {
if (SampleCode::TitleQ(*evt)) {
SkString name("P:");
const char* basename = strrchr(fFilename.c_str(), SkPATH_SEPARATOR);
name.append(basename ? basename+1: fFilename.c_str());
switch (fBBox) {
case kNo_BBoxType:
// No name appended
break;
case kRTree_BBoxType:
name.append(" <bbox: R>");
break;
default:
SkASSERT(false);
break;
}
SampleCode::TitleR(evt, name.c_str());
return true;
}
SkUnichar uni;
if (SampleCode::CharQ(*evt, &uni)) {
switch (uni) {
case 'n': fCount += 1; this->inval(nullptr); return true;
case 'p': fCount -= 1; this->inval(nullptr); return true;
case 's': fCount = 0; this->inval(nullptr); return true;
default: break;
}
}
return this->INHERITED::onQuery(evt);
}
bool onEvent(const SkEvent& evt) override {
if (evt.isType("PictFileView::toggleBBox")) {
fBBox = (BBoxType)((fBBox + 1) % kBBoxTypeCount);
return true;
}
return this->INHERITED::onEvent(evt);
}
void onDrawContent(SkCanvas* canvas) override {
SkASSERT(static_cast<int>(fBBox) < kBBoxTypeCount);
SkPicture** picture = fPictures + fBBox;
#ifdef SK_GLYPHCACHE_TRACK_HASH_STATS
SkGraphics::PurgeFontCache();
#endif
if (!*picture) {
*picture = LoadPicture(fFilename.c_str(), fBBox).release();
}
if (*picture) {
SkCounterDrawFilter filter(fCount);
if (fCount > 0) {
canvas->setDrawFilter(&filter);
}
canvas->drawPicture(*picture);
canvas->setDrawFilter(nullptr);
}
#ifdef SK_GLYPHCACHE_TRACK_HASH_STATS
SkGlyphCache::Dump();
SkDebugf("\n");
#endif
}
private:
enum BBoxType {
kNo_BBoxType,
kRTree_BBoxType,
kLast_BBoxType = kRTree_BBoxType,
};
static const int kBBoxTypeCount = kLast_BBoxType + 1;
SkString fFilename;
SkPicture* fPictures[kBBoxTypeCount];
BBoxType fBBox;
SkSize fTileSize;
int fCount;
sk_sp<SkPicture> LoadPicture(const char path[], BBoxType bbox) {
sk_sp<SkPicture> pic;
SkBitmap bm;
if (SkImageDecoder::DecodeFile(path, &bm)) {
bm.setImmutable();
SkPictureRecorder recorder;
SkCanvas* can = recorder.beginRecording(SkIntToScalar(bm.width()),
SkIntToScalar(bm.height()),
nullptr, 0);
can->drawBitmap(bm, 0, 0, nullptr);
pic = recorder.finishRecordingAsPicture();
} else {
SkFILEStream stream(path);
if (stream.isValid()) {
pic = SkPicture::MakeFromStream(&stream);
} else {
SkDebugf("coun't load picture at \"path\"\n", path);
}
if (false) { // re-record
SkPictureRecorder recorder;
pic->playback(recorder.beginRecording(pic->cullRect().width(),
pic->cullRect().height(),
nullptr, 0));
sk_sp<SkPicture> p2(recorder.finishRecordingAsPicture());
SkString path2(path);
path2.append(".new.skp");
SkFILEWStream writer(path2.c_str());
p2->serialize(&writer);
}
}
if (nullptr == pic) {
return nullptr;
}
SkAutoTDelete<SkBBHFactory> factory;
switch (bbox) {
case kNo_BBoxType:
// no bbox playback necessary
return pic;
case kRTree_BBoxType:
factory.reset(new SkRTreeFactory);
break;
default:
SkASSERT(false);
}
SkPictureRecorder recorder;
pic->playback(recorder.beginRecording(pic->cullRect().width(),
pic->cullRect().height(),
factory.get(), 0));
return recorder.finishRecordingAsPicture();
}
typedef SampleView INHERITED;
};
SampleView* CreateSamplePictFileView(const char filename[]);
SampleView* CreateSamplePictFileView(const char filename[]) {
return new PictFileView(filename);
}
//////////////////////////////////////////////////////////////////////////////
#if 0
static SkView* MyFactory() { return new PictFileView; }
static SkViewRegister reg(MyFactory);
#endif
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Module: $RCSfile$
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include <itkMultiThreader.h>
#include <itkSemaphore.h>
#include <itkFastMutexLock.h>
/*
int main()
{
std::cout<<"[PASSED]"<<std::endl;
std::cout<<"[FAILED]"<<std::endl;
return EXIT_FAILURE;
return EXIT_SUCCESS;
}
*/
// to pass some parameter to thread
class UserData
{
public:
int* intPointer;
itk::FastMutexLock* mutex;
itk::Semaphore* semaphore;
itk::Semaphore* mayIRun;
};
// this will be executed in a thread
ITK_THREAD_RETURN_TYPE ThreadedFunction(void* param)
{
std::cout<<"Getting thread info data... ";
itk::MultiThreader::ThreadInfoStruct* threadInfo = static_cast<itk::MultiThreader::ThreadInfoStruct*>(param);
if (!threadInfo)
{
std::cout<<"[FAILED]"<<std::endl;
exit(EXIT_FAILURE);
}
std::cout<<"[PASSED]"<<std::endl;
std::cout<<"Getting user data from thread... ";
UserData* userData = static_cast<UserData*>(threadInfo->UserData);
if (!userData)
{
std::cout<<"[FAILED]"<<std::endl;
exit(EXIT_FAILURE);
}
std::cout<<"[PASSED]"<<std::endl;
// inc variable FOR main thread
std::cout<<"generate 10000 results";
for (int i = 1; i <= 10000; ++i)
{
userData->mutex->Lock();
*(userData->intPointer) += 1; // generate one "result"
userData->mutex->Unlock();
userData->semaphore->Up(); // signal "work done"
}
std::cout<<"[PASSED]"<<std::endl;
std::cout<<"waiting for main thread's signal... "<<std::endl;;
userData->mayIRun->Down(); // wait for signal
std::cout<<"got main thread's signal... "<<std::endl;
// inc variable TOGETHER WITH main thread
for (int i = 1; i <= 10000; ++i)
{
userData->mutex->Lock();
*(userData->intPointer) += 1;
userData->mutex->Unlock();
}
userData->semaphore->Up(); // signal "job done"
std::cout<<"waiting for main thread's signal... "<<std::endl;;
userData->mayIRun->Down(); // wait for signal
std::cout<<"got main thread's signal... "<<std::endl;
// inc variable TOGETHER WITH main thread (using NO mutex)
for (int i = 1; i <= 1000000; ++i)
{
*(userData->intPointer) += 1;
}
userData->semaphore->Up(); // signal "job done"
return ITK_THREAD_RETURN_VALUE;
}
int mitkITKThreadingTest(int argc, char* argv[])
{
itk::MultiThreader::Pointer threader = itk::MultiThreader::New();
int localInt(0); // this will be modified by both threads
itk::Semaphore::Pointer m_ResultAvailable = itk::Semaphore::New();
m_ResultAvailable->Initialize(0); // no pieces left (thread has to create one)
itk::Semaphore::Pointer m_RunThreadRun = itk::Semaphore::New();
m_RunThreadRun->Initialize(0); // no pieces left (thread has to create one)
itk::FastMutexLock::Pointer m_Mutex = itk::FastMutexLock::New();
UserData userData;
userData.intPointer = &localInt;
userData.mutex = m_Mutex.GetPointer();
userData.semaphore = m_ResultAvailable.GetPointer();
userData.mayIRun = m_RunThreadRun.GetPointer();
itk::ThreadFunctionType pointer = &ThreadedFunction;
int thread_id = threader->SpawnThread( pointer, &userData );
// let thread generate 10 results
for (int i = 1; i <= 10000; ++i)
m_ResultAvailable->Down();
std::cout<<"signaling by semaphore thread->main ";
if (localInt == 10000)
std::cout<<"[PASSED]"<<std::endl;
else
{
std::cout<<"[FAILED] localInt == "<< localInt <<std::endl;
return EXIT_FAILURE;
}
// increase int simultaneously with thread (coordinated by mutex)
localInt = 0;
m_RunThreadRun->Up(); // let thread work again
for (int i = 1; i <= 10000; ++i)
{
m_Mutex->Lock();
++localInt;
m_Mutex->Unlock();
}
std::cout<<"waiting for thread's signal"<<std::endl;;
m_ResultAvailable->Down(); // wait for thread
std::cout<<"got thread's signal"<<std::endl;;
std::cout<<"sharing a mutex protected variable among threads";
if (localInt == 20000)
std::cout<<"[PASSED]"<<std::endl;
else
{
std::cout<<"[FAILED] localInt == "<< localInt <<std::endl;
return EXIT_FAILURE;
}
// increase int simultaneously with thread (NOT coordinated by mutex)
localInt = 0;
m_RunThreadRun->Up(); // let thread work again
for (int i = 1; i <= 1000000; ++i)
{
++localInt;
}
std::cout<<"waiting for thread's signal"<<std::endl;;
m_ResultAvailable->Down(); // wait for thread
std::cout<<"got thread's signal"<<std::endl;;
// last test is supposed to NOT result in localInt == 20000
std::cout<<"sharing an unprotected variable among threads";
if (localInt == 2000000)
{
std::cout<<"[FAILED]. THIS IS PROBABLY NO SERIOUS FAILURE! Check test if it fails regularly"<<std::endl;
return EXIT_FAILURE;
}
else
std::cout<<"[PASSED] localInt == "<< localInt <<std::endl;
// terminating work thread
std::cout<<"waiting for idling thread ";
threader->TerminateThread( thread_id );
std::cout<<"[PASSED]"<<std::endl;
std::cout<<"Whole test [PASSED]"<<std::endl;
return EXIT_SUCCESS;
}
<commit_msg>removed questionable part of test<commit_after>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Module: $RCSfile$
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include <itkMultiThreader.h>
#include <itkSemaphore.h>
#include <itkFastMutexLock.h>
/*
int main()
{
std::cout<<"[PASSED]"<<std::endl;
std::cout<<"[FAILED]"<<std::endl;
return EXIT_FAILURE;
return EXIT_SUCCESS;
}
*/
// to pass some parameter to thread
class UserData
{
public:
int* intPointer;
itk::FastMutexLock* mutex;
itk::Semaphore* semaphore;
itk::Semaphore* mayIRun;
};
// this will be executed in a thread
ITK_THREAD_RETURN_TYPE ThreadedFunction(void* param)
{
std::cout<<"Getting thread info data... ";
itk::MultiThreader::ThreadInfoStruct* threadInfo = static_cast<itk::MultiThreader::ThreadInfoStruct*>(param);
if (!threadInfo)
{
std::cout<<"[FAILED]"<<std::endl;
exit(EXIT_FAILURE);
}
std::cout<<"[PASSED]"<<std::endl;
std::cout<<"Getting user data from thread... ";
UserData* userData = static_cast<UserData*>(threadInfo->UserData);
if (!userData)
{
std::cout<<"[FAILED]"<<std::endl;
exit(EXIT_FAILURE);
}
std::cout<<"[PASSED]"<<std::endl;
// inc variable FOR main thread
std::cout<<"generate 10000 results";
for (int i = 1; i <= 10000; ++i)
{
userData->mutex->Lock();
*(userData->intPointer) += 1; // generate one "result"
userData->mutex->Unlock();
userData->semaphore->Up(); // signal "work done"
}
std::cout<<"[PASSED]"<<std::endl;
std::cout<<"waiting for main thread's signal... "<<std::endl;;
userData->mayIRun->Down(); // wait for signal
std::cout<<"got main thread's signal... "<<std::endl;
// inc variable TOGETHER WITH main thread
for (int i = 1; i <= 10000; ++i)
{
userData->mutex->Lock();
*(userData->intPointer) += 1;
userData->mutex->Unlock();
}
userData->semaphore->Up(); // signal "job done"
return ITK_THREAD_RETURN_VALUE;
}
int mitkITKThreadingTest(int argc, char* argv[])
{
itk::MultiThreader::Pointer threader = itk::MultiThreader::New();
int localInt(0); // this will be modified by both threads
itk::Semaphore::Pointer m_ResultAvailable = itk::Semaphore::New();
m_ResultAvailable->Initialize(0); // no pieces left (thread has to create one)
itk::Semaphore::Pointer m_RunThreadRun = itk::Semaphore::New();
m_RunThreadRun->Initialize(0); // no pieces left (thread has to create one)
itk::FastMutexLock::Pointer m_Mutex = itk::FastMutexLock::New();
UserData userData;
userData.intPointer = &localInt;
userData.mutex = m_Mutex.GetPointer();
userData.semaphore = m_ResultAvailable.GetPointer();
userData.mayIRun = m_RunThreadRun.GetPointer();
itk::ThreadFunctionType pointer = &ThreadedFunction;
int thread_id = threader->SpawnThread( pointer, &userData );
// let thread generate 10 results
for (int i = 1; i <= 10000; ++i)
m_ResultAvailable->Down();
std::cout<<"signaling by semaphore thread->main ";
if (localInt == 10000)
std::cout<<"[PASSED]"<<std::endl;
else
{
std::cout<<"[FAILED] localInt == "<< localInt <<std::endl;
return EXIT_FAILURE;
}
// increase int simultaneously with thread (coordinated by mutex)
localInt = 0;
m_RunThreadRun->Up(); // let thread work again
for (int i = 1; i <= 10000; ++i)
{
m_Mutex->Lock();
++localInt;
m_Mutex->Unlock();
}
std::cout<<"waiting for thread's signal"<<std::endl;;
m_ResultAvailable->Down(); // wait for thread
std::cout<<"got thread's signal"<<std::endl;;
std::cout<<"sharing a mutex protected variable among threads";
if (localInt == 20000)
std::cout<<"[PASSED]"<<std::endl;
else
{
std::cout<<"[FAILED] localInt == "<< localInt <<std::endl;
return EXIT_FAILURE;
}
// terminating work thread
std::cout<<"waiting for idling thread ";
threader->TerminateThread( thread_id );
std::cout<<"[PASSED]"<<std::endl;
std::cout<<"Whole test [PASSED]"<<std::endl;
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-CHROMIUM file.
#include "common/main_delegate.h"
#include <memory>
#include "browser/browser_client.h"
#include "common/content_client.h"
#include "base/command_line.h"
#include "base/path_service.h"
#include "content/public/common/content_switches.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/ui_base_switches.h"
namespace brightray {
namespace {
// Returns true if this subprocess type needs the ResourceBundle initialized
// and resources loaded.
bool SubprocessNeedsResourceBundle(const std::string& process_type) {
return
#if defined(OS_POSIX) && !defined(OS_MACOSX)
// The zygote process opens the resources for the renderers.
process_type == switches::kZygoteProcess ||
#endif
#if defined(OS_MACOSX)
// Mac needs them too for scrollbar related images and for sandbox
// profiles.
#if !defined(DISABLE_NACL)
process_type == switches::kNaClLoaderProcess ||
#endif
process_type == switches::kPpapiPluginProcess ||
process_type == switches::kPpapiBrokerProcess ||
process_type == switches::kGpuProcess ||
#endif
process_type == switches::kRendererProcess ||
process_type == switches::kUtilityProcess;
}
} // namespace
void InitializeResourceBundle(const std::string& locale) {
// Load locales.
ui::ResourceBundle::InitSharedInstanceWithLocale(
locale, nullptr, ui::ResourceBundle::DO_NOT_LOAD_COMMON_RESOURCES);
// Load other resource files.
base::FilePath path;
#if defined(OS_MACOSX)
path = GetResourcesPakFilePath();
#else
base::FilePath pak_dir;
PathService::Get(base::DIR_MODULE, &pak_dir);
path = pak_dir.Append(FILE_PATH_LITERAL("content_shell.pak"));
#endif
ui::ResourceBundle& bundle = ui::ResourceBundle::GetSharedInstance();
bundle.AddDataPackFromPath(path, ui::GetSupportedScaleFactors()[0]);
#if defined(OS_WIN)
bundle.AddDataPackFromPath(
pak_dir.Append(FILE_PATH_LITERAL("ui_resources_200_percent.pak")),
ui::SCALE_FACTOR_200P);
bundle.AddDataPackFromPath(
pak_dir.Append(FILE_PATH_LITERAL("content_resources_200_percent.pak")),
ui::SCALE_FACTOR_200P);
#endif
}
MainDelegate::MainDelegate() {
}
MainDelegate::~MainDelegate() {
}
std::unique_ptr<ContentClient> MainDelegate::CreateContentClient() {
return std::unique_ptr<ContentClient>(new ContentClient);
}
bool MainDelegate::BasicStartupComplete(int* exit_code) {
content_client_ = CreateContentClient();
SetContentClient(content_client_.get());
#if defined(OS_MACOSX)
OverrideChildProcessPath();
OverrideFrameworkBundlePath();
#endif
return false;
}
void MainDelegate::PreSandboxStartup() {
auto cmd = *base::CommandLine::ForCurrentProcess();
std::string process_type = cmd.GetSwitchValueASCII(switches::kProcessType);
// Initialize ResourceBundle which handles files loaded from external
// sources. The language should have been passed in to us from the
// browser process as a command line flag.
if (SubprocessNeedsResourceBundle(process_type)) {
std::string locale = cmd.GetSwitchValueASCII(switches::kLang);
InitializeResourceBundle(locale);
}
}
content::ContentBrowserClient* MainDelegate::CreateContentBrowserClient() {
browser_client_ = CreateBrowserClient();
return browser_client_.get();
}
std::unique_ptr<BrowserClient> MainDelegate::CreateBrowserClient() {
return std::unique_ptr<BrowserClient>(new BrowserClient);
}
} // namespace brightray
<commit_msg>Load a few more pak files<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-CHROMIUM file.
#include "common/main_delegate.h"
#include <memory>
#include "browser/browser_client.h"
#include "common/content_client.h"
#include "base/command_line.h"
#include "base/path_service.h"
#include "content/public/common/content_switches.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/ui_base_switches.h"
namespace brightray {
namespace {
// Returns true if this subprocess type needs the ResourceBundle initialized
// and resources loaded.
bool SubprocessNeedsResourceBundle(const std::string& process_type) {
return
#if defined(OS_POSIX) && !defined(OS_MACOSX)
// The zygote process opens the resources for the renderers.
process_type == switches::kZygoteProcess ||
#endif
#if defined(OS_MACOSX)
// Mac needs them too for scrollbar related images and for sandbox
// profiles.
#if !defined(DISABLE_NACL)
process_type == switches::kNaClLoaderProcess ||
#endif
process_type == switches::kPpapiPluginProcess ||
process_type == switches::kPpapiBrokerProcess ||
process_type == switches::kGpuProcess ||
#endif
process_type == switches::kRendererProcess ||
process_type == switches::kUtilityProcess;
}
} // namespace
void InitializeResourceBundle(const std::string& locale) {
// Load locales.
ui::ResourceBundle::InitSharedInstanceWithLocale(
locale, nullptr, ui::ResourceBundle::DO_NOT_LOAD_COMMON_RESOURCES);
// Load other resource files.
base::FilePath path;
#if defined(OS_MACOSX)
path = GetResourcesPakFilePath();
#else
base::FilePath pak_dir;
PathService::Get(base::DIR_MODULE, &pak_dir);
path = pak_dir.Append(FILE_PATH_LITERAL("content_shell.pak"));
#endif
ui::ResourceBundle& bundle = ui::ResourceBundle::GetSharedInstance();
bundle.AddDataPackFromPath(path, ui::GetSupportedScaleFactors()[0]);
#if defined(OS_WIN)
bundle.AddDataPackFromPath(
pak_dir.Append(FILE_PATH_LITERAL("blink_image_resources_200_percent.pak")),
ui::SCALE_FACTOR_200P);
bundle.AddDataPackFromPath(
pak_dir.Append(FILE_PATH_LITERAL("content_resources_200_percent.pak")),
ui::SCALE_FACTOR_200P);
bundle.AddDataPackFromPath(
pak_dir.Append(FILE_PATH_LITERAL("ui_resources_200_percent.pak")),
ui::SCALE_FACTOR_200P);
bundle.AddDataPackFromPath(
pak_dir.Append(FILE_PATH_LITERAL("views_resources_200_percent.pak")),
ui::SCALE_FACTOR_200P);
#endif
}
MainDelegate::MainDelegate() {
}
MainDelegate::~MainDelegate() {
}
std::unique_ptr<ContentClient> MainDelegate::CreateContentClient() {
return std::unique_ptr<ContentClient>(new ContentClient);
}
bool MainDelegate::BasicStartupComplete(int* exit_code) {
content_client_ = CreateContentClient();
SetContentClient(content_client_.get());
#if defined(OS_MACOSX)
OverrideChildProcessPath();
OverrideFrameworkBundlePath();
#endif
return false;
}
void MainDelegate::PreSandboxStartup() {
auto cmd = *base::CommandLine::ForCurrentProcess();
std::string process_type = cmd.GetSwitchValueASCII(switches::kProcessType);
// Initialize ResourceBundle which handles files loaded from external
// sources. The language should have been passed in to us from the
// browser process as a command line flag.
if (SubprocessNeedsResourceBundle(process_type)) {
std::string locale = cmd.GetSwitchValueASCII(switches::kLang);
InitializeResourceBundle(locale);
}
}
content::ContentBrowserClient* MainDelegate::CreateContentBrowserClient() {
browser_client_ = CreateBrowserClient();
return browser_client_.get();
}
std::unique_ptr<BrowserClient> MainDelegate::CreateBrowserClient() {
return std::unique_ptr<BrowserClient>(new BrowserClient);
}
} // namespace brightray
<|endoftext|> |
<commit_before>/**
* \file py_calc_model.cpp
* \brief Python wrappers for calc_model, calc_model_data
* \author Sergey Miryanov
* \date 02.12.2009
* \copyright This source code is released under the terms of
* the BSD License. See LICENSE for more details.
* */
#include "stdafx.h"
#ifdef BSPY_EXPORTING_PLUGIN
#include "boost_array_adapter.h"
#include "calc_model.h"
#include "py_calc_model.h"
#include BS_FORCE_PLUGIN_IMPORT ()
#include "py_scal_wrapper.h"
#include "py_data_class.h"
#include BS_STOP_PLUGIN_IMPORT ()
#include "export_python_wrapper.h"
using namespace boost::python;
namespace blue_sky
{
namespace python
{
template <typename T> int get_n_phases (T *t) { return t->n_phases; }
template <typename T> bool get_is_water (T *t) { return t->is_water (); }
template <typename T> bool get_is_gas (T *t) { return t->is_gas (); }
template <typename T> bool get_is_oil (T *t) { return t->is_oil (); }
template <typename T>
smart_ptr <named_pbase, true>
get_params (T *t)
{
return t->ts_params;
}
template <typename T>
smart_ptr <typename T::scal_3p_t, true>
get_scal_3p (T *t)
{
return t->scal_prop;
}
PY_EXPORTER (calc_model_exporter, default_exporter)
.add_property ("n_phases", get_n_phases <T>)
.add_property ("is_water", get_is_water <T>)
.add_property ("is_gas", get_is_gas <T>)
.add_property ("is_oil", get_is_oil <T>)
.add_property ("params", get_params <T>)
.add_property ("data", GET_BY_VALUE (&T::data))
.add_property ("saturation", GET_BY_VALUE (&T::saturation_3p))
.add_property ("pressure", GET_BY_VALUE (&T::pressure))
.add_property ("pvt_num", &T::n_pvt_regions)
.add_property ("sat_num", &T::n_sat_regions)
.add_property ("fip_num", &T::n_fip_regions)
.add_property ("scal", get_scal_3p <T>)
.add_property ("pvt_regions", GET_BY_VALUE (&T::pvt_regions))
.add_property ("sat_regions", GET_BY_VALUE (&T::sat_regions))
.add_property ("fip_regions", GET_BY_VALUE (&T::fip_regions))
.add_property ("rock_regions",GET_BY_VALUE (&T::rock_regions))
.add_property ("pvt_water", GET_BY_VALUE (&T::pvt_water_array))
.add_property ("pvt_gas", GET_BY_VALUE (&T::pvt_gas_array))
.add_property ("pvt_oil", GET_BY_VALUE (&T::pvt_oil_array))
PY_EXPORTER_END;
PY_EXPORTER (calc_model_data_exporter, empty_exporter)
#if 0
.add_property ("cap_pressure", detail::boost_array_adapter (&T::cap_pressure))
.add_property ("s_deriv_cap_pressure", detail::boost_array_adapter (&T::s_deriv_cap_pressure))
.add_property ("relative_perm", detail::boost_array_adapter (&T::relative_perm))
.add_property ("s_deriv_relative_perm", detail::boost_array_adapter (&T::s_deriv_relative_perm))
.add_property ("p_deriv_gas_oil_ratio", &T::p_deriv_gas_oil_ratio)
.add_property ("invers_fvf", detail::boost_array_adapter (&T::invers_fvf))
.add_property ("p_deriv_invers_fvf", detail::boost_array_adapter (&T::p_deriv_invers_fvf))
.add_property ("gor_deriv_invers_fvf", &T::gor_deriv_invers_fvf)
.add_property ("invers_visc", detail::boost_array_adapter (&T::invers_viscosity))
.add_property ("p_deriv_invers_visc", detail::boost_array_adapter (&T::p_deriv_invers_viscosity))
.add_property ("gor_deriv_invers_visc", &T::gor_deriv_invers_viscosity)
.add_property ("invers_visc_fvf", detail::boost_array_adapter (&T::invers_visc_fvf))
.add_property ("p_deriv_invers_visc_fvf", detail::boost_array_adapter (&T::p_deriv_invers_visc_fvf))
.add_property ("gor_deriv_invers_visc_fvf", &T::gor_deriv_invers_visc_fvf)
.add_property ("density", detail::boost_array_adapter (&T::density))
.add_property ("p_deriv_density", detail::boost_array_adapter (&T::p_deriv_density))
.add_property ("gor_deriv_density", &T::gor_deriv_density)
.add_property ("porosity", &T::porosity)
.add_property ("p_deriv_porosity", &T::p_deriv_porosity)
.add_property ("truns_mult", &T::truns_mult)
.add_property ("p_deriv_truns_mult", &T::p_deriv_truns_mult)
.add_property ("mobility", detail::boost_array_adapter (&T::mobility))
.add_property ("p_deriv_mobility", detail::boost_array_adapter (&T::p_deriv_mobility))
.add_property ("s_deriv_mobility", detail::boost_array_adapter (&T::s_deriv_mobility))
.add_property ("prev_fluid_volume", detail::boost_array_adapter (&T::prev_fluid_volume))
#endif //0
PY_EXPORTER_END;
template <typename T>
void
export_calc_model_data_vector (const char *name)
{
class_ <T> (name)
.def (vector_indexing_suite <T> ())
;
}
template <typename T>
typename T::value_type
get_pvt_item (T *t, size_t index)
{
return t->operator[] (index);
}
template <typename T>
struct pvt_array_iterator
{
pvt_array_iterator (T *t)
: array_ (t)
, iterator_ (t->begin ())
, iterator_end_ (t->end ())
{
}
typename T::value_type
next ()
{
#ifdef _DEBUG
if (iterator_end_ != array_->end ())
{
bs_throw_exception ("PVT array iterator not more valid");
}
#endif
if (iterator_ == iterator_end_)
{
PyErr_SetString (PyExc_StopIteration, "No more data");
boost::python::throw_error_already_set ();
}
return *(iterator_++);
}
T *array_;
typename T::iterator iterator_;
typename T::iterator iterator_end_;
};
template <typename T>
pvt_array_iterator <T>
get_pvt_iterator (T *t)
{
return pvt_array_iterator <T> (t);
}
template <typename T>
void
export_pvt_iterator (const char *name)
{
using namespace boost::python;
class_ <pvt_array_iterator <T> > (name, init <T *> ())
.def ("next", &pvt_array_iterator <T>::next)
.def ("__iter__", pass_through)
;
}
template <typename T>
void
export_pvt_array (const char *name)
{
typedef std::vector <smart_ptr <T> > T_v;
class_ <T_v> (name)
.def ("__getitem__", get_pvt_item <T_v>)
.def ("__len__", &T_v::size)
.def ("__iter__", get_pvt_iterator <T_v>)
;
export_pvt_iterator <T_v> ("pvt_array_iter");
}
void py_export_calc_model()
{
base_exporter_nobs <calc_model_data, calc_model_data_exporter, class_type::concrete_class>::export_class ("calc_model_data");
export_calc_model_data_vector <shared_vector <calc_model_data> > ("calc_model_data_vector");
export_pvt_array <pvt_dead_oil> ("pvt_dead_oil_array");
export_pvt_array <pvt_water> ("pvt_water_array");
export_pvt_array <pvt_gas> ("pvt_gas");
base_exporter <calc_model, calc_model_exporter>::export_class ("calc_model");
}
} //ns python
} //ns bs
#endif
<commit_msg>Fix export of py_calc_model<commit_after>/**
* \file py_calc_model.cpp
* \brief Python wrappers for calc_model, calc_model_data
* \author Sergey Miryanov
* \date 02.12.2009
* \copyright This source code is released under the terms of
* the BSD License. See LICENSE for more details.
* */
#include "stdafx.h"
#ifdef BSPY_EXPORTING_PLUGIN
#include "boost_array_adapter.h"
#include "calc_model.h"
#include "py_calc_model.h"
#include BS_FORCE_PLUGIN_IMPORT ()
#include "py_scal_wrapper.h"
#include "py_data_class.h"
#include BS_STOP_PLUGIN_IMPORT ()
#include "export_python_wrapper.h"
using namespace boost::python;
namespace blue_sky
{
namespace python
{
template <typename T> int get_n_phases (T *t) { return t->n_phases; }
template <typename T> bool get_is_water (T *t) { return t->is_water (); }
template <typename T> bool get_is_gas (T *t) { return t->is_gas (); }
template <typename T> bool get_is_oil (T *t) { return t->is_oil (); }
template <typename T>
smart_ptr <named_pbase, true>
get_params (T *t)
{
return t->ts_params;
}
template <typename T>
smart_ptr <typename T::scal_3p_t, true>
get_scal_3p (T *t)
{
return t->scal_prop;
}
PY_EXPORTER (calc_model_exporter, default_exporter)
.add_property ("n_phases", GET_BY_VALUE (&T::n_phases))
.add_property ("is_water", &T::is_water)
.add_property ("is_gas", &T::is_gas)
.add_property ("is_oil", &T::is_oil)
.add_property ("params", GET_BY_VALUE (&T::ts_params))
.add_property ("data", GET_BY_VALUE (&T::data))
.add_property ("saturation", GET_BY_VALUE (&T::saturation_3p))
.add_property ("pressure", GET_BY_VALUE (&T::pressure))
.add_property ("pvt_num", &T::n_pvt_regions)
.add_property ("sat_num", &T::n_sat_regions)
.add_property ("fip_num", &T::n_fip_regions)
.add_property ("scal", GET_BY_VALUE (&T::scal_prop))
.add_property ("pvt_regions", GET_BY_VALUE (&T::pvt_regions))
.add_property ("sat_regions", GET_BY_VALUE (&T::sat_regions))
.add_property ("fip_regions", GET_BY_VALUE (&T::fip_regions))
.add_property ("rock_regions",GET_BY_VALUE (&T::rock_regions))
.add_property ("pvt_water", GET_BY_VALUE (&T::pvt_water_array))
.add_property ("pvt_gas", GET_BY_VALUE (&T::pvt_gas_array))
.add_property ("pvt_oil", GET_BY_VALUE (&T::pvt_oil_array))
PY_EXPORTER_END;
PY_EXPORTER (calc_model_data_exporter, empty_exporter)
#if 0
.add_property ("cap_pressure", detail::boost_array_adapter (&T::cap_pressure))
.add_property ("s_deriv_cap_pressure", detail::boost_array_adapter (&T::s_deriv_cap_pressure))
.add_property ("relative_perm", detail::boost_array_adapter (&T::relative_perm))
.add_property ("s_deriv_relative_perm", detail::boost_array_adapter (&T::s_deriv_relative_perm))
.add_property ("p_deriv_gas_oil_ratio", &T::p_deriv_gas_oil_ratio)
.add_property ("invers_fvf", detail::boost_array_adapter (&T::invers_fvf))
.add_property ("p_deriv_invers_fvf", detail::boost_array_adapter (&T::p_deriv_invers_fvf))
.add_property ("gor_deriv_invers_fvf", &T::gor_deriv_invers_fvf)
.add_property ("invers_visc", detail::boost_array_adapter (&T::invers_viscosity))
.add_property ("p_deriv_invers_visc", detail::boost_array_adapter (&T::p_deriv_invers_viscosity))
.add_property ("gor_deriv_invers_visc", &T::gor_deriv_invers_viscosity)
.add_property ("invers_visc_fvf", detail::boost_array_adapter (&T::invers_visc_fvf))
.add_property ("p_deriv_invers_visc_fvf", detail::boost_array_adapter (&T::p_deriv_invers_visc_fvf))
.add_property ("gor_deriv_invers_visc_fvf", &T::gor_deriv_invers_visc_fvf)
.add_property ("density", detail::boost_array_adapter (&T::density))
.add_property ("p_deriv_density", detail::boost_array_adapter (&T::p_deriv_density))
.add_property ("gor_deriv_density", &T::gor_deriv_density)
.add_property ("porosity", &T::porosity)
.add_property ("p_deriv_porosity", &T::p_deriv_porosity)
.add_property ("truns_mult", &T::truns_mult)
.add_property ("p_deriv_truns_mult", &T::p_deriv_truns_mult)
.add_property ("mobility", detail::boost_array_adapter (&T::mobility))
.add_property ("p_deriv_mobility", detail::boost_array_adapter (&T::p_deriv_mobility))
.add_property ("s_deriv_mobility", detail::boost_array_adapter (&T::s_deriv_mobility))
.add_property ("prev_fluid_volume", detail::boost_array_adapter (&T::prev_fluid_volume))
#endif //0
PY_EXPORTER_END;
template <typename T>
void
export_calc_model_data_vector (const char *name)
{
class_ <T> (name)
.def (vector_indexing_suite <T> ())
;
}
template <typename T>
typename T::value_type
get_pvt_item (T *t, size_t index)
{
return t->operator[] (index);
}
template <typename T>
struct pvt_array_iterator
{
pvt_array_iterator (T *t)
: array_ (t)
, iterator_ (t->begin ())
, iterator_end_ (t->end ())
{
}
typename T::value_type
next ()
{
#ifdef _DEBUG
if (iterator_end_ != array_->end ())
{
bs_throw_exception ("PVT array iterator not more valid");
}
#endif
if (iterator_ == iterator_end_)
{
PyErr_SetString (PyExc_StopIteration, "No more data");
boost::python::throw_error_already_set ();
}
return *(iterator_++);
}
T *array_;
typename T::iterator iterator_;
typename T::iterator iterator_end_;
};
template <typename T>
pvt_array_iterator <T>
get_pvt_iterator (T *t)
{
return pvt_array_iterator <T> (t);
}
template <typename T>
void
export_pvt_iterator (const char *name)
{
using namespace boost::python;
class_ <pvt_array_iterator <T> > (name, init <T *> ())
.def ("next", &pvt_array_iterator <T>::next)
.def ("__iter__", pass_through)
;
}
template <typename T>
void
export_pvt_array (const char *name)
{
typedef std::vector <smart_ptr <T> > T_v;
class_ <T_v> (name)
.def ("__getitem__", get_pvt_item <T_v>)
.def ("__len__", &T_v::size)
.def ("__iter__", get_pvt_iterator <T_v>)
;
export_pvt_iterator <T_v> ("pvt_array_iter");
}
void py_export_calc_model()
{
base_exporter_nobs <calc_model_data, calc_model_data_exporter, class_type::concrete_class>::export_class ("calc_model_data");
export_calc_model_data_vector <shared_vector <calc_model_data> > ("calc_model_data_vector");
export_pvt_array <pvt_dead_oil> ("pvt_dead_oil_array");
export_pvt_array <pvt_water> ("pvt_water_array");
export_pvt_array <pvt_gas> ("pvt_gas");
base_exporter <calc_model, calc_model_exporter>::export_class ("calc_model");
}
} //ns python
} //ns bs
#endif
<|endoftext|> |
<commit_before>// Logger.cpp
// This file is part of the EScript programming language.
// See copyright notice in EScript.h
// ------------------------------------------------------
#include "Logger.h"
#include <stdexcept>
#include <iostream>
namespace EScript{
// ------------------------------------------------
// LoggerGroup
void LoggerGroup::addLogger(const std::string & name,Logger * logger){
if(logger==NULL)
throw std::invalid_argument("addLogger(NULL)");
loggerRegistry[name] = logger;
}
bool LoggerGroup::removeLogger(const std::string & name){
return loggerRegistry.erase(name)>0;
}
void LoggerGroup::clearLoggers(){
loggerRegistry.clear();
}
Logger * LoggerGroup::getLogger(const std::string & name){
const loggerRegistry_t::iterator lbIt = loggerRegistry.lower_bound(name);
if(lbIt!=loggerRegistry.end() && !(loggerRegistry.key_comp()(name, lbIt->first)) ){
return lbIt->second.get();
}
return NULL;
}
//! ---|> Logger
void LoggerGroup::doLog(level_t l,const std::string & msg){
for(loggerRegistry_t::iterator it=loggerRegistry.begin();it!=loggerRegistry.end();++it){
it->second->log(l,msg);
}
}
// ------------------------------------------------
// StdLogger
//! ---|> Logger
void StdLogger::doLog(level_t l,const std::string & msg){
out << std::endl;
switch(l){
case LOG_DEBUG:{
out << "Debug: ";
break;
}
case LOG_INFO:{
out << "Debug: ";
break;
}
case LOG_WARNING:{
out << "Warning: ";
break;
}
case LOG_PEDANTIC_WARNING:{
out << "Pedantic warning: ";
break;
}
case LOG_ERROR:{
out << "Error: ";
break;
}
case LOG_FATAL:{
out << "Fatal error: ";
break;
}
case LOG_ALL:
case LOG_NONE:
default:{
out << "Logging ("<<l<<"):";
}
}
out << msg << std::endl;
}
}
<commit_msg>Warning removed.<commit_after>// Logger.cpp
// This file is part of the EScript programming language.
// See copyright notice in EScript.h
// ------------------------------------------------------
#include "Logger.h"
#include <stdexcept>
#include <iostream>
namespace EScript{
// ------------------------------------------------
// LoggerGroup
void LoggerGroup::addLogger(const std::string & name,Logger * logger){
if(logger==NULL)
throw std::invalid_argument("addLogger(NULL)");
loggerRegistry[name] = logger;
}
bool LoggerGroup::removeLogger(const std::string & name){
return loggerRegistry.erase(name)>0;
}
void LoggerGroup::clearLoggers(){
loggerRegistry.clear();
}
Logger * LoggerGroup::getLogger(const std::string & name){
const loggerRegistry_t::iterator lbIt = loggerRegistry.lower_bound(name);
if(lbIt!=loggerRegistry.end() && !(loggerRegistry.key_comp()(name, lbIt->first)) ){
return lbIt->second.get();
}
return NULL;
}
//! ---|> Logger
void LoggerGroup::doLog(level_t l,const std::string & msg){
for(loggerRegistry_t::iterator it=loggerRegistry.begin();it!=loggerRegistry.end();++it){
it->second->log(l,msg);
}
}
// ------------------------------------------------
// StdLogger
//! ---|> Logger
void StdLogger::doLog(level_t l,const std::string & msg){
out << std::endl;
switch(l){
case LOG_DEBUG:{
out << "Debug: ";
break;
}
case LOG_INFO:{
out << "Debug: ";
break;
}
case LOG_WARNING:{
out << "Warning: ";
break;
}
case LOG_PEDANTIC_WARNING:{
out << "Pedantic warning: ";
break;
}
case LOG_ERROR:{
out << "Error: ";
break;
}
case LOG_FATAL:{
out << "Fatal error: ";
break;
}
case LOG_ALL:
case LOG_NONE:
default:{
out << "Logging ("<<static_cast<int>(l)<<"):";
}
}
out << msg << std::endl;
}
}
<|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$ */
// Container class for AliGenerator through recursion.
// Container is itself an AliGenerator.
// What is stored are not the pointers to the generators directly but to objects of type
// AliGenCocktail entry.
// The class provides also iterator functionality.
// Author: andreas.morsch@cern.ch
//
#include <TList.h>
#include <TObjArray.h>
#include <TFormula.h>
#include "AliGenCocktail.h"
#include "AliGenCocktailEntry.h"
#include "AliCollisionGeometry.h"
#include "AliRun.h"
#include "AliLog.h"
#include "AliMC.h"
#include "AliGenCocktailEventHeader.h"
ClassImp(AliGenCocktail)
AliGenCocktail::AliGenCocktail()
:AliGenerator(),
fNGenerators(0),
fTotalRate(0.),
fSRandom(kFALSE),
fUseSingleInjectionPerEvent(kFALSE),
fUsePerEventRate(kFALSE),
fProb(0),
fEntries(0),
flnk1(0),
flnk2(0),
fHeader(0),
fSeed(0)
{
// Constructor
fName = "Cocktail";
fTitle= "Particle Generator using cocktail of generators";
}
AliGenCocktail::~AliGenCocktail()
{
// Destructor
delete fEntries;
fEntries = 0;
// delete fHeader; // It is removed in AliRunLoader
fHeader = 0;
}
void AliGenCocktail::
AddGenerator(AliGenerator *Generator, const char* Name, Float_t RateExp, TFormula* formula, Int_t ntimes)
{
//
// Add a generator to the list
// First check that list exists
if (!fEntries) fEntries = new TList();
fTotalRate += RateExp;
//
// Forward parameters to the new generator
if(TestBit(kPtRange) && !(Generator->TestBit(kPtRange)) && !(Generator->TestBit(kMomentumRange)))
Generator->SetPtRange(fPtMin,fPtMax);
if(TestBit(kMomentumRange) && !(Generator->TestBit(kPtRange)) && !(Generator->TestBit(kMomentumRange)))
Generator->SetMomentumRange(fPMin,fPMax);
if (TestBit(kYRange) && !(Generator->TestBit(kYRange)))
Generator->SetYRange(fYMin,fYMax);
if (TestBit(kPhiRange) && !(Generator->TestBit(kPhiRange)))
Generator->SetPhiRange(fPhiMin*180/TMath::Pi(),fPhiMax*180/TMath::Pi());
if (TestBit(kThetaRange) && !(Generator->TestBit(kThetaRange)) && !(Generator->TestBit(kEtaRange)))
Generator->SetThetaRange(fThetaMin*180/TMath::Pi(),fThetaMax*180/TMath::Pi());
if (!(Generator->TestBit(kVertexRange))) {
Generator->SetOrigin(fOrigin[0], fOrigin[1], fOrigin[2]);
Generator->SetSigma(fOsigma[0], fOsigma[1], fOsigma[2]);
Generator->SetVertexSmear(fVertexSmear);
Generator->SetVertexSource(kContainer);
}
Generator->SetTrackingFlag(fTrackIt);
Generator->SetContainer(this);
//
// Add generator to list
char theName[256];
snprintf(theName, 256, "%s_%d",Name, fNGenerators);
Generator->SetName(theName);
AliGenCocktailEntry *entry =
new AliGenCocktailEntry(Generator, Name, RateExp);
if (formula) entry->SetFormula(formula);
entry->SetNTimes(ntimes);
fEntries->Add(entry);
fNGenerators++;
flnk1 = 0;
flnk2 = 0;
fSRandom = kFALSE;
fHeader = 0;
}
void AliGenCocktail::Init()
{
// Initialisation
TIter next(fEntries);
AliGenCocktailEntry *entry;
//
// Loop over generators and initialize
while((entry = (AliGenCocktailEntry*)next())) {
if (fStack) entry->Generator()->SetStack(fStack);
if (fSeed) entry->Generator()->SetSeed(fSeed);
entry->Generator()->Init();
}
next.Reset();
if (fSRandom) {
fProb.Set(fNGenerators);
next.Reset();
Float_t sum = 0.;
while((entry = (AliGenCocktailEntry*)next())) {
sum += entry->Rate();
}
next.Reset();
Int_t i = 0;
Float_t psum = 0.;
while((entry = (AliGenCocktailEntry*)next())) {
psum += entry->Rate() / sum;
fProb[i++] = psum;
}
}
next.Reset();
}
void AliGenCocktail::FinishRun()
{
// Initialisation
TIter next(fEntries);
AliGenCocktailEntry *entry;
//
// Loop over generators and initialize
while((entry = (AliGenCocktailEntry*)next())) {
entry->Generator()->FinishRun();
}
}
void AliGenCocktail::Generate()
{
//
// Generate event
TIter next(fEntries);
AliGenCocktailEntry *entry = 0;
AliGenCocktailEntry *preventry = 0;
AliGenCocktailEntry *collentry = 0;
AliGenerator* gen = 0;
if (fHeader) delete fHeader;
fHeader = new AliGenCocktailEventHeader("Cocktail Header");
const TObjArray *partArray = gAlice->GetMCApp()->Particles();
//
// Generate the vertex position used by all generators
//
if(fVertexSmear == kPerEvent) Vertex();
TArrayF eventVertex;
eventVertex.Set(3);
for (Int_t j=0; j < 3; j++) eventVertex[j] = fVertex[j];
if (!fSRandom) {
//
// Loop over generators and generate events
Int_t igen = 0;
int inj_gen = fUseSingleInjectionPerEvent ? TMath::Floor(gRandom->Uniform(1,fNGenerators)) : 0;
while((entry = (AliGenCocktailEntry*)next())) {
Int_t ntimes = entry->NTimes();
if (fUsePerEventRate && (gRandom->Rndm() > entry->Rate())) continue;
igen++;
if (igen==1) {
entry->SetFirst(0);
} else {
if (fUseSingleInjectionPerEvent && igen != inj_gen + 1) continue;
entry->SetFirst((partArray->GetEntriesFast())+1);
}
gen = entry->Generator();
if (gen->ProvidesCollisionGeometry()) collentry = entry;
//
// Handle case in which current generator needs collision geometry from previous generator
//
if (gen->NeedsCollisionGeometry() && (entry->Formula() == 0))
{
if (preventry && preventry->Generator()->ProvidesCollisionGeometry())
{
gen->SetCollisionGeometry(preventry->Generator()->CollisionGeometry());
} else {
Fatal("Generate()", "No Collision Geometry Provided");
}
}
//
// Number of signals is calculated from Collision Geometry
// and entry with given centrality bin is selected
//
if (entry->Formula() != 0)
{
if (!collentry) {
Fatal("Generate()", "No Collision Geometry Provided");
return;
}
AliCollisionGeometry* coll = (collentry->Generator())->CollisionGeometry();
Float_t b = coll->ImpactParameter();
Int_t nsig = Int_t(entry->Formula()->Eval(b));
Int_t bin = entry->Bin() - 100;
if (bin > 0) {
if (bin != nsig) continue;
} else {
if (nsig < 1) nsig = 1;
AliInfo(Form("Signal Events %13.3f %5d %5d\n", b, coll->HardScatters(), nsig));
ntimes = nsig;
}
}
gen->SetVertex(fVertex.At(0), fVertex.At(1), fVertex.At(2), fTime);
gen->GenerateN(ntimes);
entry->SetLast(partArray->GetEntriesFast());
preventry = entry;
}
} else if (fSRandom) {
//
// Select a generator randomly
//
Int_t i;
Float_t p0 = gRandom->Rndm();
for (i = 0; i < fNGenerators; i++) {
if (p0 < fProb[i]) break;
}
entry = (AliGenCocktailEntry*) fEntries->At(i);
entry->SetFirst(0);
gen = entry->Generator();
gen->SetVertex(fVertex.At(0), fVertex.At(1), fVertex.At(2), fTime);
gen->Generate();
entry->SetLast(partArray->GetEntriesFast());
}
next.Reset();
// Event Vertex
fHeader->SetPrimaryVertex(eventVertex);
fHeader->CalcNProduced();
if (fContainer) {
fHeader->SetName(fName);
fContainer->AddHeader(fHeader);
} else {
gAlice->SetGenEventHeader(fHeader);
}
}
void AliGenCocktail::SetVertexSmear(VertexSmear_t smear)
{
// Set vertex smearing and propagate it to the generators
AliGenerator::SetVertexSmear(smear);
TIter next(fEntries);
while (AliGenCocktailEntry* entry = (AliGenCocktailEntry*)next()) {
entry->Generator()->SetVertexSmear(smear);
}
}
AliGenCocktailEntry * AliGenCocktail::FirstGenerator()
{
// Iterator over generators: Initialisation
flnk1 = fEntries->FirstLink();
if (flnk1) {
return (AliGenCocktailEntry*) (flnk1->GetObject());
} else {
return 0;
}
}
AliGenCocktailEntry* AliGenCocktail::NextGenerator()
{
// Iterator over generators: Increment
flnk1 = flnk1->Next();
if (flnk1) {
return (AliGenCocktailEntry*) (flnk1->GetObject());
} else {
return 0;
}
}
void AliGenCocktail::
FirstGeneratorPair(AliGenCocktailEntry*& e1, AliGenCocktailEntry*& e2)
{
// Iterator over generator pairs: Initialisation
flnk2 = flnk1 = fEntries->FirstLink();
if (flnk1) {
e2 = e1 = (AliGenCocktailEntry*) (flnk1->GetObject());
} else {
e2= e1 = 0;
}
}
void AliGenCocktail::
NextGeneratorPair(AliGenCocktailEntry*& e1, AliGenCocktailEntry*& e2)
{
// Iterator over generators: Increment
flnk2 = flnk2->Next();
if (flnk2) {
e1 = (AliGenCocktailEntry*) (flnk1->GetObject());
e2 = (AliGenCocktailEntry*) (flnk2->GetObject());
} else {
flnk2 = flnk1 = flnk1->Next();
if (flnk1) {
e1 = (AliGenCocktailEntry*) (flnk1->GetObject());
e2 = (AliGenCocktailEntry*) (flnk2->GetObject());
} else {
e1=0;
e2=0;
}
}
}
void AliGenCocktail::AddHeader(AliGenEventHeader* header)
{
// Add a header to the list
if (fHeader) fHeader->AddHeader(header);
}
<commit_msg>Adding collision geomtery for embedded cocktail<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$ */
// Container class for AliGenerator through recursion.
// Container is itself an AliGenerator.
// What is stored are not the pointers to the generators directly but to objects of type
// AliGenCocktail entry.
// The class provides also iterator functionality.
// Author: andreas.morsch@cern.ch
//
#include <TList.h>
#include <TObjArray.h>
#include <TFormula.h>
#include "AliGenCocktail.h"
#include "AliGenCocktailEntry.h"
#include "AliCollisionGeometry.h"
#include "AliRun.h"
#include "AliLog.h"
#include "AliMC.h"
#include "AliHeader.h"
#include "AliVertexGenFile.h"
#include "AliGenCocktailEventHeader.h"
#include "AliGenHijingEventHeader.h"
#include "AliGenDPMjetEventHeader.h"
ClassImp(AliGenCocktail)
AliGenCocktail::AliGenCocktail()
:AliGenerator(),
fNGenerators(0),
fTotalRate(0.),
fSRandom(kFALSE),
fUseSingleInjectionPerEvent(kFALSE),
fUsePerEventRate(kFALSE),
fProb(0),
fEntries(0),
flnk1(0),
flnk2(0),
fHeader(0),
fSeed(0)
{
// Constructor
fName = "Cocktail";
fTitle= "Particle Generator using cocktail of generators";
}
AliGenCocktail::~AliGenCocktail()
{
// Destructor
delete fEntries;
fEntries = 0;
// delete fHeader; // It is removed in AliRunLoader
fHeader = 0;
}
void AliGenCocktail::
AddGenerator(AliGenerator *Generator, const char* Name, Float_t RateExp, TFormula* formula, Int_t ntimes)
{
//
// Add a generator to the list
// First check that list exists
if (!fEntries) fEntries = new TList();
fTotalRate += RateExp;
//
// Forward parameters to the new generator
if(TestBit(kPtRange) && !(Generator->TestBit(kPtRange)) && !(Generator->TestBit(kMomentumRange)))
Generator->SetPtRange(fPtMin,fPtMax);
if(TestBit(kMomentumRange) && !(Generator->TestBit(kPtRange)) && !(Generator->TestBit(kMomentumRange)))
Generator->SetMomentumRange(fPMin,fPMax);
if (TestBit(kYRange) && !(Generator->TestBit(kYRange)))
Generator->SetYRange(fYMin,fYMax);
if (TestBit(kPhiRange) && !(Generator->TestBit(kPhiRange)))
Generator->SetPhiRange(fPhiMin*180/TMath::Pi(),fPhiMax*180/TMath::Pi());
if (TestBit(kThetaRange) && !(Generator->TestBit(kThetaRange)) && !(Generator->TestBit(kEtaRange)))
Generator->SetThetaRange(fThetaMin*180/TMath::Pi(),fThetaMax*180/TMath::Pi());
if (!(Generator->TestBit(kVertexRange))) {
Generator->SetOrigin(fOrigin[0], fOrigin[1], fOrigin[2]);
Generator->SetSigma(fOsigma[0], fOsigma[1], fOsigma[2]);
Generator->SetVertexSmear(fVertexSmear);
Generator->SetVertexSource(kContainer);
}
Generator->SetTrackingFlag(fTrackIt);
Generator->SetContainer(this);
//
// Add generator to list
char theName[256];
snprintf(theName, 256, "%s_%d",Name, fNGenerators);
Generator->SetName(theName);
AliGenCocktailEntry *entry =
new AliGenCocktailEntry(Generator, Name, RateExp);
if (formula) entry->SetFormula(formula);
entry->SetNTimes(ntimes);
fEntries->Add(entry);
fNGenerators++;
flnk1 = 0;
flnk2 = 0;
fSRandom = kFALSE;
fHeader = 0;
}
void AliGenCocktail::Init()
{
// Initialisation
TIter next(fEntries);
AliGenCocktailEntry *entry;
//
// Loop over generators and initialize
while((entry = (AliGenCocktailEntry*)next())) {
if (fStack) entry->Generator()->SetStack(fStack);
if (fSeed) entry->Generator()->SetSeed(fSeed);
entry->Generator()->Init();
}
next.Reset();
if (fSRandom) {
fProb.Set(fNGenerators);
next.Reset();
Float_t sum = 0.;
while((entry = (AliGenCocktailEntry*)next())) {
sum += entry->Rate();
}
next.Reset();
Int_t i = 0;
Float_t psum = 0.;
while((entry = (AliGenCocktailEntry*)next())) {
psum += entry->Rate() / sum;
fProb[i++] = psum;
}
}
next.Reset();
}
void AliGenCocktail::FinishRun()
{
// Initialisation
TIter next(fEntries);
AliGenCocktailEntry *entry;
//
// Loop over generators and initialize
while((entry = (AliGenCocktailEntry*)next())) {
entry->Generator()->FinishRun();
}
}
void AliGenCocktail::Generate()
{
//
// Generate event
TIter next(fEntries);
AliGenCocktailEntry *entry = 0;
AliGenCocktailEntry *preventry = 0;
AliGenCocktailEntry *collentry = 0;
AliGenerator* gen = 0;
if (fHeader) delete fHeader;
fHeader = new AliGenCocktailEventHeader("Cocktail Header");
const TObjArray *partArray = gAlice->GetMCApp()->Particles();
//
// Generate the vertex position used by all generators
//
if(fVertexSmear == kPerEvent) Vertex();
TArrayF eventVertex;
eventVertex.Set(3);
for (Int_t j=0; j < 3; j++) eventVertex[j] = fVertex[j];
if (!fSRandom) {
//
// Loop over generators and generate events
Int_t igen = 0;
int inj_gen = fUseSingleInjectionPerEvent ? TMath::Floor(gRandom->Uniform(1,fNGenerators)) : 0;
while((entry = (AliGenCocktailEntry*)next())) {
Int_t ntimes = entry->NTimes();
if (fUsePerEventRate && (gRandom->Rndm() > entry->Rate())) continue;
igen++;
if (igen==1) {
entry->SetFirst(0);
} else {
if (fUseSingleInjectionPerEvent && igen != inj_gen + 1) continue;
entry->SetFirst((partArray->GetEntriesFast())+1);
}
gen = entry->Generator();
if (gen->ProvidesCollisionGeometry()) collentry = entry;
//
// Handle case in which current generator needs collision geometry from previous generator
//
if (gen->NeedsCollisionGeometry() && (entry->Formula() == 0))
{
if (preventry && preventry->Generator()->ProvidesCollisionGeometry())
{
gen->SetCollisionGeometry(preventry->Generator()->CollisionGeometry());
} else {
Fatal("Generate()", "No Collision Geometry Provided");
}
}
//
// Number of signals is calculated from Collision Geometry
// and entry with given centrality bin is selected
//
if (entry->Formula() != 0)
{
AliCollisionGeometry* coll = NULL;
if (!collentry) {
const AliVertexGenFile* vtxGen = (AliVertexGenFile*)gAlice->GetMCApp()->Generator()->GetVertexGenerator();
const AliHeader* hBg = vtxGen->GetHeader();
AliGenEventHeader* genHeader = hBg->GenEventHeader();
coll = ( AliCollisionGeometry*)genHeader;
}
else{
coll = (collentry->Generator())->CollisionGeometry();
}
if (!coll) {
Fatal("Generate()", "No Collision Geometry Provided");
return;
}
Float_t b = coll->ImpactParameter();
Int_t nsig = Int_t(entry->Formula()->Eval(b));
Int_t bin = entry->Bin() - 100;
if (bin > 0) {
if (bin != nsig) continue;
} else {
if (nsig < 1) nsig = 1;
AliInfo(Form("Signal Events %13.3f %5d %5d\n", b, coll->HardScatters(), nsig));
ntimes = nsig;
}
}
gen->SetVertex(fVertex.At(0), fVertex.At(1), fVertex.At(2), fTime);
gen->GenerateN(ntimes);
entry->SetLast(partArray->GetEntriesFast());
preventry = entry;
}
} else if (fSRandom) {
//
// Select a generator randomly
//
Int_t i;
Float_t p0 = gRandom->Rndm();
for (i = 0; i < fNGenerators; i++) {
if (p0 < fProb[i]) break;
}
entry = (AliGenCocktailEntry*) fEntries->At(i);
entry->SetFirst(0);
gen = entry->Generator();
gen->SetVertex(fVertex.At(0), fVertex.At(1), fVertex.At(2), fTime);
gen->Generate();
entry->SetLast(partArray->GetEntriesFast());
}
next.Reset();
// Event Vertex
fHeader->SetPrimaryVertex(eventVertex);
fHeader->CalcNProduced();
if (fContainer) {
fHeader->SetName(fName);
fContainer->AddHeader(fHeader);
} else {
gAlice->SetGenEventHeader(fHeader);
}
}
void AliGenCocktail::SetVertexSmear(VertexSmear_t smear)
{
// Set vertex smearing and propagate it to the generators
AliGenerator::SetVertexSmear(smear);
TIter next(fEntries);
while (AliGenCocktailEntry* entry = (AliGenCocktailEntry*)next()) {
entry->Generator()->SetVertexSmear(smear);
}
}
AliGenCocktailEntry * AliGenCocktail::FirstGenerator()
{
// Iterator over generators: Initialisation
flnk1 = fEntries->FirstLink();
if (flnk1) {
return (AliGenCocktailEntry*) (flnk1->GetObject());
} else {
return 0;
}
}
AliGenCocktailEntry* AliGenCocktail::NextGenerator()
{
// Iterator over generators: Increment
flnk1 = flnk1->Next();
if (flnk1) {
return (AliGenCocktailEntry*) (flnk1->GetObject());
} else {
return 0;
}
}
void AliGenCocktail::
FirstGeneratorPair(AliGenCocktailEntry*& e1, AliGenCocktailEntry*& e2)
{
// Iterator over generator pairs: Initialisation
flnk2 = flnk1 = fEntries->FirstLink();
if (flnk1) {
e2 = e1 = (AliGenCocktailEntry*) (flnk1->GetObject());
} else {
e2= e1 = 0;
}
}
void AliGenCocktail::
NextGeneratorPair(AliGenCocktailEntry*& e1, AliGenCocktailEntry*& e2)
{
// Iterator over generators: Increment
flnk2 = flnk2->Next();
if (flnk2) {
e1 = (AliGenCocktailEntry*) (flnk1->GetObject());
e2 = (AliGenCocktailEntry*) (flnk2->GetObject());
} else {
flnk2 = flnk1 = flnk1->Next();
if (flnk1) {
e1 = (AliGenCocktailEntry*) (flnk1->GetObject());
e2 = (AliGenCocktailEntry*) (flnk2->GetObject());
} else {
e1=0;
e2=0;
}
}
}
void AliGenCocktail::AddHeader(AliGenEventHeader* header)
{
// Add a header to the list
if (fHeader) fHeader->AddHeader(header);
}
<|endoftext|> |
<commit_before>#include "mag3110.h"
mag3110::mag3110() {
read_position = 0;
write_position = 0;
fill = 0;
}
mag3110::~mag3110() {}
byte mag3110::fastread(void){
Wire.beginTransmission(MAG_ADDR); // transmit to device 0x0E
Wire.write(MAG_X_REG); // x MSB reg
Wire.endTransmission(); // stop transmitting
delayMicroseconds(2); //needs at least 1.3us free time between start and stop
byte response = Wire.requestFrom(MAG_ADDR, 6);
if (response == 6){ // request 6 bytes, if we get them all, great, if not ignore
x[write_position] = Wire.read() << 8; // receive the byte
x[write_position] = x[write_position] | Wire.read(); // receive the byte
y[write_position] = Wire.read() << 8; // receive the byte
y[write_position] = y[write_position] | Wire.read(); // receive the byte
z[write_position] = Wire.read() << 8; // receive the byte
z[write_position] = z[write_position] | Wire.read(); // receive the byte
write_position = (write_position + 1) % MAG_BUFFER_DEPTH; // Move the write position into the next spot so its clearly ready
fill ++;
return 0;
}
else {
return 1;
}
}
void mag3110::config(bool active_mode, bool auto_restart){
byte config_reg = 0;
if (active_mode){
config_reg |= MAG_ACTIVE_MODE;
}
Wire.beginTransmission(MAG_ADDR); // transmit to device 0x0E
Wire.write(MAG_CONFIG_REG1); // select control register 1
Wire.write(config_reg); // Send config data
Wire.endTransmission(); // stop transmitting
delay(15); //Let config settle?
config_reg = 0;
if (auto_restart){
config_reg |= MAG_AUTO_RESTART;
}
Wire.beginTransmission(MAG_ADDR); // transmit to device 0x0E
Wire.write(MAG_CONFIG_REG2); // select control register 2
Wire.write(config_reg); // Send config data
Wire.endTransmission(); // stop transmitting
}
int16_t mag3110::getx(){
return x[read_position];
}
int16_t mag3110::gety(){
return y[read_position];
}
int16_t mag3110::getz(){
return z[read_position];
}
byte mag3110::available(){
return fill;
}
void mag3110::advance(){
read_position = (read_position + 1) % MAG_BUFFER_DEPTH;
fill --;
}
int16_t mag3110::readx(){
return mag3110::read(MAG_X_REG);
}
int16_t mag3110::ready(){
return mag3110::read(MAG_Y_REG);
}
int16_t mag3110::readz(){
return mag3110::read(MAG_Z_REG);
}
int16_t mag3110::read(byte start_offset){
Wire.beginTransmission(MAG_ADDR); // transmit to device 0x0E
Wire.write(start_offset); // z MSB reg
Wire.endTransmission(); // stop transmitting
delayMicroseconds(2); //needs at least 1.3us free time between start and stop
if (Wire.requestFrom(MAG_ADDR, 2) != 2){
return 0; // This is ghetto... should really have a way to signal an error
};
int result = Wire.read() << 8; // receive the high byte
result |= Wire.read();
return result;
}
<commit_msg>make the comment reflect reality a bit better<commit_after>#include "mag3110.h"
mag3110::mag3110() {
read_position = 0;
write_position = 0;
fill = 0;
}
mag3110::~mag3110() {}
byte mag3110::fastread(void){
Wire.beginTransmission(MAG_ADDR); // transmit to device 0x0E
Wire.write(MAG_X_REG); // x MSB reg
Wire.endTransmission(); // actually send
delayMicroseconds(2); //needs at least 1.3us free time between start and stop
byte response = Wire.requestFrom(MAG_ADDR, 6);
if (response == 6){ // request 6 bytes, if we get them all, great, if not ignore
x[write_position] = Wire.read() << 8; // receive the byte
x[write_position] = x[write_position] | Wire.read(); // receive the byte
y[write_position] = Wire.read() << 8; // receive the byte
y[write_position] = y[write_position] | Wire.read(); // receive the byte
z[write_position] = Wire.read() << 8; // receive the byte
z[write_position] = z[write_position] | Wire.read(); // receive the byte
write_position = (write_position + 1) % MAG_BUFFER_DEPTH; // Move the write position into the next spot so its clearly ready
fill ++;
return 0;
}
else {
return 1;
}
}
void mag3110::config(bool active_mode, bool auto_restart){
byte config_reg = 0;
if (active_mode){
config_reg |= MAG_ACTIVE_MODE;
}
Wire.beginTransmission(MAG_ADDR); // transmit to device 0x0E
Wire.write(MAG_CONFIG_REG1); // select control register 1
Wire.write(config_reg); // Send config data
Wire.endTransmission(); // stop transmitting
delay(15); //Let config settle?
config_reg = 0;
if (auto_restart){
config_reg |= MAG_AUTO_RESTART;
}
Wire.beginTransmission(MAG_ADDR); // transmit to device 0x0E
Wire.write(MAG_CONFIG_REG2); // select control register 2
Wire.write(config_reg); // Send config data
Wire.endTransmission(); // stop transmitting
}
int16_t mag3110::getx(){
return x[read_position];
}
int16_t mag3110::gety(){
return y[read_position];
}
int16_t mag3110::getz(){
return z[read_position];
}
byte mag3110::available(){
return fill;
}
void mag3110::advance(){
read_position = (read_position + 1) % MAG_BUFFER_DEPTH;
fill --;
}
int16_t mag3110::readx(){
return mag3110::read(MAG_X_REG);
}
int16_t mag3110::ready(){
return mag3110::read(MAG_Y_REG);
}
int16_t mag3110::readz(){
return mag3110::read(MAG_Z_REG);
}
int16_t mag3110::read(byte start_offset){
Wire.beginTransmission(MAG_ADDR); // transmit to device 0x0E
Wire.write(start_offset); // z MSB reg
Wire.endTransmission(); // stop transmitting
delayMicroseconds(2); //needs at least 1.3us free time between start and stop
if (Wire.requestFrom(MAG_ADDR, 2) != 2){
return 0; // This is ghetto... should really have a way to signal an error
};
int result = Wire.read() << 8; // receive the high byte
result |= Wire.read();
return result;
}
<|endoftext|> |
<commit_before>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <memory>
#include <iostream>
#include <QDebug>
#include "communication/Crazyflie.h"
#include <QMessageBox>
#include "opencv2/opencv.hpp"
#include "actual_values_model.h"
#include "parameter_model.h"
#include <QTableView>
void SetupTableViewWidget(QTableView* tableView)
{
// Hide vertical header
tableView->verticalHeader()->hide();
// Resize columns and rows to fit content
// tableView->resizeColumnsToContents();
// tableView->resizeRowsToContents();
// Resize TableView Widget to match content size
int w = 0;
int h = 0;
w += tableView->contentsMargins().left() + tableView->contentsMargins().right();
h += tableView->contentsMargins().top()+ tableView->contentsMargins().bottom();
h += tableView->horizontalHeader()->height();
for (int i=0; i<tableView->model()->columnCount(); ++i)
{
w += tableView->columnWidth(i);
}
for (int i=0; i < 6; ++i) // Minimum 6 rows are shown.
{
h += tableView->rowHeight(i);
}
tableView->setMinimumWidth(w);
// tableView->setMaximumWidth(w);
tableView->setMinimumHeight(h);
// tableView->setMaximumHeight(h);
tableView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
}
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
_crazyRadio(),
_crazyFlie(_crazyRadio),
ui(new Ui::MainWindow),
_actualValuesTable(nullptr),
_parameterTable(nullptr),
_dataForActualValuesModel(),
_actualValuesModel(_crazyFlie.GetLogElements(), nullptr),
_parameterModel(_dataForActualValuesModel, nullptr),
_timer_t0(),
_timer_t1(),
_cameraViewPainter(_crazyFlie.GetSensorValues().stabilizer.roll,
_crazyFlie.GetSensorValues().stabilizer.yaw,
_crazyFlie.GetSensorValues().stabilizer.pitch),
_trackingColor(),
_camera(),
_extractColor(_trackingColor.GetColor()),
_commander(_crazyFlie)
{
ui->setupUi(this);
// Event loop on main window
// T0
_timer_t0.start(crazyflieUpdateSamplingTime); // time in ms
QObject::connect(&_timer_t0, SIGNAL(timeout()), this, SLOT(UpdateCrazyFlie()));
// T1
_timer_t1.start(30); // time in ms
QObject::connect(&_timer_t1, SIGNAL(timeout()), this, SLOT(UpdateCamera()));
// T2
_timer_t2.start(100); // time in ms
QObject::connect(&_timer_t2, SIGNAL(timeout()), this, SLOT(display_sensor_values()));
QObject::connect(&_timer_t2, SIGNAL(timeout()), &_actualValuesModel, SLOT(UpdateActualValues()));
QObject::connect(&_timer_t2, SIGNAL(timeout()), this, SLOT(RePaintCameraViewPainter()));
// Custom widgets
ui->Layout_CameraView->addWidget(&_cameraViewPainter);
ui->Layout_TrackingColor->addWidget(&_trackingColor);
// Setup color bar sliders
ui->verticalSlider_hue->setMinimum(0);
ui->verticalSlider_hue->setMaximum(359);
ui->verticalSlider_hue->setValue(_trackingColor.GetHue()); // Default value is the same as defined in trackingColor
// Connections
QObject::connect(&_camera, SIGNAL(ImgReadyForDisplay(QImage const &)), &_cameraViewPainter, SLOT(SetImage(QImage const &)));
QObject::connect(&_camera, SIGNAL(ImgReadyForProcessing(cv::Mat const &)), &_extractColor, SLOT(ProcessImage(cv::Mat const &)));
QObject::connect(&_crazyFlie, SIGNAL(ConnectionTimeout()), this, SLOT(display_connection_timeout_box()));
QObject::connect(&_crazyFlie, SIGNAL(NotConnecting()), this, SLOT(display_not_connecting_box()));
// For testing purposes
TOCElement e1;
e1.id = 0;
e1.group = "Stabilizer";
e1.name_only = "Acc_x";
e1.name = e1.group + "." + e1.name_only;
e1.type = ElementType::UINT8;
e1.value = 10;
_dataForActualValuesModel.emplace_back(e1);
TOCElement e;
e1.id = 4;
e1.group = "Stabilizer";
e1.name_only = "Acc_y";
e1.name = e1.group + "." + e1.name_only;
e1.type = ElementType::UINT8;
e1.value = 20;
_dataForActualValuesModel.emplace_back(e1);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::display_sensor_values()
{
ui->actRoll->setPlainText( QString::number(_crazyFlie.GetSensorValues().stabilizer.roll));
ui->actYaw->setPlainText( QString::number(_crazyFlie.GetSensorValues().stabilizer.yaw));
ui->actPitch->setPlainText( QString::number(_crazyFlie.GetSensorValues().stabilizer.pitch));
ui->actThrust->setPlainText( QString::number(_crazyFlie.GetSensorValues().stabilizer.thrust));
ui->actAcc_x->setPlainText( QString::number(_crazyFlie.GetSensorValues().acceleration.x));
ui->actAcc_y->setPlainText( QString::number(_crazyFlie.GetSensorValues().acceleration.y));
ui->actAcc_z->setPlainText( QString::number(_crazyFlie.GetSensorValues().acceleration.z));
ui->actAcc_zw->setPlainText( QString::number(_crazyFlie.GetSensorValues().acceleration.zw));
ui->actBatterStatus->setPlainText( QString::number(_crazyFlie.GetSensorValues().battery.state));
ui->actBatteryLevel->setPlainText( QString::number(_crazyFlie.GetSensorValues().battery.level));
ui->actGyro_x->setPlainText( QString::number(_crazyFlie.GetSensorValues().gyrometer.x));
ui->actGyro_y->setPlainText( QString::number(_crazyFlie.GetSensorValues().gyrometer.y));
ui->actGyro_z->setPlainText( QString::number(_crazyFlie.GetSensorValues().gyrometer.z));
ui->actMag_x->setPlainText( QString::number(_crazyFlie.GetSensorValues().magnetometer.x));
ui->actMag_y->setPlainText( QString::number(_crazyFlie.GetSensorValues().magnetometer.y));
ui->actMag_z->setPlainText( QString::number(_crazyFlie.GetSensorValues().magnetometer.z));
ui->actAsl->setPlainText( QString::number(_crazyFlie.GetSensorValues().barometer.asl));
ui->actAslLong->setPlainText( QString::number(_crazyFlie.GetSensorValues().barometer.aslLong));
ui->actTemperature->setPlainText( QString::number(_crazyFlie.GetSensorValues().barometer.temperature));
ui->actPressure->setPlainText( QString::number(_crazyFlie.GetSensorValues().barometer.pressure));
// Also update connection status
DisplayConnectionStatus();
}
void MainWindow::display_connection_timeout_box()
{
QMessageBox msgBox;
msgBox.setWindowTitle("Connection Error");
msgBox.setText("Connection Time out.");
msgBox.exec();
}
void MainWindow::display_not_connecting_box()
{
QMessageBox msgBox;
msgBox.setWindowTitle("Connection Error");
msgBox.setText("Could not connect to CrazyFlie.");
msgBox.setInformativeText("Have you turned it on?");
msgBox.exec();
}
void MainWindow::on_disconnectRadio_clicked()
{
// _crazyRadio.StopRadio();
// _crazyFlie.EnableStateMachine(false);
QMessageBox msgBox;
msgBox.setText("Feature not implemented yet.");
msgBox.exec();
}
void MainWindow::on_connectRadio_clicked()
{
_crazyRadio.StartRadio();
if(_crazyRadio.RadioIsConnected())
{
_crazyFlie.StartConnecting(true);
}
else
{
_crazyFlie.StartConnecting(false);
QMessageBox msgBox;
msgBox.setText("Could not open Radio Dongle.");
msgBox.setInformativeText("Have you plugged it in?");
msgBox.setStandardButtons(QMessageBox::Retry | QMessageBox::Cancel);
msgBox.setDefaultButton(QMessageBox::Cancel);
int ret = msgBox.exec();
switch(ret)
{
default:
case QMessageBox::Cancel:
{
break;
}
case QMessageBox::Retry:
{
on_connectRadio_clicked();
break;
}
}
}
}
void MainWindow::on_radioSettings_Options_currentIndexChanged(int index)
{
_crazyRadio.SetRadioSettings(index);
}
void MainWindow::on_exitApp_clicked()
{
QCoreApplication::quit();
}
void MainWindow::on_actionExit_triggered()
{
QCoreApplication::quit();
}
void MainWindow::DisplayConnectionStatus()
{
QString connectionStatus;
if( _crazyFlie.IsConnected())
{
connectionStatus = "Connected";
}
else if(_crazyFlie.IsConnecting())
{
connectionStatus = "Connecting";
}
else if(_crazyFlie.IsDisconnected())
{
connectionStatus = "Disconnected";
}
else
{
connectionStatus = "Connection Status unknown";
}
ui->display_ConnectionStatus->setText(connectionStatus);
}
void MainWindow::on_verticalSlider_hue_valueChanged(int value)
{
_trackingColor.SetHue(value);
_trackingColor.repaint();
ui->Hue_Num->setText(QString::number(value));
}
void MainWindow::UpdateCamera()
{
_camera.Update();
}
void MainWindow::on_pushButton_CameraOnlyMode_clicked()
{
bool activate = (_camera.GetState() == Camera::CameraState::DISABLED);
if(activate)
{
_cameraViewPainter.SetCameraBackGround();
}
else
{
_cameraViewPainter.SetHorizon();
}
_camera.Activate(activate);
}
void MainWindow::on_pushButton_Stop_clicked()
{
_camera.Activate(false);
_commander.Stop();
}
void MainWindow::on_pushButton_hoverMode_clicked()
{
_commander.ActivateHoverMode(true);
}
void MainWindow::UpdateCrazyFlie()
{
_commander.Update();
_crazyFlie.Update();
}
void MainWindow::on_pushButton_SafeLandingMode_clicked()
{
_crazyRadio.ReadParameter();
}
void MainWindow::on_pushButton_ActualValues_clicked()
{
if(_actualValuesTable == nullptr)
{
_actualValuesTable = new QTableView();
_actualValuesTable->setModel(&_actualValuesModel);
SetupTableViewWidget(_actualValuesTable);
_actualValuesTable->setWindowTitle("Actual Values");
_actualValuesTable->show();
}
else
{
delete _actualValuesTable;
_actualValuesTable = nullptr;
}
}
void MainWindow::on_pushButton_ParameterTable_clicked()
{
if(_parameterTable == nullptr)
{
_parameterTable = new QTableView();
_parameterTable->setModel(&_parameterModel);
SetupTableViewWidget(_parameterTable);
_parameterTable->setWindowTitle("Parameter Table");
_parameterTable->show();
}
else
{
delete _parameterTable;
_parameterTable = nullptr;
}
}
void MainWindow::on_pushButton_TestAddElement_clicked()
{
static int index = 0;
++index;
TOCElement e;
e.id = index;
_dataForActualValuesModel.push_back(e);
}
void MainWindow::on_pushButton_TestRemoveElement_clicked()
{
_dataForActualValuesModel.pop_back();
}
<commit_msg>Make the window actual values a bit nicer.<commit_after>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <memory>
#include <iostream>
#include <QDebug>
#include "communication/Crazyflie.h"
#include <QMessageBox>
#include "opencv2/opencv.hpp"
#include "actual_values_model.h"
#include "parameter_model.h"
#include <QTableView>
#include <QScrollBar>
void SetupTableViewWidget(QTableView* tableView)
{
// Hide vertical header
tableView->verticalHeader()->hide();
// Resize columns and rows to fit content
// tableView->resizeColumnsToContents();
// tableView->resizeRowsToContents();
// Resize TableView Widget to match content size
int w = 0;
int h = 0;
w += tableView->contentsMargins().left() + tableView->contentsMargins().right();
w += tableView->horizontalScrollBar()->width()/4; // TODO SF: Somehow the width of the horizontalScrollBar is way too large?
h += tableView->contentsMargins().top()+ tableView->contentsMargins().bottom();
h += tableView->horizontalHeader()->height();
for (int i=0; i<tableView->model()->columnCount(); ++i)
{
w += tableView->columnWidth(i);
}
for (int i=0; i < 6; ++i) // Minimum 6 rows are shown.
{
h += tableView->rowHeight(i);
}
tableView->setMinimumWidth(w);
tableView->setMaximumWidth(w);
tableView->setMinimumHeight(h);
// tableView->setMaximumHeight(h);
tableView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
}
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
_crazyRadio(),
_crazyFlie(_crazyRadio),
ui(new Ui::MainWindow),
_actualValuesTable(nullptr),
_parameterTable(nullptr),
_dataForActualValuesModel(),
_actualValuesModel(_crazyFlie.GetLogElements(), nullptr),
_parameterModel(_dataForActualValuesModel, nullptr),
_timer_t0(),
_timer_t1(),
_cameraViewPainter(_crazyFlie.GetSensorValues().stabilizer.roll,
_crazyFlie.GetSensorValues().stabilizer.yaw,
_crazyFlie.GetSensorValues().stabilizer.pitch),
_trackingColor(),
_camera(),
_extractColor(_trackingColor.GetColor()),
_commander(_crazyFlie)
{
ui->setupUi(this);
// Event loop on main window
// T0
_timer_t0.start(crazyflieUpdateSamplingTime); // time in ms
QObject::connect(&_timer_t0, SIGNAL(timeout()), this, SLOT(UpdateCrazyFlie()));
// T1
_timer_t1.start(30); // time in ms
QObject::connect(&_timer_t1, SIGNAL(timeout()), this, SLOT(UpdateCamera()));
// T2
_timer_t2.start(100); // time in ms
QObject::connect(&_timer_t2, SIGNAL(timeout()), this, SLOT(display_sensor_values()));
QObject::connect(&_timer_t2, SIGNAL(timeout()), &_actualValuesModel, SLOT(UpdateActualValues()));
QObject::connect(&_timer_t2, SIGNAL(timeout()), this, SLOT(RePaintCameraViewPainter()));
// Custom widgets
ui->Layout_CameraView->addWidget(&_cameraViewPainter);
ui->Layout_TrackingColor->addWidget(&_trackingColor);
// Setup color bar sliders
ui->verticalSlider_hue->setMinimum(0);
ui->verticalSlider_hue->setMaximum(359);
ui->verticalSlider_hue->setValue(_trackingColor.GetHue()); // Default value is the same as defined in trackingColor
// Connections
QObject::connect(&_camera, SIGNAL(ImgReadyForDisplay(QImage const &)), &_cameraViewPainter, SLOT(SetImage(QImage const &)));
QObject::connect(&_camera, SIGNAL(ImgReadyForProcessing(cv::Mat const &)), &_extractColor, SLOT(ProcessImage(cv::Mat const &)));
QObject::connect(&_crazyFlie, SIGNAL(ConnectionTimeout()), this, SLOT(display_connection_timeout_box()));
QObject::connect(&_crazyFlie, SIGNAL(NotConnecting()), this, SLOT(display_not_connecting_box()));
// For testing purposes
TOCElement e1;
e1.id = 0;
e1.group = "Stabilizer";
e1.name_only = "Acc_x";
e1.name = e1.group + "." + e1.name_only;
e1.type = ElementType::UINT8;
e1.value = 10;
_dataForActualValuesModel.emplace_back(e1);
TOCElement e;
e1.id = 4;
e1.group = "Stabilizer";
e1.name_only = "Acc_y";
e1.name = e1.group + "." + e1.name_only;
e1.type = ElementType::UINT8;
e1.value = 20;
_dataForActualValuesModel.emplace_back(e1);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::display_sensor_values()
{
ui->actRoll->setPlainText( QString::number(_crazyFlie.GetSensorValues().stabilizer.roll));
ui->actYaw->setPlainText( QString::number(_crazyFlie.GetSensorValues().stabilizer.yaw));
ui->actPitch->setPlainText( QString::number(_crazyFlie.GetSensorValues().stabilizer.pitch));
ui->actThrust->setPlainText( QString::number(_crazyFlie.GetSensorValues().stabilizer.thrust));
ui->actAcc_x->setPlainText( QString::number(_crazyFlie.GetSensorValues().acceleration.x));
ui->actAcc_y->setPlainText( QString::number(_crazyFlie.GetSensorValues().acceleration.y));
ui->actAcc_z->setPlainText( QString::number(_crazyFlie.GetSensorValues().acceleration.z));
ui->actAcc_zw->setPlainText( QString::number(_crazyFlie.GetSensorValues().acceleration.zw));
ui->actBatterStatus->setPlainText( QString::number(_crazyFlie.GetSensorValues().battery.state));
ui->actBatteryLevel->setPlainText( QString::number(_crazyFlie.GetSensorValues().battery.level));
ui->actGyro_x->setPlainText( QString::number(_crazyFlie.GetSensorValues().gyrometer.x));
ui->actGyro_y->setPlainText( QString::number(_crazyFlie.GetSensorValues().gyrometer.y));
ui->actGyro_z->setPlainText( QString::number(_crazyFlie.GetSensorValues().gyrometer.z));
ui->actMag_x->setPlainText( QString::number(_crazyFlie.GetSensorValues().magnetometer.x));
ui->actMag_y->setPlainText( QString::number(_crazyFlie.GetSensorValues().magnetometer.y));
ui->actMag_z->setPlainText( QString::number(_crazyFlie.GetSensorValues().magnetometer.z));
ui->actAsl->setPlainText( QString::number(_crazyFlie.GetSensorValues().barometer.asl));
ui->actAslLong->setPlainText( QString::number(_crazyFlie.GetSensorValues().barometer.aslLong));
ui->actTemperature->setPlainText( QString::number(_crazyFlie.GetSensorValues().barometer.temperature));
ui->actPressure->setPlainText( QString::number(_crazyFlie.GetSensorValues().barometer.pressure));
// Also update connection status
DisplayConnectionStatus();
}
void MainWindow::display_connection_timeout_box()
{
QMessageBox msgBox;
msgBox.setWindowTitle("Connection Error");
msgBox.setText("Connection Time out.");
msgBox.exec();
}
void MainWindow::display_not_connecting_box()
{
QMessageBox msgBox;
msgBox.setWindowTitle("Connection Error");
msgBox.setText("Could not connect to CrazyFlie.");
msgBox.setInformativeText("Have you turned it on?");
msgBox.exec();
}
void MainWindow::on_disconnectRadio_clicked()
{
// _crazyRadio.StopRadio();
// _crazyFlie.EnableStateMachine(false);
QMessageBox msgBox;
msgBox.setText("Feature not implemented yet.");
msgBox.exec();
}
void MainWindow::on_connectRadio_clicked()
{
_crazyRadio.StartRadio();
if(_crazyRadio.RadioIsConnected())
{
_crazyFlie.StartConnecting(true);
}
else
{
_crazyFlie.StartConnecting(false);
QMessageBox msgBox;
msgBox.setText("Could not open Radio Dongle.");
msgBox.setInformativeText("Have you plugged it in?");
msgBox.setStandardButtons(QMessageBox::Retry | QMessageBox::Cancel);
msgBox.setDefaultButton(QMessageBox::Cancel);
int ret = msgBox.exec();
switch(ret)
{
default:
case QMessageBox::Cancel:
{
break;
}
case QMessageBox::Retry:
{
on_connectRadio_clicked();
break;
}
}
}
}
void MainWindow::on_radioSettings_Options_currentIndexChanged(int index)
{
_crazyRadio.SetRadioSettings(index);
}
void MainWindow::on_exitApp_clicked()
{
QCoreApplication::quit();
}
void MainWindow::on_actionExit_triggered()
{
QCoreApplication::quit();
}
void MainWindow::DisplayConnectionStatus()
{
QString connectionStatus;
if( _crazyFlie.IsConnected())
{
connectionStatus = "Connected";
}
else if(_crazyFlie.IsConnecting())
{
connectionStatus = "Connecting";
}
else if(_crazyFlie.IsDisconnected())
{
connectionStatus = "Disconnected";
}
else
{
connectionStatus = "Connection Status unknown";
}
ui->display_ConnectionStatus->setText(connectionStatus);
}
void MainWindow::on_verticalSlider_hue_valueChanged(int value)
{
_trackingColor.SetHue(value);
_trackingColor.repaint();
ui->Hue_Num->setText(QString::number(value));
}
void MainWindow::UpdateCamera()
{
_camera.Update();
}
void MainWindow::on_pushButton_CameraOnlyMode_clicked()
{
bool activate = (_camera.GetState() == Camera::CameraState::DISABLED);
if(activate)
{
_cameraViewPainter.SetCameraBackGround();
}
else
{
_cameraViewPainter.SetHorizon();
}
_camera.Activate(activate);
}
void MainWindow::on_pushButton_Stop_clicked()
{
_camera.Activate(false);
_commander.Stop();
}
void MainWindow::on_pushButton_hoverMode_clicked()
{
_commander.ActivateHoverMode(true);
}
void MainWindow::UpdateCrazyFlie()
{
_commander.Update();
_crazyFlie.Update();
}
void MainWindow::on_pushButton_SafeLandingMode_clicked()
{
_crazyRadio.ReadParameter();
}
void MainWindow::on_pushButton_ActualValues_clicked()
{
if(_actualValuesTable == nullptr)
{
_actualValuesTable = new QTableView();
_actualValuesTable->setModel(&_actualValuesModel);
SetupTableViewWidget(_actualValuesTable);
_actualValuesTable->setWindowTitle("Actual Values");
_actualValuesTable->show();
}
else
{
delete _actualValuesTable;
_actualValuesTable = nullptr;
}
}
void MainWindow::on_pushButton_ParameterTable_clicked()
{
if(_parameterTable == nullptr)
{
_parameterTable = new QTableView();
_parameterTable->setModel(&_parameterModel);
SetupTableViewWidget(_parameterTable);
_parameterTable->setWindowTitle("Parameter Table");
_parameterTable->show();
}
else
{
delete _parameterTable;
_parameterTable = nullptr;
}
}
void MainWindow::on_pushButton_TestAddElement_clicked()
{
static int index = 0;
++index;
TOCElement e;
e.id = index;
_dataForActualValuesModel.push_back(e);
}
void MainWindow::on_pushButton_TestRemoveElement_clicked()
{
_dataForActualValuesModel.pop_back();
}
<|endoftext|> |
<commit_before><commit_msg>#include what you use: <Security/Security.h> for SecKeychainAddCallback and friends following r43492.<commit_after><|endoftext|> |
<commit_before><commit_msg>Looks like both VideoBearTheora and VideoBearSilentTheora are crashy.<commit_after><|endoftext|> |
<commit_before><commit_msg>Restoring the old media UI test before the move from ui_test to interactive_uitest.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/basictypes.h"
#include "base/file_path.h"
#include "base/platform_thread.h"
#include "base/string_util.h"
#include "chrome/test/ui/ui_layout_test.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"
class MediaTest : public UITest {
protected:
void PlayMedia(const char* tag, const char* media_file) {
FilePath test_file(test_data_directory_);
test_file = test_file.AppendASCII("media/player.html");
GURL player_gurl = net::FilePathToFileURL(test_file);
std::string url = StringPrintf("%s?%s=%s",
player_gurl.spec().c_str(),
tag,
media_file);
NavigateToURL(GURL(url));
// Allow the media file to be loaded.
const std::wstring kPlaying = L"PLAYING";
const std::wstring kFailed = L"FAILED";
const std::wstring kError = L"ERROR";
for (int i = 0; i < 10; ++i) {
PlatformThread::Sleep(sleep_timeout_ms());
const std::wstring& title = GetActiveTabTitle();
if (title == kPlaying || title == kFailed ||
StartsWith(title, kError, true))
break;
}
EXPECT_EQ(kPlaying, GetActiveTabTitle());
}
void PlayAudio(const char* url) {
PlayMedia("audio", url);
}
void PlayVideo(const char* url) {
PlayMedia("video", url);
}
};
#if defined(OS_WIN)
// Tests may fail on windows: http://crbug.com/55477
#define MAYBE_VideoBearTheora FLAKY_VideoBearTheora
#define MAYBE_VideoBearSilentTheora FLAKY_VideoBearSilentTheora
#define MAYBE_VideoBearWebm FLAKY_VideoBearWebm
#define MAYBE_VideoBearSilentWebm FLAKY_VideoBearSilentWebm
#define MAYBE_VideoBearMp4 FLAKY_VideoBearMp4
#define MAYBE_VideoBearSilentMp4 FLAKY_VideoBearSilentMp4
#define MAYBE_MediaUILayoutTest FLAKY_MediaUILayoutTest
#else
#define MAYBE_VideoBearTheora VideoBearTheora
#define MAYBE_VideoBearSilentTheora VideoBearSilentTheora
#define MAYBE_VideoBearWebm VideoBearWebm
#define MAYBE_VideoBearSilentWebm VideoBearSilentWebm
#define MAYBE_VideoBearMp4 VideoBearMp4
#define MAYBE_VideoBearSilentMp4 VideoBearSilentMp4
#define MAYBE_MediaUILayoutTest MediaUILayoutTest
#endif
TEST_F(MediaTest, MAYBE_VideoBearTheora) {
PlayVideo("bear.ogv");
}
TEST_F(MediaTest, MAYBE_VideoBearSilentTheora) {
PlayVideo("bear_silent.ogv");
}
TEST_F(MediaTest, MAYBE_VideoBearWebm) {
PlayVideo("bear.webm");
}
TEST_F(MediaTest, MAYBE_VideoBearSilentWebm) {
PlayVideo("bear_silent.webm");
}
#if defined(GOOGLE_CHROME_BUILD) || defined(USE_PROPRIETARY_CODECS)
TEST_F(MediaTest, MAYBE_VideoBearMp4) {
PlayVideo("bear.mp4");
}
TEST_F(MediaTest, MAYBE_VideoBearSilentMp4) {
PlayVideo("bear_silent.mp4");
}
#endif
TEST_F(UILayoutTest, MAYBE_MediaUILayoutTest) {
static const char* kResources[] = {
"content",
"media-file.js",
"media-fullscreen.js",
"video-paint-test.js",
"video-played.js",
"video-test.js",
};
static const char* kMediaTests[] = {
"video-autoplay.html",
// "video-loop.html", disabled due to 52887.
"video-no-autoplay.html",
// TODO(sergeyu): Add more tests here.
};
FilePath test_dir;
FilePath media_test_dir;
media_test_dir = media_test_dir.AppendASCII("media");
InitializeForLayoutTest(test_dir, media_test_dir, kNoHttpPort);
// Copy resources first.
for (size_t i = 0; i < arraysize(kResources); ++i)
AddResourceForLayoutTest(
test_dir, media_test_dir.AppendASCII(kResources[i]));
for (size_t i = 0; i < arraysize(kMediaTests); ++i)
RunLayoutTest(kMediaTests[i], kNoHttpPort);
}
<|endoftext|> |
<commit_before><commit_msg>Fix for spell check toggle checkbox not getting selected after reset to default button is clicked. Patch by tfarina (original patch: http://codereview.chromium.org/165524)<commit_after><|endoftext|> |
<commit_before><commit_msg>Linux: fix "goats teleported" task manager column. Some glibc library functions behave a little differently than Windows so this column was not working correctly. BUG=none TEST=none<commit_after><|endoftext|> |
<commit_before>#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>
#include <vector>
namespace {
class person_t final {
public:
enum gender_t { male, female, other };
person_t() : name_{ "none" }, gender_{ gender_t::male } { }
person_t(std::string const& name, gender_t const gender)
: name_{ name }, gender_{ gender } {}
std::string name() const { return name_; }
gender_t gender() const { return gender_; }
friend std::ostream& operator << (std::ostream&, person_t const&);
private:
std::string name_;
gender_t gender_;
};
std::ostream& operator << (std::ostream& out, person_t const& person) {
out << person.name();
return out;
}
} // anonymous namespace
bool is_female(person_t const& person) { return person_t::female == person.gender(); }
bool is_not_female(person_t const& person) { return not is_female(person); }
int main() {
std::vector<person_t> people {
{ "David" , person_t::male },
{ "Jane" , person_t::female },
{ "Martha", person_t::female },
{ "Peter" , person_t::male },
{ "Rose" , person_t::female },
{ "Tom" , person_t::male }
};
people.erase(
std::remove_if(people.begin(), people.end(), is_not_female),
people.end());
std::copy(std::cbegin(people), std::cend(people),
std::ostream_iterator<person_t>(std::cout, " "));
return 0;
}
<commit_msg>[i_cukic-func_progr_in_cpp][ch 02] slightly rewrite the example with std::remove_if usage<commit_after>#include <algorithm>
#include <iterator>
#include <string>
#include <vector>
#include <cassert>
namespace test {
class Person final {
public:
enum class Gender { Male, Female, Other };
Person(std::string const& name = "none", Gender const gender = Gender::Male)
: name_{name}, gender_{gender} {}
bool operator ==(Person const& other) const { return other.name_ == name_ and other.gender_ == gender_; }
std::string name() const { return name_; }
Gender gender() const { return gender_; }
private:
std::string name_;
Gender gender_;
};
bool isFemale(Person const& person) { return Person::Gender::Female == person.gender(); }
bool isNotFemale(Person const& person) { return not isFemale(person); }
void run() {
std::vector<Person> people {
{ "David" , Person::Gender::Male },
{ "Jane" , Person::Gender::Female },
{ "Martha", Person::Gender::Female },
{ "Peter" , Person::Gender::Male },
{ "Rose" , Person::Gender::Female },
{ "Tom" , Person::Gender::Male }};
people.erase(
std::remove_if(std::begin(people), std::end(people), isNotFemale),
std::end(people));
std::vector<Person> const expected {
{ "Jane" , Person::Gender::Female },
{ "Martha", Person::Gender::Female },
{ "Rose" , Person::Gender::Female } };
assert(expected == people);
}
} // test
#include <iostream>
int main() {
std::cout << "test => [ok]" << std::endl; test::run(); std::cout << std::endl;
return 0;
}
<|endoftext|> |
<commit_before>#include "Base.h"
#include "BoundingBox.h"
#include "BoundingSphere.h"
#include "Plane.h"
namespace gameplay
{
BoundingBox::BoundingBox()
{
}
BoundingBox::BoundingBox(const Vector3& min, const Vector3& max)
{
set(min, max);
}
BoundingBox::BoundingBox(const BoundingBox& copy)
{
set(copy);
}
BoundingBox::~BoundingBox()
{
}
const BoundingBox& BoundingBox::empty()
{
static BoundingBox b;
return b;
}
void BoundingBox::getCorners(Vector3* dst) const
{
assert(dst);
// Near face, specified counter-clockwise looking towards the origin from the positive z-axis.
// Left-top-front.
dst[0].set(min.x, max.y, max.z);
// Left-bottom-front.
dst[1].set(min.x, min.y, max.z);
// Right-bottom-front.
dst[2].set(max.x, min.y, max.z);
// Right-top-front.
dst[3].set(max.x, max.y, max.z);
// Far face, specified counter-clockwise looking towards the origin from the negative z-axis.
// Right-top-back.
dst[4].set(max.x, max.y, min.z);
// Right-bottom-back.
dst[5].set(max.x, min.y, min.z);
// Left-bottom-back.
dst[6].set(min.x, min.y, min.z);
// Left-top-back.
dst[7].set(min.x, max.y, min.z);
}
void BoundingBox::getCenter(Vector3* dst) const
{
dst->set(min, max);
dst->scale(0.5f);
dst->add(min);
}
bool BoundingBox::intersects(const BoundingSphere& sphere) const
{
return sphere.intersects(*this);
}
bool BoundingBox::intersects(const BoundingBox& box) const
{
return ((min.x >= box.min.x && min.x <= max.x) || (box.min.x >= min.x && box.min.x <= max.x)) &&
((min.y >= box.min.y && min.y <= max.y) || (box.min.y >= min.y && box.min.y <= max.y)) &&
((min.z >= box.min.z && min.z <= max.z) || (box.min.z >= min.z && box.min.z <= max.z));
}
bool BoundingBox::intersects(const Frustum& frustum) const
{
// The box must either intersect or be in the positive half-space of all six planes of the frustum.
return (intersects(frustum.getNear()) != Plane::INTERSECTS_BACK &&
intersects(frustum.getFar()) != Plane::INTERSECTS_BACK &&
intersects(frustum.getLeft()) != Plane::INTERSECTS_BACK &&
intersects(frustum.getRight()) != Plane::INTERSECTS_BACK &&
intersects(frustum.getBottom()) != Plane::INTERSECTS_BACK &&
intersects(frustum.getTop()) != Plane::INTERSECTS_BACK);
}
float BoundingBox::intersects(const Plane& plane) const
{
// Calculate the distance from the center of the box to the plane.
Vector3 center((min.x + max.x) * 0.5f, (min.y + max.y) * 0.5f, (min.z + max.z) * 0.5f);
float distance = plane.distance(center);
// Get the extents of the box from its center along each axis.
float extentX = (max.x - min.x) * 0.5f;
float extentY = (max.y - min.y) * 0.5f;
float extentZ = (max.z - min.z) * 0.5f;
const Vector3& planeNormal = plane.getNormal();
if (fabsf(distance) <= (fabsf(extentX * planeNormal.x) + fabsf(extentY * planeNormal.y) + fabsf(
extentZ * planeNormal.z)))
{
return Plane::INTERSECTS_INTERSECTING;
}
return (distance > 0.0f) ? (float)Plane::INTERSECTS_FRONT : (float)Plane::INTERSECTS_BACK;
}
float BoundingBox::intersects(const Ray& ray) const
{
// Intermediate calculation variables.
float dnear = 0.0f;
float dfar = 0.0f;
float tmin = 0.0f;
float tmax = 0.0f;
const Vector3& origin = ray.getOrigin();
const Vector3& direction = ray.getDirection();
// X direction.
float div = 1.0f / direction.x;
if (div >= 0.0f)
{
tmin = (min.x - origin.x) * div;
tmax = (max.x - origin.x) * div;
}
else
{
tmin = (max.x - origin.x) * div;
tmax = (min.x - origin.x) * div;
}
dnear = tmin;
dfar = tmax;
// Check if the ray misses the box.
if (dnear > dfar || dfar < 0.0f)
{
return Ray::INTERSECTS_NONE;
}
// Y direction.
div = 1.0f / direction.y;
if (div >= 0.0f)
{
tmin = (min.y - origin.y) * div;
tmax = (max.y - origin.y) * div;
}
else
{
tmin = (max.y - origin.y) * div;
tmax = (min.y - origin.y) * div;
}
// Update the near and far intersection distances.
if (tmin > dnear)
{
dnear = tmin;
}
if (tmax < dfar)
{
dfar = tmax;
}
// Check if the ray misses the box.
if (dnear > dfar || dfar < 0.0f)
{
return Ray::INTERSECTS_NONE;
}
// Z direction.
div = 1.0f / direction.z;
if (div >= 0.0f)
{
tmin = (min.z - origin.z) * div;
tmax = (max.z - origin.z) * div;
}
else
{
tmin = (max.z - origin.z) * div;
tmax = (min.z - origin.z) * div;
}
// Update the near and far intersection distances.
if (tmin > dnear)
{
dnear = tmin;
}
if (tmax < dfar)
{
dfar = tmax;
}
// Check if the ray misses the box.
if (dnear > dfar || dfar < 0.0f)
{
return Ray::INTERSECTS_NONE;
}
// The ray intersects the box (and since the direction of a Ray is normalized, dnear is the distance to the ray).
return dnear;
}
bool BoundingBox::isEmpty() const
{
return min.x == max.x && min.y == max.y && min.z == max.z;
}
void BoundingBox::merge(const BoundingBox& box)
{
// Calculate the new minimum point.
min.x = std::min(min.x, box.min.x);
min.y = std::min(min.y, box.min.y);
min.z = std::min(min.z, box.min.z);
// Calculate the new maximum point.
max.x = std::max(max.x, box.max.x);
max.y = std::max(max.y, box.max.y);
max.z = std::max(max.z, box.max.z);
}
void BoundingBox::merge(const BoundingSphere& sphere)
{
const Vector3& center = sphere.center;
float radius = sphere.radius;
// Calculate the new minimum point for the merged bounding box.
min.x = std::min(min.x, center.x - radius);
min.y = std::min(min.y, center.y - radius);
min.z = std::min(min.z, center.z - radius);
// Calculate the new maximum point for the merged bounding box.
max.x = std::max(max.x, center.x + radius);
max.y = std::max(max.y, center.y + radius);
max.z = std::max(max.z, center.z + radius);
}
void BoundingBox::set(const Vector3& min, const Vector3& max)
{
this->min = min;
this->max = max;
}
void updateMinMax(Vector3* point, Vector3* min, Vector3* max)
{
// Leftmost point.
if (point->x < min->x)
{
min->x = point->x;
}
// Rightmost point.
if (point->x > max->x)
{
max->x = point->x;
}
// Lowest point.
if (point->y < min->y)
{
min->y = point->y;
}
// Highest point.
if (point->y > max->y)
{
max->y = point->y;
}
// Farthest point.
if (point->z < min->z)
{
min->z = point->z;
}
// Nearest point.
if (point->z > max->z)
{
max->z = point->z;
}
}
void BoundingBox::set(const BoundingBox& box)
{
min = box.min;
max = box.max;
}
void BoundingBox::set(const BoundingSphere& sphere)
{
std::vector<int> v;
v.push_back(0);
std::vector<int> v2 = v;
const Vector3& center = sphere.center;
float radius = sphere.radius;
// Calculate the minimum point for the box.
min.x = center.x - radius;
min.y = center.y - radius;
min.z = center.z - radius;
// Calculate the maximum point for the box.
max.x = center.x + radius;
max.y = center.y + radius;
max.z = center.z + radius;
}
void BoundingBox::transform(const Matrix& matrix)
{
// Calculate the corners.
Vector3 corners[8];
getCorners(corners);
// Transform the corners, recalculating the min and max points along the way.
matrix.transformPoint(&corners[0]);
Vector3 newMin = corners[0];
Vector3 newMax = corners[0];
for (int i = 1; i < 8; i++)
{
matrix.transformPoint(&corners[i]);
updateMinMax(&corners[i], &newMin, &newMax);
}
this->min.x = newMin.x;
this->min.y = newMin.y;
this->min.z = newMin.z;
this->max.x = newMax.x;
this->max.y = newMax.y;
this->max.z = newMax.z;
}
}
<commit_msg>Fixed BoundingBox::intersects(BoundingBox)<commit_after>#include "Base.h"
#include "BoundingBox.h"
#include "BoundingSphere.h"
#include "Plane.h"
namespace gameplay
{
BoundingBox::BoundingBox()
{
}
BoundingBox::BoundingBox(const Vector3& min, const Vector3& max)
{
set(min, max);
}
BoundingBox::BoundingBox(const BoundingBox& copy)
{
set(copy);
}
BoundingBox::~BoundingBox()
{
}
const BoundingBox& BoundingBox::empty()
{
static BoundingBox b;
return b;
}
void BoundingBox::getCorners(Vector3* dst) const
{
assert(dst);
// Near face, specified counter-clockwise looking towards the origin from the positive z-axis.
// Left-top-front.
dst[0].set(min.x, max.y, max.z);
// Left-bottom-front.
dst[1].set(min.x, min.y, max.z);
// Right-bottom-front.
dst[2].set(max.x, min.y, max.z);
// Right-top-front.
dst[3].set(max.x, max.y, max.z);
// Far face, specified counter-clockwise looking towards the origin from the negative z-axis.
// Right-top-back.
dst[4].set(max.x, max.y, min.z);
// Right-bottom-back.
dst[5].set(max.x, min.y, min.z);
// Left-bottom-back.
dst[6].set(min.x, min.y, min.z);
// Left-top-back.
dst[7].set(min.x, max.y, min.z);
}
void BoundingBox::getCenter(Vector3* dst) const
{
dst->set(min, max);
dst->scale(0.5f);
dst->add(min);
}
bool BoundingBox::intersects(const BoundingSphere& sphere) const
{
return sphere.intersects(*this);
}
bool BoundingBox::intersects(const BoundingBox& box) const
{
return ((min.x >= box.min.x && min.x <= box.max.x) || (box.min.x >= min.x && box.min.x <= max.x)) &&
((min.y >= box.min.y && min.y <= box.max.y) || (box.min.y >= min.y && box.min.y <= max.y)) &&
((min.z >= box.min.z && min.z <= box.max.z) || (box.min.z >= min.z && box.min.z <= max.z));
}
bool BoundingBox::intersects(const Frustum& frustum) const
{
// The box must either intersect or be in the positive half-space of all six planes of the frustum.
return (intersects(frustum.getNear()) != Plane::INTERSECTS_BACK &&
intersects(frustum.getFar()) != Plane::INTERSECTS_BACK &&
intersects(frustum.getLeft()) != Plane::INTERSECTS_BACK &&
intersects(frustum.getRight()) != Plane::INTERSECTS_BACK &&
intersects(frustum.getBottom()) != Plane::INTERSECTS_BACK &&
intersects(frustum.getTop()) != Plane::INTERSECTS_BACK);
}
float BoundingBox::intersects(const Plane& plane) const
{
// Calculate the distance from the center of the box to the plane.
Vector3 center((min.x + max.x) * 0.5f, (min.y + max.y) * 0.5f, (min.z + max.z) * 0.5f);
float distance = plane.distance(center);
// Get the extents of the box from its center along each axis.
float extentX = (max.x - min.x) * 0.5f;
float extentY = (max.y - min.y) * 0.5f;
float extentZ = (max.z - min.z) * 0.5f;
const Vector3& planeNormal = plane.getNormal();
if (fabsf(distance) <= (fabsf(extentX * planeNormal.x) + fabsf(extentY * planeNormal.y) + fabsf(
extentZ * planeNormal.z)))
{
return Plane::INTERSECTS_INTERSECTING;
}
return (distance > 0.0f) ? (float)Plane::INTERSECTS_FRONT : (float)Plane::INTERSECTS_BACK;
}
float BoundingBox::intersects(const Ray& ray) const
{
// Intermediate calculation variables.
float dnear = 0.0f;
float dfar = 0.0f;
float tmin = 0.0f;
float tmax = 0.0f;
const Vector3& origin = ray.getOrigin();
const Vector3& direction = ray.getDirection();
// X direction.
float div = 1.0f / direction.x;
if (div >= 0.0f)
{
tmin = (min.x - origin.x) * div;
tmax = (max.x - origin.x) * div;
}
else
{
tmin = (max.x - origin.x) * div;
tmax = (min.x - origin.x) * div;
}
dnear = tmin;
dfar = tmax;
// Check if the ray misses the box.
if (dnear > dfar || dfar < 0.0f)
{
return Ray::INTERSECTS_NONE;
}
// Y direction.
div = 1.0f / direction.y;
if (div >= 0.0f)
{
tmin = (min.y - origin.y) * div;
tmax = (max.y - origin.y) * div;
}
else
{
tmin = (max.y - origin.y) * div;
tmax = (min.y - origin.y) * div;
}
// Update the near and far intersection distances.
if (tmin > dnear)
{
dnear = tmin;
}
if (tmax < dfar)
{
dfar = tmax;
}
// Check if the ray misses the box.
if (dnear > dfar || dfar < 0.0f)
{
return Ray::INTERSECTS_NONE;
}
// Z direction.
div = 1.0f / direction.z;
if (div >= 0.0f)
{
tmin = (min.z - origin.z) * div;
tmax = (max.z - origin.z) * div;
}
else
{
tmin = (max.z - origin.z) * div;
tmax = (min.z - origin.z) * div;
}
// Update the near and far intersection distances.
if (tmin > dnear)
{
dnear = tmin;
}
if (tmax < dfar)
{
dfar = tmax;
}
// Check if the ray misses the box.
if (dnear > dfar || dfar < 0.0f)
{
return Ray::INTERSECTS_NONE;
}
// The ray intersects the box (and since the direction of a Ray is normalized, dnear is the distance to the ray).
return dnear;
}
bool BoundingBox::isEmpty() const
{
return min.x == max.x && min.y == max.y && min.z == max.z;
}
void BoundingBox::merge(const BoundingBox& box)
{
// Calculate the new minimum point.
min.x = std::min(min.x, box.min.x);
min.y = std::min(min.y, box.min.y);
min.z = std::min(min.z, box.min.z);
// Calculate the new maximum point.
max.x = std::max(max.x, box.max.x);
max.y = std::max(max.y, box.max.y);
max.z = std::max(max.z, box.max.z);
}
void BoundingBox::merge(const BoundingSphere& sphere)
{
const Vector3& center = sphere.center;
float radius = sphere.radius;
// Calculate the new minimum point for the merged bounding box.
min.x = std::min(min.x, center.x - radius);
min.y = std::min(min.y, center.y - radius);
min.z = std::min(min.z, center.z - radius);
// Calculate the new maximum point for the merged bounding box.
max.x = std::max(max.x, center.x + radius);
max.y = std::max(max.y, center.y + radius);
max.z = std::max(max.z, center.z + radius);
}
void BoundingBox::set(const Vector3& min, const Vector3& max)
{
this->min = min;
this->max = max;
}
void updateMinMax(Vector3* point, Vector3* min, Vector3* max)
{
// Leftmost point.
if (point->x < min->x)
{
min->x = point->x;
}
// Rightmost point.
if (point->x > max->x)
{
max->x = point->x;
}
// Lowest point.
if (point->y < min->y)
{
min->y = point->y;
}
// Highest point.
if (point->y > max->y)
{
max->y = point->y;
}
// Farthest point.
if (point->z < min->z)
{
min->z = point->z;
}
// Nearest point.
if (point->z > max->z)
{
max->z = point->z;
}
}
void BoundingBox::set(const BoundingBox& box)
{
min = box.min;
max = box.max;
}
void BoundingBox::set(const BoundingSphere& sphere)
{
std::vector<int> v;
v.push_back(0);
std::vector<int> v2 = v;
const Vector3& center = sphere.center;
float radius = sphere.radius;
// Calculate the minimum point for the box.
min.x = center.x - radius;
min.y = center.y - radius;
min.z = center.z - radius;
// Calculate the maximum point for the box.
max.x = center.x + radius;
max.y = center.y + radius;
max.z = center.z + radius;
}
void BoundingBox::transform(const Matrix& matrix)
{
// Calculate the corners.
Vector3 corners[8];
getCorners(corners);
// Transform the corners, recalculating the min and max points along the way.
matrix.transformPoint(&corners[0]);
Vector3 newMin = corners[0];
Vector3 newMax = corners[0];
for (int i = 1; i < 8; i++)
{
matrix.transformPoint(&corners[i]);
updateMinMax(&corners[i], &newMin, &newMax);
}
this->min.x = newMin.x;
this->min.y = newMin.y;
this->min.z = newMin.z;
this->max.x = newMax.x;
this->max.y = newMax.y;
this->max.z = newMax.z;
}
}
<|endoftext|> |
<commit_before>/*****************************************************************************
* Licensed to Qualys, Inc. (QUALYS) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* QUALYS licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
****************************************************************************/
/**
* @file
* @brief IronBee --- CLIPP Configuration Parser Implementation
*
* @author Christopher Alfeld <calfeld@qualys.com>
*/
#include "configuration_parser.hpp"
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix.hpp>
#include <boost/fusion/adapted.hpp>
#include <fstream>
using namespace std;
BOOST_FUSION_ADAPT_STRUCT(
IronBee::CLIPP::ConfigurationParser::component_t,
(string, name)
(string, arg)
)
BOOST_FUSION_ADAPT_STRUCT(
IronBee::CLIPP::ConfigurationParser::chain_t,
(IronBee::CLIPP::ConfigurationParser::component_t, base)
(IronBee::CLIPP::ConfigurationParser::component_vec_t, modifiers)
)
namespace IronBee {
namespace CLIPP {
namespace ConfigurationParser {
namespace {
chain_vec_t parse(const std::string& input)
{
using namespace boost::spirit;
using ascii::char_;
using ascii::space;
using qi::lit;
using qi::_1;
using qi::_2;
using qi::_val;
using qi::lexeme;
using qi::omit;
using boost::phoenix::push_back;
typedef string::const_iterator iterator;
typedef qi::rule<iterator, char()> char_rule;
typedef qi::rule<iterator, string()> string_rule;
typedef qi::rule<iterator, component_t()> component_rule;
typedef qi::rule<iterator, chain_t()> chain_rule;
typedef qi::rule<iterator, component_vec_t()> component_vec_rule;
typedef qi::rule<iterator, chain_vec_t()> chains_rule;
char_rule escaped = lit('\\') >> char_;
string_rule quoted_cfg_string =
lit('"') >> +(escaped | (char_ - '"')) >> '"';
string_rule unquoted_cfg_string =
+(char_ - '@' - space - '"');
string_rule cfg_string;
cfg_string = lexeme[
(unquoted_cfg_string >> -cfg_string) |
(quoted_cfg_string >> -cfg_string)
];
component_rule component =
+(char_ - ':' - space) >> -(':' >> -cfg_string);
component_rule modifier = lit('@') >> component;
component_rule base = component;
component_vec_rule modifiers =
*(omit[*space] >> modifier >> omit[*space]);
chain_rule chain = base >> omit[*space] >> modifiers;
chains_rule chains = *(omit[*space] >> chain >> omit[*space]);
chain_vec_t result;
iterator begin = input.begin();
iterator end = input.end();
bool success = qi::parse(
begin, end,
chains,
result
);
if (! success) {
size_t pos = begin - input.begin();
throw runtime_error(
"Parsing failed, next text = " + input.substr(pos, 100)
);
}
if (begin != end) {
size_t pos = begin - input.begin();
throw runtime_error(
"Parsing did not consumer all input. next text = " +
input.substr(pos, 100)
);
}
return result;
}
} // Anonymous
chain_vec_t parse_string(const std::string& input)
{
return parse(input);
}
chain_vec_t parse_file(const std::string& path)
{
ifstream in(path.c_str());
if (! in) {
throw runtime_error("Could not open " + path + " for reading.");
}
string input;
string line;
while (in) {
getline(in, line);
size_t pos = line.find_first_not_of(' ');
if (pos != string::npos && line[pos] != '#') {
input += line;
input += " ";
}
}
return parse_string(input);
}
} // ConfigurationParser
} // CLIPP
} // IronBee
<commit_msg>clipp/configuration_parser.cpp: Fix typo.<commit_after>/*****************************************************************************
* Licensed to Qualys, Inc. (QUALYS) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* QUALYS licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
****************************************************************************/
/**
* @file
* @brief IronBee --- CLIPP Configuration Parser Implementation
*
* @author Christopher Alfeld <calfeld@qualys.com>
*/
#include "configuration_parser.hpp"
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix.hpp>
#include <boost/fusion/adapted.hpp>
#include <fstream>
using namespace std;
BOOST_FUSION_ADAPT_STRUCT(
IronBee::CLIPP::ConfigurationParser::component_t,
(string, name)
(string, arg)
)
BOOST_FUSION_ADAPT_STRUCT(
IronBee::CLIPP::ConfigurationParser::chain_t,
(IronBee::CLIPP::ConfigurationParser::component_t, base)
(IronBee::CLIPP::ConfigurationParser::component_vec_t, modifiers)
)
namespace IronBee {
namespace CLIPP {
namespace ConfigurationParser {
namespace {
chain_vec_t parse(const std::string& input)
{
using namespace boost::spirit;
using ascii::char_;
using ascii::space;
using qi::lit;
using qi::_1;
using qi::_2;
using qi::_val;
using qi::lexeme;
using qi::omit;
using boost::phoenix::push_back;
typedef string::const_iterator iterator;
typedef qi::rule<iterator, char()> char_rule;
typedef qi::rule<iterator, string()> string_rule;
typedef qi::rule<iterator, component_t()> component_rule;
typedef qi::rule<iterator, chain_t()> chain_rule;
typedef qi::rule<iterator, component_vec_t()> component_vec_rule;
typedef qi::rule<iterator, chain_vec_t()> chains_rule;
char_rule escaped = lit('\\') >> char_;
string_rule quoted_cfg_string =
lit('"') >> +(escaped | (char_ - '"')) >> '"';
string_rule unquoted_cfg_string =
+(char_ - '@' - space - '"');
string_rule cfg_string;
cfg_string = lexeme[
(unquoted_cfg_string >> -cfg_string) |
(quoted_cfg_string >> -cfg_string)
];
component_rule component =
+(char_ - ':' - space) >> -(':' >> -cfg_string);
component_rule modifier = lit('@') >> component;
component_rule base = component;
component_vec_rule modifiers =
*(omit[*space] >> modifier >> omit[*space]);
chain_rule chain = base >> omit[*space] >> modifiers;
chains_rule chains = *(omit[*space] >> chain >> omit[*space]);
chain_vec_t result;
iterator begin = input.begin();
iterator end = input.end();
bool success = qi::parse(
begin, end,
chains,
result
);
if (! success) {
size_t pos = begin - input.begin();
throw runtime_error(
"Parsing failed, next text = " + input.substr(pos, 100)
);
}
if (begin != end) {
size_t pos = begin - input.begin();
throw runtime_error(
"Parsing did not consume all input. next text = " +
input.substr(pos, 100)
);
}
return result;
}
} // Anonymous
chain_vec_t parse_string(const std::string& input)
{
return parse(input);
}
chain_vec_t parse_file(const std::string& path)
{
ifstream in(path.c_str());
if (! in) {
throw runtime_error("Could not open " + path + " for reading.");
}
string input;
string line;
while (in) {
getline(in, line);
size_t pos = line.find_first_not_of(' ');
if (pos != string::npos && line[pos] != '#') {
input += line;
input += " ";
}
}
return parse_string(input);
}
} // ConfigurationParser
} // CLIPP
} // IronBee
<|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 <stdio.h>
#include <cstdlib>
#include "gtest/gtest.h"
#include "webrtc/common_video/libyuv/include/webrtc_libyuv.h"
#include "webrtc/system_wrappers/interface/scoped_ptr.h"
#include "webrtc/test/testsupport/fileutils.h"
#include "webrtc/tools/frame_editing/frame_editing_lib.h"
namespace webrtc {
namespace test {
const int kWidth = 352;
const int kHeight = 288;
const int kFrameSize = CalcBufferSize(kI420, kWidth, kHeight);
const std::string kRefVideo = ResourcePath("foreman_cif", "yuv");
const std::string kTestVideo = OutputPath() + "testvideo.yuv";
class FrameEditingTest : public ::testing::Test {
protected:
virtual void SetUp() {
original_fid_ = fopen(kRefVideo.c_str(), "rb");
ASSERT_TRUE(original_fid_ != NULL);
edited_fid_ = fopen(kTestVideo.c_str(), "rb");
ASSERT_TRUE(edited_fid_ != NULL);
original_buffer_.reset(new int[kFrameSize]);
edited_buffer_.reset(new int[kFrameSize]);
num_frames_read_ = 0;
}
virtual void TearDown() {
fclose(original_fid_);
fclose(edited_fid_);
}
// Compares the frames in both streams to the end of one of the streams.
void CompareToTheEnd(FILE* test_video_fid, FILE* ref_video_fid,
scoped_array<int>* ref_buffer,
scoped_array<int>* test_buffer) {
while (!feof(test_video_fid) && !feof(ref_video_fid)) {
num_bytes_read_ = fread(ref_buffer->get(), 1, kFrameSize, ref_video_fid);
if (!feof(ref_video_fid)) {
EXPECT_EQ(kFrameSize, num_bytes_read_);
}
num_bytes_read_ = fread(test_buffer->get(), 1, kFrameSize,
test_video_fid);
if (!feof(test_video_fid)) {
EXPECT_EQ(kFrameSize, num_bytes_read_);
}
if (!feof(test_video_fid) && !feof(test_video_fid)) {
EXPECT_EQ(0, memcmp(ref_buffer->get(), test_buffer->get(),
kFrameSize));
}
}
// There should not be anything left in either stream.
EXPECT_EQ(!feof(test_video_fid), !feof(ref_video_fid));
}
FILE* original_fid_;
FILE* edited_fid_;
int kFrameSize_;
int num_bytes_read_;
scoped_array<int> original_buffer_;
scoped_array<int> edited_buffer_;
int num_frames_read_;
};
TEST_F(FrameEditingTest, ValidInPath) {
const int kFirstFrameToProcess = 160;
const int kInterval = -1;
const int kLastFrameToProcess = 240;
int result = EditFrames(kRefVideo, kWidth, kHeight, kFirstFrameToProcess,
kInterval, kLastFrameToProcess, kTestVideo);
EXPECT_EQ(0, result);
for (int i = 1; i < kFirstFrameToProcess; ++i) {
num_bytes_read_ = fread(original_buffer_.get(), 1, kFrameSize,
original_fid_);
EXPECT_EQ(kFrameSize, num_bytes_read_);
num_bytes_read_ = fread(edited_buffer_.get(), 1, kFrameSize, edited_fid_);
EXPECT_EQ(kFrameSize, num_bytes_read_);
EXPECT_EQ(0, memcmp(original_buffer_.get(), edited_buffer_.get(),
kFrameSize));
}
// Do not compare the frames that have been cut.
for (int i = kFirstFrameToProcess; i <= kLastFrameToProcess; ++i) {
num_bytes_read_ = fread(original_buffer_.get(), 1, kFrameSize,
original_fid_);
EXPECT_EQ(kFrameSize, num_bytes_read_);
}
CompareToTheEnd(edited_fid_, original_fid_, &original_buffer_,
&edited_buffer_);
}
TEST_F(FrameEditingTest, EmptySetToCut) {
const int kFirstFrameToProcess = 2;
const int kInterval = -1;
const int kLastFrameToProcess = 1;
int result = EditFrames(kRefVideo, kWidth, kHeight, kFirstFrameToProcess,
kInterval, kLastFrameToProcess, kTestVideo);
EXPECT_EQ(-10, result);
}
TEST_F(FrameEditingTest, InValidInPath) {
const std::string kRefVideo = "PATH/THAT/DOES/NOT/EXIST";
const int kFirstFrameToProcess = 30;
const int kInterval = 1;
const int kLastFrameToProcess = 120;
int result = EditFrames(kRefVideo, kWidth, kHeight, kFirstFrameToProcess,
kInterval, kLastFrameToProcess, kTestVideo);
EXPECT_EQ(-11, result);
}
TEST_F(FrameEditingTest, DeletingEverySecondFrame) {
const int kFirstFrameToProcess = 1;
const int kInterval = -2;
const int kLastFrameToProcess = 10000;
// Set kLastFrameToProcess to a large value so that all frame are processed.
int result = EditFrames(kRefVideo, kWidth, kHeight, kFirstFrameToProcess,
kInterval, kLastFrameToProcess, kTestVideo);
EXPECT_EQ(0, result);
while (!feof(original_fid_) && !feof(edited_fid_)) {
num_bytes_read_ =
fread(original_buffer_.get(), 1, kFrameSize, original_fid_);
if (!feof(original_fid_)) {
EXPECT_EQ(kFrameSize, num_bytes_read_);
num_frames_read_++;
}
// We want to compare every second frame of the original to the edited.
// kInterval=-2 and (num_frames_read_ - 1) % kInterval will be -1 for
// every second frame.
// num_frames_read_ - 1 because we have deleted frame number 2, 4 , 6 etc.
if ((num_frames_read_ - 1) % kInterval == -1) {
num_bytes_read_ = fread(edited_buffer_.get(), 1, kFrameSize,
edited_fid_);
if (!feof(edited_fid_)) {
EXPECT_EQ(kFrameSize, num_bytes_read_);
}
if (!feof(original_fid_) && !feof(edited_fid_)) {
EXPECT_EQ(0, memcmp(original_buffer_.get(),
edited_buffer_.get(), kFrameSize));
}
}
}
}
TEST_F(FrameEditingTest, RepeatFrames) {
const int kFirstFrameToProcess = 160;
const int kInterval = 2;
const int kLastFrameToProcess = 240;
int result = EditFrames(kRefVideo, kWidth, kHeight, kFirstFrameToProcess,
kInterval, kLastFrameToProcess, kTestVideo);
EXPECT_EQ(0, result);
for (int i = 1; i < kFirstFrameToProcess; ++i) {
num_bytes_read_ = fread(original_buffer_.get(), 1, kFrameSize,
original_fid_);
EXPECT_EQ(kFrameSize, num_bytes_read_);
num_bytes_read_ = fread(edited_buffer_.get(), 1, kFrameSize, edited_fid_);
EXPECT_EQ(kFrameSize, num_bytes_read_);
EXPECT_EQ(0, memcmp(original_buffer_.get(), edited_buffer_.get(),
kFrameSize));
}
// Do not compare the frames that have been repeated.
for (int i = kFirstFrameToProcess; i <= kLastFrameToProcess; ++i) {
num_bytes_read_ = fread(original_buffer_.get(), 1, kFrameSize,
original_fid_);
EXPECT_EQ(kFrameSize, num_bytes_read_);
for (int i = 1; i <= kInterval; ++i) {
num_bytes_read_ = fread(edited_buffer_.get(), 1, kFrameSize,
edited_fid_);
EXPECT_EQ(kFrameSize, num_bytes_read_);
EXPECT_EQ(0, memcmp(original_buffer_.get(), edited_buffer_.get(),
kFrameSize));
}
}
CompareToTheEnd(edited_fid_, original_fid_, &original_buffer_,
&edited_buffer_);
}
} // namespace test
} // namespace webrtc
<commit_msg>Fix frame_editing_unittest.cc<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 <stdio.h>
#include <cstdlib>
#include <fstream>
#include "gtest/gtest.h"
#include "webrtc/common_video/libyuv/include/webrtc_libyuv.h"
#include "webrtc/system_wrappers/interface/scoped_ptr.h"
#include "webrtc/test/testsupport/fileutils.h"
#include "webrtc/tools/frame_editing/frame_editing_lib.h"
namespace webrtc {
namespace test {
const int kWidth = 352;
const int kHeight = 288;
const int kFrameSize = CalcBufferSize(kI420, kWidth, kHeight);
const std::string kRefVideo = ResourcePath("foreman_cif", "yuv");
const std::string kTestVideo = OutputPath() + "testvideo.yuv";
class FrameEditingTest : public ::testing::Test {
protected:
virtual void SetUp() {
original_fid_ = fopen(kRefVideo.c_str(), "rb");
ASSERT_TRUE(original_fid_ != NULL);
// Ensure the output file exists on disk.
std::ofstream(kTestVideo.c_str(), std::ios::out);
// Open the output file for reading.
// TODO(holmer): Figure out why this file has to be opened here (test fails
// if it's opened after the write operation performed in EditFrames).
edited_fid_ = fopen(kTestVideo.c_str(), "rb");
ASSERT_TRUE(edited_fid_ != NULL);
original_buffer_.reset(new int[kFrameSize]);
edited_buffer_.reset(new int[kFrameSize]);
num_frames_read_ = 0;
}
virtual void TearDown() {
fclose(original_fid_);
fclose(edited_fid_);
}
// Compares the frames in both streams to the end of one of the streams.
void CompareToTheEnd(FILE* test_video_fid, FILE* ref_video_fid,
scoped_array<int>* ref_buffer,
scoped_array<int>* test_buffer) {
while (!feof(test_video_fid) && !feof(ref_video_fid)) {
num_bytes_read_ = fread(ref_buffer->get(), 1, kFrameSize, ref_video_fid);
if (!feof(ref_video_fid)) {
EXPECT_EQ(kFrameSize, num_bytes_read_);
}
num_bytes_read_ = fread(test_buffer->get(), 1, kFrameSize,
test_video_fid);
if (!feof(test_video_fid)) {
EXPECT_EQ(kFrameSize, num_bytes_read_);
}
if (!feof(test_video_fid) && !feof(test_video_fid)) {
EXPECT_EQ(0, memcmp(ref_buffer->get(), test_buffer->get(),
kFrameSize));
}
}
// There should not be anything left in either stream.
EXPECT_EQ(!feof(test_video_fid), !feof(ref_video_fid));
}
FILE* original_fid_;
FILE* edited_fid_;
int kFrameSize_;
int num_bytes_read_;
scoped_array<int> original_buffer_;
scoped_array<int> edited_buffer_;
int num_frames_read_;
};
TEST_F(FrameEditingTest, ValidInPath) {
const int kFirstFrameToProcess = 160;
const int kInterval = -1;
const int kLastFrameToProcess = 240;
int result = EditFrames(kRefVideo, kWidth, kHeight, kFirstFrameToProcess,
kInterval, kLastFrameToProcess, kTestVideo);
EXPECT_EQ(0, result);
for (int i = 1; i < kFirstFrameToProcess; ++i) {
num_bytes_read_ = fread(original_buffer_.get(), 1, kFrameSize,
original_fid_);
EXPECT_EQ(kFrameSize, num_bytes_read_);
num_bytes_read_ = fread(edited_buffer_.get(), 1, kFrameSize, edited_fid_);
EXPECT_EQ(kFrameSize, num_bytes_read_);
EXPECT_EQ(0, memcmp(original_buffer_.get(), edited_buffer_.get(),
kFrameSize));
}
// Do not compare the frames that have been cut.
for (int i = kFirstFrameToProcess; i <= kLastFrameToProcess; ++i) {
num_bytes_read_ = fread(original_buffer_.get(), 1, kFrameSize,
original_fid_);
EXPECT_EQ(kFrameSize, num_bytes_read_);
}
CompareToTheEnd(edited_fid_, original_fid_, &original_buffer_,
&edited_buffer_);
}
TEST_F(FrameEditingTest, EmptySetToCut) {
const int kFirstFrameToProcess = 2;
const int kInterval = -1;
const int kLastFrameToProcess = 1;
int result = EditFrames(kRefVideo, kWidth, kHeight, kFirstFrameToProcess,
kInterval, kLastFrameToProcess, kTestVideo);
EXPECT_EQ(-10, result);
}
TEST_F(FrameEditingTest, InValidInPath) {
const std::string kRefVideo = "PATH/THAT/DOES/NOT/EXIST";
const int kFirstFrameToProcess = 30;
const int kInterval = 1;
const int kLastFrameToProcess = 120;
int result = EditFrames(kRefVideo, kWidth, kHeight, kFirstFrameToProcess,
kInterval, kLastFrameToProcess, kTestVideo);
EXPECT_EQ(-11, result);
}
TEST_F(FrameEditingTest, DeletingEverySecondFrame) {
const int kFirstFrameToProcess = 1;
const int kInterval = -2;
const int kLastFrameToProcess = 10000;
// Set kLastFrameToProcess to a large value so that all frame are processed.
int result = EditFrames(kRefVideo, kWidth, kHeight, kFirstFrameToProcess,
kInterval, kLastFrameToProcess, kTestVideo);
EXPECT_EQ(0, result);
while (!feof(original_fid_) && !feof(edited_fid_)) {
num_bytes_read_ =
fread(original_buffer_.get(), 1, kFrameSize, original_fid_);
if (!feof(original_fid_)) {
EXPECT_EQ(kFrameSize, num_bytes_read_);
num_frames_read_++;
}
// We want to compare every second frame of the original to the edited.
// kInterval=-2 and (num_frames_read_ - 1) % kInterval will be -1 for
// every second frame.
// num_frames_read_ - 1 because we have deleted frame number 2, 4 , 6 etc.
if ((num_frames_read_ - 1) % kInterval == -1) {
num_bytes_read_ = fread(edited_buffer_.get(), 1, kFrameSize,
edited_fid_);
if (!feof(edited_fid_)) {
EXPECT_EQ(kFrameSize, num_bytes_read_);
}
if (!feof(original_fid_) && !feof(edited_fid_)) {
EXPECT_EQ(0, memcmp(original_buffer_.get(),
edited_buffer_.get(), kFrameSize));
}
}
}
}
TEST_F(FrameEditingTest, RepeatFrames) {
const int kFirstFrameToProcess = 160;
const int kInterval = 2;
const int kLastFrameToProcess = 240;
int result = EditFrames(kRefVideo, kWidth, kHeight, kFirstFrameToProcess,
kInterval, kLastFrameToProcess, kTestVideo);
EXPECT_EQ(0, result);
for (int i = 1; i < kFirstFrameToProcess; ++i) {
num_bytes_read_ = fread(original_buffer_.get(), 1, kFrameSize,
original_fid_);
EXPECT_EQ(kFrameSize, num_bytes_read_);
num_bytes_read_ = fread(edited_buffer_.get(), 1, kFrameSize, edited_fid_);
EXPECT_EQ(kFrameSize, num_bytes_read_);
EXPECT_EQ(0, memcmp(original_buffer_.get(), edited_buffer_.get(),
kFrameSize));
}
// Do not compare the frames that have been repeated.
for (int i = kFirstFrameToProcess; i <= kLastFrameToProcess; ++i) {
num_bytes_read_ = fread(original_buffer_.get(), 1, kFrameSize,
original_fid_);
EXPECT_EQ(kFrameSize, num_bytes_read_);
for (int i = 1; i <= kInterval; ++i) {
num_bytes_read_ = fread(edited_buffer_.get(), 1, kFrameSize,
edited_fid_);
EXPECT_EQ(kFrameSize, num_bytes_read_);
EXPECT_EQ(0, memcmp(original_buffer_.get(), edited_buffer_.get(),
kFrameSize));
}
}
CompareToTheEnd(edited_fid_, original_fid_, &original_buffer_,
&edited_buffer_);
}
} // namespace test
} // namespace webrtc
<|endoftext|> |
<commit_before>//
// CartridgePitfall2.h
// Clock Signal
//
// Created by Thomas Harte on 18/03/2017.
// Copyright © 2017 Thomas Harte. All rights reserved.
//
#ifndef Atari2600_CartridgePitfall2_hpp
#define Atari2600_CartridgePitfall2_hpp
namespace Atari2600 {
class CartridgePitfall2: public Cartridge<CartridgePitfall2> {
public:
CartridgePitfall2(const std::vector<uint8_t> &rom) :
Cartridge(rom),
random_number_generator_(0),
featcher_address_{0, 0, 0, 0, 0, 0, 0, 0} {
rom_ptr_ = rom_.data();
}
void perform_bus_operation(CPU6502::BusOperation operation, uint16_t address, uint8_t *value) {
address &= 0x1fff;
if(!(address & 0x1000)) return;
switch(address) {
#pragma mark - Reads
// The random number generator
case 0x1000: case 0x1001: case 0x1002: case 0x1003: case 0x1004:
if(isReadOperation(operation)) {
*value = random_number_generator_;
}
random_number_generator_ = (uint8_t)(
(random_number_generator_ << 1) |
~(( (random_number_generator_ >> 7) ^
(random_number_generator_ >> 5) ^
(random_number_generator_ >> 4) ^
(random_number_generator_ >> 3)
) & 1));
break;
// Music fetcher
case 0x1005: case 0x1006: case 0x1007:
*value = 0x00;
break;
case 0x1008: case 0x1009: case 0x100a: case 0x100b: case 0x100c: case 0x100d: case 0x100e: case 0x100f:
*value = 0x20;
break;
case 0x1010: case 0x1011: case 0x1012: case 0x1013: case 0x1014: case 0x1015: case 0x1016: case 0x1017:
*value = 0x40;
break;
#pragma mark - Writes
case 0x1040: case 0x1041: case 0x1042: case 0x1043: case 0x1044: case 0x1045: case 0x1046: case 0x1047:
top_[address & 7] = *value;
break;
case 0x1048: case 0x1049: case 0x104a: case 0x104b: case 0x104c: case 0x104d: case 0x104e: case 0x104f:
bottom_[address & 7] = *value;
break;
case 0x1050: case 0x1051: case 0x1052: case 0x1053: case 0x1054: case 0x1055: case 0x1056: case 0x1057:
featcher_address_[address & 7] = (featcher_address_[address & 7] & 0xff00) | *value;
break;
case 0x1058: case 0x1059: case 0x105a: case 0x105b: case 0x105c: case 0x105d: case 0x105e: case 0x105f:
featcher_address_[address & 7] = (featcher_address_[address & 7] & 0x00ff) | (uint16_t)(*value << 8);
break;
case 0x1070: case 0x1071: case 0x1072: case 0x1073: case 0x1074: case 0x1075: case 0x1076: case 0x1077:
random_number_generator_ = 0;
break;
#pragma mark - Paging
case 0x1ff8: rom_ptr_ = rom_.data(); break;
case 0x1ff9: rom_ptr_ = rom_.data() + 4096; break;
#pragma mark - Business as usual
default:
if(isReadOperation(operation)) {
*value = rom_ptr_[address & 4095];
}
break;
}
}
private:
uint16_t featcher_address_[8];
uint8_t top_[8], bottom_[8];
uint8_t music_mode_[3];
uint8_t random_number_generator_;
uint8_t *rom_ptr_;
};
}
#endif /* Atari2600_CartridgePitfall2_hpp */
<commit_msg>This gives something that might be the correct background.<commit_after>//
// CartridgePitfall2.h
// Clock Signal
//
// Created by Thomas Harte on 18/03/2017.
// Copyright © 2017 Thomas Harte. All rights reserved.
//
#ifndef Atari2600_CartridgePitfall2_hpp
#define Atari2600_CartridgePitfall2_hpp
namespace Atari2600 {
class CartridgePitfall2: public Cartridge<CartridgePitfall2> {
public:
CartridgePitfall2(const std::vector<uint8_t> &rom) :
Cartridge(rom),
random_number_generator_(0),
featcher_address_{0, 0, 0, 0, 0, 0, 0, 0} {
rom_ptr_ = rom_.data();
}
void perform_bus_operation(CPU6502::BusOperation operation, uint16_t address, uint8_t *value) {
address &= 0x1fff;
if(!(address & 0x1000)) return;
switch(address) {
#pragma mark - Reads
// The random number generator
case 0x1000: case 0x1001: case 0x1002: case 0x1003: case 0x1004:
if(isReadOperation(operation)) {
*value = random_number_generator_;
}
random_number_generator_ = (uint8_t)(
(random_number_generator_ << 1) |
~(( (random_number_generator_ >> 7) ^
(random_number_generator_ >> 5) ^
(random_number_generator_ >> 4) ^
(random_number_generator_ >> 3)
) & 1));
break;
// Music fetcher
case 0x1005: case 0x1006: case 0x1007:
*value = 0x00;
break;
case 0x1008: case 0x1009: case 0x100a: case 0x100b: case 0x100c: case 0x100d: case 0x100e: case 0x100f: {
uint16_t fetch_address = (featcher_address_[address & 7] & 2047) ^ 2047;
featcher_address_[address & 7]--;
*value = rom_[8192 + fetch_address];
} break;
case 0x1010: case 0x1011: case 0x1012: case 0x1013: case 0x1014: case 0x1015: case 0x1016: case 0x1017:
*value = 0xff;
break;
#pragma mark - Writes
case 0x1040: case 0x1041: case 0x1042: case 0x1043: case 0x1044: case 0x1045: case 0x1046: case 0x1047:
top_[address & 7] = *value;
break;
case 0x1048: case 0x1049: case 0x104a: case 0x104b: case 0x104c: case 0x104d: case 0x104e: case 0x104f:
bottom_[address & 7] = *value;
break;
case 0x1050: case 0x1051: case 0x1052: case 0x1053: case 0x1054: case 0x1055: case 0x1056: case 0x1057:
featcher_address_[address & 7] = (featcher_address_[address & 7] & 0xff00) | *value;
break;
case 0x1058: case 0x1059: case 0x105a: case 0x105b: case 0x105c: case 0x105d: case 0x105e: case 0x105f:
featcher_address_[address & 7] = (featcher_address_[address & 7] & 0x00ff) | (uint16_t)(*value << 8);
break;
case 0x1070: case 0x1071: case 0x1072: case 0x1073: case 0x1074: case 0x1075: case 0x1076: case 0x1077:
random_number_generator_ = 0;
break;
#pragma mark - Paging
case 0x1ff8: rom_ptr_ = rom_.data(); break;
case 0x1ff9: rom_ptr_ = rom_.data() + 4096; break;
#pragma mark - Business as usual
default:
if(isReadOperation(operation)) {
*value = rom_ptr_[address & 4095];
}
break;
}
}
private:
uint16_t featcher_address_[8];
uint8_t top_[8], bottom_[8];
uint8_t music_mode_[3];
uint8_t random_number_generator_;
uint8_t *rom_ptr_;
};
}
#endif /* Atari2600_CartridgePitfall2_hpp */
<|endoftext|> |
<commit_before>//Fitting a TGraph2D
//Author: Olivier Couet
#include <TMath.h>
#include <TGraph2D.h>
#include <TRandom.h>
#include <TStyle.h>
#include <TCanvas.h>
#include <TF2.h>
#include <TH1.h>
TCanvas* graph2dfit()
{
gStyle->SetOptStat(0);
gStyle->SetOptFit();
TCanvas *c = new TCanvas("c","Graph2D example",0,0,800,800);
c->Divide(2,3);
Double_t rnd, x, y, z;
Double_t e = 0.3;
Int_t nd = 400;
Int_t np = 10000;
TRandom r;
Double_t fl = 6;
TF2 *f2 = new TF2("f2","1000*(([0]*sin(x)/x)*([1]*sin(y)/y))+200",
-fl,fl,-fl,fl);
f2->SetParameters(1,1);
TGraph2D *dt = new TGraph2D();
// Fill the 2D graph
Double_t zmax = 0;
for (Int_t N=0; N<nd; N++) {
f2->GetRandom2(x,y);
// Generate a random number in [-e,e]
rnd = 2*r.Rndm()*e-e;
z = f2->Eval(x,y)*(1+rnd);
if (z>zmax) zmax = z;
dt->SetPoint(N,x,y,z);
}
Double_t hr = 350;
TH1D *h1 = new TH1D("h1",
"#splitline{Difference between Original function}{and Function with noise}",
100, -hr, hr);
TH1D *h2 = new TH1D("h2",
"#splitline{Difference between Original function}{and Interpolation with Delaunay triangles}",
100, -hr, hr);
TH1D *h3 = new TH1D("h3",
"#splitline{Difference between Original function}{and Minuit fit}",
500, -hr, hr);
f2->SetParameters(0.5,1.5);
dt->Fit(f2);
TF2 *fit2 = (TF2*)dt->FindObject("f2");
f2->SetParameters(1,1);
for (Int_t N=0; N<np; N++) {
f2->GetRandom2(x,y);
// Generate a random number in [-e,e]
rnd = 2*r.Rndm()*e-e;
z = f2->Eval(x,y)*(1+rnd);
h1->Fill(f2->Eval(x,y)-z);
z = dt->Interpolate(x,y);
h2->Fill(f2->Eval(x,y)-z);
z = fit2->Eval(x,y);
h3->Fill(f2->Eval(x,y)-z);
}
gStyle->SetPalette(1);
c->cd(1);
f2->SetTitle("Original function with Graph2D points on top");
f2->SetMaximum(zmax);
gStyle->SetHistTopMargin(0);
f2->Draw("surf1");
dt->Draw("same p0");
c->cd(3);
dt->SetMargin(0.1);
dt->SetFillColor(36);
dt->SetTitle("Histogram produced with Delaunay interpolation");
dt->Draw("surf4");
c->cd(5);
fit2->SetTitle("Minuit fit result on the Graph2D points");
fit2->Draw("surf1");
h1->SetFillColor(47);
h2->SetFillColor(38);
h3->SetFillColor(29);
c->cd(2); h1->Fit("gaus","Q") ; h1->Draw();
c->cd(4); h2->Fit("gaus","Q") ; h2->Draw();
c->cd(6); h3->Fit("gaus","Q") ; h3->Draw();
c->cd();
return c;
}
<commit_msg>- This macro is used by the TGraph2D ref manual page. The canvas produced was too large for that page.<commit_after>//Fitting a TGraph2D
//Author: Olivier Couet
#include <TMath.h>
#include <TGraph2D.h>
#include <TRandom.h>
#include <TStyle.h>
#include <TCanvas.h>
#include <TF2.h>
#include <TH1.h>
TCanvas* graph2dfit()
{
gStyle->SetOptStat(0);
gStyle->SetOptFit();
TCanvas *c = new TCanvas("c","Graph2D example",0,0,600,800);
c->Divide(2,3);
Double_t rnd, x, y, z;
Double_t e = 0.3;
Int_t nd = 400;
Int_t np = 10000;
TRandom r;
Double_t fl = 6;
TF2 *f2 = new TF2("f2","1000*(([0]*sin(x)/x)*([1]*sin(y)/y))+200",
-fl,fl,-fl,fl);
f2->SetParameters(1,1);
TGraph2D *dt = new TGraph2D();
// Fill the 2D graph
Double_t zmax = 0;
for (Int_t N=0; N<nd; N++) {
f2->GetRandom2(x,y);
// Generate a random number in [-e,e]
rnd = 2*r.Rndm()*e-e;
z = f2->Eval(x,y)*(1+rnd);
if (z>zmax) zmax = z;
dt->SetPoint(N,x,y,z);
}
Double_t hr = 350;
TH1D *h1 = new TH1D("h1",
"#splitline{Difference between Original}{#splitline{function and Function}{with noise}}",
100, -hr, hr);
TH1D *h2 = new TH1D("h2",
"#splitline{Difference between Original}{#splitline{function and Delaunay triangles}{interpolation}}",
100, -hr, hr);
TH1D *h3 = new TH1D("h3",
"#splitline{Difference between Original}{function and Minuit fit}",
500, -hr, hr);
f2->SetParameters(0.5,1.5);
dt->Fit(f2);
TF2 *fit2 = (TF2*)dt->FindObject("f2");
f2->SetParameters(1,1);
for (Int_t N=0; N<np; N++) {
f2->GetRandom2(x,y);
// Generate a random number in [-e,e]
rnd = 2*r.Rndm()*e-e;
z = f2->Eval(x,y)*(1+rnd);
h1->Fill(f2->Eval(x,y)-z);
z = dt->Interpolate(x,y);
h2->Fill(f2->Eval(x,y)-z);
z = fit2->Eval(x,y);
h3->Fill(f2->Eval(x,y)-z);
}
gStyle->SetPalette(1);
c->cd(1);
f2->SetTitle("Original function with Graph2D points on top");
f2->SetMaximum(zmax);
gStyle->SetHistTopMargin(0);
f2->Draw("surf1");
dt->Draw("same p0");
c->cd(3);
dt->SetMargin(0.1);
dt->SetFillColor(36);
dt->SetTitle("Histogram produced with Delaunay interpolation");
dt->Draw("surf4");
c->cd(5);
fit2->SetTitle("Minuit fit result on the Graph2D points");
fit2->Draw("surf1");
h1->SetFillColor(47);
h2->SetFillColor(38);
h3->SetFillColor(29);
c->cd(2); h1->Fit("gaus","Q") ; h1->Draw();
c->cd(4); h2->Fit("gaus","Q") ; h2->Draw();
c->cd(6); h3->Fit("gaus","Q") ; h3->Draw();
c->cd();
return c;
}
<|endoftext|> |
<commit_before>// ConstrainedObject.cpp
// Copyright (c) 2009, Dan Heeks
// This program is released under the BSD license. See the file COPYING for details.
#include "stdafx.h"
#include "Constraint.h"
#include "ConstrainedObject.h"
#include "../tinyxml/tinyxml.h"
std::string AbsoluteAngle[] = {
"AbsoluteAngleHorizontal",
"AbsoluteAngleVertical"
};
std::string ConstraintTypes[]={
"CoincidantPointConstraint",
"ParallelLineConstraint",
"PerpendicularLineConstraint",
"AbsoluteAngleConstraint",
"LineLengthConstraint",
"LineTangentConstraint",
"RadiusConstraint",
"EqualLengthConstraint",
"ColinearConstraint",
"EqualRadiusConstraint",
"ConcentricConstraint",
"PointOnLineConstraint",
"PointOnLineMidpointConstraint",
"PointOnArcMidpointConstraint",
"PointOnArcConstraint"
};
Constraint::Constraint(){
}
Constraint::Constraint(const Constraint* obj){
m_type = obj->m_type;
m_angle = obj->m_angle;
m_length = obj->m_length;
m_obj1 = obj->m_obj1;
m_obj2 = obj->m_obj2;
}
Constraint::Constraint(EnumConstraintType type,EnumAbsoluteAngle angle, ConstrainedObject* obj)
{
m_type = type;
m_angle = angle;
m_obj1 = obj;
m_obj2 = NULL;
m_length = 0;
m_obj1->Add(this,NULL);
}
Constraint::Constraint(EnumConstraintType type,EnumAbsoluteAngle angle, double length, ConstrainedObject* obj1, ConstrainedObject* obj2)
{
m_type = type;
m_angle = angle;
m_obj1 = obj1;
m_obj2 = obj2;
m_length = length;
m_obj1->Add(this,NULL);
if(m_obj2)
m_obj2->Add(this,NULL);
}
Constraint::Constraint(EnumConstraintType type,ConstrainedObject* obj1,ConstrainedObject* obj2)
{
m_type = type;
m_angle = (EnumAbsoluteAngle)0;
m_obj1 = obj1;
m_obj2 = obj2;
m_length = 0;
m_obj1->Add(this,NULL);
m_obj2->Add(this,NULL);
}
Constraint::Constraint(EnumConstraintType type,double length,ConstrainedObject* obj1)
{
m_type = type;
m_angle = (EnumAbsoluteAngle)0;
m_obj1 = obj1;
m_obj2 = 0;
m_length = length;
}
const Constraint& Constraint::operator=(const Constraint &b){
HeeksObj::operator=(b);
m_type = b.m_type;
m_angle = b.m_angle;
m_obj1 = b.m_obj1;
m_obj2 = b.m_obj2;
m_length = b.m_length;
return *this;
}
Constraint::~Constraint()
{
//TODO: objlist will get us removed from obj1's list and obj2's list, however we may want to get out
//of constrained objects constraint list as well
//the 3 boolean like constraints should be handled as well
/* if(m_obj1 && !m_obj1->constraints.empty())
{
m_obj1->constraints.remove(this);
}
if(m_obj2 && !m_obj2->constraints.empty())
m_obj2->constraints.remove(this);
*/
}
void Constraint::render_text(const wxChar* str)
{
wxGetApp().create_font();
//glColor4ub(0, 0, 0, 255);
glEnable(GL_BLEND);
glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
glEnable(GL_TEXTURE_2D);
glDepthMask(0);
glDisable(GL_POLYGON_OFFSET_FILL);
wxGetApp().m_gl_font.Begin();
//Draws text with a glFont
float scale = 0.08f;
std::pair<int,int> size;
wxGetApp().m_gl_font.GetStringSize(str,&size);
wxGetApp().m_gl_font.DrawString(str, scale, -size.first/2.0f*scale, size.second/2.0f*scale);
glDepthMask(1);
glEnable(GL_POLYGON_OFFSET_FILL);
glDisable(GL_TEXTURE_2D);
glDisable(GL_BLEND);
}
void Constraint::glCommands(HeeksColor color, gp_Ax1 axis)
{
double mag = sqrt(axis.Direction().X() * axis.Direction().X() + axis.Direction().Y() * axis.Direction().Y());
float rot = (float)atan2(axis.Direction().Y()/mag,axis.Direction().X()/mag);
glPushMatrix();
glTranslatef((float)axis.Location().X(),(float)axis.Location().Y(),(float)axis.Location().Z());
glRotatef(rot*180/(float)Pi,0,0,1);
glTranslatef(0,ANGLE_OFFSET_FROM_LINE,0);
switch(m_type)
{
case AbsoluteAngleConstraint:
switch(m_angle)
{
case AbsoluteAngleHorizontal:
render_text(_("H"));
break;
case AbsoluteAngleVertical:
glRotatef(90,0,0,1);
render_text(_("V"));
break;
}
break;
case LineLengthConstraint:
wxChar str[100];
wxSprintf(str,_("%f"),m_length);
render_text(str);
break;
case ParallelLineConstraint:
render_text(_("L"));
break;
case PerpendicularLineConstraint:
render_text(_("P"));
break;
default:
break;
}
glPopMatrix();
}
HeeksObj *Constraint::MakeACopy(void)const
{
return new Constraint(this);
}
static std::list<Constraint*> obj_to_save;
static std::set<Constraint*> obj_to_save_find;
void Constraint::BeginSave()
{
obj_to_save.clear();
obj_to_save_find.clear();
}
void Constraint::EndSave(TiXmlNode *root)
{
std::list<Constraint*>::iterator it;
for(it = obj_to_save.begin(); it != obj_to_save.end(); it++)
{
Constraint *c = *it;
TiXmlElement * element;
element = new TiXmlElement( "Constraint" );
root->LinkEndChild( element );
element->SetAttribute("type", ConstraintTypes[c->m_type].c_str());
element->SetAttribute("angle", AbsoluteAngle[c->m_angle].c_str());
element->SetDoubleAttribute("length", c->m_length);
element->SetAttribute("obj1_id",c->m_obj1->m_id);
element->SetAttribute("obj1_type",c->m_obj1->GetIDGroupType());
if(c->m_obj2)
{
element->SetAttribute("obj2_id",c->m_obj2->m_id);
element->SetAttribute("obj2_type",c->m_obj2->GetIDGroupType());
}
c->WriteBaseXML(element);
}
}
void Constraint::WriteXML(TiXmlNode *root)
{
if(obj_to_save_find.find(this)!=obj_to_save_find.end())
return;
obj_to_save.push_back(this);
obj_to_save_find.insert(this);
}
HeeksObj* Constraint::ReadFromXMLElement(TiXmlElement* pElem)
{
const char* type=0;
EnumConstraintType etype=(EnumConstraintType)0;
const char* angle=0;
EnumAbsoluteAngle eangle=(EnumAbsoluteAngle)0;
double length=0;
int obj1_id=0;
int obj2_id=0;
int obj1_type=0;
int obj2_type=0;
ConstrainedObject* obj1=0;
ConstrainedObject* obj2=0;
// get the attributes
for(TiXmlAttribute* a = pElem->FirstAttribute(); a; a = a->Next())
{
std::string name(a->Name());
if(name == "type"){type = a->Value();}
else if(name == "angle"){angle = a->Value();}
else if(name == "length"){length = a->DoubleValue();}
else if(name == "obj1_id"){obj1_id = a->IntValue();}
else if(name == "obj1_type"){obj1_type = a->IntValue();}
else if(name == "obj2_id"){obj2_id = a->IntValue();}
else if(name == "obj2_type"){obj2_type = a->IntValue();}
}
//Ugh, we need to convert the strings back into types
for(unsigned i=0; i < sizeof(ConstraintTypes); i++)
{
if(strcmp(ConstraintTypes[i].c_str(),type)==0)
{
etype = (EnumConstraintType)i;
break;
}
}
for(unsigned i=0; i < sizeof(AbsoluteAngle); i++)
{
if(strcmp(AbsoluteAngle[i].c_str(),angle)==0)
{
eangle = (EnumAbsoluteAngle)i;
break;
}
}
//Get real pointers to the objects
obj1 = (ConstrainedObject*)wxGetApp().GetIDObject(obj1_type,obj1_id);
obj2 = (ConstrainedObject*)wxGetApp().GetIDObject(obj2_type,obj2_id);
if(obj1 == NULL || obj2 == NULL)return NULL;
Constraint *c = new Constraint(etype,eangle,length,obj1,obj2);
//Set up the quick pointers
if(etype == AbsoluteAngleConstraint)
obj1->absoluteangleconstraint = c;
else if(etype == RadiusConstraint)
obj1->radiusconstraint = c;
else if(etype == LineLengthConstraint)
obj1->linelengthconstraint = c;
else
{
obj1->constraints.push_back(c);
obj2->constraints.push_back(c);
}
obj1->Add(c,NULL);
if(obj2)
obj2->Add(c,NULL);
//Don't let the xml reader try to insert us in the tree
return NULL;
}
<commit_msg>constraints were being added twice, once in constructor of Constraint and again after in Constraint::ReadFromXMLElement. This caused a crash when deleting, when opening a new file, later.<commit_after>// ConstrainedObject.cpp
// Copyright (c) 2009, Dan Heeks
// This program is released under the BSD license. See the file COPYING for details.
#include "stdafx.h"
#include "Constraint.h"
#include "ConstrainedObject.h"
#include "../tinyxml/tinyxml.h"
std::string AbsoluteAngle[] = {
"AbsoluteAngleHorizontal",
"AbsoluteAngleVertical"
};
std::string ConstraintTypes[]={
"CoincidantPointConstraint",
"ParallelLineConstraint",
"PerpendicularLineConstraint",
"AbsoluteAngleConstraint",
"LineLengthConstraint",
"LineTangentConstraint",
"RadiusConstraint",
"EqualLengthConstraint",
"ColinearConstraint",
"EqualRadiusConstraint",
"ConcentricConstraint",
"PointOnLineConstraint",
"PointOnLineMidpointConstraint",
"PointOnArcMidpointConstraint",
"PointOnArcConstraint"
};
Constraint::Constraint(){
}
Constraint::Constraint(const Constraint* obj){
m_type = obj->m_type;
m_angle = obj->m_angle;
m_length = obj->m_length;
m_obj1 = obj->m_obj1;
m_obj2 = obj->m_obj2;
}
Constraint::Constraint(EnumConstraintType type,EnumAbsoluteAngle angle, ConstrainedObject* obj)
{
m_type = type;
m_angle = angle;
m_obj1 = obj;
m_obj2 = NULL;
m_length = 0;
m_obj1->Add(this,NULL);
}
Constraint::Constraint(EnumConstraintType type,EnumAbsoluteAngle angle, double length, ConstrainedObject* obj1, ConstrainedObject* obj2)
{
m_type = type;
m_angle = angle;
m_obj1 = obj1;
m_obj2 = obj2;
m_length = length;
m_obj1->Add(this,NULL);
if(m_obj2)
m_obj2->Add(this,NULL);
}
Constraint::Constraint(EnumConstraintType type,ConstrainedObject* obj1,ConstrainedObject* obj2)
{
m_type = type;
m_angle = (EnumAbsoluteAngle)0;
m_obj1 = obj1;
m_obj2 = obj2;
m_length = 0;
m_obj1->Add(this,NULL);
m_obj2->Add(this,NULL);
}
Constraint::Constraint(EnumConstraintType type,double length,ConstrainedObject* obj1)
{
m_type = type;
m_angle = (EnumAbsoluteAngle)0;
m_obj1 = obj1;
m_obj2 = 0;
m_length = length;
}
const Constraint& Constraint::operator=(const Constraint &b){
HeeksObj::operator=(b);
m_type = b.m_type;
m_angle = b.m_angle;
m_obj1 = b.m_obj1;
m_obj2 = b.m_obj2;
m_length = b.m_length;
return *this;
}
Constraint::~Constraint()
{
//TODO: objlist will get us removed from obj1's list and obj2's list, however we may want to get out
//of constrained objects constraint list as well
//the 3 boolean like constraints should be handled as well
/* if(m_obj1 && !m_obj1->constraints.empty())
{
m_obj1->constraints.remove(this);
}
if(m_obj2 && !m_obj2->constraints.empty())
m_obj2->constraints.remove(this);
*/
}
void Constraint::render_text(const wxChar* str)
{
wxGetApp().create_font();
//glColor4ub(0, 0, 0, 255);
glEnable(GL_BLEND);
glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
glEnable(GL_TEXTURE_2D);
glDepthMask(0);
glDisable(GL_POLYGON_OFFSET_FILL);
wxGetApp().m_gl_font.Begin();
//Draws text with a glFont
float scale = 0.08f;
std::pair<int,int> size;
wxGetApp().m_gl_font.GetStringSize(str,&size);
wxGetApp().m_gl_font.DrawString(str, scale, -size.first/2.0f*scale, size.second/2.0f*scale);
glDepthMask(1);
glEnable(GL_POLYGON_OFFSET_FILL);
glDisable(GL_TEXTURE_2D);
glDisable(GL_BLEND);
}
void Constraint::glCommands(HeeksColor color, gp_Ax1 axis)
{
double mag = sqrt(axis.Direction().X() * axis.Direction().X() + axis.Direction().Y() * axis.Direction().Y());
float rot = (float)atan2(axis.Direction().Y()/mag,axis.Direction().X()/mag);
glPushMatrix();
glTranslatef((float)axis.Location().X(),(float)axis.Location().Y(),(float)axis.Location().Z());
glRotatef(rot*180/(float)Pi,0,0,1);
glTranslatef(0,ANGLE_OFFSET_FROM_LINE,0);
switch(m_type)
{
case AbsoluteAngleConstraint:
switch(m_angle)
{
case AbsoluteAngleHorizontal:
render_text(_("H"));
break;
case AbsoluteAngleVertical:
glRotatef(90,0,0,1);
render_text(_("V"));
break;
}
break;
case LineLengthConstraint:
wxChar str[100];
wxSprintf(str,_("%f"),m_length);
render_text(str);
break;
case ParallelLineConstraint:
render_text(_("L"));
break;
case PerpendicularLineConstraint:
render_text(_("P"));
break;
default:
break;
}
glPopMatrix();
}
HeeksObj *Constraint::MakeACopy(void)const
{
return new Constraint(this);
}
static std::list<Constraint*> obj_to_save;
static std::set<Constraint*> obj_to_save_find;
void Constraint::BeginSave()
{
obj_to_save.clear();
obj_to_save_find.clear();
}
void Constraint::EndSave(TiXmlNode *root)
{
std::list<Constraint*>::iterator it;
for(it = obj_to_save.begin(); it != obj_to_save.end(); it++)
{
Constraint *c = *it;
TiXmlElement * element;
element = new TiXmlElement( "Constraint" );
root->LinkEndChild( element );
element->SetAttribute("type", ConstraintTypes[c->m_type].c_str());
element->SetAttribute("angle", AbsoluteAngle[c->m_angle].c_str());
element->SetDoubleAttribute("length", c->m_length);
element->SetAttribute("obj1_id",c->m_obj1->m_id);
element->SetAttribute("obj1_type",c->m_obj1->GetIDGroupType());
if(c->m_obj2)
{
element->SetAttribute("obj2_id",c->m_obj2->m_id);
element->SetAttribute("obj2_type",c->m_obj2->GetIDGroupType());
}
c->WriteBaseXML(element);
}
}
void Constraint::WriteXML(TiXmlNode *root)
{
if(obj_to_save_find.find(this)!=obj_to_save_find.end())
return;
obj_to_save.push_back(this);
obj_to_save_find.insert(this);
}
HeeksObj* Constraint::ReadFromXMLElement(TiXmlElement* pElem)
{
const char* type=0;
EnumConstraintType etype=(EnumConstraintType)0;
const char* angle=0;
EnumAbsoluteAngle eangle=(EnumAbsoluteAngle)0;
double length=0;
int obj1_id=0;
int obj2_id=0;
int obj1_type=0;
int obj2_type=0;
ConstrainedObject* obj1=0;
ConstrainedObject* obj2=0;
// get the attributes
for(TiXmlAttribute* a = pElem->FirstAttribute(); a; a = a->Next())
{
std::string name(a->Name());
if(name == "type"){type = a->Value();}
else if(name == "angle"){angle = a->Value();}
else if(name == "length"){length = a->DoubleValue();}
else if(name == "obj1_id"){obj1_id = a->IntValue();}
else if(name == "obj1_type"){obj1_type = a->IntValue();}
else if(name == "obj2_id"){obj2_id = a->IntValue();}
else if(name == "obj2_type"){obj2_type = a->IntValue();}
}
//Ugh, we need to convert the strings back into types
for(unsigned i=0; i < sizeof(ConstraintTypes); i++)
{
if(strcmp(ConstraintTypes[i].c_str(),type)==0)
{
etype = (EnumConstraintType)i;
break;
}
}
for(unsigned i=0; i < sizeof(AbsoluteAngle); i++)
{
if(strcmp(AbsoluteAngle[i].c_str(),angle)==0)
{
eangle = (EnumAbsoluteAngle)i;
break;
}
}
//Get real pointers to the objects
obj1 = (ConstrainedObject*)wxGetApp().GetIDObject(obj1_type,obj1_id);
obj2 = (ConstrainedObject*)wxGetApp().GetIDObject(obj2_type,obj2_id);
if(obj1 == NULL || obj2 == NULL)return NULL;
Constraint *c = new Constraint(etype,eangle,length,obj1,obj2);
//Set up the quick pointers
if(etype == AbsoluteAngleConstraint)
obj1->absoluteangleconstraint = c;
else if(etype == RadiusConstraint)
obj1->radiusconstraint = c;
else if(etype == LineLengthConstraint)
obj1->linelengthconstraint = c;
else
{
obj1->constraints.push_back(c);
obj2->constraints.push_back(c);
}
//Don't let the xml reader try to insert us in the tree
return NULL;
}
<|endoftext|> |
<commit_before>#include <algorithm>
#include <iomanip>
#include <ios>
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>
using std::cin; using std::setprecision;
using std::cout; using std::string;
using std::endl; using std::streamsize;
using std::sort; using std::vector;
using std::domain_error;
// compute a student's overall grade from midterm and final exam
// grades and homework
double grade(double midterm, double final, double homework)
{
return 0.2 * midterm + 0.4 * final + 0.4 * homework;
}
// compute the median of a vector<double>
// note that calling this function copies the entire argument vector
double median(vector<double> vec)
{
typedef vector<double>::size_type vec_sz;
vec_sz size = vec.size();
if (size == 0)
throw domain_error("median of an empty vector");
sort(vec.begin(), vec.end());
vec_sz mid = size / 2;
return size % 2 == 0 ? (vec[mid] + vec[mid-1]) / 2 : vec[mid];
}
int main()
{
// ask for and read the student's name
cout << "Please enter your first name: ";
string name;
cin >> name;
cout << "Hello, " << name << "!" << endl;
// ask for and read the midterm and final grades
cout << "Please enter your midterm and final grades: ";
double midterm, final;
cin >> midterm >> final;
// ask for the homework grades
cout << "Enter all your homework grades, "
"followed by end-of-file: ";
// a variable into which to read
double x;
vector<double> homework;
// invariant:
// we have read count grades so far, and
// sum is the sum of the first count grades
while ( cin >> x )
homework.push_back(x);
//write the result
streamsize prec = cout.precision();
cout << "Your final grade is " << setprecision(3)
<< grade(midterm, final, median(homework))
<< setprecision(prec) << endl;
return 0;
}
<commit_msg>4.1.4 complete<commit_after>#include <algorithm>
#include <iomanip>
#include <ios>
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>
using std::cin; using std::setprecision;
using std::cout; using std::string;
using std::endl; using std::streamsize;
using std::sort; using std::vector;
using std::domain_error; using std::istream;
// read homework grades from an input stream into a vector<double>
istream& read_hw(istream& in, vector<double>& hw)
{
if (in) {
// get rid of previous contents
hw.clear();
// read homework grades
double x;
while (in >> x)
hw.push_back(x);
//clear the stream so that input will work for the next student
in.clear();
}
return in;
}
// compute a student's overall grade from midterm and final exam
// grades and homework
double grade(double midterm, double final, double homework)
{
return 0.2 * midterm + 0.4 * final + 0.4 * homework;
}
// compute the median of a vector<double>
// note that calling this function copies the entire argument vector
double median(vector<double> vec)
{
typedef vector<double>::size_type vec_sz;
vec_sz size = vec.size();
if (size == 0)
throw domain_error("median of an empty vector");
sort(vec.begin(), vec.end());
vec_sz mid = size / 2;
return size % 2 == 0 ? (vec[mid] + vec[mid-1]) / 2 : vec[mid];
}
// compute a student's overall grade from midterm and final exam grades
// and vector of homework grades
// this function does not copy its argument, because median does so for us
double grade(double midterm, double final, const vector<double>& hw)
{
if (hw.size() == 0)
throw domain_error("student has done no homework");
return grade(midterm, final, median(hw));
}
int main()
{
// ask for and read the student's name
cout << "Please enter your first name: ";
string name;
cin >> name;
cout << "Hello, " << name << "!" << endl;
// ask for and read the midterm and final grades
cout << "Please enter your midterm and final grades: ";
double midterm, final;
cin >> midterm >> final;
// ask for the homework grades
cout << "Enter all your homework grades, "
"followed by end-of-file: ";
// a variable into which to read
double x;
vector<double> homework;
// invariant:
// we have read count grades so far, and
// sum is the sum of the first count grades
while ( cin >> x )
homework.push_back(x);
//write the result
streamsize prec = cout.precision();
cout << "Your final grade is " << setprecision(3)
<< grade(midterm, final, median(homework))
<< setprecision(prec) << endl;
return 0;
}
<|endoftext|> |
<commit_before>#include "GameWindow.h"
GameWindow::GameWindow(QMainWindow *parent) : QMainWindow(parent), m_fpga(this), m_game()
{
/****General setup****/
this->setWindowTitle("Scorch");
this->setStatusBar(new QStatusBar);
this->setWindowIcon(QIcon(QPixmap(":/resources/icon_big.png")));
setFocus();
setStyleSheet("QMainWindow::separator{ width:0px; height:0px;}");
m_game.getView()->setFocusPolicy(Qt::NoFocus);
/****Central widget****/
GameModeWidget * m_gameModeWidget;
AngleStatusWidget * m_currentAngle;
FirePowerWidget * m_currentPower;
this->setCentralWidget(m_game.getView());
/****Bottom Widget (Information about player)****/
QWidget* bottomWidget = new QWidget;
QDockWidget* informationPanel = new QDockWidget;
informationPanel->setAllowedAreas(Qt::BottomDockWidgetArea);
informationPanel->setFeatures(QDockWidget::NoDockWidgetFeatures);
GameBottomLayout *bottomLayout = new GameBottomLayout;
m_gameModeWidget = new GameModeWidget;
bottomLayout->addWidget(m_gameModeWidget);
//This should be an object with custom paint method to make it interesting
m_currentAngle = new AngleStatusWidget;
m_currentAngle->setAngle(0);
//This will be an object with custom paint method to make it interesting
m_currentPower = new FirePowerWidget;
m_currentPower->setPower(50);
bottomLayout->addStretch();
bottomLayout->addWidget(m_currentAngle);
bottomLayout->setAlignment(m_currentAngle, Qt::AlignRight);
bottomLayout->addWidget(m_currentPower);
bottomWidget->setLayout(bottomLayout);
informationPanel->setWidget(bottomWidget);
this->addDockWidget(Qt::BottomDockWidgetArea, informationPanel);
/****Menus****/
m_menuBar = new QMenuBar;
// File menu
m_menuFichier = new QMenu("Fichier");
m_actionQuit = new QAction("Quitter", this);
m_actionQuit->setShortcut(QKeySequence("Q"));
m_actionNewGame = new QAction("Nouvelle partie", this);
m_actionNewGame->setShortcut(QKeySequence("N"));
m_menuFichier->addAction(m_actionNewGame);
m_menuFichier->addSeparator();
m_menuFichier->addAction(m_actionQuit);
m_menuBar->addMenu(m_menuFichier);
// Game menu
m_menuJeux = new QMenu("Jeux");
m_actionPause = new QAction("Pause", this);
m_actionPause->setShortcut(QKeySequence("P"));
m_actionMuet = new QAction("Muet", this);
m_actionMuet->setShortcut(QKeySequence("M"));
m_menuJeux->addAction(m_actionPause);
m_menuJeux->addSeparator();
m_menuJeux->addAction(m_actionMuet);
m_menuBar->addMenu(m_menuJeux);
//Help menu
m_menuAide = new QMenu("Aide");
m_actionTutoriel = new QAction("Tutoriel", this);
m_actionVersion = new QAction("Version", this);
QAction* actionAboutQt = new QAction("A Propos de Qt", this);
m_menuAide->addAction(m_actionTutoriel);
m_menuAide->addSeparator();
m_menuAide->addAction(m_actionVersion);
m_menuAide->addSeparator();
m_menuAide->addAction(actionAboutQt);
m_menuBar->addMenu(m_menuAide);
this->setMenuBar(m_menuBar);
/****Connections****/
// Connect Menu
connect(m_actionQuit, &QAction::triggered, QApplication::instance(), &QApplication::quit);
connect(actionAboutQt, &QAction::triggered, QApplication::instance(), &QApplication::aboutQt);
connect(m_actionPause, &QAction::triggered, this, &GameWindow::pausedTriggered);
connect(m_actionNewGame, SIGNAL(triggered()), this, SLOT(openNewGame()));
connect(m_actionTutoriel, SIGNAL(triggered()), this, SLOT(openTutoriel()));
connect(m_actionVersion, SIGNAL(triggered()), this, SLOT(openVersion()));
// Connect Input
connect(&m_fpga, &FPGAReceiver::fpgaError, this, &GameWindow::displayStatusMessage);
// Connect Game
connect(&m_game, &Game::playerChanged, this, &GameWindow::playerChanged);
connect(&m_game, &Game::angleChanged, this, &GameWindow::angleChanged);
connect(&m_game, &Game::powerChanged, this, &GameWindow::powerChanged);
connect(&m_game, &Game::stateChanged, this, &GameWindow::stateChanged);
// Connect Info Widgets
connect(this, &GameWindow::changeAngle, m_currentAngle, &AngleStatusWidget::setAngle);
connect(this, &GameWindow::changePlayer, m_gameModeWidget, &GameModeWidget::setCurrentPlayer);
connect(this, &GameWindow::changePower, m_currentPower, &FirePowerWidget::setPower);
connect(this, &GameWindow::changeState, m_gameModeWidget, &GameModeWidget::setCurrentMode);
}
GameWindow::~GameWindow()
{
}
void GameWindow::displayStatusMessage(QString message)
{
statusBar()->showMessage(message);
}
void GameWindow::playerChanged(Player p_player)
{
emit changePlayer(p_player);
}
void GameWindow::stateChanged(InputState p_state)
{
emit changeState(p_state);
}
void GameWindow::angleChanged(float p_angle)
{
emit changeAngle(p_angle);
}
void GameWindow::powerChanged(float p_power)
{
emit changePower(p_power);
}
void GameWindow::pausedTriggered()
{
if (m_game.pause()) {
m_game.setPause(false);
m_actionPause->setText("&Pause");
}
else {
m_game.setPause(true);
if(m_game.pause())
m_actionPause->setText("&Play");
}
}
void GameWindow::keyPressEvent(QKeyEvent * KeyEvent)
{
//NOTE: Hack to simulate correctly the FPGA input
m_fpga.handlePressEvent(KeyEvent);
}
void GameWindow::customEvent(QEvent *event)
{
if(event->type() == FPGAEvent::customFPGAEvent) {
FPGAEvent* fpgaEvent = static_cast<FPGAEvent *>(event);
QCoreApplication::postEvent(&m_game, new FPGAEvent(*fpgaEvent));
}
}
void GameWindow::openNewGame()
{
FenetreNewGame fenNewGame;
fenNewGame.exec();
if (fenNewGame.result() == QDialog::Accepted)
m_game.newGame();
}
void GameWindow::openTutoriel()
{
FenetreTutoriel fenTutoriel;
fenTutoriel.exec();
}
void GameWindow::openVersion()
{
FenetreVersion fenVersion;
fenVersion.exec();
}
void GameWindow::resizeEvent(QResizeEvent *event)
{
QMainWindow::resizeEvent(event);
m_game.getView()->fitInView(m_game.getView()->sceneRect(), Qt::KeepAspectRatio);
}
<commit_msg>Add missing shorcuts<commit_after>#include "GameWindow.h"
GameWindow::GameWindow(QMainWindow *parent) : QMainWindow(parent), m_fpga(this), m_game()
{
/****General setup****/
this->setWindowTitle("Scorch");
this->setStatusBar(new QStatusBar);
this->setWindowIcon(QIcon(QPixmap(":/resources/icon_big.png")));
setFocus();
setStyleSheet("QMainWindow::separator{ width:0px; height:0px;}");
m_game.getView()->setFocusPolicy(Qt::NoFocus);
/****Central widget****/
GameModeWidget * m_gameModeWidget;
AngleStatusWidget * m_currentAngle;
FirePowerWidget * m_currentPower;
this->setCentralWidget(m_game.getView());
/****Bottom Widget (Information about player)****/
QWidget* bottomWidget = new QWidget;
QDockWidget* informationPanel = new QDockWidget;
informationPanel->setAllowedAreas(Qt::BottomDockWidgetArea);
informationPanel->setFeatures(QDockWidget::NoDockWidgetFeatures);
GameBottomLayout *bottomLayout = new GameBottomLayout;
m_gameModeWidget = new GameModeWidget;
bottomLayout->addWidget(m_gameModeWidget);
//This should be an object with custom paint method to make it interesting
m_currentAngle = new AngleStatusWidget;
m_currentAngle->setAngle(0);
//This will be an object with custom paint method to make it interesting
m_currentPower = new FirePowerWidget;
m_currentPower->setPower(50);
bottomLayout->addStretch();
bottomLayout->addWidget(m_currentAngle);
bottomLayout->setAlignment(m_currentAngle, Qt::AlignRight);
bottomLayout->addWidget(m_currentPower);
bottomWidget->setLayout(bottomLayout);
informationPanel->setWidget(bottomWidget);
this->addDockWidget(Qt::BottomDockWidgetArea, informationPanel);
/****Menus****/
m_menuBar = new QMenuBar;
// File menu
m_menuFichier = new QMenu("Fichier");
m_actionQuit = new QAction("Quitter", this);
m_actionQuit->setShortcut(QKeySequence("Q"));
m_actionNewGame = new QAction("Nouvelle partie", this);
m_actionNewGame->setShortcut(QKeySequence("N"));
m_menuFichier->addAction(m_actionNewGame);
m_menuFichier->addSeparator();
m_menuFichier->addAction(m_actionQuit);
m_menuBar->addMenu(m_menuFichier);
// Game menu
m_menuJeux = new QMenu("Jeux");
m_actionPause = new QAction("Pause", this);
m_actionPause->setShortcut(QKeySequence("P"));
m_actionMuet = new QAction("Muet", this);
m_actionMuet->setShortcut(QKeySequence("M"));
m_menuJeux->addAction(m_actionPause);
m_menuJeux->addSeparator();
m_menuJeux->addAction(m_actionMuet);
m_menuBar->addMenu(m_menuJeux);
//Help menu
m_menuAide = new QMenu("Aide");
m_actionTutoriel = new QAction("Tutoriel", this);
m_actionPause->setShortcut(QKeySequence("F2"));
m_actionVersion = new QAction("Version", this);
m_actionPause->setShortcut(QKeySequence("F1"));
QAction* actionAboutQt = new QAction("A Propos de Qt", this);
m_actionPause->setShortcut(QKeySequence("F3"));
m_menuAide->addAction(m_actionTutoriel);
m_menuAide->addSeparator();
m_menuAide->addAction(m_actionVersion);
m_menuAide->addSeparator();
m_menuAide->addAction(actionAboutQt);
m_menuBar->addMenu(m_menuAide);
this->setMenuBar(m_menuBar);
/****Connections****/
// Connect Menu
connect(m_actionQuit, &QAction::triggered, QApplication::instance(), &QApplication::quit);
connect(actionAboutQt, &QAction::triggered, QApplication::instance(), &QApplication::aboutQt);
connect(m_actionPause, &QAction::triggered, this, &GameWindow::pausedTriggered);
connect(m_actionNewGame, SIGNAL(triggered()), this, SLOT(openNewGame()));
connect(m_actionTutoriel, SIGNAL(triggered()), this, SLOT(openTutoriel()));
connect(m_actionVersion, SIGNAL(triggered()), this, SLOT(openVersion()));
// Connect Input
connect(&m_fpga, &FPGAReceiver::fpgaError, this, &GameWindow::displayStatusMessage);
// Connect Game
connect(&m_game, &Game::playerChanged, this, &GameWindow::playerChanged);
connect(&m_game, &Game::angleChanged, this, &GameWindow::angleChanged);
connect(&m_game, &Game::powerChanged, this, &GameWindow::powerChanged);
connect(&m_game, &Game::stateChanged, this, &GameWindow::stateChanged);
// Connect Info Widgets
connect(this, &GameWindow::changeAngle, m_currentAngle, &AngleStatusWidget::setAngle);
connect(this, &GameWindow::changePlayer, m_gameModeWidget, &GameModeWidget::setCurrentPlayer);
connect(this, &GameWindow::changePower, m_currentPower, &FirePowerWidget::setPower);
connect(this, &GameWindow::changeState, m_gameModeWidget, &GameModeWidget::setCurrentMode);
}
GameWindow::~GameWindow()
{
}
void GameWindow::displayStatusMessage(QString message)
{
statusBar()->showMessage(message);
}
void GameWindow::playerChanged(Player p_player)
{
emit changePlayer(p_player);
}
void GameWindow::stateChanged(InputState p_state)
{
emit changeState(p_state);
}
void GameWindow::angleChanged(float p_angle)
{
emit changeAngle(p_angle);
}
void GameWindow::powerChanged(float p_power)
{
emit changePower(p_power);
}
void GameWindow::pausedTriggered()
{
if (m_game.pause()) {
m_game.setPause(false);
m_actionPause->setText("&Pause");
}
else {
m_game.setPause(true);
if(m_game.pause())
m_actionPause->setText("&Play");
}
}
void GameWindow::keyPressEvent(QKeyEvent * KeyEvent)
{
//NOTE: Hack to simulate correctly the FPGA input
m_fpga.handlePressEvent(KeyEvent);
}
void GameWindow::customEvent(QEvent *event)
{
if(event->type() == FPGAEvent::customFPGAEvent) {
FPGAEvent* fpgaEvent = static_cast<FPGAEvent *>(event);
QCoreApplication::postEvent(&m_game, new FPGAEvent(*fpgaEvent));
}
}
void GameWindow::openNewGame()
{
FenetreNewGame fenNewGame;
fenNewGame.exec();
if (fenNewGame.result() == QDialog::Accepted)
m_game.newGame();
}
void GameWindow::openTutoriel()
{
FenetreTutoriel fenTutoriel;
fenTutoriel.exec();
}
void GameWindow::openVersion()
{
FenetreVersion fenVersion;
fenVersion.exec();
}
void GameWindow::resizeEvent(QResizeEvent *event)
{
QMainWindow::resizeEvent(event);
m_game.getView()->fitInView(m_game.getView()->sceneRect(), Qt::KeepAspectRatio);
}
<|endoftext|> |
<commit_before>#include "Genes/Gene.h"
#include <cmath>
#include <iostream>
#include <algorithm>
#include <utility>
#include <map>
#include <fstream>
#include <numeric>
#include <iterator>
#include "Game/Board.h"
#include "Game/Color.h"
#include "Utility/Random.h"
#include "Utility/String.h"
#include "Utility/Exceptions.h"
std::map<std::string, double> Gene::list_properties() const noexcept
{
auto properties = std::map<std::string, double>{{"Priority", scoring_priority}, {"Active", double(active)}};
adjust_properties(properties);
return properties;
}
void Gene::adjust_properties(std::map<std::string, double>&) const noexcept
{
}
void Gene::load_properties(const std::map<std::string, double>& properties)
{
if(properties.count("Priority") > 0)
{
scoring_priority = properties.at("Priority");
}
if(properties.count("Active") > 0)
{
active = properties.at("Active") > 0.0;
}
load_gene_properties(properties);
}
void Gene::load_gene_properties(const std::map<std::string, double>&)
{
}
size_t Gene::mutatable_components() const noexcept
{
return list_properties().size();
}
void Gene::read_from(std::istream& is)
{
auto properties = list_properties();
std::map<std::string, bool> property_found;
std::transform(properties.begin(), properties.end(), std::inserter(property_found, property_found.begin()),
[](const auto& key_value)
{
return std::make_pair(key_value.first, false);
});
std::string line;
while(std::getline(is, line))
{
if(String::trim_outer_whitespace(line).empty())
{
break;
}
line = String::strip_comments(line, "#");
if(line.empty())
{
continue;
}
auto split_line = String::split(line, ":");
if(split_line.size() != 2)
{
throw_on_invalid_line(line, "There should be exactly one colon per gene property line.");
}
auto property_name = String::remove_extra_whitespace(split_line[0]);
auto property_data = String::remove_extra_whitespace(split_line[1]);
if(property_name == "Name")
{
if(String::remove_extra_whitespace(property_data) == name())
{
continue;
}
else
{
throw_on_invalid_line(line, "Reading data for wrong gene. Gene is " + name() + ", data is for " + property_data + ".");
}
}
try
{
properties.at(property_name) = String::to_number<double>(property_data);
property_found.at(property_name) = true;
}
catch(const std::out_of_range& e)
{
if(String::contains(e.what(), "at") || String::contains(e.what(), "invalid map<K, T> key"))
{
throw_on_invalid_line(line, "Unrecognized parameter name: " + property_name);
}
else if(String::contains(e.what(), "stod"))
{
throw_on_invalid_line(line, "Bad parameter value: " + property_data);
}
}
catch(const std::invalid_argument&)
{
throw_on_invalid_line(line, "Bad parameter value: " + property_data);
}
}
auto missing_data = std::accumulate(property_found.begin(), property_found.end(), std::string{},
[](const auto& so_far, const auto& name_found)
{
return so_far + ( ! name_found.second ? "\n" + name_found.first : "");
});
if( ! missing_data.empty())
{
throw Genetic_AI_Creation_Error("Missing gene data for " + name() + ":" + missing_data);
}
load_properties(properties);
}
void Gene::read_from(const std::string& file_name)
{
auto ifs = std::ifstream(file_name);
if( ! ifs)
{
throw Genetic_AI_Creation_Error("Could not open " + file_name + " to read.");
}
std::string line;
while(std::getline(ifs, line))
{
if(String::starts_with(line, "Name: "))
{
auto gene_name = String::remove_extra_whitespace(String::split(line, ":", 1)[1]);
if(gene_name == name())
{
try
{
read_from(ifs);
return;
}
catch(const std::exception& e)
{
throw Genetic_AI_Creation_Error("Error in reading data for " + name() + " from " + file_name + "\n" + e.what());
}
}
}
}
throw Genetic_AI_Creation_Error(name() + " not found in " + file_name);
}
void Gene::throw_on_invalid_line(const std::string& line, const std::string& reason) const
{
throw Genetic_AI_Creation_Error("Invalid line in while reading for " + name() + ": " + line + "\n" + reason);
}
void Gene::mutate() noexcept
{
auto properties = list_properties();
if(properties.count("Active") > 0)
{
if(is_active())
{
if(Random::success_probability(1, 1000))
{
active = false;
}
}
else
{
if(Random::success_probability(1, 100))
{
active = true;
}
}
if( ! is_active())
{
return;
}
}
if(Random::success_probability(properties.count("Priority"), properties.size()))
{
scoring_priority += Random::random_laplace(0.005);
}
else
{
gene_specific_mutation();
}
}
void Gene::gene_specific_mutation() noexcept
{
}
double Gene::evaluate(const Board& board, Piece_Color perspective, size_t depth) const noexcept
{
if(is_active())
{
return scoring_priority*score_board(board, perspective, depth);
}
else
{
return 0.0;
}
}
void Gene::print(std::ostream& os) const noexcept
{
auto properties = list_properties();
os << "Name: " << name() << "\n";
for(const auto& [name, value] : properties)
{
os << name << ": " << value << "\n";
}
os << "\n";
}
void Gene::reset_piece_strength_gene(const Piece_Strength_Gene*) noexcept
{
}
double Gene::priority() const noexcept
{
return scoring_priority;
}
void Gene::scale_priority(double k) noexcept
{
scoring_priority *= k;
}
void Gene::zero_out_priority() noexcept
{
scoring_priority = 0.0;
}
bool Gene::is_active() const noexcept
{
return active;
}
void Gene::test(bool& test_variable, const Board& board, Piece_Color perspective, double expected_score) const noexcept
{
auto result = score_board(board, perspective, board.game_length() == 0 ? 0 : 1);
if(std::abs(result - expected_score) > 1e-6)
{
std::cerr << "Error in " << name() << ": Expected " << expected_score << ", Got: " << result << '\n';
test_variable = false;
}
}
<commit_msg>Make sure to throw on all errors<commit_after>#include "Genes/Gene.h"
#include <cmath>
#include <iostream>
#include <algorithm>
#include <utility>
#include <map>
#include <fstream>
#include <numeric>
#include <iterator>
#include "Game/Board.h"
#include "Game/Color.h"
#include "Utility/Random.h"
#include "Utility/String.h"
#include "Utility/Exceptions.h"
std::map<std::string, double> Gene::list_properties() const noexcept
{
auto properties = std::map<std::string, double>{{"Priority", scoring_priority}, {"Active", double(active)}};
adjust_properties(properties);
return properties;
}
void Gene::adjust_properties(std::map<std::string, double>&) const noexcept
{
}
void Gene::load_properties(const std::map<std::string, double>& properties)
{
if(properties.count("Priority") > 0)
{
scoring_priority = properties.at("Priority");
}
if(properties.count("Active") > 0)
{
active = properties.at("Active") > 0.0;
}
load_gene_properties(properties);
}
void Gene::load_gene_properties(const std::map<std::string, double>&)
{
}
size_t Gene::mutatable_components() const noexcept
{
return list_properties().size();
}
void Gene::read_from(std::istream& is)
{
auto properties = list_properties();
std::map<std::string, bool> property_found;
std::transform(properties.begin(), properties.end(), std::inserter(property_found, property_found.begin()),
[](const auto& key_value)
{
return std::make_pair(key_value.first, false);
});
std::string line;
while(std::getline(is, line))
{
if(String::trim_outer_whitespace(line).empty())
{
break;
}
line = String::strip_comments(line, "#");
if(line.empty())
{
continue;
}
auto split_line = String::split(line, ":");
if(split_line.size() != 2)
{
throw_on_invalid_line(line, "There should be exactly one colon per gene property line.");
}
auto property_name = String::remove_extra_whitespace(split_line[0]);
auto property_data = String::remove_extra_whitespace(split_line[1]);
if(property_name == "Name")
{
if(String::remove_extra_whitespace(property_data) == name())
{
continue;
}
else
{
throw_on_invalid_line(line, "Reading data for wrong gene. Gene is " + name() + ", data is for " + property_data + ".");
}
}
try
{
properties.at(property_name) = String::to_number<double>(property_data);
property_found.at(property_name) = true;
}
catch(const std::out_of_range& e)
{
if(String::contains(e.what(), "at") || String::contains(e.what(), "invalid map<K, T> key"))
{
throw_on_invalid_line(line, "Unrecognized parameter name: " + property_name);
}
else if(String::contains(e.what(), "stod"))
{
throw_on_invalid_line(line, "Bad parameter value: " + property_data);
}
else
{
throw_on_invalid_line(line, e.what());
}
}
catch(const std::invalid_argument&)
{
throw_on_invalid_line(line, "Bad parameter value: " + property_data);
}
}
auto missing_data = std::accumulate(property_found.begin(), property_found.end(), std::string{},
[](const auto& so_far, const auto& name_found)
{
return so_far + ( ! name_found.second ? "\n" + name_found.first : "");
});
if( ! missing_data.empty())
{
throw Genetic_AI_Creation_Error("Missing gene data for " + name() + ":" + missing_data);
}
load_properties(properties);
}
void Gene::read_from(const std::string& file_name)
{
auto ifs = std::ifstream(file_name);
if( ! ifs)
{
throw Genetic_AI_Creation_Error("Could not open " + file_name + " to read.");
}
std::string line;
while(std::getline(ifs, line))
{
if(String::starts_with(line, "Name: "))
{
auto gene_name = String::remove_extra_whitespace(String::split(line, ":", 1)[1]);
if(gene_name == name())
{
try
{
read_from(ifs);
return;
}
catch(const std::exception& e)
{
throw Genetic_AI_Creation_Error("Error in reading data for " + name() + " from " + file_name + "\n" + e.what());
}
}
}
}
throw Genetic_AI_Creation_Error(name() + " not found in " + file_name);
}
void Gene::throw_on_invalid_line(const std::string& line, const std::string& reason) const
{
throw Genetic_AI_Creation_Error("Invalid line in while reading for " + name() + ": " + line + "\n" + reason);
}
void Gene::mutate() noexcept
{
auto properties = list_properties();
if(properties.count("Active") > 0)
{
if(is_active())
{
if(Random::success_probability(1, 1000))
{
active = false;
}
}
else
{
if(Random::success_probability(1, 100))
{
active = true;
}
}
if( ! is_active())
{
return;
}
}
if(Random::success_probability(properties.count("Priority"), properties.size()))
{
scoring_priority += Random::random_laplace(0.005);
}
else
{
gene_specific_mutation();
}
}
void Gene::gene_specific_mutation() noexcept
{
}
double Gene::evaluate(const Board& board, Piece_Color perspective, size_t depth) const noexcept
{
if(is_active())
{
return scoring_priority*score_board(board, perspective, depth);
}
else
{
return 0.0;
}
}
void Gene::print(std::ostream& os) const noexcept
{
auto properties = list_properties();
os << "Name: " << name() << "\n";
for(const auto& [name, value] : properties)
{
os << name << ": " << value << "\n";
}
os << "\n";
}
void Gene::reset_piece_strength_gene(const Piece_Strength_Gene*) noexcept
{
}
double Gene::priority() const noexcept
{
return scoring_priority;
}
void Gene::scale_priority(double k) noexcept
{
scoring_priority *= k;
}
void Gene::zero_out_priority() noexcept
{
scoring_priority = 0.0;
}
bool Gene::is_active() const noexcept
{
return active;
}
void Gene::test(bool& test_variable, const Board& board, Piece_Color perspective, double expected_score) const noexcept
{
auto result = score_board(board, perspective, board.game_length() == 0 ? 0 : 1);
if(std::abs(result - expected_score) > 1e-6)
{
std::cerr << "Error in " << name() << ": Expected " << expected_score << ", Got: " << result << '\n';
test_variable = false;
}
}
<|endoftext|> |
<commit_before>/**
* Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>
* All Rights Reserved.
*
* This file is CONFIDENTIAL -- Distribution or duplication of this material or
* the information contained herein is strictly forbidden unless prior written
* permission is obtained.
*/
#include "IndexWriter.h"
#include <fnord-fts/AnalyzerAdapter.h>
using namespace fnord;
namespace cm {
RefPtr<IndexWriter> IndexWriter::openIndex(
const String& index_path,
const String& conf_path) {
if (!FileUtil::exists(index_path) || !FileUtil::isDirectory(index_path)) {
RAISEF(kIllegalArgumentError, "invalid index path: $0", index_path);
}
/* set up feature schema */
FeatureSchema feature_schema;
feature_schema.registerFeature("shop_id", 1, 1);
feature_schema.registerFeature("category1", 2, 1);
feature_schema.registerFeature("category2", 3, 1);
feature_schema.registerFeature("category3", 4, 1);
feature_schema.registerFeature("price_cents", 8, 1);
feature_schema.registerFeature("title~de", 5, 2);
feature_schema.registerFeature("description~de", 6, 2);
feature_schema.registerFeature("size_description~de", 14, 2);
feature_schema.registerFeature("material_description~de", 15, 2);
feature_schema.registerFeature("basic_attributes~de", 16, 2);
feature_schema.registerFeature("tags_as_text~de", 7, 2);
feature_schema.registerFeature("title~pl", 18, 2);
feature_schema.registerFeature("description~pl", 19, 2);
feature_schema.registerFeature("size_description~pl", 20, 2);
feature_schema.registerFeature("material_description~pl", 21, 2);
feature_schema.registerFeature("basic_attributes~pl", 22, 2);
feature_schema.registerFeature("tags_as_text~pl", 23, 2);
feature_schema.registerFeature("image_filename", 24, 2);
feature_schema.registerFeature("cm_clicked_terms", 31, 2);
feature_schema.registerFeature("shop_name", 26, 3);
feature_schema.registerFeature("shop_platform", 27, 3);
feature_schema.registerFeature("shop_country", 28, 3);
feature_schema.registerFeature("shop_rating_alt", 9, 3);
feature_schema.registerFeature("shop_rating_alt2", 15, 3);
feature_schema.registerFeature("shop_products_count", 10, 3);
feature_schema.registerFeature("shop_orders_count", 11, 3);
feature_schema.registerFeature("shop_rating_count", 12, 3);
feature_schema.registerFeature("shop_rating_avg", 13, 3);
feature_schema.registerFeature("cm_views", 29, 3);
feature_schema.registerFeature("cm_clicks", 30, 3);
feature_schema.registerFeature("cm_ctr", 32, 3);
feature_schema.registerFeature("cm_ctr_norm", 33, 3);
feature_schema.registerFeature("cm_ctr_std", 34, 3);
feature_schema.registerFeature("cm_ctr_norm_std", 35, 3);
/* open mdb */
auto db_path = FileUtil::joinPaths(index_path, "db");
FileUtil::mkdir_p(db_path);
auto db = mdb::MDB::open(db_path, false, 68719476736lu); // 64 GiB
/* open lucene */
RefPtr<fnord::fts::Analyzer> analyzer(new fnord::fts::Analyzer(conf_path));
auto adapter = std::make_shared<fnord::fts::AnalyzerAdapter>(analyzer);
auto fts_path = FileUtil::joinPaths(index_path, "fts");
bool create = false;
if (!FileUtil::exists(fts_path)) {
FileUtil::mkdir_p(fts_path);
create = true;
}
auto fts =
fts::newLucene<fts::IndexWriter>(
fts::FSDirectory::open(StringUtil::convertUTF8To16(fts_path)),
adapter,
create,
fts::IndexWriter::MaxFieldLengthLIMITED);
return RefPtr<IndexWriter>(new IndexWriter(feature_schema, db, fts));
}
IndexWriter::IndexWriter(
FeatureSchema schema,
RefPtr<mdb::MDB> db,
std::shared_ptr<fts::IndexWriter> fts) :
schema_(schema),
db_(db),
db_txn_(db_->startTransaction()),
feature_idx_(new FeatureIndexWriter(&schema_)),
fts_(fts) {}
IndexWriter::~IndexWriter() {
if (db_txn_.get()) {
db_txn_->commit();
}
fts_->close();
}
void IndexWriter::updateDocument(const IndexRequest& index_request) {
stat_documents_indexed_total_.incr(1);
auto docid = index_request.item.docID();
feature_idx_->updateDocument(index_request, db_txn_.get());
auto doc = feature_idx_->findDocument(docid, db_txn_.get());
rebuildFTS(doc);
stat_documents_indexed_success_.incr(1);
}
void IndexWriter::commit() {
db_txn_->commit();
db_txn_ = db_->startTransaction();
fts_->commit();
}
void IndexWriter::rebuildFTS(DocID docid) {
auto doc = feature_idx_->findDocument(docid, db_txn_.get());
doc->debugPrint();
rebuildFTS(doc);
}
void IndexWriter::rebuildFTS(RefPtr<Document> doc) {
stat_documents_indexed_fts_.incr(1);
auto fts_doc = fts::newLucene<fts::Document>();
fts_doc->add(
fts::newLucene<fts::Field>(
L"_docid",
StringUtil::convertUTF8To16(doc->docID().docid),
fts::Field::STORE_YES,
fts::Field::INDEX_NOT_ANALYZED_NO_NORMS));
double boost = 1.0;
double cm_clicks = 0;
double cm_views = 0;
double cm_ctr_norm_std = 1.0;
HashMap<String, String> fts_fields_anal;
for (const auto& f : doc->fields()) {
/* title~LANG */
if (StringUtil::beginsWith(f.first, "title~")) {
auto k = f.first;
StringUtil::replaceAll(&k, "title~","title~");
fts_fields_anal[k] += " " + f.second;
}
/* description~LANG */
else if (StringUtil::beginsWith(f.first, "description~")) {
auto k = f.first;
StringUtil::replaceAll(&k, "description~","text~");
fts_fields_anal[k] += " " + f.second;
}
/* size_description~LANG */
else if (StringUtil::beginsWith(f.first, "size_description~")) {
auto k = f.first;
StringUtil::replaceAll(&k, "size_description~","text~");
fts_fields_anal[k] += " " + f.second;
}
/* material_description~LANG */
else if (StringUtil::beginsWith(f.first, "material_description~")) {
auto k = f.first;
StringUtil::replaceAll(&k, "material_description~","text~");
fts_fields_anal[k] += " " + f.second;
}
/* manufacturing_description~LANG */
else if (StringUtil::beginsWith(f.first, "manufacturing_description~")) {
auto k = f.first;
StringUtil::replaceAll(&k, "manufacturing_description~","text~");
fts_fields_anal[k] += " " + f.second;
}
/* tags_as_text~LANG */
else if (StringUtil::beginsWith(f.first, "tags_as_text~")) {
fts_fields_anal["tags"] += " " + f.second;
}
/* shop_name */
else if (f.first == "shop_name") {
fts_fields_anal["tags"] += " " + f.second;
}
/* cm_clicked_terms */
else if (f.first == "cm_clicked_terms") {
fts_doc->add(
fts::newLucene<fts::Field>(
L"cm_clicked_terms",
StringUtil::convertUTF8To16(f.second),
fts::Field::STORE_NO,
fts::Field::INDEX_ANALYZED));
}
else if (f.first == "cm_ctr_norm_std") {
cm_ctr_norm_std = std::stod(f.second);
}
else if (f.first == "cm_clicks") {
cm_clicks = std::stod(f.second);
}
else if (f.first == "cm_views") {
cm_views = std::stod(f.second);
}
}
for (const auto& f : fts_fields_anal) {
fts_doc->add(
fts::newLucene<fts::Field>(
StringUtil::convertUTF8To16(f.first),
StringUtil::convertUTF8To16(f.second),
fts::Field::STORE_NO,
fts::Field::INDEX_ANALYZED));
}
if (cm_views > 1000 && cm_clicks > 15) {
boost = cm_ctr_norm_std;
}
fts_doc->setBoost(boost);
fnord::logDebug(
"cm.indexwriter",
"Rebuilding FTS Index for docid=$0 boost=$1",
doc->docID().docid,
boost);
auto del_term = fts::newLucene<fts::Term>(
L"_docid",
StringUtil::convertUTF8To16(doc->docID().docid));
fts_->updateDocument(del_term, fts_doc);
}
void IndexWriter::rebuildFTS() {
//docs_->listDocuments([this] (const DocID& docid) -> bool {
// rebuildFTS(docid);
// return true;
//});
}
RefPtr<mdb::MDBTransaction> IndexWriter::dbTransaction() {
return db_txn_;
}
void IndexWriter::exportStats(const String& prefix) {
exportStat(
StringUtil::format("$0/documents_indexed_total", prefix),
&stat_documents_indexed_total_,
fnord::stats::ExportMode::EXPORT_DELTA);
exportStat(
StringUtil::format("$0/documents_indexed_success", prefix),
&stat_documents_indexed_success_,
fnord::stats::ExportMode::EXPORT_DELTA);
exportStat(
StringUtil::format("$0/documents_indexed_error", prefix),
&stat_documents_indexed_error_,
fnord::stats::ExportMode::EXPORT_DELTA);
exportStat(
StringUtil::format("$0/documents_indexed_fts", prefix),
&stat_documents_indexed_fts_,
fnord::stats::ExportMode::EXPORT_DELTA);
}
} // namespace cm
<commit_msg>don't index inactive docs<commit_after>/**
* Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>
* All Rights Reserved.
*
* This file is CONFIDENTIAL -- Distribution or duplication of this material or
* the information contained herein is strictly forbidden unless prior written
* permission is obtained.
*/
#include "IndexWriter.h"
#include <fnord-fts/AnalyzerAdapter.h>
using namespace fnord;
namespace cm {
RefPtr<IndexWriter> IndexWriter::openIndex(
const String& index_path,
const String& conf_path) {
if (!FileUtil::exists(index_path) || !FileUtil::isDirectory(index_path)) {
RAISEF(kIllegalArgumentError, "invalid index path: $0", index_path);
}
/* set up feature schema */
FeatureSchema feature_schema;
feature_schema.registerFeature("shop_id", 1, 1);
feature_schema.registerFeature("category1", 2, 1);
feature_schema.registerFeature("category2", 3, 1);
feature_schema.registerFeature("category3", 4, 1);
feature_schema.registerFeature("price_cents", 8, 1);
feature_schema.registerFeature("title~de", 5, 2);
feature_schema.registerFeature("description~de", 6, 2);
feature_schema.registerFeature("size_description~de", 14, 2);
feature_schema.registerFeature("material_description~de", 15, 2);
feature_schema.registerFeature("basic_attributes~de", 16, 2);
feature_schema.registerFeature("tags_as_text~de", 7, 2);
feature_schema.registerFeature("title~pl", 18, 2);
feature_schema.registerFeature("description~pl", 19, 2);
feature_schema.registerFeature("size_description~pl", 20, 2);
feature_schema.registerFeature("material_description~pl", 21, 2);
feature_schema.registerFeature("basic_attributes~pl", 22, 2);
feature_schema.registerFeature("tags_as_text~pl", 23, 2);
feature_schema.registerFeature("image_filename", 24, 2);
feature_schema.registerFeature("cm_clicked_terms", 31, 2);
feature_schema.registerFeature("shop_name", 26, 3);
feature_schema.registerFeature("shop_platform", 27, 3);
feature_schema.registerFeature("shop_country", 28, 3);
feature_schema.registerFeature("shop_rating_alt", 9, 3);
feature_schema.registerFeature("shop_rating_alt2", 15, 3);
feature_schema.registerFeature("shop_products_count", 10, 3);
feature_schema.registerFeature("shop_orders_count", 11, 3);
feature_schema.registerFeature("shop_rating_count", 12, 3);
feature_schema.registerFeature("shop_rating_avg", 13, 3);
feature_schema.registerFeature("cm_views", 29, 3);
feature_schema.registerFeature("cm_clicks", 30, 3);
feature_schema.registerFeature("cm_ctr", 32, 3);
feature_schema.registerFeature("cm_ctr_norm", 33, 3);
feature_schema.registerFeature("cm_ctr_std", 34, 3);
feature_schema.registerFeature("cm_ctr_norm_std", 35, 3);
/* open mdb */
auto db_path = FileUtil::joinPaths(index_path, "db");
FileUtil::mkdir_p(db_path);
auto db = mdb::MDB::open(db_path, false, 68719476736lu); // 64 GiB
/* open lucene */
RefPtr<fnord::fts::Analyzer> analyzer(new fnord::fts::Analyzer(conf_path));
auto adapter = std::make_shared<fnord::fts::AnalyzerAdapter>(analyzer);
auto fts_path = FileUtil::joinPaths(index_path, "fts");
bool create = false;
if (!FileUtil::exists(fts_path)) {
FileUtil::mkdir_p(fts_path);
create = true;
}
auto fts =
fts::newLucene<fts::IndexWriter>(
fts::FSDirectory::open(StringUtil::convertUTF8To16(fts_path)),
adapter,
create,
fts::IndexWriter::MaxFieldLengthLIMITED);
return RefPtr<IndexWriter>(new IndexWriter(feature_schema, db, fts));
}
IndexWriter::IndexWriter(
FeatureSchema schema,
RefPtr<mdb::MDB> db,
std::shared_ptr<fts::IndexWriter> fts) :
schema_(schema),
db_(db),
db_txn_(db_->startTransaction()),
feature_idx_(new FeatureIndexWriter(&schema_)),
fts_(fts) {}
IndexWriter::~IndexWriter() {
if (db_txn_.get()) {
db_txn_->commit();
}
fts_->close();
}
void IndexWriter::updateDocument(const IndexRequest& index_request) {
stat_documents_indexed_total_.incr(1);
auto docid = index_request.item.docID();
feature_idx_->updateDocument(index_request, db_txn_.get());
auto doc = feature_idx_->findDocument(docid, db_txn_.get());
rebuildFTS(doc);
stat_documents_indexed_success_.incr(1);
}
void IndexWriter::commit() {
db_txn_->commit();
db_txn_ = db_->startTransaction();
fts_->commit();
}
void IndexWriter::rebuildFTS(DocID docid) {
auto doc = feature_idx_->findDocument(docid, db_txn_.get());
doc->debugPrint();
rebuildFTS(doc);
}
void IndexWriter::rebuildFTS(RefPtr<Document> doc) {
stat_documents_indexed_fts_.incr(1);
auto fts_doc = fts::newLucene<fts::Document>();
fts_doc->add(
fts::newLucene<fts::Field>(
L"_docid",
StringUtil::convertUTF8To16(doc->docID().docid),
fts::Field::STORE_YES,
fts::Field::INDEX_NOT_ANALYZED_NO_NORMS));
double boost = 1.0;
double cm_clicks = 0;
double cm_views = 0;
double cm_ctr_norm_std = 1.0;
bool is_active = false;
HashMap<String, String> fts_fields_anal;
for (const auto& f : doc->fields()) {
/* title~LANG */
if (StringUtil::beginsWith(f.first, "title~")) {
is_active = true;
auto k = f.first;
StringUtil::replaceAll(&k, "title~","title~");
fts_fields_anal[k] += " " + f.second;
}
/* description~LANG */
else if (StringUtil::beginsWith(f.first, "description~")) {
auto k = f.first;
StringUtil::replaceAll(&k, "description~","text~");
fts_fields_anal[k] += " " + f.second;
}
/* size_description~LANG */
else if (StringUtil::beginsWith(f.first, "size_description~")) {
auto k = f.first;
StringUtil::replaceAll(&k, "size_description~","text~");
fts_fields_anal[k] += " " + f.second;
}
/* material_description~LANG */
else if (StringUtil::beginsWith(f.first, "material_description~")) {
auto k = f.first;
StringUtil::replaceAll(&k, "material_description~","text~");
fts_fields_anal[k] += " " + f.second;
}
/* manufacturing_description~LANG */
else if (StringUtil::beginsWith(f.first, "manufacturing_description~")) {
auto k = f.first;
StringUtil::replaceAll(&k, "manufacturing_description~","text~");
fts_fields_anal[k] += " " + f.second;
}
/* tags_as_text~LANG */
else if (StringUtil::beginsWith(f.first, "tags_as_text~")) {
fts_fields_anal["tags"] += " " + f.second;
}
/* shop_name */
else if (f.first == "shop_name") {
fts_fields_anal["tags"] += " " + f.second;
}
/* cm_clicked_terms */
else if (f.first == "cm_clicked_terms") {
fts_doc->add(
fts::newLucene<fts::Field>(
L"cm_clicked_terms",
StringUtil::convertUTF8To16(f.second),
fts::Field::STORE_NO,
fts::Field::INDEX_ANALYZED));
}
else if (f.first == "cm_ctr_norm_std") {
cm_ctr_norm_std = std::stod(f.second);
}
else if (f.first == "cm_clicks") {
cm_clicks = std::stod(f.second);
}
else if (f.first == "cm_views") {
cm_views = std::stod(f.second);
}
}
for (const auto& f : fts_fields_anal) {
fts_doc->add(
fts::newLucene<fts::Field>(
StringUtil::convertUTF8To16(f.first),
StringUtil::convertUTF8To16(f.second),
fts::Field::STORE_NO,
fts::Field::INDEX_ANALYZED));
}
if (cm_views > 1000 && cm_clicks > 15) {
boost = cm_ctr_norm_std;
}
fts_doc->setBoost(boost);
fnord::logDebug(
"cm.indexwriter",
"Rebuilding FTS Index for docid=$0 boost=$1",
doc->docID().docid,
boost);
auto del_term = fts::newLucene<fts::Term>(
L"_docid",
StringUtil::convertUTF8To16(doc->docID().docid));
if (is_active) {
fts_->updateDocument(del_term, fts_doc);
} else {
fts_->deleteDocuments(del_term);
}
}
void IndexWriter::rebuildFTS() {
//docs_->listDocuments([this] (const DocID& docid) -> bool {
// rebuildFTS(docid);
// return true;
//});
}
RefPtr<mdb::MDBTransaction> IndexWriter::dbTransaction() {
return db_txn_;
}
void IndexWriter::exportStats(const String& prefix) {
exportStat(
StringUtil::format("$0/documents_indexed_total", prefix),
&stat_documents_indexed_total_,
fnord::stats::ExportMode::EXPORT_DELTA);
exportStat(
StringUtil::format("$0/documents_indexed_success", prefix),
&stat_documents_indexed_success_,
fnord::stats::ExportMode::EXPORT_DELTA);
exportStat(
StringUtil::format("$0/documents_indexed_error", prefix),
&stat_documents_indexed_error_,
fnord::stats::ExportMode::EXPORT_DELTA);
exportStat(
StringUtil::format("$0/documents_indexed_fts", prefix),
&stat_documents_indexed_fts_,
fnord::stats::ExportMode::EXPORT_DELTA);
}
} // namespace cm
<|endoftext|> |
<commit_before>
#include "Globals.h" // NOTE: MSVC stupidness requires this to be the same across all modules
#include "MobSpawner.h"
#include "Mobs/IncludeAllMonsters.h"
cMobSpawner::cMobSpawner(cMonster::eFamily a_MonsterFamily, const std::set<eMonsterType>& a_AllowedTypes) :
m_MonsterFamily(a_MonsterFamily),
m_NewPack(true),
m_MobType(mtInvalidType)
{
for (std::set<eMonsterType>::const_iterator itr = a_AllowedTypes.begin(); itr != a_AllowedTypes.end(); ++itr)
{
if (cMonster::FamilyFromType(*itr) == a_MonsterFamily)
{
m_AllowedTypes.insert(*itr);
}
}
}
bool cMobSpawner::CheckPackCenter(BLOCKTYPE a_BlockType)
{
// Packs of non-water mobs can only be centered on an air block
// Packs of water mobs can only be centered on a water block
if (m_MonsterFamily == cMonster::mfWater)
{
return IsBlockWater(a_BlockType);
}
else
{
return a_BlockType == E_BLOCK_AIR;
}
}
void cMobSpawner::addIfAllowed(eMonsterType toAdd, std::set<eMonsterType>& toAddIn)
{
std::set<eMonsterType>::iterator itr = m_AllowedTypes.find(toAdd);
if (itr != m_AllowedTypes.end())
{
toAddIn.insert(toAdd);
}
}
eMonsterType cMobSpawner::ChooseMobType(EMCSBiome a_Biome)
{
std::set<eMonsterType> allowedMobs;
if (a_Biome == biMushroomIsland || a_Biome == biMushroomShore)
{
addIfAllowed(mtMooshroom, allowedMobs);
}
else if (a_Biome == biNether)
{
addIfAllowed(mtGhast, allowedMobs);
addIfAllowed(mtZombiePigman, allowedMobs);
addIfAllowed(mtMagmaCube, allowedMobs);
}
else if (a_Biome == biEnd)
{
addIfAllowed(mtEnderman, allowedMobs);
}
else
{
addIfAllowed(mtBat, allowedMobs);
addIfAllowed(mtSpider, allowedMobs);
addIfAllowed(mtZombie, allowedMobs);
addIfAllowed(mtSkeleton, allowedMobs);
addIfAllowed(mtCreeper, allowedMobs);
addIfAllowed(mtSquid, allowedMobs);
if (a_Biome != biDesert && a_Biome != biBeach && a_Biome != biOcean)
{
addIfAllowed(mtSheep, allowedMobs);
addIfAllowed(mtPig, allowedMobs);
addIfAllowed(mtCow, allowedMobs);
addIfAllowed(mtChicken, allowedMobs);
addIfAllowed(mtEnderman, allowedMobs);
addIfAllowed(mtSlime, allowedMobs); // MG TODO : much more complicated rule
if (a_Biome == biForest || a_Biome == biForestHills || a_Biome == biTaiga || a_Biome == biTaigaHills)
{
addIfAllowed(mtWolf, allowedMobs);
}
else if (a_Biome == biJungle || a_Biome == biJungleHills)
{
addIfAllowed(mtOcelot, allowedMobs);
}
}
}
size_t allowedMobsSize = allowedMobs.size();
if (allowedMobsSize > 0)
{
std::set<eMonsterType>::iterator itr = allowedMobs.begin();
int iRandom = m_Random.NextInt((int)allowedMobsSize, a_Biome);
for (int i = 0; i < iRandom; i++)
{
++itr;
}
return *itr;
}
return mtInvalidType;
}
bool cMobSpawner::CanSpawnHere(cChunk * a_Chunk, int a_RelX, int a_RelY, int a_RelZ, eMonsterType a_MobType, EMCSBiome a_Biome)
{
cFastRandom Random;
BLOCKTYPE TargetBlock = E_BLOCK_AIR;
if (a_Chunk->UnboundedRelGetBlockType(a_RelX, a_RelY, a_RelZ, TargetBlock))
{
if ((a_RelY + 1 > cChunkDef::Height) || (a_RelY - 1 < 0))
{
return false;
}
NIBBLETYPE BlockLight = a_Chunk->GetBlockLight(a_RelX, a_RelY, a_RelZ);
NIBBLETYPE SkyLight = a_Chunk->GetSkyLight(a_RelX, a_RelY, a_RelZ);
BLOCKTYPE BlockAbove = a_Chunk->GetBlock(a_RelX, a_RelY + 1, a_RelZ);
BLOCKTYPE BlockBelow = a_Chunk->GetBlock(a_RelX, a_RelY - 1, a_RelZ);
SkyLight = a_Chunk->GetTimeAlteredLight(SkyLight);
switch (a_MobType)
{
case mtSquid:
{
return IsBlockWater(TargetBlock) && (a_RelY >= 45) && (a_RelY <= 62);
}
case mtBat:
{
return (a_RelY <= 63) && (BlockLight <= 4) && (SkyLight <= 4) && (TargetBlock == E_BLOCK_AIR) && !cBlockInfo::IsTransparent(BlockAbove);
}
case mtChicken:
case mtCow:
case mtPig:
case mtHorse:
case mtSheep:
{
return (
(TargetBlock == E_BLOCK_AIR) &&
(BlockAbove == E_BLOCK_AIR) &&
(!cBlockInfo::IsTransparent(BlockBelow)) &&
(BlockBelow == E_BLOCK_GRASS) &&
(SkyLight >= 9)
);
}
case mtOcelot:
{
return (
(TargetBlock == E_BLOCK_AIR) &&
(BlockAbove == E_BLOCK_AIR) &&
(
(BlockBelow == E_BLOCK_GRASS) || (BlockBelow == E_BLOCK_LEAVES) || (BlockBelow == E_BLOCK_NEW_LEAVES)
) &&
(a_RelY >= 62) &&
(Random.NextInt(3, a_Biome) != 0)
);
}
case mtEnderman:
{
if (a_RelY < 250)
{
BLOCKTYPE BlockTop = a_Chunk->GetBlock(a_RelX, a_RelY + 2, a_RelZ);
if (BlockTop == E_BLOCK_AIR)
{
BlockTop = a_Chunk->GetBlock(a_RelX, a_RelY + 3, a_RelZ);
return (
(TargetBlock == E_BLOCK_AIR) &&
(BlockAbove == E_BLOCK_AIR) &&
(BlockTop == E_BLOCK_AIR) &&
(!cBlockInfo::IsTransparent(BlockBelow)) &&
(SkyLight <= 7) &&
(BlockLight <= 7)
);
}
}
break;
}
case mtSpider:
{
bool CanSpawn = true;
bool HasFloor = false;
for (int x = 0; x < 2; ++x)
{
for (int z = 0; z < 2; ++z)
{
CanSpawn = a_Chunk->UnboundedRelGetBlockType(a_RelX + x, a_RelY, a_RelZ + z, TargetBlock);
CanSpawn = CanSpawn && (TargetBlock == E_BLOCK_AIR);
if (!CanSpawn)
{
return false;
}
HasFloor = (
HasFloor ||
(
a_Chunk->UnboundedRelGetBlockType(a_RelX + x, a_RelY - 1, a_RelZ + z, TargetBlock) &&
!cBlockInfo::IsTransparent(TargetBlock)
)
);
}
}
return CanSpawn && HasFloor && (SkyLight <= 7) && (BlockLight <= 7);
}
case mtCreeper:
case mtSkeleton:
case mtZombie:
{
return (
(TargetBlock == E_BLOCK_AIR) &&
(BlockAbove == E_BLOCK_AIR) &&
(!cBlockInfo::IsTransparent(BlockBelow)) &&
(SkyLight <= 7) &&
(BlockLight <= 7) &&
(Random.NextInt(2, a_Biome) == 0)
);
}
case mtMagmaCube:
case mtSlime:
{
return (
(TargetBlock == E_BLOCK_AIR) &&
(BlockAbove == E_BLOCK_AIR) &&
(!cBlockInfo::IsTransparent(BlockBelow)) &&
(
(a_RelY <= 40) || (a_Biome == biSwampland)
)
);
}
case mtGhast:
case mtZombiePigman:
{
return (
(TargetBlock == E_BLOCK_AIR) &&
(BlockAbove == E_BLOCK_AIR) &&
(!cBlockInfo::IsTransparent(BlockBelow)) &&
(Random.NextInt(20, a_Biome) == 0)
);
}
case mtWolf:
{
return (
(TargetBlock == E_BLOCK_GRASS) &&
(BlockAbove == E_BLOCK_AIR) &&
(
(a_Biome == biTaiga) ||
(a_Biome == biTaigaHills) ||
(a_Biome == biForest) ||
(a_Biome == biForestHills) ||
(a_Biome == biColdTaiga) ||
(a_Biome == biColdTaigaHills) ||
(a_Biome == biTaigaM) ||
(a_Biome == biMegaTaiga) ||
(a_Biome == biMegaTaigaHills)
)
);
}
case mtMooshroom:
{
return (
(TargetBlock == E_BLOCK_AIR) &&
(BlockAbove == E_BLOCK_AIR) &&
(!cBlockInfo::IsTransparent(BlockBelow)) &&
(
a_Biome == biMushroomShore ||
a_Biome == biMushroomIsland
)
);
}
default:
{
LOGD("MG TODO: Write spawning rule for mob type %d", a_MobType);
return false;
}
}
}
return false;
}
cMonster* cMobSpawner::TryToSpawnHere(cChunk * a_Chunk, int a_RelX, int a_RelY, int a_RelZ, EMCSBiome a_Biome, int& a_MaxPackSize)
{
cMonster* toReturn = nullptr;
if (m_NewPack)
{
m_MobType = ChooseMobType(a_Biome);
if (m_MobType == mtInvalidType)
{
return toReturn;
}
if (m_MobType == mtWolf)
{
a_MaxPackSize = 8;
}
else if (m_MobType == mtGhast)
{
a_MaxPackSize = 1;
}
m_NewPack = false;
}
// Make sure we are looking at the right chunk to spawn in
a_Chunk = a_Chunk->GetRelNeighborChunkAdjustCoords(a_RelX, a_RelZ);
if ((m_AllowedTypes.find(m_MobType) != m_AllowedTypes.end()) && CanSpawnHere(a_Chunk, a_RelX, a_RelY, a_RelZ, m_MobType, a_Biome))
{
cMonster * newMob = cMonster::NewMonsterFromType(m_MobType);
if (newMob)
{
m_Spawned.insert(newMob);
}
toReturn = newMob;
}
return toReturn;
}
void cMobSpawner::NewPack()
{
m_NewPack = true;
}
cMobSpawner::tSpawnedContainer & cMobSpawner::getSpawned(void)
{
return m_Spawned;
}
bool cMobSpawner::CanSpawnAnything(void)
{
return !m_AllowedTypes.empty();
}
<commit_msg>extra formatting parentheses<commit_after>
#include "Globals.h" // NOTE: MSVC stupidness requires this to be the same across all modules
#include "MobSpawner.h"
#include "Mobs/IncludeAllMonsters.h"
cMobSpawner::cMobSpawner(cMonster::eFamily a_MonsterFamily, const std::set<eMonsterType>& a_AllowedTypes) :
m_MonsterFamily(a_MonsterFamily),
m_NewPack(true),
m_MobType(mtInvalidType)
{
for (std::set<eMonsterType>::const_iterator itr = a_AllowedTypes.begin(); itr != a_AllowedTypes.end(); ++itr)
{
if (cMonster::FamilyFromType(*itr) == a_MonsterFamily)
{
m_AllowedTypes.insert(*itr);
}
}
}
bool cMobSpawner::CheckPackCenter(BLOCKTYPE a_BlockType)
{
// Packs of non-water mobs can only be centered on an air block
// Packs of water mobs can only be centered on a water block
if (m_MonsterFamily == cMonster::mfWater)
{
return IsBlockWater(a_BlockType);
}
else
{
return a_BlockType == E_BLOCK_AIR;
}
}
void cMobSpawner::addIfAllowed(eMonsterType toAdd, std::set<eMonsterType>& toAddIn)
{
std::set<eMonsterType>::iterator itr = m_AllowedTypes.find(toAdd);
if (itr != m_AllowedTypes.end())
{
toAddIn.insert(toAdd);
}
}
eMonsterType cMobSpawner::ChooseMobType(EMCSBiome a_Biome)
{
std::set<eMonsterType> allowedMobs;
if (a_Biome == biMushroomIsland || a_Biome == biMushroomShore)
{
addIfAllowed(mtMooshroom, allowedMobs);
}
else if (a_Biome == biNether)
{
addIfAllowed(mtGhast, allowedMobs);
addIfAllowed(mtZombiePigman, allowedMobs);
addIfAllowed(mtMagmaCube, allowedMobs);
}
else if (a_Biome == biEnd)
{
addIfAllowed(mtEnderman, allowedMobs);
}
else
{
addIfAllowed(mtBat, allowedMobs);
addIfAllowed(mtSpider, allowedMobs);
addIfAllowed(mtZombie, allowedMobs);
addIfAllowed(mtSkeleton, allowedMobs);
addIfAllowed(mtCreeper, allowedMobs);
addIfAllowed(mtSquid, allowedMobs);
if (a_Biome != biDesert && a_Biome != biBeach && a_Biome != biOcean)
{
addIfAllowed(mtSheep, allowedMobs);
addIfAllowed(mtPig, allowedMobs);
addIfAllowed(mtCow, allowedMobs);
addIfAllowed(mtChicken, allowedMobs);
addIfAllowed(mtEnderman, allowedMobs);
addIfAllowed(mtSlime, allowedMobs); // MG TODO : much more complicated rule
if (a_Biome == biForest || a_Biome == biForestHills || a_Biome == biTaiga || a_Biome == biTaigaHills)
{
addIfAllowed(mtWolf, allowedMobs);
}
else if (a_Biome == biJungle || a_Biome == biJungleHills)
{
addIfAllowed(mtOcelot, allowedMobs);
}
}
}
size_t allowedMobsSize = allowedMobs.size();
if (allowedMobsSize > 0)
{
std::set<eMonsterType>::iterator itr = allowedMobs.begin();
int iRandom = m_Random.NextInt((int)allowedMobsSize, a_Biome);
for (int i = 0; i < iRandom; i++)
{
++itr;
}
return *itr;
}
return mtInvalidType;
}
bool cMobSpawner::CanSpawnHere(cChunk * a_Chunk, int a_RelX, int a_RelY, int a_RelZ, eMonsterType a_MobType, EMCSBiome a_Biome)
{
cFastRandom Random;
BLOCKTYPE TargetBlock = E_BLOCK_AIR;
if (a_Chunk->UnboundedRelGetBlockType(a_RelX, a_RelY, a_RelZ, TargetBlock))
{
if ((a_RelY + 1 > cChunkDef::Height) || (a_RelY - 1 < 0))
{
return false;
}
NIBBLETYPE BlockLight = a_Chunk->GetBlockLight(a_RelX, a_RelY, a_RelZ);
NIBBLETYPE SkyLight = a_Chunk->GetSkyLight(a_RelX, a_RelY, a_RelZ);
BLOCKTYPE BlockAbove = a_Chunk->GetBlock(a_RelX, a_RelY + 1, a_RelZ);
BLOCKTYPE BlockBelow = a_Chunk->GetBlock(a_RelX, a_RelY - 1, a_RelZ);
SkyLight = a_Chunk->GetTimeAlteredLight(SkyLight);
switch (a_MobType)
{
case mtSquid:
{
return IsBlockWater(TargetBlock) && (a_RelY >= 45) && (a_RelY <= 62);
}
case mtBat:
{
return (a_RelY <= 63) && (BlockLight <= 4) && (SkyLight <= 4) && (TargetBlock == E_BLOCK_AIR) && !cBlockInfo::IsTransparent(BlockAbove);
}
case mtChicken:
case mtCow:
case mtPig:
case mtHorse:
case mtSheep:
{
return (
(TargetBlock == E_BLOCK_AIR) &&
(BlockAbove == E_BLOCK_AIR) &&
(!cBlockInfo::IsTransparent(BlockBelow)) &&
(BlockBelow == E_BLOCK_GRASS) &&
(SkyLight >= 9)
);
}
case mtOcelot:
{
return (
(TargetBlock == E_BLOCK_AIR) &&
(BlockAbove == E_BLOCK_AIR) &&
(
(BlockBelow == E_BLOCK_GRASS) || (BlockBelow == E_BLOCK_LEAVES) || (BlockBelow == E_BLOCK_NEW_LEAVES)
) &&
(a_RelY >= 62) &&
(Random.NextInt(3, a_Biome) != 0)
);
}
case mtEnderman:
{
if (a_RelY < 250)
{
BLOCKTYPE BlockTop = a_Chunk->GetBlock(a_RelX, a_RelY + 2, a_RelZ);
if (BlockTop == E_BLOCK_AIR)
{
BlockTop = a_Chunk->GetBlock(a_RelX, a_RelY + 3, a_RelZ);
return (
(TargetBlock == E_BLOCK_AIR) &&
(BlockAbove == E_BLOCK_AIR) &&
(BlockTop == E_BLOCK_AIR) &&
(!cBlockInfo::IsTransparent(BlockBelow)) &&
(SkyLight <= 7) &&
(BlockLight <= 7)
);
}
}
break;
}
case mtSpider:
{
bool CanSpawn = true;
bool HasFloor = false;
for (int x = 0; x < 2; ++x)
{
for (int z = 0; z < 2; ++z)
{
CanSpawn = a_Chunk->UnboundedRelGetBlockType(a_RelX + x, a_RelY, a_RelZ + z, TargetBlock);
CanSpawn = CanSpawn && (TargetBlock == E_BLOCK_AIR);
if (!CanSpawn)
{
return false;
}
HasFloor = (
HasFloor ||
(
a_Chunk->UnboundedRelGetBlockType(a_RelX + x, a_RelY - 1, a_RelZ + z, TargetBlock) &&
!cBlockInfo::IsTransparent(TargetBlock)
)
);
}
}
return CanSpawn && HasFloor && (SkyLight <= 7) && (BlockLight <= 7);
}
case mtCreeper:
case mtSkeleton:
case mtZombie:
{
return (
(TargetBlock == E_BLOCK_AIR) &&
(BlockAbove == E_BLOCK_AIR) &&
(!cBlockInfo::IsTransparent(BlockBelow)) &&
(SkyLight <= 7) &&
(BlockLight <= 7) &&
(Random.NextInt(2, a_Biome) == 0)
);
}
case mtMagmaCube:
case mtSlime:
{
return (
(TargetBlock == E_BLOCK_AIR) &&
(BlockAbove == E_BLOCK_AIR) &&
(!cBlockInfo::IsTransparent(BlockBelow)) &&
(
(a_RelY <= 40) || (a_Biome == biSwampland)
)
);
}
case mtGhast:
case mtZombiePigman:
{
return (
(TargetBlock == E_BLOCK_AIR) &&
(BlockAbove == E_BLOCK_AIR) &&
(!cBlockInfo::IsTransparent(BlockBelow)) &&
(Random.NextInt(20, a_Biome) == 0)
);
}
case mtWolf:
{
return (
(TargetBlock == E_BLOCK_GRASS) &&
(BlockAbove == E_BLOCK_AIR) &&
(
(a_Biome == biTaiga) ||
(a_Biome == biTaigaHills) ||
(a_Biome == biForest) ||
(a_Biome == biForestHills) ||
(a_Biome == biColdTaiga) ||
(a_Biome == biColdTaigaHills) ||
(a_Biome == biTaigaM) ||
(a_Biome == biMegaTaiga) ||
(a_Biome == biMegaTaigaHills)
)
);
}
case mtMooshroom:
{
return (
(TargetBlock == E_BLOCK_AIR) &&
(BlockAbove == E_BLOCK_AIR) &&
(!cBlockInfo::IsTransparent(BlockBelow)) &&
(
(a_Biome == biMushroomShore) ||
(a_Biome == biMushroomIsland)
)
);
}
default:
{
LOGD("MG TODO: Write spawning rule for mob type %d", a_MobType);
return false;
}
}
}
return false;
}
cMonster* cMobSpawner::TryToSpawnHere(cChunk * a_Chunk, int a_RelX, int a_RelY, int a_RelZ, EMCSBiome a_Biome, int& a_MaxPackSize)
{
cMonster* toReturn = nullptr;
if (m_NewPack)
{
m_MobType = ChooseMobType(a_Biome);
if (m_MobType == mtInvalidType)
{
return toReturn;
}
if (m_MobType == mtWolf)
{
a_MaxPackSize = 8;
}
else if (m_MobType == mtGhast)
{
a_MaxPackSize = 1;
}
m_NewPack = false;
}
// Make sure we are looking at the right chunk to spawn in
a_Chunk = a_Chunk->GetRelNeighborChunkAdjustCoords(a_RelX, a_RelZ);
if ((m_AllowedTypes.find(m_MobType) != m_AllowedTypes.end()) && CanSpawnHere(a_Chunk, a_RelX, a_RelY, a_RelZ, m_MobType, a_Biome))
{
cMonster * newMob = cMonster::NewMonsterFromType(m_MobType);
if (newMob)
{
m_Spawned.insert(newMob);
}
toReturn = newMob;
}
return toReturn;
}
void cMobSpawner::NewPack()
{
m_NewPack = true;
}
cMobSpawner::tSpawnedContainer & cMobSpawner::getSpawned(void)
{
return m_Spawned;
}
bool cMobSpawner::CanSpawnAnything(void)
{
return !m_AllowedTypes.empty();
}
<|endoftext|> |
<commit_before>#include "Moves/Move.h"
#include <cassert>
#include "Game/Board.h"
#include "Pieces/Piece.h"
#include "Utility.h"
#include "Exceptions/Illegal_Move_Exception.h"
Move::Move(char file_start, int rank_start,
char file_end, int rank_end) :
starting_file(file_start),
starting_rank(rank_start),
ending_file(file_end),
ending_rank(rank_end)
{
assert(std::abs(file_change()) < 8);
assert(std::abs(rank_change()) < 8);
assert(file_change() != 0 || rank_change() != 0);
}
void Move::side_effects(Board&) const
{
}
bool Move::is_legal(const Board& board) const
{
assert(Board::inside_board(starting_file, starting_rank));
assert(Board::inside_board(ending_file, ending_rank));
// Piece-move compatibility
auto moving_piece = board.piece_on_square(starting_file, starting_rank);
assert(moving_piece);
assert(moving_piece->color() == board.whose_turn());
assert(moving_piece->can_move(this));
auto attacked_piece = board.piece_on_square(ending_file, ending_rank);
if(attacked_piece)
{
// Cannot capture piece of same color
if(moving_piece->color() == attacked_piece->color())
{
return false;
}
// Enforce non-capturing moves
if( ! can_capture())
{
return false;
}
}
if( ! move_specific_legal(board))
{
return false;
}
// Check that there are no intervening pieces for straight-line moves
// if(...) conditional excludes checking knight moves
if(file_change() == 0
|| rank_change() == 0
|| abs(file_change()) == abs(rank_change()))
{
int max_move = std::max(abs(file_change()), abs(rank_change()));
int file_step = file_change()/max_move;
int rank_step = rank_change()/max_move;
for(int step = 1; step < max_move; ++step)
{
if(board.piece_on_square(starting_file + file_step*step,
starting_rank + rank_step*step))
{
return false;
}
}
}
// King should not be in check after move
return ! board.king_is_in_check_after_move(*this);
}
bool Move::move_specific_legal(const Board&) const
{
return true;
}
bool Move::can_capture() const
{
return true;
}
char Move::start_file() const
{
return starting_file;
}
int Move::start_rank() const
{
return starting_rank;
}
int Move::file_change() const
{
return ending_file - starting_file;
}
int Move::rank_change() const
{
return ending_rank - starting_rank;
}
char Move::end_file() const
{
return ending_file;
}
int Move::end_rank() const
{
return ending_rank;
}
std::string Move::game_record_item(const Board& board) const
{
return game_record_move_item(board) + game_record_ending_item(board);
}
std::string Move::game_record_move_item(const Board& board) const
{
auto original_piece = board.piece_on_square(starting_file, starting_rank);
std::string move_record = original_piece->pgn_symbol();
bool record_file = false;
bool record_rank = false;
for(char file_other = 'a'; file_other <= 'h'; ++file_other)
{
for(int rank_other = 1; rank_other <= 8; ++rank_other)
{
if( ! board.piece_on_square(file_other, rank_other))
{
continue;
}
if(file_other == starting_file && rank_other == starting_rank)
{
continue;
}
if(file_other == ending_file && rank_other == ending_rank)
{
continue;
}
auto new_piece = board.piece_on_square(file_other, rank_other);
if(original_piece != new_piece)
{
continue;
}
if(board.is_legal(file_other, rank_other, ending_file, ending_rank))
{
if(file_other != starting_file && ! record_file)
{
record_file = true;
continue;
}
if(rank_other != starting_rank)
{
record_rank = true;
}
}
}
}
if(record_file)
{
move_record += starting_file;
}
if(record_rank)
{
move_record += std::to_string(starting_rank);
}
if(board.piece_on_square(ending_file, ending_rank))
{
move_record += 'x';
}
move_record += ending_file + std::to_string(ending_rank);
return move_record;
}
std::string Move::game_record_ending_item(Board board) const
{
auto result = board.submit_move(*this);
if(result.game_has_ended())
{
return result.get_game_record_annotation();
}
if(board.king_is_in_check(board.whose_turn()))
{
return "+";
}
return {};
}
std::string Move::coordinate_move() const
{
return starting_file
+ std::to_string(starting_rank)
+ ending_file
+ std::to_string(ending_rank);
}
bool Move::is_en_passant() const
{
return false;
}
char Move::promotion_piece_symbol() const
{
return '\0';
}
const Piece* Move::promotion_piece() const
{
return nullptr;
}
<commit_msg>Replace complicated if() and comment with simple method call<commit_after>#include "Moves/Move.h"
#include <cassert>
#include "Game/Board.h"
#include "Pieces/Piece.h"
#include "Utility.h"
#include "Exceptions/Illegal_Move_Exception.h"
Move::Move(char file_start, int rank_start,
char file_end, int rank_end) :
starting_file(file_start),
starting_rank(rank_start),
ending_file(file_end),
ending_rank(rank_end)
{
assert(std::abs(file_change()) < 8);
assert(std::abs(rank_change()) < 8);
assert(file_change() != 0 || rank_change() != 0);
}
void Move::side_effects(Board&) const
{
}
bool Move::is_legal(const Board& board) const
{
assert(Board::inside_board(starting_file, starting_rank));
assert(Board::inside_board(ending_file, ending_rank));
// Piece-move compatibility
auto moving_piece = board.piece_on_square(starting_file, starting_rank);
assert(moving_piece);
assert(moving_piece->color() == board.whose_turn());
assert(moving_piece->can_move(this));
auto attacked_piece = board.piece_on_square(ending_file, ending_rank);
if(attacked_piece)
{
// Cannot capture piece of same color
if(moving_piece->color() == attacked_piece->color())
{
return false;
}
// Enforce non-capturing moves
if( ! can_capture())
{
return false;
}
}
if( ! move_specific_legal(board))
{
return false;
}
// Check that there are no intervening pieces for straight-line moves
if( ! moving_piece->is_knight())
{
int max_move = std::max(abs(file_change()), abs(rank_change()));
int file_step = file_change()/max_move;
int rank_step = rank_change()/max_move;
for(int step = 1; step < max_move; ++step)
{
if(board.piece_on_square(starting_file + file_step*step,
starting_rank + rank_step*step))
{
return false;
}
}
}
// King should not be in check after move
return ! board.king_is_in_check_after_move(*this);
}
bool Move::move_specific_legal(const Board&) const
{
return true;
}
bool Move::can_capture() const
{
return true;
}
char Move::start_file() const
{
return starting_file;
}
int Move::start_rank() const
{
return starting_rank;
}
int Move::file_change() const
{
return ending_file - starting_file;
}
int Move::rank_change() const
{
return ending_rank - starting_rank;
}
char Move::end_file() const
{
return ending_file;
}
int Move::end_rank() const
{
return ending_rank;
}
std::string Move::game_record_item(const Board& board) const
{
return game_record_move_item(board) + game_record_ending_item(board);
}
std::string Move::game_record_move_item(const Board& board) const
{
auto original_piece = board.piece_on_square(starting_file, starting_rank);
std::string move_record = original_piece->pgn_symbol();
bool record_file = false;
bool record_rank = false;
for(char file_other = 'a'; file_other <= 'h'; ++file_other)
{
for(int rank_other = 1; rank_other <= 8; ++rank_other)
{
if( ! board.piece_on_square(file_other, rank_other))
{
continue;
}
if(file_other == starting_file && rank_other == starting_rank)
{
continue;
}
if(file_other == ending_file && rank_other == ending_rank)
{
continue;
}
auto new_piece = board.piece_on_square(file_other, rank_other);
if(original_piece != new_piece)
{
continue;
}
if(board.is_legal(file_other, rank_other, ending_file, ending_rank))
{
if(file_other != starting_file && ! record_file)
{
record_file = true;
continue;
}
if(rank_other != starting_rank)
{
record_rank = true;
}
}
}
}
if(record_file)
{
move_record += starting_file;
}
if(record_rank)
{
move_record += std::to_string(starting_rank);
}
if(board.piece_on_square(ending_file, ending_rank))
{
move_record += 'x';
}
move_record += ending_file + std::to_string(ending_rank);
return move_record;
}
std::string Move::game_record_ending_item(Board board) const
{
auto result = board.submit_move(*this);
if(result.game_has_ended())
{
return result.get_game_record_annotation();
}
if(board.king_is_in_check(board.whose_turn()))
{
return "+";
}
return {};
}
std::string Move::coordinate_move() const
{
return starting_file
+ std::to_string(starting_rank)
+ ending_file
+ std::to_string(ending_rank);
}
bool Move::is_en_passant() const
{
return false;
}
char Move::promotion_piece_symbol() const
{
return '\0';
}
const Piece* Move::promotion_piece() const
{
return nullptr;
}
<|endoftext|> |
<commit_before>#include <array>
#include <string>
#include <pcap/pcap.h>
#include "PcapSource.h"
using namespace regexbench;
class Pcap {
public:
Pcap() = delete;
explicit Pcap(const std::string &filename);
Pcap(const Pcap &) = delete;
Pcap(Pcap &&o) : handle(o.handle) { o.handle = nullptr; }
~Pcap() { if (handle) pcap_close(handle); }
Pcap &operator=(const Pcap &) = delete;
Pcap &operator=(Pcap &&o) {
if (handle) pcap_close(handle);
handle = o.handle;
return *this;
}
pcap_t *operator()() { return handle; }
private:
pcap_t *handle;
};
Pcap::Pcap(const std::string &filename) {
std::array<char, PCAP_ERRBUF_SIZE> errbuf;
handle = pcap_open_offline(filename.data(), errbuf.data());
if (handle == nullptr)
throw std::runtime_error(errbuf.data());
}
PcapSource::PcapSource(const std::string &filename) : nbytes(0) {
Pcap pcap(filename);
pcap_pkthdr *header;
const unsigned char *packet;
int result;
while ((result = pcap_next_ex(pcap(), &header, &packet)) == 1) {
packets.emplace_back(
std::string(reinterpret_cast<const char *>(packet), header->caplen));
nbytes += header->caplen + 24;
}
}
<commit_msg>Fix total bytes calculation<commit_after>#include <array>
#include <string>
#include <pcap/pcap.h>
#include "PcapSource.h"
using namespace regexbench;
class Pcap {
public:
Pcap() = delete;
explicit Pcap(const std::string &filename);
Pcap(const Pcap &) = delete;
Pcap(Pcap &&o) : handle(o.handle) { o.handle = nullptr; }
~Pcap() { if (handle) pcap_close(handle); }
Pcap &operator=(const Pcap &) = delete;
Pcap &operator=(Pcap &&o) {
if (handle) pcap_close(handle);
handle = o.handle;
return *this;
}
pcap_t *operator()() { return handle; }
private:
pcap_t *handle;
};
Pcap::Pcap(const std::string &filename) {
std::array<char, PCAP_ERRBUF_SIZE> errbuf;
handle = pcap_open_offline(filename.data(), errbuf.data());
if (handle == nullptr)
throw std::runtime_error(errbuf.data());
}
PcapSource::PcapSource(const std::string &filename) : nbytes(0) {
Pcap pcap(filename);
pcap_pkthdr *header;
const unsigned char *packet;
int result;
while ((result = pcap_next_ex(pcap(), &header, &packet)) == 1) {
packets.emplace_back(
std::string(reinterpret_cast<const char *>(packet), header->caplen));
nbytes += header->len;
}
}
<|endoftext|> |
<commit_before>#include "PlatformId.h"
#include <string.h>
extern const char* mameNameToRealName[];
namespace PlatformIds
{
const char* PlatformNames[PLATFORM_COUNT + 1] = {
"unknown", // nothing set
"3do",
"amiga",
"amstradcpc",
"apple2",
"arcade",
"atari800",
"atari2600",
"atari5200",
"atari7800",
"atarilynx",
"atarist",
"atarijaguar",
"atarijaguarcd",
"atarixe",
"colecovision",
"c64", // commodore 64
"intellivision",
"mac",
"xbox",
"xbox360",
"neogeo",
"ngp", // neo geo pocket
"ngpc", // neo geo pocket color
"n3ds", // nintendo 3DS
"n64", // nintendo 64
"nds", // nintendo DS
"nes", // nintendo entertainment system
"gb", // game boy
"gba", // game boy advance
"gbc", // game boy color
"gc", // gamecube
"wii",
"wiiu",
"pc",
"sega32x",
"segacd",
"dreamcast",
"gamegear",
"genesis", // sega genesis
"mastersystem", // sega master system
"megadrive", // sega megadrive
"saturn", // sega saturn
"psx",
"ps2",
"ps3",
"ps4",
"psvita",
"psp", // playstation portable
"snes", // super nintendo entertainment system
"pcengine", // turbografx-16/pcengine
"wonderswan",
"wonderswancolor",
"zxspectrum",
"ignore", // do not allow scraping for this system
"invalid"
};
PlatformId getPlatformId(const char* str)
{
if(str == NULL)
return PLATFORM_UNKNOWN;
for(unsigned int i = 1; i < PLATFORM_COUNT; i++)
{
if(strcmp(PlatformNames[i], str) == 0)
return (PlatformId)i;
}
return PLATFORM_UNKNOWN;
}
const char* getPlatformName(PlatformId id)
{
return PlatformNames[id];
}
const char* getCleanMameName(const char* from)
{
const char** mameNames = mameNameToRealName;
while(*mameNames != NULL && strcmp(from, *mameNames) != 0)
mameNames += 2;
if(*mameNames)
return *(mameNames + 1);
return from;
}
}
<commit_msg>Renamed "mac" platform to "macintosh".<commit_after>#include "PlatformId.h"
#include <string.h>
extern const char* mameNameToRealName[];
namespace PlatformIds
{
const char* PlatformNames[PLATFORM_COUNT + 1] = {
"unknown", // nothing set
"3do",
"amiga",
"amstradcpc",
"apple2",
"arcade",
"atari800",
"atari2600",
"atari5200",
"atari7800",
"atarilynx",
"atarist",
"atarijaguar",
"atarijaguarcd",
"atarixe",
"colecovision",
"c64", // commodore 64
"intellivision",
"macintosh",
"xbox",
"xbox360",
"neogeo",
"ngp", // neo geo pocket
"ngpc", // neo geo pocket color
"n3ds", // nintendo 3DS
"n64", // nintendo 64
"nds", // nintendo DS
"nes", // nintendo entertainment system
"gb", // game boy
"gba", // game boy advance
"gbc", // game boy color
"gc", // gamecube
"wii",
"wiiu",
"pc",
"sega32x",
"segacd",
"dreamcast",
"gamegear",
"genesis", // sega genesis
"mastersystem", // sega master system
"megadrive", // sega megadrive
"saturn", // sega saturn
"psx",
"ps2",
"ps3",
"ps4",
"psvita",
"psp", // playstation portable
"snes", // super nintendo entertainment system
"pcengine", // turbografx-16/pcengine
"wonderswan",
"wonderswancolor",
"zxspectrum",
"ignore", // do not allow scraping for this system
"invalid"
};
PlatformId getPlatformId(const char* str)
{
if(str == NULL)
return PLATFORM_UNKNOWN;
for(unsigned int i = 1; i < PLATFORM_COUNT; i++)
{
if(strcmp(PlatformNames[i], str) == 0)
return (PlatformId)i;
}
return PLATFORM_UNKNOWN;
}
const char* getPlatformName(PlatformId id)
{
return PlatformNames[id];
}
const char* getCleanMameName(const char* from)
{
const char** mameNames = mameNameToRealName;
while(*mameNames != NULL && strcmp(from, *mameNames) != 0)
mameNames += 2;
if(*mameNames)
return *(mameNames + 1);
return from;
}
}
<|endoftext|> |
<commit_before>#include "PlatformId.h"
namespace PlatformIds
{
const char* PlatformNames[PLATFORM_COUNT + 1] = {
"unknown", // = 0,
"3do", // = 1,
"amiga", // = 2,
"arcade", // = 3,
"atari2600", // = 4,
"atari5200", // = 5,
"atari7800", // = 6,
"atariJaguar", // = 7,
"atariJaguarCD", // = 8,
"atariXE", // = 9,
"colecovision", // = 10,
"commodore64", // = 11,
"intellivision", // = 12,
"mac", // = 13,
"xbox", // = 14,
"xbox360", // = 15,
"neogeo", // = 16,
"ngp", // = 17,
"ngpc", // = 18,
"n3ds", // = 19,
"n64", // = 20,
"nds", // = 21,
"nes", // = 22,
"gb", // = 23,
"gba", // = 24,
"gbc", // = 25,
"gamecube", // = 26,
"wii", // = 27,
"wiiu", // = 28,
"pc", // = 29,
"sega32x", // = 30,
"segacd", // = 31,
"dreamcast", // = 32,
"gamegear", // = 33,
"genesis", // = 34,
"mastersystem", // = 35,
"megadrive", // = 36,
"saturn", // = 37,
"psx", // = 38,
"ps2", // = 39,
"ps3", // = 40,
"ps4", // = 41,
"psvita", // = 42,
"psp", // = 43,
"snes", // = 44,
"pcengine", // = 45,
"zxspectrum", // = 46,
"invalid" // = 47
};
PlatformId getPlatformId(const char* str)
{
if(str == NULL)
return PLATFORM_UNKNOWN;
for(unsigned int i = 1; i < PLATFORM_COUNT; i++)
{
if(strcmp(PlatformNames[i], str) == 0)
return (PlatformId)i;
}
return PLATFORM_UNKNOWN;
}
const char* getPlatformName(PlatformId id)
{
return PlatformNames[id];
}
}
<commit_msg>Add missing #include to fix building on Linux.<commit_after>#include "PlatformId.h"
#include <string.h>
namespace PlatformIds
{
const char* PlatformNames[PLATFORM_COUNT + 1] = {
"unknown", // = 0,
"3do", // = 1,
"amiga", // = 2,
"arcade", // = 3,
"atari2600", // = 4,
"atari5200", // = 5,
"atari7800", // = 6,
"atariJaguar", // = 7,
"atariJaguarCD", // = 8,
"atariXE", // = 9,
"colecovision", // = 10,
"commodore64", // = 11,
"intellivision", // = 12,
"mac", // = 13,
"xbox", // = 14,
"xbox360", // = 15,
"neogeo", // = 16,
"ngp", // = 17,
"ngpc", // = 18,
"n3ds", // = 19,
"n64", // = 20,
"nds", // = 21,
"nes", // = 22,
"gb", // = 23,
"gba", // = 24,
"gbc", // = 25,
"gamecube", // = 26,
"wii", // = 27,
"wiiu", // = 28,
"pc", // = 29,
"sega32x", // = 30,
"segacd", // = 31,
"dreamcast", // = 32,
"gamegear", // = 33,
"genesis", // = 34,
"mastersystem", // = 35,
"megadrive", // = 36,
"saturn", // = 37,
"psx", // = 38,
"ps2", // = 39,
"ps3", // = 40,
"ps4", // = 41,
"psvita", // = 42,
"psp", // = 43,
"snes", // = 44,
"pcengine", // = 45,
"zxspectrum", // = 46,
"invalid" // = 47
};
PlatformId getPlatformId(const char* str)
{
if(str == NULL)
return PLATFORM_UNKNOWN;
for(unsigned int i = 1; i < PLATFORM_COUNT; i++)
{
if(strcmp(PlatformNames[i], str) == 0)
return (PlatformId)i;
}
return PLATFORM_UNKNOWN;
}
const char* getPlatformName(PlatformId id)
{
return PlatformNames[id];
}
}
<|endoftext|> |
<commit_before>//Copyright (c) 2018 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.
#include <algorithm>
#include <limits>
#include "Application.h" //To get settings.
#include "ExtruderTrain.h"
#include "gcodeExport.h"
#include "infill.h"
#include "LayerPlan.h"
#include "PrimeTower.h"
#include "PrintFeature.h"
#include "raft.h"
#include "sliceDataStorage.h"
#define CIRCLE_RESOLUTION 32 //The number of vertices in each circle.
namespace cura
{
PrimeTower::PrimeTower()
: wipe_from_middle(false)
{
const Scene& scene = Application::getInstance().current_slice->scene;
enabled = scene.current_mesh_group->settings.get<bool>("prime_tower_enable")
&& scene.current_mesh_group->settings.get<coord_t>("prime_tower_min_volume") > 10
&& scene.current_mesh_group->settings.get<coord_t>("prime_tower_size") > 10;
extruder_count = scene.extruders.size();
extruder_order.resize(extruder_count);
for (unsigned int extruder_nr = 0; extruder_nr < extruder_count; extruder_nr++)
{
extruder_order[extruder_nr] = extruder_nr; //Start with default order, then sort.
}
//Sort from high adhesion to low adhesion.
const Scene* scene_pointer = &scene; //Communicate to lambda via pointer to prevent copy.
std::sort(extruder_order.begin(), extruder_order.end(), [scene_pointer](const unsigned int& extruder_nr_a, const unsigned int& extruder_nr_b) -> bool
{
const Ratio adhesion_a = scene_pointer->extruders[extruder_nr_a].settings.get<Ratio>("material_adhesion_tendency");
const Ratio adhesion_b = scene_pointer->extruders[extruder_nr_b].settings.get<Ratio>("material_adhesion_tendency");
return adhesion_a < adhesion_b;
});
}
void PrimeTower::generateGroundpoly()
{
if (!enabled)
{
return;
}
const Settings& mesh_group_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings;
const coord_t tower_size = mesh_group_settings.get<coord_t>("prime_tower_size");
const bool circular_prime_tower = mesh_group_settings.get<bool>("prime_tower_circular");
PolygonRef p = outer_poly.newPoly();
int tower_distance = 0;
const coord_t x = mesh_group_settings.get<coord_t>("prime_tower_position_x");
const coord_t y = mesh_group_settings.get<coord_t>("prime_tower_position_y");
if (circular_prime_tower)
{
const coord_t tower_radius = tower_size / 2;
for (unsigned int i = 0; i < CIRCLE_RESOLUTION; i++)
{
const double angle = (double) i / CIRCLE_RESOLUTION * 2 * M_PI; //In radians.
p.add(Point(x - tower_radius + tower_distance + cos(angle) * tower_radius,
y + tower_radius + tower_distance + sin(angle) * tower_radius));
}
}
else
{
p.add(Point(x + tower_distance, y + tower_distance));
p.add(Point(x + tower_distance, y + tower_distance + tower_size));
p.add(Point(x + tower_distance - tower_size, y + tower_distance + tower_size));
p.add(Point(x + tower_distance - tower_size, y + tower_distance));
}
middle = Point(x - tower_size / 2, y + tower_size / 2);
post_wipe_point = Point(x + tower_distance - tower_size / 2, y + tower_distance + tower_size / 2);
}
void PrimeTower::generatePaths(const SliceDataStorage& storage)
{
enabled &= storage.max_print_height_second_to_last_extruder >= 0; //Maybe it turns out that we don't need a prime tower after all because there are no layer switches.
if (enabled)
{
generatePaths_denseInfill();
generateStartLocations();
}
}
void PrimeTower::generatePaths_denseInfill()
{
const Scene& scene = Application::getInstance().current_slice->scene;
const Settings& mesh_group_settings = scene.current_mesh_group->settings;
const coord_t layer_height = mesh_group_settings.get<coord_t>("layer_height");
pattern_per_extruder.resize(extruder_count);
coord_t cumulative_inset = 0; //Each tower shape is going to be printed inside the other. This is the inset we're doing for each extruder.
for (size_t extruder_nr : extruder_order)
{
const coord_t line_width = scene.extruders[extruder_nr].settings.get<coord_t>("prime_tower_line_width");
const coord_t required_volume = scene.extruders[extruder_nr].settings.get<double>("prime_tower_min_volume") * 1000000000; //To cubic microns.
const Ratio flow = scene.extruders[extruder_nr].settings.get<Ratio>("prime_tower_flow");
coord_t current_volume = 0;
ExtrusionMoves& pattern = pattern_per_extruder[extruder_nr];
//Create the walls of the prime tower.
unsigned int wall_nr = 0;
for (; current_volume < required_volume; wall_nr++)
{
//Create a new polygon with an offset from the outer polygon.
Polygons polygons = outer_poly.offset(-cumulative_inset - wall_nr * line_width - line_width / 2);
pattern.polygons.add(polygons);
current_volume += polygons.polygonLength() * line_width * layer_height * flow;
if (polygons.empty()) //Don't continue. We won't ever reach the required volume because it doesn't fit.
{
break;
}
}
cumulative_inset += wall_nr * line_width;
//Generate the pattern for the first layer.
coord_t line_width_layer0 = line_width;
if (mesh_group_settings.get<EPlatformAdhesion>("adhesion_type") != EPlatformAdhesion::RAFT)
{
line_width_layer0 *= scene.extruders[extruder_nr].settings.get<Ratio>("initial_layer_line_width_factor");
}
pattern_per_extruder_layer0.emplace_back();
ExtrusionMoves& pattern_layer0 = pattern_per_extruder_layer0.back();
// Generate a concentric infill pattern in the form insets for the prime tower's first layer instead of using
// the infill pattern because the infill pattern tries to connect polygons in different insets which causes the
// first layer of the prime tower to not stick well.
Polygons inset = outer_poly.offset(-line_width_layer0 / 2);
while (!inset.empty())
{
pattern_layer0.polygons.add(inset);
inset = inset.offset(-line_width_layer0);
}
}
}
void PrimeTower::generateStartLocations()
{
// Evenly spread out a number of dots along the prime tower's outline. This is done for the complete outline,
// so use the same start and end segments for this.
PolygonsPointIndex segment_start = PolygonsPointIndex(&outer_poly, 0, 0);
PolygonsPointIndex segment_end = segment_start;
PolygonUtils::spreadDots(segment_start, segment_end, number_of_prime_tower_start_locations, prime_tower_start_locations);
}
void PrimeTower::addToGcode(const SliceDataStorage& storage, LayerPlan& gcode_layer, const int prev_extruder, const int new_extruder) const
{
if (!enabled)
{
return;
}
if (gcode_layer.getPrimeTowerIsPlanned(new_extruder))
{ // don't print the prime tower if it has been printed already with this extruder.
return;
}
const LayerIndex layer_nr = gcode_layer.getLayerNr();
if (layer_nr > storage.max_print_height_second_to_last_extruder + 1)
{
return;
}
bool post_wipe = Application::getInstance().current_slice->scene.extruders[prev_extruder].settings.get<bool>("prime_tower_wipe_enabled");
// Do not wipe on the first layer, we will generate non-hollow prime tower there for better bed adhesion.
if (prev_extruder == new_extruder || layer_nr == 0)
{
post_wipe = false;
}
// Go to the start location if it's not the first layer
if (layer_nr != 0)
{
gotoStartLocation(gcode_layer, new_extruder);
}
addToGcode_denseInfill(gcode_layer, new_extruder);
// post-wipe:
if (post_wipe)
{
//Make sure we wipe the old extruder on the prime tower.
const Settings& previous_settings = Application::getInstance().current_slice->scene.extruders[prev_extruder].settings;
const Point previous_nozzle_offset = Point(previous_settings.get<coord_t>("machine_nozzle_offset_x"), previous_settings.get<coord_t>("machine_nozzle_offset_y"));
const Settings& new_settings = Application::getInstance().current_slice->scene.extruders[new_extruder].settings;
const Point new_nozzle_offset = Point(new_settings.get<coord_t>("machine_nozzle_offset_x"), new_settings.get<coord_t>("machine_nozzle_offset_y"));
gcode_layer.addTravel(post_wipe_point - previous_nozzle_offset + new_nozzle_offset);
}
gcode_layer.setPrimeTowerIsPlanned(new_extruder);
}
void PrimeTower::addToGcode_denseInfill(LayerPlan& gcode_layer, const size_t extruder_nr) const
{
const ExtrusionMoves& pattern = (gcode_layer.getLayerNr() == -static_cast<LayerIndex>(Raft::getFillerLayerCount()))
? pattern_per_extruder_layer0[extruder_nr]
: pattern_per_extruder[extruder_nr];
const GCodePathConfig& config = gcode_layer.configs_storage.prime_tower_config_per_extruder[extruder_nr];
gcode_layer.addPolygonsByOptimizer(pattern.polygons, config);
gcode_layer.addLinesByOptimizer(pattern.lines, config, SpaceFillType::Lines);
}
void PrimeTower::subtractFromSupport(SliceDataStorage& storage)
{
const Polygons outside_polygon = outer_poly.getOutsidePolygons();
AABB outside_polygon_boundary_box(outside_polygon);
for(size_t layer = 0; layer <= (size_t)storage.max_print_height_second_to_last_extruder + 1 && layer < storage.support.supportLayers.size(); layer++)
{
SupportLayer& support_layer = storage.support.supportLayers[layer];
// take the differences of the support infill parts and the prime tower area
support_layer.excludeAreasFromSupportInfillAreas(outside_polygon, outside_polygon_boundary_box);
}
}
void PrimeTower::gotoStartLocation(LayerPlan& gcode_layer, const int extruder_nr) const
{
int current_start_location_idx = ((((extruder_nr + 1) * gcode_layer.getLayerNr()) % number_of_prime_tower_start_locations)
+ number_of_prime_tower_start_locations) % number_of_prime_tower_start_locations;
const ClosestPolygonPoint wipe_location = prime_tower_start_locations[current_start_location_idx];
const ExtruderTrain& train = Application::getInstance().current_slice->scene.extruders[extruder_nr];
const coord_t inward_dist = train.settings.get<coord_t>("machine_nozzle_size") * 3 / 2 ;
const coord_t start_dist = train.settings.get<coord_t>("machine_nozzle_size") * 2;
const Point prime_end = PolygonUtils::moveInsideDiagonally(wipe_location, inward_dist);
const Point outward_dir = wipe_location.location - prime_end;
const Point prime_start = wipe_location.location + normal(outward_dir, start_dist);
gcode_layer.addTravel(prime_start);
}
}//namespace cura
<commit_msg>Make prime tower ordering sort stable<commit_after>//Copyright (c) 2018 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.
#include <algorithm>
#include <limits>
#include "Application.h" //To get settings.
#include "ExtruderTrain.h"
#include "gcodeExport.h"
#include "infill.h"
#include "LayerPlan.h"
#include "PrimeTower.h"
#include "PrintFeature.h"
#include "raft.h"
#include "sliceDataStorage.h"
#define CIRCLE_RESOLUTION 32 //The number of vertices in each circle.
namespace cura
{
PrimeTower::PrimeTower()
: wipe_from_middle(false)
{
const Scene& scene = Application::getInstance().current_slice->scene;
enabled = scene.current_mesh_group->settings.get<bool>("prime_tower_enable")
&& scene.current_mesh_group->settings.get<coord_t>("prime_tower_min_volume") > 10
&& scene.current_mesh_group->settings.get<coord_t>("prime_tower_size") > 10;
extruder_count = scene.extruders.size();
extruder_order.resize(extruder_count);
for (unsigned int extruder_nr = 0; extruder_nr < extruder_count; extruder_nr++)
{
extruder_order[extruder_nr] = extruder_nr; //Start with default order, then sort.
}
//Sort from high adhesion to low adhesion.
const Scene* scene_pointer = &scene; //Communicate to lambda via pointer to prevent copy.
std::stable_sort(extruder_order.begin(), extruder_order.end(), [scene_pointer](const unsigned int& extruder_nr_a, const unsigned int& extruder_nr_b) -> bool
{
const Ratio adhesion_a = scene_pointer->extruders[extruder_nr_a].settings.get<Ratio>("material_adhesion_tendency");
const Ratio adhesion_b = scene_pointer->extruders[extruder_nr_b].settings.get<Ratio>("material_adhesion_tendency");
return adhesion_a < adhesion_b;
});
}
void PrimeTower::generateGroundpoly()
{
if (!enabled)
{
return;
}
const Settings& mesh_group_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings;
const coord_t tower_size = mesh_group_settings.get<coord_t>("prime_tower_size");
const bool circular_prime_tower = mesh_group_settings.get<bool>("prime_tower_circular");
PolygonRef p = outer_poly.newPoly();
int tower_distance = 0;
const coord_t x = mesh_group_settings.get<coord_t>("prime_tower_position_x");
const coord_t y = mesh_group_settings.get<coord_t>("prime_tower_position_y");
if (circular_prime_tower)
{
const coord_t tower_radius = tower_size / 2;
for (unsigned int i = 0; i < CIRCLE_RESOLUTION; i++)
{
const double angle = (double) i / CIRCLE_RESOLUTION * 2 * M_PI; //In radians.
p.add(Point(x - tower_radius + tower_distance + cos(angle) * tower_radius,
y + tower_radius + tower_distance + sin(angle) * tower_radius));
}
}
else
{
p.add(Point(x + tower_distance, y + tower_distance));
p.add(Point(x + tower_distance, y + tower_distance + tower_size));
p.add(Point(x + tower_distance - tower_size, y + tower_distance + tower_size));
p.add(Point(x + tower_distance - tower_size, y + tower_distance));
}
middle = Point(x - tower_size / 2, y + tower_size / 2);
post_wipe_point = Point(x + tower_distance - tower_size / 2, y + tower_distance + tower_size / 2);
}
void PrimeTower::generatePaths(const SliceDataStorage& storage)
{
enabled &= storage.max_print_height_second_to_last_extruder >= 0; //Maybe it turns out that we don't need a prime tower after all because there are no layer switches.
if (enabled)
{
generatePaths_denseInfill();
generateStartLocations();
}
}
void PrimeTower::generatePaths_denseInfill()
{
const Scene& scene = Application::getInstance().current_slice->scene;
const Settings& mesh_group_settings = scene.current_mesh_group->settings;
const coord_t layer_height = mesh_group_settings.get<coord_t>("layer_height");
pattern_per_extruder.resize(extruder_count);
coord_t cumulative_inset = 0; //Each tower shape is going to be printed inside the other. This is the inset we're doing for each extruder.
for (size_t extruder_nr : extruder_order)
{
const coord_t line_width = scene.extruders[extruder_nr].settings.get<coord_t>("prime_tower_line_width");
const coord_t required_volume = scene.extruders[extruder_nr].settings.get<double>("prime_tower_min_volume") * 1000000000; //To cubic microns.
const Ratio flow = scene.extruders[extruder_nr].settings.get<Ratio>("prime_tower_flow");
coord_t current_volume = 0;
ExtrusionMoves& pattern = pattern_per_extruder[extruder_nr];
//Create the walls of the prime tower.
unsigned int wall_nr = 0;
for (; current_volume < required_volume; wall_nr++)
{
//Create a new polygon with an offset from the outer polygon.
Polygons polygons = outer_poly.offset(-cumulative_inset - wall_nr * line_width - line_width / 2);
pattern.polygons.add(polygons);
current_volume += polygons.polygonLength() * line_width * layer_height * flow;
if (polygons.empty()) //Don't continue. We won't ever reach the required volume because it doesn't fit.
{
break;
}
}
cumulative_inset += wall_nr * line_width;
//Generate the pattern for the first layer.
coord_t line_width_layer0 = line_width;
if (mesh_group_settings.get<EPlatformAdhesion>("adhesion_type") != EPlatformAdhesion::RAFT)
{
line_width_layer0 *= scene.extruders[extruder_nr].settings.get<Ratio>("initial_layer_line_width_factor");
}
pattern_per_extruder_layer0.emplace_back();
ExtrusionMoves& pattern_layer0 = pattern_per_extruder_layer0.back();
// Generate a concentric infill pattern in the form insets for the prime tower's first layer instead of using
// the infill pattern because the infill pattern tries to connect polygons in different insets which causes the
// first layer of the prime tower to not stick well.
Polygons inset = outer_poly.offset(-line_width_layer0 / 2);
while (!inset.empty())
{
pattern_layer0.polygons.add(inset);
inset = inset.offset(-line_width_layer0);
}
}
}
void PrimeTower::generateStartLocations()
{
// Evenly spread out a number of dots along the prime tower's outline. This is done for the complete outline,
// so use the same start and end segments for this.
PolygonsPointIndex segment_start = PolygonsPointIndex(&outer_poly, 0, 0);
PolygonsPointIndex segment_end = segment_start;
PolygonUtils::spreadDots(segment_start, segment_end, number_of_prime_tower_start_locations, prime_tower_start_locations);
}
void PrimeTower::addToGcode(const SliceDataStorage& storage, LayerPlan& gcode_layer, const int prev_extruder, const int new_extruder) const
{
if (!enabled)
{
return;
}
if (gcode_layer.getPrimeTowerIsPlanned(new_extruder))
{ // don't print the prime tower if it has been printed already with this extruder.
return;
}
const LayerIndex layer_nr = gcode_layer.getLayerNr();
if (layer_nr > storage.max_print_height_second_to_last_extruder + 1)
{
return;
}
bool post_wipe = Application::getInstance().current_slice->scene.extruders[prev_extruder].settings.get<bool>("prime_tower_wipe_enabled");
// Do not wipe on the first layer, we will generate non-hollow prime tower there for better bed adhesion.
if (prev_extruder == new_extruder || layer_nr == 0)
{
post_wipe = false;
}
// Go to the start location if it's not the first layer
if (layer_nr != 0)
{
gotoStartLocation(gcode_layer, new_extruder);
}
addToGcode_denseInfill(gcode_layer, new_extruder);
// post-wipe:
if (post_wipe)
{
//Make sure we wipe the old extruder on the prime tower.
const Settings& previous_settings = Application::getInstance().current_slice->scene.extruders[prev_extruder].settings;
const Point previous_nozzle_offset = Point(previous_settings.get<coord_t>("machine_nozzle_offset_x"), previous_settings.get<coord_t>("machine_nozzle_offset_y"));
const Settings& new_settings = Application::getInstance().current_slice->scene.extruders[new_extruder].settings;
const Point new_nozzle_offset = Point(new_settings.get<coord_t>("machine_nozzle_offset_x"), new_settings.get<coord_t>("machine_nozzle_offset_y"));
gcode_layer.addTravel(post_wipe_point - previous_nozzle_offset + new_nozzle_offset);
}
gcode_layer.setPrimeTowerIsPlanned(new_extruder);
}
void PrimeTower::addToGcode_denseInfill(LayerPlan& gcode_layer, const size_t extruder_nr) const
{
const ExtrusionMoves& pattern = (gcode_layer.getLayerNr() == -static_cast<LayerIndex>(Raft::getFillerLayerCount()))
? pattern_per_extruder_layer0[extruder_nr]
: pattern_per_extruder[extruder_nr];
const GCodePathConfig& config = gcode_layer.configs_storage.prime_tower_config_per_extruder[extruder_nr];
gcode_layer.addPolygonsByOptimizer(pattern.polygons, config);
gcode_layer.addLinesByOptimizer(pattern.lines, config, SpaceFillType::Lines);
}
void PrimeTower::subtractFromSupport(SliceDataStorage& storage)
{
const Polygons outside_polygon = outer_poly.getOutsidePolygons();
AABB outside_polygon_boundary_box(outside_polygon);
for(size_t layer = 0; layer <= (size_t)storage.max_print_height_second_to_last_extruder + 1 && layer < storage.support.supportLayers.size(); layer++)
{
SupportLayer& support_layer = storage.support.supportLayers[layer];
// take the differences of the support infill parts and the prime tower area
support_layer.excludeAreasFromSupportInfillAreas(outside_polygon, outside_polygon_boundary_box);
}
}
void PrimeTower::gotoStartLocation(LayerPlan& gcode_layer, const int extruder_nr) const
{
int current_start_location_idx = ((((extruder_nr + 1) * gcode_layer.getLayerNr()) % number_of_prime_tower_start_locations)
+ number_of_prime_tower_start_locations) % number_of_prime_tower_start_locations;
const ClosestPolygonPoint wipe_location = prime_tower_start_locations[current_start_location_idx];
const ExtruderTrain& train = Application::getInstance().current_slice->scene.extruders[extruder_nr];
const coord_t inward_dist = train.settings.get<coord_t>("machine_nozzle_size") * 3 / 2 ;
const coord_t start_dist = train.settings.get<coord_t>("machine_nozzle_size") * 2;
const Point prime_end = PolygonUtils::moveInsideDiagonally(wipe_location, inward_dist);
const Point outward_dir = wipe_location.location - prime_end;
const Point prime_start = wipe_location.location + normal(outward_dir, start_dist);
gcode_layer.addTravel(prime_start);
}
}//namespace cura
<|endoftext|> |
<commit_before>#include "Rasterizer.h"
Rasterizer::Rasterizer()
: Renderer() {
}
Rasterizer::Rasterizer(World* world)
: Renderer(world) {
}
Rasterizer::~Rasterizer() {
}
const Fragment Rasterizer::calculateFragmentAttributes(const Triangle3D& triangle_world, const Point3D& point_world, const Material& material) const {
const Vector2D text_coords = calculateTextureCoords(triangle_world, point_world);
const Fragment f {
point_world,
calculateColor(triangle_world, point_world),
material.getDiffuseColor(text_coords),
material.getSpecularColor(text_coords),
material.getNormal(triangle_world, text_coords)
};
return f;
}
const double Rasterizer::calculateDepth(const Triangle3D& triangle_world, const Triangle2D& triangle_screen, const Point2D& pixel_screen) const {
const Triangle3D triangle_camera = Triangle3D(
Vertex3D (m_camera->viewTransform(triangle_world.v1.position), triangle_world.v1.color, triangle_world.v1.texture_coords, triangle_world.v1.normal),
Vertex3D(m_camera->viewTransform(triangle_world.v2.position), triangle_world.v2.color, triangle_world.v2.texture_coords, triangle_world.v1.normal),
Vertex3D(m_camera->viewTransform(triangle_world.v3.position), triangle_world.v3.color, triangle_world.v3.texture_coords, triangle_world.v1.normal)
);
// Calculate barycentric coords in camera space
double u, v, w;
triangle_screen.calculateBarycentricCoords(u, v, w, pixel_screen);
// Interpolate Z in 3D using inverse function and barycentric coordinates in 2D
const double depth = 1 /
(
(1 / triangle_camera.v1.position.z) * u +
(1 / triangle_camera.v2.position.z) * v +
(1 / triangle_camera.v3.position.z) * w
);
return depth;
}
const Vector2D Rasterizer::calculateTextureCoords(const Triangle3D& triangle_world, const Point3D& point_world) const {
// Calculate barycentric coords in camera space
double u, v, w;
triangle_world.calculateBarycentricCoords(u, v, w, point_world);
const Vector2D texture_coords = triangle_world.v1.texture_coords * u + triangle_world.v2.texture_coords * v + triangle_world.v3.texture_coords * w;
const Vector2D texture_coords_abs {
abs(texture_coords.x),
abs(texture_coords.y)
};
return texture_coords_abs;
}
const RGBColor Rasterizer::calculateColor(const Triangle3D& triangle_world, const Point3D& point_world) const {
// Calculate barycentric coords in camera space
double u, v, w;
triangle_world.calculateBarycentricCoords(u, v, w, point_world);
const RGBColor new_color = triangle_world.v1.color * u + triangle_world.v2.color * v + triangle_world.v3.color * w;
return new_color;
}
const Point2D Rasterizer::rasterize(const Point3D& point_world) const {
const Point3D point_camera = m_camera->viewTransform(point_world);
const Point2D point_projected = m_camera->projectTransform(point_camera);
const Point2D point_ndc = m_camera->ndcTransform(point_projected);
const Point2D point_raster = m_camera->viewportTransform(point_ndc);
return point_raster;
}
const Triangle2D Rasterizer::rasterize(const Triangle3D& triangle_world) const {
return Triangle2D(
rasterize(triangle_world.v1.position),
rasterize(triangle_world.v2.position),
rasterize(triangle_world.v3.position)
);
}
const Triangle2D Rasterizer::project(const Triangle3D& triangle_world) const {
return Triangle2D(
project(triangle_world.v1.position),
project(triangle_world.v2.position),
project(triangle_world.v3.position)
);
}
const Point2D Rasterizer::project(const Point3D& point_world) const {
const Point3D point_camera = m_camera->viewTransform(point_world);
const Point2D point_projected = m_camera->projectTransform(point_camera);
return point_projected;
}
const Point2D Rasterizer::unproject(const Point2D& point_raster) const {
const Point2D point_ndc = m_camera->viewportTransformInv(point_raster);
const Point2D point_projected = m_camera->ndcTransformInv(point_ndc);
return point_projected;
}
void Rasterizer::exportDepthBuffer(const std::vector<double>& depth_buffer, const std::string output_path, const uint16_t image_width, const uint16_t image_height) const {
std::vector<RGBColor> depth_buffer_grey(image_height*image_width, RGBColor(1.0));
for (int i = 0; i < depth_buffer.size(); ++i) {
const double depth = depth_buffer[i];
if (depth != m_camera->get_far_plane()) {
// Convert depth in the range [near, far] to [0,1]
const double slope = 1.0 / (m_camera->get_far_plane() - m_camera->get_near_plane());
const double depth_normalized = slope * (depth - m_camera->get_near_plane());
depth_buffer_grey[i] = RGBColor(depth_normalized);
}
}
exportImage(depth_buffer_grey, output_path, image_width, image_height);
}<commit_msg>Added perspective corrected mapping along with previously implemented affine mapping<commit_after>#include "Rasterizer.h"
Rasterizer::Rasterizer()
: Renderer() {
}
Rasterizer::Rasterizer(World* world)
: Renderer(world) {
}
Rasterizer::~Rasterizer() {
}
const Fragment Rasterizer::calculateFragmentAttributes(const Triangle3D& triangle_world, const Point3D& point_world, const Triangle2D& triangle_screen, const Point2D& pixel_screen, const Material& material) const {
const Vector2D text_coords = calculateTextureCoords(triangle_world, point_world, triangle_screen, pixel_screen);
const Fragment f {
point_world,
calculateColor(triangle_world, point_world),
material.getDiffuseColor(text_coords),
material.getSpecularColor(text_coords),
material.getNormal(triangle_world, text_coords)
};
return f;
}
const double Rasterizer::calculateDepth(const Triangle3D& triangle_world, const Triangle2D& triangle_screen, const Point2D& pixel_screen) const {
const Triangle3D triangle_camera = Triangle3D(
Vertex3D (m_camera->viewTransform(triangle_world.v1.position), triangle_world.v1.color, triangle_world.v1.texture_coords, triangle_world.v1.normal),
Vertex3D(m_camera->viewTransform(triangle_world.v2.position), triangle_world.v2.color, triangle_world.v2.texture_coords, triangle_world.v1.normal),
Vertex3D(m_camera->viewTransform(triangle_world.v3.position), triangle_world.v3.color, triangle_world.v3.texture_coords, triangle_world.v1.normal)
);
// Calculate barycentric coords in camera space
double u, v, w;
triangle_screen.calculateBarycentricCoords(u, v, w, pixel_screen);
// Interpolate Z in 3D using inverse function and barycentric coordinates in 2D
const double depth = 1 /
(
(1 / triangle_camera.v1.position.z) * u +
(1 / triangle_camera.v2.position.z) * v +
(1 / triangle_camera.v3.position.z) * w
);
return depth;
}
const Vector2D Rasterizer::calculateTextureCoords(const Triangle3D& triangle_world, const Point3D& pixel_world, const Triangle2D& triangle_camera, const Point2D& pixel_camera) const {
// Calculate barycentric coords in screen space (inverse linear)
double u, v, w;
triangle_camera.calculateBarycentricCoords(u, v, w, pixel_camera);
const Vector2D texture_coords = triangle_world.v1.texture_coords * u + triangle_world.v2.texture_coords * v + triangle_world.v3.texture_coords * w;
// Affine texture mapping (in screen space)
const Vector2D texture_coords_abs_screen {
abs(texture_coords.x),
abs(texture_coords.y)
};
#ifdef _AFFINE_TEXTURES
return texture_coords_abs_screen;
#endif
#ifdef _PERSPECTIVE_TEXTURES
// Lets take into account z
const double z = 1 / (1 / pixel_world.z);
const Vector2D texture_coords_perspective_corrected{
(texture_coords_abs_screen.x / z) * z,
(texture_coords_abs_screen.y / z) * z
};
return texture_coords_perspective_corrected;
#endif
}
const RGBColor Rasterizer::calculateColor(const Triangle3D& triangle_world, const Point3D& point_world) const {
// Calculate barycentric coords in camera space
double u, v, w;
triangle_world.calculateBarycentricCoords(u, v, w, point_world);
const RGBColor new_color = triangle_world.v1.color * u + triangle_world.v2.color * v + triangle_world.v3.color * w;
return new_color;
}
const Point2D Rasterizer::rasterize(const Point3D& point_world) const {
const Point3D point_camera = m_camera->viewTransform(point_world);
const Point2D point_projected = m_camera->projectTransform(point_camera);
const Point2D point_ndc = m_camera->ndcTransform(point_projected);
const Point2D point_raster = m_camera->viewportTransform(point_ndc);
return point_raster;
}
const Triangle2D Rasterizer::rasterize(const Triangle3D& triangle_world) const {
return Triangle2D(
rasterize(triangle_world.v1.position),
rasterize(triangle_world.v2.position),
rasterize(triangle_world.v3.position)
);
}
const Triangle2D Rasterizer::project(const Triangle3D& triangle_world) const {
return Triangle2D(
project(triangle_world.v1.position),
project(triangle_world.v2.position),
project(triangle_world.v3.position)
);
}
const Point2D Rasterizer::project(const Point3D& point_world) const {
const Point3D point_camera = m_camera->viewTransform(point_world);
const Point2D point_projected = m_camera->projectTransform(point_camera);
return point_projected;
}
const Point2D Rasterizer::unproject(const Point2D& point_raster) const {
const Point2D point_ndc = m_camera->viewportTransformInv(point_raster);
const Point2D point_projected = m_camera->ndcTransformInv(point_ndc);
return point_projected;
}
void Rasterizer::exportDepthBuffer(const std::vector<double>& depth_buffer, const std::string output_path, const uint16_t image_width, const uint16_t image_height) const {
std::vector<RGBColor> depth_buffer_grey(image_height*image_width, RGBColor(1.0));
for (int i = 0; i < depth_buffer.size(); ++i) {
const double depth = depth_buffer[i];
if (depth != m_camera->get_far_plane()) {
// Convert depth in the range [near, far] to [0,1]
const double slope = 1.0 / (m_camera->get_far_plane() - m_camera->get_near_plane());
const double depth_normalized = slope * (depth - m_camera->get_near_plane());
depth_buffer_grey[i] = RGBColor(depth_normalized);
}
}
exportImage(depth_buffer_grey, output_path, image_width, image_height);
}<|endoftext|> |
<commit_before>#include "SkipStages.h"
#include "IRMutator.h"
#include "IRPrinter.h"
#include "IROperator.h"
#include "Scope.h"
#include "Simplify.h"
#include "Substitute.h"
#include "ExprUsesVar.h"
namespace Halide {
namespace Internal {
using std::string;
using std::vector;
using std::map;
class PredicateFinder : public IRVisitor {
public:
Expr predicate;
PredicateFinder(const string &b) : predicate(const_false()), buffer(b), varies(false) {}
private:
using IRVisitor::visit;
string buffer;
bool varies;
Scope<int> varying;
void visit(const Variable *op) {
bool this_varies = varying.contains(op->name);
varies |= this_varies;
}
void visit(const For *op) {
op->min.accept(this);
bool min_varies = varies;
op->extent.accept(this);
bool should_pop = false;
if (!is_one(op->extent) || min_varies) {
should_pop = true;
varying.push(op->name, 0);
}
op->body.accept(this);
if (should_pop) {
varying.pop(op->name);
//internal_assert(!expr_uses_var(predicate, op->name));
} else {
predicate = substitute(op->name, op->min, predicate);
}
}
template<typename T>
void visit_let(const std::string &name, Expr value, T body) {
bool old_varies = varies;
varies = false;
value.accept(this);
bool value_varies = varies;
varies |= old_varies;
if (value_varies) {
varying.push(name, 0);
}
body.accept(this);
if (value_varies) {
varying.pop(name);
}
predicate = substitute(name, value, predicate);
}
void visit(const LetStmt *op) {
visit_let(op->name, op->value, op->body);
}
void visit(const Let *op) {
visit_let(op->name, op->value, op->body);
}
void visit(const Pipeline *op) {
if (op->name != buffer) {
op->produce.accept(this);
if (op->update.defined()) {
op->update.accept(this);
}
}
op->consume.accept(this);
}
template<typename T>
void visit_conditional(Expr condition, T true_case, T false_case) {
Expr old_predicate = predicate;
predicate = const_false();
true_case.accept(this);
Expr true_predicate = predicate;
predicate = const_false();
if (false_case.defined()) false_case.accept(this);
Expr false_predicate = predicate;
bool old_varies = varies;
predicate = const_false();
varies = false;
condition.accept(this);
if (is_one(predicate) || is_one(old_predicate)) {
predicate = const_true();
} else if (varies) {
if (is_one(true_predicate) || is_one(false_predicate)) {
predicate = const_true();
} else {
predicate = (old_predicate || predicate ||
true_predicate || false_predicate);
}
} else {
predicate = (old_predicate || predicate ||
(condition && true_predicate) ||
((!condition) && false_predicate));
}
varies = varies || old_varies;
}
void visit(const Select *op) {
visit_conditional(op->condition, op->true_value, op->false_value);
}
void visit(const IfThenElse *op) {
visit_conditional(op->condition, op->then_case, op->else_case);
}
void visit(const Call *op) {
IRVisitor::visit(op);
if (op->name == buffer) {
predicate = const_true();
}
}
};
class ProductionGuarder : public IRMutator {
public:
ProductionGuarder(const string &b, Expr p): buffer(b), predicate(p) {}
private:
string buffer;
Expr predicate;
using IRMutator::visit;
void visit(const Pipeline *op) {
// If the predicate at this stage depends on something
// vectorized we should bail out.
if (op->name == buffer) {
Stmt produce = op->produce, update = op->update;
if (update.defined()) {
Expr predicate_var = Variable::make(Bool(), buffer + ".needed");
Stmt produce = IfThenElse::make(predicate_var, op->produce);
Stmt update = IfThenElse::make(predicate_var, op->update);
stmt = Pipeline::make(op->name, produce, update, op->consume);
stmt = LetStmt::make(buffer + ".needed", predicate, stmt);
} else {
Stmt produce = IfThenElse::make(predicate, op->produce);
stmt = Pipeline::make(op->name, produce, Stmt(), op->consume);
}
} else {
IRMutator::visit(op);
}
}
};
class StageSkipper : public IRMutator {
public:
StageSkipper(const string &f) : func(f), in_vector_loop(false) {}
private:
string func;
using IRMutator::visit;
Scope<int> vector_vars;
bool in_vector_loop;
void visit(const For *op) {
bool old_in_vector_loop = in_vector_loop;
// We want to be sure that the predicate doesn't vectorize.
if (op->for_type == For::Vectorized) {
vector_vars.push(op->name, 0);
in_vector_loop = true;
}
IRMutator::visit(op);
if (op->for_type == For::Vectorized) {
vector_vars.pop(op->name);
}
in_vector_loop = old_in_vector_loop;
}
void visit(const LetStmt *op) {
bool should_pop = false;
if (in_vector_loop &&
expr_uses_vars(op->value, vector_vars)) {
should_pop = true;
vector_vars.push(op->name, 0);
}
IRMutator::visit(op);
if (should_pop) {
vector_vars.pop(op->name);
}
}
void visit(const Realize *op) {
if (op->name == func) {
PredicateFinder f(op->name);
op->body.accept(&f);
Expr predicate = simplify(f.predicate);
if (expr_uses_vars(predicate, vector_vars)) {
// Don't try to skip stages if the predicate may vary
// per lane. This will just unvectorize the
// production, which is probably contrary to the
// intent of the user.
predicate = const_true();
}
if (!is_one(predicate)) {
ProductionGuarder g(op->name, predicate);
Stmt body = g.mutate(op->body);
// In the future we may be able to shrink the size
// updated, but right now those values may be
// loaded. They can be incorrect, but they must be
// loadable. Perhaps we can mmap some readable junk memory
// (e.g. lots of pages of /dev/zero).
stmt = Realize::make(op->name, op->types, op->bounds, body);
} else {
IRMutator::visit(op);
}
} else {
IRMutator::visit(op);
}
}
};
// Check if all calls to a given function are behind an if of some
// sort (but don't worry about what it is).
class MightBeSkippable : public IRVisitor {
using IRVisitor::visit;
void visit(const Call *op) {
IRVisitor::visit(op);
if (op->name == func) {
if (!found_call) {
result = guarded;
found_call = true;
} else {
result &= guarded;
}
}
}
void visit(const IfThenElse *op) {
op->condition.accept(this);
bool old = guarded;
guarded = true;
op->then_case.accept(this);
if (op->else_case.defined()) {
op->else_case.accept(this);
}
guarded = old;
}
void visit(const Select *op) {
op->condition.accept(this);
bool old = guarded;
guarded = true;
op->true_value.accept(this);
op->false_value.accept(this);
guarded = old;
}
void visit(const Realize *op) {
if (op->name == func) {
guarded = false;
}
IRVisitor::visit(op);
}
void visit(const Pipeline *op) {
if (op->name == func) {
op->consume.accept(this);
} else {
IRVisitor::visit(op);
}
}
string func;
bool guarded;
public:
bool result;
bool found_call;
MightBeSkippable(string f) : func(f), result(false), found_call(false) {}
};
Stmt skip_stages(Stmt stmt, const vector<string> &order) {
for (size_t i = order.size()-1; i > 0; i--) {
MightBeSkippable check(order[i-1]);
stmt.accept(&check);
if (check.result) {
StageSkipper skipper(order[i-1]);
stmt = skipper.mutate(stmt);
}
}
return stmt;
}
}
}
<commit_msg>Fix uninitialized member in skip stages<commit_after>#include "SkipStages.h"
#include "IRMutator.h"
#include "IRPrinter.h"
#include "IROperator.h"
#include "Scope.h"
#include "Simplify.h"
#include "Substitute.h"
#include "ExprUsesVar.h"
namespace Halide {
namespace Internal {
using std::string;
using std::vector;
using std::map;
class PredicateFinder : public IRVisitor {
public:
Expr predicate;
PredicateFinder(const string &b) : predicate(const_false()), buffer(b), varies(false) {}
private:
using IRVisitor::visit;
string buffer;
bool varies;
Scope<int> varying;
void visit(const Variable *op) {
bool this_varies = varying.contains(op->name);
varies |= this_varies;
}
void visit(const For *op) {
op->min.accept(this);
bool min_varies = varies;
op->extent.accept(this);
bool should_pop = false;
if (!is_one(op->extent) || min_varies) {
should_pop = true;
varying.push(op->name, 0);
}
op->body.accept(this);
if (should_pop) {
varying.pop(op->name);
//internal_assert(!expr_uses_var(predicate, op->name));
} else {
predicate = substitute(op->name, op->min, predicate);
}
}
template<typename T>
void visit_let(const std::string &name, Expr value, T body) {
bool old_varies = varies;
varies = false;
value.accept(this);
bool value_varies = varies;
varies |= old_varies;
if (value_varies) {
varying.push(name, 0);
}
body.accept(this);
if (value_varies) {
varying.pop(name);
}
predicate = substitute(name, value, predicate);
}
void visit(const LetStmt *op) {
visit_let(op->name, op->value, op->body);
}
void visit(const Let *op) {
visit_let(op->name, op->value, op->body);
}
void visit(const Pipeline *op) {
if (op->name != buffer) {
op->produce.accept(this);
if (op->update.defined()) {
op->update.accept(this);
}
}
op->consume.accept(this);
}
template<typename T>
void visit_conditional(Expr condition, T true_case, T false_case) {
Expr old_predicate = predicate;
predicate = const_false();
true_case.accept(this);
Expr true_predicate = predicate;
predicate = const_false();
if (false_case.defined()) false_case.accept(this);
Expr false_predicate = predicate;
bool old_varies = varies;
predicate = const_false();
varies = false;
condition.accept(this);
if (is_one(predicate) || is_one(old_predicate)) {
predicate = const_true();
} else if (varies) {
if (is_one(true_predicate) || is_one(false_predicate)) {
predicate = const_true();
} else {
predicate = (old_predicate || predicate ||
true_predicate || false_predicate);
}
} else {
predicate = (old_predicate || predicate ||
(condition && true_predicate) ||
((!condition) && false_predicate));
}
varies = varies || old_varies;
}
void visit(const Select *op) {
visit_conditional(op->condition, op->true_value, op->false_value);
}
void visit(const IfThenElse *op) {
visit_conditional(op->condition, op->then_case, op->else_case);
}
void visit(const Call *op) {
IRVisitor::visit(op);
if (op->name == buffer) {
predicate = const_true();
}
}
};
class ProductionGuarder : public IRMutator {
public:
ProductionGuarder(const string &b, Expr p): buffer(b), predicate(p) {}
private:
string buffer;
Expr predicate;
using IRMutator::visit;
void visit(const Pipeline *op) {
// If the predicate at this stage depends on something
// vectorized we should bail out.
if (op->name == buffer) {
Stmt produce = op->produce, update = op->update;
if (update.defined()) {
Expr predicate_var = Variable::make(Bool(), buffer + ".needed");
Stmt produce = IfThenElse::make(predicate_var, op->produce);
Stmt update = IfThenElse::make(predicate_var, op->update);
stmt = Pipeline::make(op->name, produce, update, op->consume);
stmt = LetStmt::make(buffer + ".needed", predicate, stmt);
} else {
Stmt produce = IfThenElse::make(predicate, op->produce);
stmt = Pipeline::make(op->name, produce, Stmt(), op->consume);
}
} else {
IRMutator::visit(op);
}
}
};
class StageSkipper : public IRMutator {
public:
StageSkipper(const string &f) : func(f), in_vector_loop(false) {}
private:
string func;
using IRMutator::visit;
Scope<int> vector_vars;
bool in_vector_loop;
void visit(const For *op) {
bool old_in_vector_loop = in_vector_loop;
// We want to be sure that the predicate doesn't vectorize.
if (op->for_type == For::Vectorized) {
vector_vars.push(op->name, 0);
in_vector_loop = true;
}
IRMutator::visit(op);
if (op->for_type == For::Vectorized) {
vector_vars.pop(op->name);
}
in_vector_loop = old_in_vector_loop;
}
void visit(const LetStmt *op) {
bool should_pop = false;
if (in_vector_loop &&
expr_uses_vars(op->value, vector_vars)) {
should_pop = true;
vector_vars.push(op->name, 0);
}
IRMutator::visit(op);
if (should_pop) {
vector_vars.pop(op->name);
}
}
void visit(const Realize *op) {
if (op->name == func) {
PredicateFinder f(op->name);
op->body.accept(&f);
Expr predicate = simplify(f.predicate);
if (expr_uses_vars(predicate, vector_vars)) {
// Don't try to skip stages if the predicate may vary
// per lane. This will just unvectorize the
// production, which is probably contrary to the
// intent of the user.
predicate = const_true();
}
if (!is_one(predicate)) {
ProductionGuarder g(op->name, predicate);
Stmt body = g.mutate(op->body);
// In the future we may be able to shrink the size
// updated, but right now those values may be
// loaded. They can be incorrect, but they must be
// loadable. Perhaps we can mmap some readable junk memory
// (e.g. lots of pages of /dev/zero).
stmt = Realize::make(op->name, op->types, op->bounds, body);
} else {
IRMutator::visit(op);
}
} else {
IRMutator::visit(op);
}
}
};
// Check if all calls to a given function are behind an if of some
// sort (but don't worry about what it is).
class MightBeSkippable : public IRVisitor {
using IRVisitor::visit;
void visit(const Call *op) {
IRVisitor::visit(op);
if (op->name == func) {
if (!found_call) {
result = guarded;
found_call = true;
} else {
result &= guarded;
}
}
}
void visit(const IfThenElse *op) {
op->condition.accept(this);
bool old = guarded;
guarded = true;
op->then_case.accept(this);
if (op->else_case.defined()) {
op->else_case.accept(this);
}
guarded = old;
}
void visit(const Select *op) {
op->condition.accept(this);
bool old = guarded;
guarded = true;
op->true_value.accept(this);
op->false_value.accept(this);
guarded = old;
}
void visit(const Realize *op) {
if (op->name == func) {
guarded = false;
}
IRVisitor::visit(op);
}
void visit(const Pipeline *op) {
if (op->name == func) {
op->consume.accept(this);
} else {
IRVisitor::visit(op);
}
}
string func;
bool guarded;
public:
bool result;
bool found_call;
MightBeSkippable(string f) : func(f), guarded(false), result(false), found_call(false) {}
};
Stmt skip_stages(Stmt stmt, const vector<string> &order) {
// Don't consider the last stage, because it's the output, so it's
// never skippable.
for (size_t i = order.size()-1; i > 0; i--) {
MightBeSkippable check(order[i-1]);
stmt.accept(&check);
if (check.result) {
StageSkipper skipper(order[i-1]);
stmt = skipper.mutate(stmt);
}
}
return stmt;
}
}
}
<|endoftext|> |
<commit_before>#include "SystemData.h"
#include "GameData.h"
#include "XMLReader.h"
#include <boost/filesystem.hpp>
#include <fstream>
#include <stdlib.h>
#include <SDL_joystick.h>
#include "Renderer.h"
#include "AudioManager.h"
#include "VolumeControl.h"
#include "Log.h"
#include "InputManager.h"
#include <iostream>
#include "Settings.h"
std::vector<SystemData*> SystemData::sSystemVector;
namespace fs = boost::filesystem;
std::string SystemData::getStartPath() { return mStartPath; }
std::string SystemData::getExtension() { return mSearchExtension; }
SystemData::SystemData(std::string name, std::string descName, std::string startPath, std::string extension, std::string command)
{
mName = name;
mDescName = descName;
//expand home symbol if the startpath contains ~
if(startPath[0] == '~')
{
startPath.erase(0, 1);
std::string home = getHomePath();
startPath.insert(0, home);
}
mStartPath = startPath;
mSearchExtension = extension;
mLaunchCommand = command;
mRootFolder = new FolderData(this, mStartPath, "Search Root");
if(!Settings::getInstance()->getBool("PARSEGAMELISTONLY"))
populateFolder(mRootFolder);
if(!Settings::getInstance()->getBool("IGNOREGAMELIST"))
parseGamelist(this);
mRootFolder->sort();
}
SystemData::~SystemData()
{
//save changed game data back to xml
if(!Settings::getInstance()->getBool("IGNOREGAMELIST")) {
updateGamelist(this);
}
delete mRootFolder;
}
std::string strreplace(std::string& str, std::string replace, std::string with)
{
size_t pos = str.find(replace);
if(pos != std::string::npos)
return str.replace(pos, replace.length(), with.c_str(), with.length());
else
return str;
}
void SystemData::launchGame(Window* window, GameData* game)
{
LOG(LogInfo) << "Attempting to launch game...";
AudioManager::getInstance()->deinit();
VolumeControl::getInstance()->deinit();
window->deinit();
std::string command = mLaunchCommand;
command = strreplace(command, "%ROM%", game->getBashPath());
command = strreplace(command, "%BASENAME%", game->getBaseName());
command = strreplace(command, "%ROM_RAW%", game->getPath());
LOG(LogInfo) << " " << command;
std::cout << "==============================================\n";
int exitCode = system(command.c_str());
std::cout << "==============================================\n";
if(exitCode != 0)
{
LOG(LogWarning) << "...launch terminated with nonzero exit code " << exitCode << "!";
}
window->init();
VolumeControl::getInstance()->init();
AudioManager::getInstance()->init();
//update number of times the game has been launched and the time
game->setTimesPlayed(game->getTimesPlayed() + 1);
game->setLastPlayed(std::time(nullptr));
}
void SystemData::populateFolder(FolderData* folder)
{
std::string folderPath = folder->getPath();
if(!fs::is_directory(folderPath))
{
LOG(LogWarning) << "Error - folder with path \"" << folderPath << "\" is not a directory!";
return;
}
//make sure that this isn't a symlink to a thing we already have
if(fs::is_symlink(folderPath))
{
//if this symlink resolves to somewhere that's at the beginning of our path, it's gonna recurse
if(folderPath.find(fs::canonical(folderPath).string()) == 0)
{
LOG(LogWarning) << "Skipping infinitely recursive symlink \"" << folderPath << "\"";
return;
}
}
for(fs::directory_iterator end, dir(folderPath); dir != end; ++dir)
{
fs::path filePath = (*dir).path();
if(filePath.stem().string().empty())
continue;
//this is a little complicated because we allow a list of extensions to be defined (delimited with a space)
//we first get the extension of the file itself:
std::string extension = filePath.extension().string();
std::string chkExt;
size_t extPos = 0;
//folders *can* also match the extension and be added as games - this is mostly just to support higan
//see issue #75: https://github.com/Aloshi/EmulationStation/issues/75
bool isGame = false;
do {
//now we loop through every extension in the list
size_t cpos = extPos;
extPos = mSearchExtension.find(" ", extPos);
chkExt = mSearchExtension.substr(cpos, ((extPos == std::string::npos) ? mSearchExtension.length() - cpos: extPos - cpos));
//if it matches, add it
if(chkExt == extension)
{
GameData* newGame = new GameData(this, filePath.string(), filePath.stem().string());
folder->pushFileData(newGame);
isGame = true;
break;
}else if(extPos != std::string::npos) //if not, add one to the "next position" marker to skip the space when reading the next extension
{
extPos++;
}
} while(extPos != std::string::npos && chkExt != "" && chkExt.find(".") != std::string::npos);
//add directories that also do not match an extension as folders
if(!isGame && fs::is_directory(filePath))
{
FolderData* newFolder = new FolderData(this, filePath.string(), filePath.stem().string());
populateFolder(newFolder);
//ignore folders that do not contain games
if(newFolder->getFileCount() == 0)
delete newFolder;
else
folder->pushFileData(newFolder);
}
}
}
std::string SystemData::getName()
{
return mName;
}
std::string SystemData::getDescName()
{
return mDescName;
}
//creates systems from information located in a config file
void SystemData::loadConfig()
{
deleteSystems();
std::string path = getConfigPath();
LOG(LogInfo) << "Loading system config file...";
std::ifstream file(path.c_str());
if(file.is_open())
{
size_t lineNr = 0;
std::string line;
std::string sysName, sysDescName, sysPath, sysExtension, sysCommand;
while(file.good())
{
lineNr++;
std::getline(file, line);
//remove whitespace from line through STL and lambda magic
line.erase(std::remove_if(line.begin(), line.end(), [&](char c){ return std::string("\t\r\n\v\f").find(c) != std::string::npos; }), line.end());
//skip blank lines and comments
if(line.empty() || line.at(0) == '#')
continue;
//find the name (left of the equals sign) and the value (right of the equals sign)
bool lineValid = false;
std::string varName;
std::string varValue;
const std::string::size_type equalsPos = line.find('=', 1);
if(equalsPos != std::string::npos)
{
lineValid = true;
varName = line.substr(0, equalsPos);
varValue = line.substr(equalsPos + 1, line.length() - 1);
}
if(lineValid)
{
//map the value to the appropriate variable
if(varName == "NAME")
sysName = varValue;
else if(varName == "DESCNAME")
sysDescName = varValue;
else if(varName == "PATH")
{
if(varValue[varValue.length() - 1] == '/')
sysPath = varValue.substr(0, varValue.length() - 1);
else
sysPath = varValue;
}else if(varName == "EXTENSION")
sysExtension = varValue;
else if(varName == "COMMAND")
sysCommand = varValue;
//we have all our variables - create the system object
if(!sysName.empty() && !sysPath.empty() &&!sysExtension.empty() && !sysCommand.empty())
{
if(sysDescName.empty())
sysDescName = sysName;
SystemData* newSystem = new SystemData(sysName, sysDescName, sysPath, sysExtension, sysCommand);
if(newSystem->getRootFolder()->getFileCount() == 0)
{
LOG(LogWarning) << "System \"" << sysName << "\" has no games! Ignoring it.";
delete newSystem;
}else{
sSystemVector.push_back(newSystem);
}
//reset the variables for the next block (should there be one)
sysName = ""; sysDescName = ""; sysPath = ""; sysExtension = ""; sysCommand = "" ;
}
}else{
LOG(LogError) << "Error reading config file \"" << path << "\" - no equals sign found on line " << lineNr << ": \"" << line << "\"!";
return;
}
}
}else{
LOG(LogError) << "Error - could not load config file \"" << path << "\"!";
return;
}
LOG(LogInfo) << "Finished loading config file - created " << sSystemVector.size() << " systems.";
return;
}
void SystemData::writeExampleConfig()
{
std::string path = getConfigPath();
std::ofstream file(path.c_str());
file << "# This is the EmulationStation Systems configuration file." << std::endl;
file << "# Lines that begin with a hash (#) are ignored, as are empty lines." << std::endl;
file << "# A sample system might look like this:" << std::endl;
file << "#NAME=nes" << std::endl;
file << "#DESCNAME=Nintendo Entertainment System" << std::endl;
file << "#PATH=~/ROMs/nes/" << std::endl;
file << "#EXTENSION=.nes .NES" << std::endl;
file << "#COMMAND=retroarch -L ~/cores/libretro-fceumm.so %ROM%" << std::endl << std::endl;
file << "#NAME is a short name used internally (and in alternative paths)." << std::endl;
file << "#DESCNAME is a descriptive name to identify the system. It may be displayed in a header." << std::endl;
file << "#PATH is the path to start the recursive search for ROMs in. ~ will be expanded into the $HOME variable." << std::endl;
file << "#EXTENSION is a list of extensions to search for, separated by spaces. You MUST include the period, and it must be exact - it's case sensitive, and no wildcards." << std::endl;
file << "#COMMAND is the shell command to execute when a game is selected. %ROM% will be replaced with the (bash special-character escaped) path to the ROM." << std::endl << std::endl;
file << "#Now try your own!" << std::endl;
file << "NAME=" << std::endl;
file << "DESCNAME=" << std::endl;
file << "PATH=" << std::endl;
file << "EXTENSION=" << std::endl;
file << "COMMAND=" << std::endl;
file.close();
}
void SystemData::deleteSystems()
{
for(unsigned int i = 0; i < sSystemVector.size(); i++)
{
delete sSystemVector.at(i);
}
sSystemVector.clear();
}
std::string SystemData::getConfigPath()
{
std::string home = getHomePath();
if(home.empty())
{
LOG(LogError) << "$HOME environment variable empty or nonexistant!";
exit(1);
return "";
}
return(home + "/.emulationstation/es_systems.cfg");
}
FolderData* SystemData::getRootFolder()
{
return mRootFolder;
}
std::string SystemData::getGamelistPath()
{
std::string filePath;
filePath = mRootFolder->getPath() + "/gamelist.xml";
if(fs::exists(filePath))
return filePath;
filePath = getHomePath();
filePath += "/.emulationstation/"+ getName() + "/gamelist.xml";
if(fs::exists(filePath))
return filePath;
return "";
}
bool SystemData::hasGamelist()
{
if(getGamelistPath().empty())
return false;
else
return true;
}
<commit_msg>Use path.generic_string() for game paths. Should now only use forward slashes, regardless of platform.<commit_after>#include "SystemData.h"
#include "GameData.h"
#include "XMLReader.h"
#include <boost/filesystem.hpp>
#include <fstream>
#include <stdlib.h>
#include <SDL_joystick.h>
#include "Renderer.h"
#include "AudioManager.h"
#include "VolumeControl.h"
#include "Log.h"
#include "InputManager.h"
#include <iostream>
#include "Settings.h"
std::vector<SystemData*> SystemData::sSystemVector;
namespace fs = boost::filesystem;
std::string SystemData::getStartPath() { return mStartPath; }
std::string SystemData::getExtension() { return mSearchExtension; }
SystemData::SystemData(std::string name, std::string descName, std::string startPath, std::string extension, std::string command)
{
mName = name;
mDescName = descName;
//expand home symbol if the startpath contains ~
if(startPath[0] == '~')
{
startPath.erase(0, 1);
std::string home = getHomePath();
startPath.insert(0, home);
}
mStartPath = startPath;
mSearchExtension = extension;
mLaunchCommand = command;
mRootFolder = new FolderData(this, mStartPath, "Search Root");
if(!Settings::getInstance()->getBool("PARSEGAMELISTONLY"))
populateFolder(mRootFolder);
if(!Settings::getInstance()->getBool("IGNOREGAMELIST"))
parseGamelist(this);
mRootFolder->sort();
}
SystemData::~SystemData()
{
//save changed game data back to xml
if(!Settings::getInstance()->getBool("IGNOREGAMELIST")) {
updateGamelist(this);
}
delete mRootFolder;
}
std::string strreplace(std::string& str, std::string replace, std::string with)
{
size_t pos = str.find(replace);
if(pos != std::string::npos)
return str.replace(pos, replace.length(), with.c_str(), with.length());
else
return str;
}
void SystemData::launchGame(Window* window, GameData* game)
{
LOG(LogInfo) << "Attempting to launch game...";
AudioManager::getInstance()->deinit();
VolumeControl::getInstance()->deinit();
window->deinit();
std::string command = mLaunchCommand;
command = strreplace(command, "%ROM%", game->getBashPath());
command = strreplace(command, "%BASENAME%", game->getBaseName());
command = strreplace(command, "%ROM_RAW%", game->getPath());
LOG(LogInfo) << " " << command;
std::cout << "==============================================\n";
int exitCode = system(command.c_str());
std::cout << "==============================================\n";
if(exitCode != 0)
{
LOG(LogWarning) << "...launch terminated with nonzero exit code " << exitCode << "!";
}
window->init();
VolumeControl::getInstance()->init();
AudioManager::getInstance()->init();
//update number of times the game has been launched and the time
game->setTimesPlayed(game->getTimesPlayed() + 1);
game->setLastPlayed(std::time(nullptr));
}
void SystemData::populateFolder(FolderData* folder)
{
std::string folderPath = folder->getPath();
if(!fs::is_directory(folderPath))
{
LOG(LogWarning) << "Error - folder with path \"" << folderPath << "\" is not a directory!";
return;
}
//make sure that this isn't a symlink to a thing we already have
if(fs::is_symlink(folderPath))
{
//if this symlink resolves to somewhere that's at the beginning of our path, it's gonna recurse
if(folderPath.find(fs::canonical(folderPath).string()) == 0)
{
LOG(LogWarning) << "Skipping infinitely recursive symlink \"" << folderPath << "\"";
return;
}
}
for(fs::directory_iterator end, dir(folderPath); dir != end; ++dir)
{
fs::path filePath = (*dir).path();
if(filePath.stem().string().empty())
continue;
//this is a little complicated because we allow a list of extensions to be defined (delimited with a space)
//we first get the extension of the file itself:
std::string extension = filePath.extension().string();
std::string chkExt;
size_t extPos = 0;
//folders *can* also match the extension and be added as games - this is mostly just to support higan
//see issue #75: https://github.com/Aloshi/EmulationStation/issues/75
bool isGame = false;
do {
//now we loop through every extension in the list
size_t cpos = extPos;
extPos = mSearchExtension.find(" ", extPos);
chkExt = mSearchExtension.substr(cpos, ((extPos == std::string::npos) ? mSearchExtension.length() - cpos: extPos - cpos));
//if it matches, add it
if(chkExt == extension)
{
GameData* newGame = new GameData(this, filePath.generic_string(), filePath.stem().string());
folder->pushFileData(newGame);
isGame = true;
break;
}else if(extPos != std::string::npos) //if not, add one to the "next position" marker to skip the space when reading the next extension
{
extPos++;
}
} while(extPos != std::string::npos && chkExt != "" && chkExt.find(".") != std::string::npos);
//add directories that also do not match an extension as folders
if(!isGame && fs::is_directory(filePath))
{
FolderData* newFolder = new FolderData(this, filePath.string(), filePath.stem().string());
populateFolder(newFolder);
//ignore folders that do not contain games
if(newFolder->getFileCount() == 0)
delete newFolder;
else
folder->pushFileData(newFolder);
}
}
}
std::string SystemData::getName()
{
return mName;
}
std::string SystemData::getDescName()
{
return mDescName;
}
//creates systems from information located in a config file
void SystemData::loadConfig()
{
deleteSystems();
std::string path = getConfigPath();
LOG(LogInfo) << "Loading system config file...";
std::ifstream file(path.c_str());
if(file.is_open())
{
size_t lineNr = 0;
std::string line;
std::string sysName, sysDescName, sysPath, sysExtension, sysCommand;
while(file.good())
{
lineNr++;
std::getline(file, line);
//remove whitespace from line through STL and lambda magic
line.erase(std::remove_if(line.begin(), line.end(), [&](char c){ return std::string("\t\r\n\v\f").find(c) != std::string::npos; }), line.end());
//skip blank lines and comments
if(line.empty() || line.at(0) == '#')
continue;
//find the name (left of the equals sign) and the value (right of the equals sign)
bool lineValid = false;
std::string varName;
std::string varValue;
const std::string::size_type equalsPos = line.find('=', 1);
if(equalsPos != std::string::npos)
{
lineValid = true;
varName = line.substr(0, equalsPos);
varValue = line.substr(equalsPos + 1, line.length() - 1);
}
if(lineValid)
{
//map the value to the appropriate variable
if(varName == "NAME")
sysName = varValue;
else if(varName == "DESCNAME")
sysDescName = varValue;
else if(varName == "PATH")
{
if(varValue[varValue.length() - 1] == '/')
sysPath = varValue.substr(0, varValue.length() - 1);
else
sysPath = varValue;
}else if(varName == "EXTENSION")
sysExtension = varValue;
else if(varName == "COMMAND")
sysCommand = varValue;
//we have all our variables - create the system object
if(!sysName.empty() && !sysPath.empty() &&!sysExtension.empty() && !sysCommand.empty())
{
if(sysDescName.empty())
sysDescName = sysName;
SystemData* newSystem = new SystemData(sysName, sysDescName, sysPath, sysExtension, sysCommand);
if(newSystem->getRootFolder()->getFileCount() == 0)
{
LOG(LogWarning) << "System \"" << sysName << "\" has no games! Ignoring it.";
delete newSystem;
}else{
sSystemVector.push_back(newSystem);
}
//reset the variables for the next block (should there be one)
sysName = ""; sysDescName = ""; sysPath = ""; sysExtension = ""; sysCommand = "" ;
}
}else{
LOG(LogError) << "Error reading config file \"" << path << "\" - no equals sign found on line " << lineNr << ": \"" << line << "\"!";
return;
}
}
}else{
LOG(LogError) << "Error - could not load config file \"" << path << "\"!";
return;
}
LOG(LogInfo) << "Finished loading config file - created " << sSystemVector.size() << " systems.";
return;
}
void SystemData::writeExampleConfig()
{
std::string path = getConfigPath();
std::ofstream file(path.c_str());
file << "# This is the EmulationStation Systems configuration file." << std::endl;
file << "# Lines that begin with a hash (#) are ignored, as are empty lines." << std::endl;
file << "# A sample system might look like this:" << std::endl;
file << "#NAME=nes" << std::endl;
file << "#DESCNAME=Nintendo Entertainment System" << std::endl;
file << "#PATH=~/ROMs/nes/" << std::endl;
file << "#EXTENSION=.nes .NES" << std::endl;
file << "#COMMAND=retroarch -L ~/cores/libretro-fceumm.so %ROM%" << std::endl << std::endl;
file << "#NAME is a short name used internally (and in alternative paths)." << std::endl;
file << "#DESCNAME is a descriptive name to identify the system. It may be displayed in a header." << std::endl;
file << "#PATH is the path to start the recursive search for ROMs in. ~ will be expanded into the $HOME variable." << std::endl;
file << "#EXTENSION is a list of extensions to search for, separated by spaces. You MUST include the period, and it must be exact - it's case sensitive, and no wildcards." << std::endl;
file << "#COMMAND is the shell command to execute when a game is selected. %ROM% will be replaced with the (bash special-character escaped) path to the ROM." << std::endl << std::endl;
file << "#Now try your own!" << std::endl;
file << "NAME=" << std::endl;
file << "DESCNAME=" << std::endl;
file << "PATH=" << std::endl;
file << "EXTENSION=" << std::endl;
file << "COMMAND=" << std::endl;
file.close();
}
void SystemData::deleteSystems()
{
for(unsigned int i = 0; i < sSystemVector.size(); i++)
{
delete sSystemVector.at(i);
}
sSystemVector.clear();
}
std::string SystemData::getConfigPath()
{
std::string home = getHomePath();
if(home.empty())
{
LOG(LogError) << "$HOME environment variable empty or nonexistant!";
exit(1);
return "";
}
return(home + "/.emulationstation/es_systems.cfg");
}
FolderData* SystemData::getRootFolder()
{
return mRootFolder;
}
std::string SystemData::getGamelistPath()
{
std::string filePath;
filePath = mRootFolder->getPath() + "/gamelist.xml";
if(fs::exists(filePath))
return filePath;
filePath = getHomePath();
filePath += "/.emulationstation/"+ getName() + "/gamelist.xml";
if(fs::exists(filePath))
return filePath;
return "";
}
bool SystemData::hasGamelist()
{
if(getGamelistPath().empty())
return false;
else
return true;
}
<|endoftext|> |
<commit_before>#include <vector>
#include "TH1D.h"
#include "TList.h"
#include "RooAddPdf.h"
#include "RooArgSet.h"
#include "RooRealVar.h"
#include "RooCategory.h"
#include "RooDataSet.h"
#include "RooKeysPdf.h"
#include "FitTools.h"
using namespace RooFit;
ClassImp(FitTools)
//--------------------------------------------------------------------
FitTools::FitTools()
{
SetMultiplyLumi(true);
}
//--------------------------------------------------------------------
FitTools::~FitTools()
{ }
//--------------------------------------------------------------------
void
FitTools::GetJointPdf(const char* name, std::vector<TString> files, FileType type)
{
std::vector<FileInfo*> *info = GetFileInfo(type);
// Open the files and get the TTrees
OpenFiles(files);
// Initialize an empty dataset
const char *dataname = TString::Format("Dataset_%s", name);
RooDataSet dataset(dataname, dataname,
RooArgSet(*fWorkspace.var(fDefaultExpr),
*fWorkspace.cat("categories")));
// Add the data from each tree to the dataset
for (UInt_t iTree = 0; iTree != fInTrees.size(); ++iTree) {
const char *datasetname = TString::Format("Dataset_%s_%i", name, iTree).Data();
RooDataSet *tempData = new RooDataSet(datasetname, datasetname, fInTrees[iTree],
RooArgSet(*fWorkspace.var(fDefaultExpr),
*fWorkspace.cat("categories")),
fBaseCut, fMCWeight);
dataset.append(*tempData);
}
// Split and add these pdfs together with the proper relative weights, if needed
const char *pdfName = TString::Format("pdf_%s", name);
if (name[0] == 'F') {
TList *dataList = dataset.split(*fWorkspace.cat("categories"));
Message(eDebug, "Dataset list size: %i", dataList->GetSize());
RooArgSet pdfSet;
RooArgSet coeffSet;
for (UInt_t iBin = 0; iBin != fCategoryNames.size(); ++iBin) {
const char *pdfNameTemp = TString::Format("pdf_%s_%i", name, iBin);
RooKeysPdf *tempPdf = new RooKeysPdf(pdfNameTemp, pdfNameTemp, *fWorkspace.var(fDefaultExpr),
*(static_cast<RooDataSet*>(dataList->At(iBin))));
pdfSet.add(*tempPdf);
if (iBin != fCategoryNames.size() - 1) {
const char *coeffName = TString::Format("coeff_%s_%i", name, iBin);
RooRealVar *tempVar = new RooRealVar(coeffName, coeffName, 0.0, 1.0);
coeffSet.add(*tempVar);
}
}
RooAddPdf finalPdf(pdfName, pdfName, pdfSet, coeffSet);
fWorkspace.import(finalPdf);
}
else {
RooKeysPdf finalPdf(pdfName, pdfName, *fWorkspace.var(fDefaultExpr), dataset);
fWorkspace.import(finalPdf);
}
CloseFiles();
// create the pdf
}
//--------------------------------------------------------------------
void
FitTools::FitCategories(TString CategoryVar, Int_t NumCategories,
Double_t Shape_Min, Double_t Shape_Max, const char* ShapeLabel)
{
DisplayFunc(__func__);
Message(eDebug, "About to fit %i categories %s to shape of %s",
NumCategories, CategoryVar.Data(), fDefaultExpr.Data());
Message(eDebug, "Data cut is %s", fDataBaseCut.GetTitle());
Message(eDebug, " MC cut is %s", fBaseCut.GetTitle());
if (fSignalName != "")
Message(eDebug, "Only reweighting %s", fSignalName.Data());
Int_t NumBins = 1;
Double_t *XBins;
ConvertToArray(NumBins, Shape_Min, Shape_Max, XBins);
// Create the variable being plotted
RooRealVar variable = RooRealVar(fDefaultExpr, ShapeLabel, Shape_Min, Shape_Max);
// Create category variable
RooCategory category = RooCategory("categories", "categories");
// Set category names
for (UInt_t iCat = 0; iCat != fCategoryNames.size(); ++iCat)
category.defineType(fCategoryNames[iCat], iCat);
fWorkspace.import(variable);
fWorkspace.import(category);
TH1D *FloatSize = GetHist(NumBins, XBins, fSignalType, fSignalName, fSearchBy, true);
// Get the pdf that we'll be floating
GetJointPdf("Floating", ReturnFileNames(fSignalType, fSignalName, fSearchBy, true), fSignalType);
TH1D *StaticSize = GetHist(NumBins, XBins, kBackground, fSignalName, fSearchBy, false);
// Get the other background files that will be static
GetJointPdf("Static", ReturnFileNames(kBackground, fSignalName, fSearchBy, false));
}
<commit_msg>Fixed the allocation of the array.<commit_after>#include <vector>
#include "TH1D.h"
#include "TList.h"
#include "RooAddPdf.h"
#include "RooArgSet.h"
#include "RooRealVar.h"
#include "RooCategory.h"
#include "RooDataSet.h"
#include "RooKeysPdf.h"
#include "FitTools.h"
using namespace RooFit;
ClassImp(FitTools)
//--------------------------------------------------------------------
FitTools::FitTools()
{
SetMultiplyLumi(true);
}
//--------------------------------------------------------------------
FitTools::~FitTools()
{ }
//--------------------------------------------------------------------
void
FitTools::GetJointPdf(const char* name, std::vector<TString> files, FileType type)
{
std::vector<FileInfo*> *info = GetFileInfo(type);
// Open the files and get the TTrees
OpenFiles(files);
// Initialize an empty dataset
const char *dataname = TString::Format("Dataset_%s", name);
RooDataSet dataset(dataname, dataname,
RooArgSet(*fWorkspace.var(fDefaultExpr),
*fWorkspace.cat("categories")));
// Add the data from each tree to the dataset
for (UInt_t iTree = 0; iTree != fInTrees.size(); ++iTree) {
const char *datasetname = TString::Format("Dataset_%s_%i", name, iTree).Data();
RooDataSet *tempData = new RooDataSet(datasetname, datasetname, fInTrees[iTree],
RooArgSet(*fWorkspace.var(fDefaultExpr),
*fWorkspace.cat("categories")),
fBaseCut, fMCWeight);
dataset.append(*tempData);
}
// Split and add these pdfs together with the proper relative weights, if needed
const char *pdfName = TString::Format("pdf_%s", name);
if (name[0] == 'F') {
TList *dataList = dataset.split(*fWorkspace.cat("categories"));
Message(eDebug, "Dataset list size: %i", dataList->GetSize());
RooArgSet pdfSet;
RooArgSet coeffSet;
for (UInt_t iBin = 0; iBin != fCategoryNames.size(); ++iBin) {
const char *pdfNameTemp = TString::Format("pdf_%s_%i", name, iBin);
RooKeysPdf *tempPdf = new RooKeysPdf(pdfNameTemp, pdfNameTemp, *fWorkspace.var(fDefaultExpr),
*(static_cast<RooDataSet*>(dataList->At(iBin))));
pdfSet.add(*tempPdf);
if (iBin != fCategoryNames.size() - 1) {
const char *coeffName = TString::Format("coeff_%s_%i", name, iBin);
RooRealVar *tempVar = new RooRealVar(coeffName, coeffName, 0.0, 1.0);
coeffSet.add(*tempVar);
}
}
RooAddPdf finalPdf(pdfName, pdfName, pdfSet, coeffSet);
fWorkspace.import(finalPdf);
}
else {
RooKeysPdf finalPdf(pdfName, pdfName, *fWorkspace.var(fDefaultExpr), dataset);
fWorkspace.import(finalPdf);
}
CloseFiles();
// create the pdf
}
//--------------------------------------------------------------------
void
FitTools::FitCategories(TString CategoryVar, Int_t NumCategories,
Double_t Shape_Min, Double_t Shape_Max, const char* ShapeLabel)
{
DisplayFunc(__func__);
Message(eDebug, "About to fit %i categories %s to shape of %s",
NumCategories, CategoryVar.Data(), fDefaultExpr.Data());
Message(eDebug, "Data cut is %s", fDataBaseCut.GetTitle());
Message(eDebug, " MC cut is %s", fBaseCut.GetTitle());
if (fSignalName != "")
Message(eDebug, "Only reweighting %s", fSignalName.Data());
Double_t XBins[2];
ConvertToArray(1, Shape_Min, Shape_Max, XBins);
// Create the variable being plotted
RooRealVar variable = RooRealVar(fDefaultExpr, ShapeLabel, Shape_Min, Shape_Max);
// Create category variable
RooCategory category = RooCategory("categories", "categories");
// Set category names
for (UInt_t iCat = 0; iCat != fCategoryNames.size(); ++iCat)
category.defineType(fCategoryNames[iCat], iCat);
fWorkspace.import(variable);
fWorkspace.import(category);
TH1D *FloatSize = GetHist(1, XBins, fSignalType, fSignalName, fSearchBy, true);
// Get the pdf that we'll be floating, named "pdf_Floating"
GetJointPdf("Floating", ReturnFileNames(fSignalType, fSignalName, fSearchBy, true), fSignalType);
TH1D *StaticSize = GetHist(1, XBins, kBackground, fSignalName, fSearchBy, false);
// Get the other background files that will be static, named "pdf_Static"
GetJointPdf("Static", ReturnFileNames(kBackground, fSignalName, fSearchBy, false));
}
<|endoftext|> |
<commit_before>#ifdef _WINDOWS
/*
* NOTE: Some macros must be defined in project options of Visual Studio.
* - _CRT_SECURE_NO_WARNINGS
* To use strncpy().
* - NOMINMAX
* To use std::min(), std::max().
*/
#include <windows.h>
BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
{
switch (ul_reason_for_call) {
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
#endif
<commit_msg>Add comment about suppress the warning C4251 of Visual Studio.<commit_after>#ifdef _WINDOWS
/*
* NOTE: Some macros must be defined in project options of Visual Studio.
* - _CRT_SECURE_NO_WARNINGS
* To use strncpy().
* - NOMINMAX
* To use std::min(), std::max().
* NOTE: Suppress some warnings of Visual Studio.
* - C4251
*/
#include <windows.h>
BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
{
switch (ul_reason_for_call) {
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
#endif
<|endoftext|> |
<commit_before>#include <iostream>
#include <vector>
using namespace std;
class MyData
{
public:
const int foo;
int bar;
MyData(const int& _initBar ) : foo(_initBar)
{
bar = _initBar; //some cool operation to set up bar
}
void update(const int& _newbar) { bar = _newbar;};
string get(){ return "foo: " + to_string(foo) + " bar: " + to_string(bar);};
};
class A
{
protected:
const string s;
MyData d;
public:
A( auto _s, int& _i ): s( _s ), d( _i ) { cout << "Constructor A: " << s <<endl; };
virtual ~A(void) { cout << "destructor A" << endl; };
virtual void f() { cout << "A::f()" << endl; };
virtual void g() { cout << "A::g()" << endl; };
virtual string get(){ return "s: " + s + "d: (" + d.get() +")";};
};
class BA : public A
{
protected:
virtual string k() = 0;
public:
BA( auto _s, auto _i) : A( _s, _i) { cout << "Constructor B: " << endl; };
void h() { cout << "B::h()" << endl; };
};
class CBA : public BA
{
int foobar;
public:
CBA( auto _s, auto _i ) : BA( _s, _i ), foobar(42) { l(); };
CBA( auto _s, auto _i, auto _fb ) : BA( _s, _i ), foobar(_fb) { l(); };
private:
string k() {return "CBA needs to implement BA::k() because it is pure virtual";};
void l() { cout << "CBA::l()" << endl; };
};
class DA : public A
{
vector<string> s_vec;
BA* b_ptr;
public:
DA( auto _s, auto _i ) : A ( _s, _i ) {};
void m() { cout << "DA::m()" << endl; };
~DA(){ cout << "~DA" <<endl; };
};
void show(const string who, const string info)
{
cout << "MAIN:: "+ who + info << endl;
}
int main( int argc, const char** argv )
{
MyData d(33);
show("d", d.get());
d.update(99);
show("d", d.get());
CBA cba("cbaName", 100);
show("cba", cba.get());
DA da("cbaName", 200);
show("da", da.get());
}
<commit_msg>Added a working MWE<commit_after>#include <iostream>
#include <vector>
using namespace std;
class MyData
{
public:
const int foo;
int bar;
MyData(const int& _initBar ) : foo(_initBar)
{
bar = _initBar; //some cool operation to set up bar
}
void update(const int& _newbar) { bar = _newbar;};
string get(){ return "foo: " + to_string(foo) + " bar: " + to_string(bar);};
};
class A
{
protected:
const string s;
MyData d;
public:
A( auto _s, int& _i ): s( _s ), d( _i ) { cout << "Constructor A: " << s <<endl; };
virtual ~A(void) { cout << "destructor A" << endl; };
virtual void f() { cout << "A::f()" << endl; };
virtual void g() { cout << "A::g()" << endl; };
virtual string get(){ return "s: " + s + "d: (" + d.get() +")";};
};
class BA : public A
{
protected:
virtual string k() = 0;
public:
BA( auto _s, auto _i) : A( _s, _i) { cout << "Constructor B: " << endl; };
void h() { cout << "B::h()" << endl; };
};
class CBA : public BA
{
int foobar;
public:
CBA( auto _s, auto _i ) : BA( _s, _i ), foobar(42) { cout << "Constructor C (foobar default):"; l(); };
CBA( auto _s, auto _i, auto _fb ) : BA( _s, _i ), foobar(_fb) { cout << "Constructor C (foobar parameter):"; l(); };
private:
string k() {return "CBA needs to implement BA::k() because it is pure virtual";};
void l() { cout << "CBA::l()" << endl; };
};
class DA : public A
{
vector<string> s_vec;
BA* b_ptr;
public:
DA( auto _s, auto _i ) : A ( _s, _i ) {};
void m() { cout << "DA::m()" << endl; };
~DA(){ cout << "destructor DA" <<endl; };
};
void show(const string who, const string info)
{
cout << "MAIN::"+ who +" info: "+ info << endl;
}
int main( int argc, const char** argv )
{
MyData d(33);
show("d", d.get());
d.update(99);
show("d", d.get());
CBA cba("cbaName", 100);
show("cba", cba.get());
DA da("cbaName", 200);
show("da", da.get());
}
<|endoftext|> |
<commit_before>/*
Flexisip, a flexible SIP proxy server with media capabilities.
Copyright (C) 2010-2015 Belledonne Communications SARL, 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 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 "authdb.hh"
#include "utils/threadpool.hh"
#include <thread>
#include <chrono>
using namespace soci;
using namespace chrono;
void SociAuthDB::declareConfig(GenericStruct *mc) {
// ODBC-specific configuration keys
ConfigItemDescriptor items[] = {
{String, "soci-password-request",
"Soci SQL request to execute to obtain the password.\n"
"Named parameters are:\n -':id' : the user found in the from header,\n -':domain' : the authorization realm, "
"and\n -':authid' : the authorization username.\n"
"The use of the :id parameter is mandatory.",
"select password from accounts where id = :id and domain = :domain and authid=:authid"},
{Integer, "soci-poolsize",
"Size of the pool of connections that Soci will use. We open a thread for each DB query, and this pool will "
"allow each thread to get a connection.\n"
"The threads are blocked until a connection is released back to the pool, so increasing the pool size will "
"allow more connections to occur simultaneously.\n"
"On the other hand, you should not keep too many open connections to your DB at the same time.",
"100"},
{String, "soci-backend", "Choose the type of backend that Soci will use for the connection.\n"
"Depending on your Soci package and the modules you installed, this could be 'mysql', "
"'oracle', 'postgresql' or something else.",
"mysql"},
{String, "soci-connection-string", "The configuration parameters of the Soci backend.\n"
"The basic format is \"key=value key2=value2\". For a mysql backend, this "
"is a valid config: \"db=mydb user=user password='pass' host=myhost.com\".\n"
"Please refer to the Soci documentation of your backend, for intance: "
"http://soci.sourceforge.net/doc/3.2/backends/mysql.html",
"db=mydb user=myuser password='mypass' host=myhost.com"},
{Integer, "soci-max-queue-size", "Amount of queries that will be allowed to be queued before bailing password "
"requests. This value should be chosen accordingly with 'soci-poolsize', so "
"that you have a coherent behavior. This limit is here mainly as a safeguard "
"against out-of-control growth of the queue in the event of a flood or big "
"delays in the database backend.",
"1000"},
config_item_end};
mc->addChildrenValues(items);
}
SociAuthDB::SociAuthDB() : conn_pool(NULL) {
GenericStruct *cr=GenericManager::get()->getRoot();
GenericStruct *ma=cr->get<GenericStruct>("module::Authentication");
poolSize = ma->get< ConfigInt >("soci-poolsize")->read();;
connection_string = ma->get<ConfigString>("soci-connection-string")->read();
backend = ma->get<ConfigString>("soci-backend")->read();
get_password_request = ma->get<ConfigString>("soci-password-request")->read();
int max_queue_size = ma->get<ConfigInt>("soci-max-queue-size")->read();
conn_pool = new connection_pool(poolSize);
thread_pool = new ThreadPool(poolSize, max_queue_size);
LOGD("[SOCI] Authentication provider for backend %s created. Pooled for %d connections", backend.c_str(),
(int)poolSize);
for (size_t i = 0; i < poolSize; i++) {
conn_pool->at(i).open(backend, connection_string);
}
}
SociAuthDB::~SociAuthDB() {
delete thread_pool; // will automatically shut it down, clearing threads
delete conn_pool;
}
#define DURATION_MS(start, stop) (unsigned long) duration_cast<milliseconds>((stop) - (start)).count()
void SociAuthDB::getPasswordWithPool(su_root_t *root, const std::string &id, const std::string &domain,
const std::string &authid, AuthDbListener *listener) {
steady_clock::time_point start = steady_clock::now();
// Either:
// will grab a connection from the pool. This is thread safe
session sql(*conn_pool);
std::string pass;
steady_clock::time_point stop = steady_clock::now();
SLOGD << "[SOCI] Pool acquired in " << DURATION_MS(start, stop) << "ms";
start = stop;
try {
sql << get_password_request, into(pass), use(id, "id"), use(domain, "domain"), use(authid, "authid");
stop = steady_clock::now();
SLOGD << "[SOCI] Got pass for " << id << " in " << DURATION_MS(start, stop) << "ms";
cachePassword(createPasswordKey(id, domain, authid), domain, pass, mCacheExpire);
notifyPasswordRetrieved(root, listener, PASSWORD_FOUND, pass);
} catch (mysql_soci_error const &e) {
stop = steady_clock::now();
SLOGE << "[SOCI] MySQL error after " << DURATION_MS(start, stop) << "ms : " << e.err_num_ << " " << e.what();
notifyPasswordRetrieved(root, listener, PASSWORD_NOT_FOUND, pass);
} catch (exception const &e) {
stop = steady_clock::now();
SLOGE << "[SOCI] Some other error after " << DURATION_MS(start, stop) << "ms : " << e.what();
notifyPasswordRetrieved(root, listener, PASSWORD_NOT_FOUND, pass);
}
}
#pragma mark - Inherited virtuals
void SociAuthDB::getPasswordFromBackend(su_root_t *root, const std::string &id, const std::string &domain,
const std::string &authid, AuthDbListener *listener) {
// create a thread to grab a pool connection and use it to retrieve the auth information
auto func = bind(&SociAuthDB::getPasswordWithPool, this, root, id, domain, authid, listener);
// the thread pool only accepts function<void>(), so we use a closure here.
// it can also fail to enqueue when the queue is full, so we have to act on that
bool success = thread_pool->Enqueue([func]() { func(); });
if (success == FALSE) {
SLOGE << "[SOCI] Auth queue is full, cannot fullfil password request for " << id << " / " << domain << " / "
<< authid;
notifyPasswordRetrieved(root, listener, AUTH_ERROR, "");
}
return;
}<commit_msg>Soci re-indentation<commit_after>/*
Flexisip, a flexible SIP proxy server with media capabilities.
Copyright (C) 2010-2015 Belledonne Communications SARL, 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 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 "authdb.hh"
#include "utils/threadpool.hh"
#include <thread>
#include <chrono>
using namespace soci;
using namespace chrono;
void SociAuthDB::declareConfig(GenericStruct *mc) {
// ODBC-specific configuration keys
ConfigItemDescriptor items[] = {
{String, "soci-password-request",
"Soci SQL request to execute to obtain the password.\n"
"Named parameters are:\n -':id' : the user found in the from header,\n -':domain' : the authorization realm, "
"and\n -':authid' : the authorization username.\n"
"The use of the :id parameter is mandatory.",
"select password from accounts where id = :id and domain = :domain and authid=:authid"},
{Integer, "soci-poolsize",
"Size of the pool of connections that Soci will use. We open a thread for each DB query, and this pool will "
"allow each thread to get a connection.\n"
"The threads are blocked until a connection is released back to the pool, so increasing the pool size will "
"allow more connections to occur simultaneously.\n"
"On the other hand, you should not keep too many open connections to your DB at the same time.",
"100"},
{String, "soci-backend", "Choose the type of backend that Soci will use for the connection.\n"
"Depending on your Soci package and the modules you installed, this could be 'mysql', "
"'oracle', 'postgresql' or something else.",
"mysql"},
{String, "soci-connection-string", "The configuration parameters of the Soci backend.\n"
"The basic format is \"key=value key2=value2\". For a mysql backend, this "
"is a valid config: \"db=mydb user=user password='pass' host=myhost.com\".\n"
"Please refer to the Soci documentation of your backend, for intance: "
"http://soci.sourceforge.net/doc/3.2/backends/mysql.html",
"db=mydb user=myuser password='mypass' host=myhost.com"},
{Integer, "soci-max-queue-size", "Amount of queries that will be allowed to be queued before bailing password "
"requests. This value should be chosen accordingly with 'soci-poolsize', so "
"that you have a coherent behavior. This limit is here mainly as a safeguard "
"against out-of-control growth of the queue in the event of a flood or big "
"delays in the database backend.",
"1000"},
config_item_end};
mc->addChildrenValues(items);
}
SociAuthDB::SociAuthDB() : conn_pool(NULL) {
GenericStruct *cr = GenericManager::get()->getRoot();
GenericStruct *ma = cr->get<GenericStruct>("module::Authentication");
poolSize = ma->get<ConfigInt>("soci-poolsize")->read();
connection_string = ma->get<ConfigString>("soci-connection-string")->read();
backend = ma->get<ConfigString>("soci-backend")->read();
get_password_request = ma->get<ConfigString>("soci-password-request")->read();
int max_queue_size = ma->get<ConfigInt>("soci-max-queue-size")->read();
conn_pool = new connection_pool(poolSize);
thread_pool = new ThreadPool(poolSize, max_queue_size);
LOGD("[SOCI] Authentication provider for backend %s created. Pooled for %d connections", backend.c_str(),
(int)poolSize);
for (size_t i = 0; i < poolSize; i++) {
conn_pool->at(i).open(backend, connection_string);
}
}
SociAuthDB::~SociAuthDB() {
delete thread_pool; // will automatically shut it down, clearing threads
delete conn_pool;
}
#define DURATION_MS(start, stop) (unsigned long) duration_cast<milliseconds>((stop) - (start)).count()
void SociAuthDB::getPasswordWithPool(su_root_t *root, const std::string &id, const std::string &domain,
const std::string &authid, AuthDbListener *listener) {
steady_clock::time_point start = steady_clock::now();
// Either:
// will grab a connection from the pool. This is thread safe
session sql(*conn_pool);
std::string pass;
steady_clock::time_point stop = steady_clock::now();
SLOGD << "[SOCI] Pool acquired in " << DURATION_MS(start, stop) << "ms";
start = stop;
try {
sql << get_password_request, into(pass), use(id, "id"), use(domain, "domain"), use(authid, "authid");
stop = steady_clock::now();
SLOGD << "[SOCI] Got pass for " << id << " in " << DURATION_MS(start, stop) << "ms";
cachePassword(createPasswordKey(id, domain, authid), domain, pass, mCacheExpire);
notifyPasswordRetrieved(root, listener, PASSWORD_FOUND, pass);
} catch (mysql_soci_error const &e) {
stop = steady_clock::now();
SLOGE << "[SOCI] MySQL error after " << DURATION_MS(start, stop) << "ms : " << e.err_num_ << " " << e.what();
notifyPasswordRetrieved(root, listener, PASSWORD_NOT_FOUND, pass);
} catch (exception const &e) {
stop = steady_clock::now();
SLOGE << "[SOCI] Some other error after " << DURATION_MS(start, stop) << "ms : " << e.what();
notifyPasswordRetrieved(root, listener, PASSWORD_NOT_FOUND, pass);
}
}
#pragma mark - Inherited virtuals
void SociAuthDB::getPasswordFromBackend(su_root_t *root, const std::string &id, const std::string &domain,
const std::string &authid, AuthDbListener *listener) {
// create a thread to grab a pool connection and use it to retrieve the auth information
auto func = bind(&SociAuthDB::getPasswordWithPool, this, root, id, domain, authid, listener);
// the thread pool only accepts function<void>(), so we use a closure here.
// it can also fail to enqueue when the queue is full, so we have to act on that
bool success = thread_pool->Enqueue([func]() { func(); });
if (success == FALSE) {
SLOGE << "[SOCI] Auth queue is full, cannot fullfil password request for " << id << " / " << domain << " / "
<< authid;
notifyPasswordRetrieved(root, listener, AUTH_ERROR, "");
}
return;
}<|endoftext|> |
<commit_before>#include <napi.h>
#include <string>
#include <cstring>
#include <vector>
#include <stdlib.h> // atoi
#include "node_blf.h"
#define NODE_LESS_THAN (!(NODE_VERSION_AT_LEAST(0, 5, 4)))
namespace {
bool ValidateSalt(const char* salt) {
if (!salt || *salt != '$') {
return false;
}
// discard $
salt++;
if (*salt > BCRYPT_VERSION) {
return false;
}
if (salt[1] != '$') {
switch (salt[1]) {
case 'a':
salt++;
break;
default:
return false;
}
}
// discard version + $
salt += 2;
if (salt[2] != '$') {
return false;
}
int n = atoi(salt);
if (n > 31 || n < 0) {
return false;
}
if (((uint8_t)1 << (uint8_t)n) < BCRYPT_MINROUNDS) {
return false;
}
salt += 3;
if (strlen(salt) * 3 / 4 < BCRYPT_MAXSALT) {
return false;
}
return true;
}
/* SALT GENERATION */
class SaltAsyncWorker : public Napi::AsyncWorker {
public:
SaltAsyncWorker(Napi::Function& callback, std::string seed, ssize_t rounds)
: Napi::AsyncWorker(callback), seed(seed), rounds(rounds) {
}
~SaltAsyncWorker() {}
void Execute() {
char salt[_SALT_LEN];
bcrypt_gensalt((char) rounds, (u_int8_t *)&seed[0], salt);
this->salt = std::string(salt);
}
void OnOK() {
Napi::HandleScope scope(Env());
Callback().Call({Env().Undefined(), Napi::String::New(Env(), salt)});
}
private:
std::string seed;
std::string salt;
ssize_t rounds;
};
Napi::Value GenerateSalt(const Napi::CallbackInfo& info) {
if (info.Length() < 3) {
throw Napi::TypeError::New(info.Env(), "3 arguments expected");
return info.Env().Undefined();
}
if (!info[1].IsBuffer() || (info[1].As<Napi::Buffer<char>>()).Length() != 16) {
throw Napi::TypeError::New(info.Env(), "Second argument must be a 16 byte Buffer");
return info.Env().Undefined();
}
const int32_t rounds = info[0].As<Napi::Number>();
Napi::Function callback = info[2].As<Napi::Function>();
Napi::Buffer<char> seed = info[1].As<Napi::Buffer<char>>();
SaltAsyncWorker* saltWorker = new SaltAsyncWorker(callback, std::string(seed.Data(), 16), rounds);
saltWorker->Queue();
return info.Env().Undefined();
}
Napi::Value GenerateSaltSync (const Napi::CallbackInfo& info) {
if (info.Length() < 2) {
throw Napi::TypeError::New(info.Env(), "2 arguments expected");
return info.Env().Undefined();
}
if (!info[1].IsBuffer() || (info[1].As<Napi::Buffer<char>>()).Length() != 16) {
throw Napi::TypeError::New(info.Env(), "Second argument must be a 16 byte Buffer");
return info.Env().Undefined();
}
const int32_t rounds = info[0].As<Napi::Number>();
Napi::Buffer<u_int8_t> buffer = info[1].As<Napi::Buffer<u_int8_t>>();
u_int8_t* seed = (u_int8_t*) buffer.Data();
char salt[_SALT_LEN];
bcrypt_gensalt(rounds, seed, salt);
return Napi::String::New(info.Env(), salt, strlen(salt));
}
/* ENCRYPT DATA - USED TO BE HASHPW */
class EncryptAsyncWorker : public Napi::AsyncWorker {
public:
EncryptAsyncWorker(Napi::Function& callback, std::string input, std::string salt)
: Napi::AsyncWorker(callback), input(input), salt(salt) {
}
~EncryptAsyncWorker() {}
void Execute() {
if (!(ValidateSalt(salt.c_str()))) {
error = "Invalid salt. Salt must be in the form of: $Vers$log2(NumRounds)$saltvalue";
}
char bcrypted[_PASSWORD_LEN];
bcrypt(input.c_str(), salt.c_str(), bcrypted);
output = std::string(bcrypted);
}
void OnOK() {
Napi::HandleScope scope(Env());
if (!error.empty()) {
Callback().Call({
Napi::Error::New(Env(), error.c_str()).Value(),
Env().Undefined()
});
} else {
Callback().Call({
Env().Undefined(),
Napi::String::New(Env(), output)
});
}
}
private:
std::string input;
std::string salt;
std::string error;
std::string output;
};
Napi::Value Encrypt(const Napi::CallbackInfo& info) {
if (info.Length() < 3) {
throw Napi::TypeError::New(info.Env(), "3 arguments expected");
return info.Env().Undefined();
}
std::string data = info[0].As<Napi::String>();;
std::string salt = info[1].As<Napi::String>();;
Napi::Function callback = info[2].As<Napi::Function>();
EncryptAsyncWorker* encryptWorker = new EncryptAsyncWorker(callback, data, salt);
encryptWorker->Queue();
return info.Env().Undefined();
}
Napi::Value EncryptSync(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
if (info.Length() < 2) {
throw Napi::TypeError::New(info.Env(), "2 arguments expected");
return info.Env().Undefined();
}
std::string data = info[0].As<Napi::String>();;
std::string salt = info[1].As<Napi::String>();;
if (!(ValidateSalt(salt.c_str()))) {
throw Napi::Error::New(info.Env(), "Invalid salt. Salt must be in the form of: $Vers$log2(NumRounds)$saltvalue");
return info.Env().Undefined();
}
char bcrypted[_PASSWORD_LEN];
bcrypt(data.c_str(), salt.c_str(), bcrypted);
return Napi::String::New(env, bcrypted, strlen(bcrypted));
}
/* COMPARATOR */
bool CompareStrings(const char* s1, const char* s2) {
bool eq = true;
int s1_len = strlen(s1);
int s2_len = strlen(s2);
if (s1_len != s2_len) {
eq = false;
}
const int max_len = (s2_len < s1_len) ? s1_len : s2_len;
// to prevent timing attacks, should check entire string
// don't exit after found to be false
for (int i = 0; i < max_len; ++i) {
if (s1_len >= i && s2_len >= i && s1[i] != s2[i]) {
eq = false;
}
}
return eq;
}
class CompareAsyncWorker : public Napi::AsyncWorker {
public:
CompareAsyncWorker(Napi::Function& callback, std::string input, std::string encrypted)
: Napi::AsyncWorker(callback), input(input), encrypted(encrypted) {
result = false;
}
~CompareAsyncWorker() {}
void Execute() {
char bcrypted[_PASSWORD_LEN];
if (ValidateSalt(encrypted.c_str())) {
bcrypt(input.c_str(), encrypted.c_str(), bcrypted);
result = CompareStrings(bcrypted, encrypted.c_str());
}
}
void OnOK() {
Napi::HandleScope scope(Env());
Callback().Call({Env().Undefined(), Napi::Boolean::New(Env(), result)});
}
private:
std::string input;
std::string encrypted;
bool result;
};
Napi::Value Compare(const Napi::CallbackInfo& info) {
if (info.Length() < 3) {
throw Napi::TypeError::New(info.Env(), "3 arguments expected");
return info.Env().Undefined();
}
std::string input = info[0].As<Napi::String>();
std::string encrypted = info[1].As<Napi::String>();
Napi::Function callback = info[2].As<Napi::Function>();
CompareAsyncWorker* compareWorker = new CompareAsyncWorker(callback, input, encrypted);
compareWorker->Queue();
return info.Env().Undefined();
}
Napi::Value CompareSync(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
if (info.Length() < 2) {
throw Napi::TypeError::New(info.Env(), "2 arguments expected");
return info.Env().Undefined();
}
std::string pw = info[0].As<Napi::String>();
std::string hash = info[1].As<Napi::String>();
char bcrypted[_PASSWORD_LEN];
if (ValidateSalt(hash.c_str())) {
bcrypt(pw.c_str(), hash.c_str(), bcrypted);
return Napi::Boolean::New(env, CompareStrings(bcrypted, hash.c_str()));
} else {
return Napi::Boolean::New(env, false);
}
}
Napi::Value GetRounds(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
if (info.Length() < 1) {
throw Napi::TypeError::New(info.Env(), "1 argument expected");
return info.Env().Undefined();
}
Napi::String hashed = info[0].As<Napi::String>();
std::string hash = hashed.ToString();
const char* bcrypt_hash = hash.c_str();
u_int32_t rounds;
if (!(rounds = bcrypt_get_rounds(bcrypt_hash))) {
throw Napi::Error::New(info.Env(), "invalid hash provided");
return info.Env().Undefined();
}
return Napi::Number::New(env, rounds);
}
} // anonymous namespace
Napi::Object init(Napi::Env env, Napi::Object exports) {
exports.Set(Napi::String::New(env, "gen_salt_sync"), Napi::Function::New(env, GenerateSaltSync));
exports.Set(Napi::String::New(env, "encrypt_sync"), Napi::Function::New(env, EncryptSync));
exports.Set(Napi::String::New(env, "compare_sync"), Napi::Function::New(env, CompareSync));
exports.Set(Napi::String::New(env, "get_rounds"), Napi::Function::New(env, GetRounds));
exports.Set(Napi::String::New(env, "gen_salt"), Napi::Function::New(env, GenerateSalt));
exports.Set(Napi::String::New(env, "encrypt"), Napi::Function::New(env, Encrypt));
exports.Set(Napi::String::New(env, "compare"), Napi::Function::New(env, Compare));
return exports;
};
NODE_API_MODULE(bcrypt_lib, init);
<commit_msg>Removed return info.Env().Undefined(); It's unnecessary if exceptions system is enabled<commit_after>#include <napi.h>
#include <string>
#include <cstring>
#include <vector>
#include <stdlib.h> // atoi
#include "node_blf.h"
#define NODE_LESS_THAN (!(NODE_VERSION_AT_LEAST(0, 5, 4)))
namespace {
bool ValidateSalt(const char* salt) {
if (!salt || *salt != '$') {
return false;
}
// discard $
salt++;
if (*salt > BCRYPT_VERSION) {
return false;
}
if (salt[1] != '$') {
switch (salt[1]) {
case 'a':
salt++;
break;
default:
return false;
}
}
// discard version + $
salt += 2;
if (salt[2] != '$') {
return false;
}
int n = atoi(salt);
if (n > 31 || n < 0) {
return false;
}
if (((uint8_t)1 << (uint8_t)n) < BCRYPT_MINROUNDS) {
return false;
}
salt += 3;
if (strlen(salt) * 3 / 4 < BCRYPT_MAXSALT) {
return false;
}
return true;
}
/* SALT GENERATION */
class SaltAsyncWorker : public Napi::AsyncWorker {
public:
SaltAsyncWorker(Napi::Function& callback, std::string seed, ssize_t rounds)
: Napi::AsyncWorker(callback), seed(seed), rounds(rounds) {
}
~SaltAsyncWorker() {}
void Execute() {
char salt[_SALT_LEN];
bcrypt_gensalt((char) rounds, (u_int8_t *)&seed[0], salt);
this->salt = std::string(salt);
}
void OnOK() {
Napi::HandleScope scope(Env());
Callback().Call({Env().Undefined(), Napi::String::New(Env(), salt)});
}
private:
std::string seed;
std::string salt;
ssize_t rounds;
};
Napi::Value GenerateSalt(const Napi::CallbackInfo& info) {
if (info.Length() < 3) {
throw Napi::TypeError::New(info.Env(), "3 arguments expected");
}
if (!info[1].IsBuffer() || (info[1].As<Napi::Buffer<char>>()).Length() != 16) {
throw Napi::TypeError::New(info.Env(), "Second argument must be a 16 byte Buffer");
}
const int32_t rounds = info[0].As<Napi::Number>();
Napi::Function callback = info[2].As<Napi::Function>();
Napi::Buffer<char> seed = info[1].As<Napi::Buffer<char>>();
SaltAsyncWorker* saltWorker = new SaltAsyncWorker(callback, std::string(seed.Data(), 16), rounds);
saltWorker->Queue();
return info.Env().Undefined();
}
Napi::Value GenerateSaltSync (const Napi::CallbackInfo& info) {
if (info.Length() < 2) {
throw Napi::TypeError::New(info.Env(), "2 arguments expected");
}
if (!info[1].IsBuffer() || (info[1].As<Napi::Buffer<char>>()).Length() != 16) {
throw Napi::TypeError::New(info.Env(), "Second argument must be a 16 byte Buffer");
}
const int32_t rounds = info[0].As<Napi::Number>();
Napi::Buffer<u_int8_t> buffer = info[1].As<Napi::Buffer<u_int8_t>>();
u_int8_t* seed = (u_int8_t*) buffer.Data();
char salt[_SALT_LEN];
bcrypt_gensalt(rounds, seed, salt);
return Napi::String::New(info.Env(), salt, strlen(salt));
}
/* ENCRYPT DATA - USED TO BE HASHPW */
class EncryptAsyncWorker : public Napi::AsyncWorker {
public:
EncryptAsyncWorker(Napi::Function& callback, std::string input, std::string salt)
: Napi::AsyncWorker(callback), input(input), salt(salt) {
}
~EncryptAsyncWorker() {}
void Execute() {
if (!(ValidateSalt(salt.c_str()))) {
error = "Invalid salt. Salt must be in the form of: $Vers$log2(NumRounds)$saltvalue";
}
char bcrypted[_PASSWORD_LEN];
bcrypt(input.c_str(), salt.c_str(), bcrypted);
output = std::string(bcrypted);
}
void OnOK() {
Napi::HandleScope scope(Env());
if (!error.empty()) {
Callback().Call({
Napi::Error::New(Env(), error.c_str()).Value(),
Env().Undefined()
});
} else {
Callback().Call({
Env().Undefined(),
Napi::String::New(Env(), output)
});
}
}
private:
std::string input;
std::string salt;
std::string error;
std::string output;
};
Napi::Value Encrypt(const Napi::CallbackInfo& info) {
if (info.Length() < 3) {
throw Napi::TypeError::New(info.Env(), "3 arguments expected");
}
std::string data = info[0].As<Napi::String>();;
std::string salt = info[1].As<Napi::String>();;
Napi::Function callback = info[2].As<Napi::Function>();
EncryptAsyncWorker* encryptWorker = new EncryptAsyncWorker(callback, data, salt);
encryptWorker->Queue();
return info.Env().Undefined();
}
Napi::Value EncryptSync(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
if (info.Length() < 2) {
throw Napi::TypeError::New(info.Env(), "2 arguments expected");
}
std::string data = info[0].As<Napi::String>();;
std::string salt = info[1].As<Napi::String>();;
if (!(ValidateSalt(salt.c_str()))) {
throw Napi::Error::New(info.Env(), "Invalid salt. Salt must be in the form of: $Vers$log2(NumRounds)$saltvalue");
}
char bcrypted[_PASSWORD_LEN];
bcrypt(data.c_str(), salt.c_str(), bcrypted);
return Napi::String::New(env, bcrypted, strlen(bcrypted));
}
/* COMPARATOR */
bool CompareStrings(const char* s1, const char* s2) {
bool eq = true;
int s1_len = strlen(s1);
int s2_len = strlen(s2);
if (s1_len != s2_len) {
eq = false;
}
const int max_len = (s2_len < s1_len) ? s1_len : s2_len;
// to prevent timing attacks, should check entire string
// don't exit after found to be false
for (int i = 0; i < max_len; ++i) {
if (s1_len >= i && s2_len >= i && s1[i] != s2[i]) {
eq = false;
}
}
return eq;
}
class CompareAsyncWorker : public Napi::AsyncWorker {
public:
CompareAsyncWorker(Napi::Function& callback, std::string input, std::string encrypted)
: Napi::AsyncWorker(callback), input(input), encrypted(encrypted) {
result = false;
}
~CompareAsyncWorker() {}
void Execute() {
char bcrypted[_PASSWORD_LEN];
if (ValidateSalt(encrypted.c_str())) {
bcrypt(input.c_str(), encrypted.c_str(), bcrypted);
result = CompareStrings(bcrypted, encrypted.c_str());
}
}
void OnOK() {
Napi::HandleScope scope(Env());
Callback().Call({Env().Undefined(), Napi::Boolean::New(Env(), result)});
}
private:
std::string input;
std::string encrypted;
bool result;
};
Napi::Value Compare(const Napi::CallbackInfo& info) {
if (info.Length() < 3) {
throw Napi::TypeError::New(info.Env(), "3 arguments expected");
}
std::string input = info[0].As<Napi::String>();
std::string encrypted = info[1].As<Napi::String>();
Napi::Function callback = info[2].As<Napi::Function>();
CompareAsyncWorker* compareWorker = new CompareAsyncWorker(callback, input, encrypted);
compareWorker->Queue();
return info.Env().Undefined();
}
Napi::Value CompareSync(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
if (info.Length() < 2) {
throw Napi::TypeError::New(info.Env(), "2 arguments expected");
}
std::string pw = info[0].As<Napi::String>();
std::string hash = info[1].As<Napi::String>();
char bcrypted[_PASSWORD_LEN];
if (ValidateSalt(hash.c_str())) {
bcrypt(pw.c_str(), hash.c_str(), bcrypted);
return Napi::Boolean::New(env, CompareStrings(bcrypted, hash.c_str()));
} else {
return Napi::Boolean::New(env, false);
}
}
Napi::Value GetRounds(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
if (info.Length() < 1) {
throw Napi::TypeError::New(info.Env(), "1 argument expected");
}
Napi::String hashed = info[0].As<Napi::String>();
std::string hash = hashed.ToString();
const char* bcrypt_hash = hash.c_str();
u_int32_t rounds;
if (!(rounds = bcrypt_get_rounds(bcrypt_hash))) {
throw Napi::Error::New(info.Env(), "invalid hash provided");
}
return Napi::Number::New(env, rounds);
}
} // anonymous namespace
Napi::Object init(Napi::Env env, Napi::Object exports) {
exports.Set(Napi::String::New(env, "gen_salt_sync"), Napi::Function::New(env, GenerateSaltSync));
exports.Set(Napi::String::New(env, "encrypt_sync"), Napi::Function::New(env, EncryptSync));
exports.Set(Napi::String::New(env, "compare_sync"), Napi::Function::New(env, CompareSync));
exports.Set(Napi::String::New(env, "get_rounds"), Napi::Function::New(env, GetRounds));
exports.Set(Napi::String::New(env, "gen_salt"), Napi::Function::New(env, GenerateSalt));
exports.Set(Napi::String::New(env, "encrypt"), Napi::Function::New(env, Encrypt));
exports.Set(Napi::String::New(env, "compare"), Napi::Function::New(env, Compare));
return exports;
};
NODE_API_MODULE(bcrypt_lib, init);
<|endoftext|> |
<commit_before>/******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright 2011-2018 Dominik Charousset *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#include "caf/node_id.hpp"
#include <cstdio>
#include <cstring>
#include <iterator>
#include <random>
#include <sstream>
#include "caf/binary_deserializer.hpp"
#include "caf/binary_serializer.hpp"
#include "caf/config.hpp"
#include "caf/deserializer.hpp"
#include "caf/detail/get_mac_addresses.hpp"
#include "caf/detail/get_process_id.hpp"
#include "caf/detail/get_root_uuid.hpp"
#include "caf/detail/parser/ascii_to_int.hpp"
#include "caf/detail/ripemd_160.hpp"
#include "caf/logger.hpp"
#include "caf/make_counted.hpp"
#include "caf/sec.hpp"
#include "caf/serializer.hpp"
#include "caf/string_algorithms.hpp"
namespace caf {
node_id::data::~data() {
// nop
}
node_id::default_data::default_data() : pid_(0) {
memset(host_.data(), 0, host_.size());
}
node_id::default_data::default_data(uint32_t pid, const host_id_type& host)
: pid_(pid), host_(host) {
// nop
}
namespace {
std::atomic<uint8_t> system_id;
} // namespace
node_id node_id::default_data::local(const actor_system_config&) {
CAF_LOG_TRACE("");
auto ifs = detail::get_mac_addresses();
std::vector<std::string> macs;
macs.reserve(ifs.size());
for (auto& i : ifs)
macs.emplace_back(std::move(i.second));
auto seeded_hd_serial_and_mac_addr = join(macs, "") + detail::get_root_uuid();
// By adding 8 random ASCII characters, we make sure to assign a new (random)
// ID to a node every time we start it. Otherwise, we might run into issues
// where a restarted node produces identical actor IDs than the node it
// replaces. Especially when running nodes in a container, because then the
// process ID is most likely the same.
std::random_device rd;
std::minstd_rand gen{rd()};
std::uniform_int_distribution<> dis(33, 126);
for (int i = 0; i < 8; ++i)
seeded_hd_serial_and_mac_addr += static_cast<char>(dis(gen));
// One final tweak: we add another character that makes sure two actor systems
// in the same process won't have the same node ID - even if the user
// manipulates the system to always produce the same seed for its randomness.
auto sys_seed = static_cast<char>(system_id.fetch_add(1) + 33);
seeded_hd_serial_and_mac_addr += sys_seed;
host_id_type hid;
detail::ripemd_160(hid, seeded_hd_serial_and_mac_addr);
return make_node_id(detail::get_process_id(), hid);
}
bool node_id::default_data::valid(const host_id_type& x) noexcept {
auto is_zero = [](uint8_t x) { return x == 0; };
return !std::all_of(x.begin(), x.end(), is_zero);
}
bool node_id::default_data::valid() const noexcept {
return pid_ != 0 && valid(host_);
}
size_t node_id::default_data::hash_code() const noexcept {
// XOR the first few bytes from the node ID and the process ID.
auto x = static_cast<size_t>(pid_);
auto y = *reinterpret_cast<const size_t*>(host_.data());
return x ^ y;
}
atom_value node_id::default_data::implementation_id() const noexcept {
return class_id;
}
int node_id::default_data::compare(const data& other) const noexcept {
if (this == &other)
return 0;
auto other_id = other.implementation_id();
if (class_id != other_id)
return caf::compare(class_id, other_id);
auto& x = static_cast<const default_data&>(other);
if (pid_ != x.pid_)
return pid_ < x.pid_ ? -1 : 1;
return memcmp(host_.data(), x.host_.data(), host_.size());
}
void node_id::default_data::print(std::string& dst) const {
if (!valid()) {
dst += "invalid-node";
return;
}
detail::append_hex(dst, host_);
dst += '#';
dst += std::to_string(pid_);
}
error node_id::default_data::serialize(serializer& sink) const {
return sink(pid_, host_);
}
error node_id::default_data::deserialize(deserializer& source) {
return source(pid_, host_);
}
error_code<sec>
node_id::default_data::serialize(binary_serializer& sink) const {
return sink(pid_, host_);
}
error_code<sec>
node_id::default_data::deserialize(binary_deserializer& source) {
return source(pid_, host_);
}
node_id::uri_data::uri_data(uri value) : value_(std::move(value)) {
// nop
}
bool node_id::uri_data::valid() const noexcept {
return !value_.empty();
}
size_t node_id::uri_data::hash_code() const noexcept {
std::hash<uri> f;
return f(value_);
}
atom_value node_id::uri_data::implementation_id() const noexcept {
return class_id;
}
int node_id::uri_data::compare(const data& other) const noexcept {
if (this == &other)
return 0;
auto other_id = other.implementation_id();
if (class_id != other_id)
return caf::compare(class_id, other_id);
return value_.compare(static_cast<const uri_data&>(other).value_);
}
void node_id::uri_data::print(std::string& dst) const {
if (!valid()) {
dst += "invalid-node";
return;
}
dst += to_string(value_);
}
error node_id::uri_data::serialize(serializer& sink) const {
return sink(value_);
}
error node_id::uri_data::deserialize(deserializer& source) {
return source(value_);
}
error_code<sec> node_id::uri_data::serialize(binary_serializer& sink) const {
return sink(value_);
}
error_code<sec> node_id::uri_data::deserialize(binary_deserializer& source) {
return source(value_);
}
node_id& node_id::operator=(const none_t&) {
data_.reset();
return *this;
}
node_id::node_id(intrusive_ptr<data> data) : data_(std::move(data)) {
// nop
}
node_id::~node_id() {
// nop
}
node_id::operator bool() const {
return static_cast<bool>(data_);
}
int node_id::compare(const node_id& other) const noexcept {
if (this == &other || data_ == other.data_)
return 0;
if (data_ == nullptr)
return other.data_ == nullptr ? 0 : -1;
return other.data_ == nullptr ? 1 : data_->compare(*other.data_);
}
void node_id::swap(node_id& x) {
data_.swap(x.data_);
}
namespace {
template <class Serializer>
auto serialize_data(Serializer& sink, const intrusive_ptr<node_id::data>& ptr) {
if (ptr && ptr->valid()) {
if (auto err = sink(ptr->implementation_id()))
return err;
return ptr->serialize(sink);
}
return sink(atom(""));
}
template <class Deserializer>
auto deserialize_data(Deserializer& source, intrusive_ptr<node_id::data>& ptr) {
using result_type = typename Deserializer::result_type;
auto impl = static_cast<atom_value>(0);
if (auto err = source(impl))
return err;
if (impl == atom("")) {
ptr.reset();
return result_type{};
}
if (impl == node_id::default_data::class_id) {
if (ptr == nullptr
|| ptr->implementation_id() != node_id::default_data::class_id)
ptr = make_counted<node_id::default_data>();
return ptr->deserialize(source);
} else if (impl == node_id::uri_data::class_id) {
if (ptr == nullptr
|| ptr->implementation_id() != node_id::uri_data::class_id)
ptr = make_counted<node_id::uri_data>();
return ptr->deserialize(source);
}
return result_type{sec::unknown_type};
}
} // namespace
error inspect(serializer& sink, node_id& x) {
return serialize_data(sink, x.data_);
}
error inspect(deserializer& source, node_id& x) {
return deserialize_data(source, x.data_);
}
error_code<sec> inspect(binary_serializer& sink, node_id& x) {
return serialize_data(sink, x.data_);
}
error_code<sec> inspect(binary_deserializer& source, node_id& x) {
return deserialize_data(source, x.data_);
}
void append_to_string(std::string& str, const node_id& x) {
if (x != none)
x->print(str);
else
str += "invalid-node";
}
std::string to_string(const node_id& x) {
std::string result;
append_to_string(result, x);
return result;
}
node_id make_node_id(uri from) {
auto ptr = make_counted<node_id::uri_data>(std::move(from));
return node_id{std::move(ptr)};
}
node_id make_node_id(uint32_t process_id,
const node_id::default_data::host_id_type& host_id) {
auto ptr = make_counted<node_id::default_data>(process_id, host_id);
return node_id{std::move(ptr)};
}
optional<node_id> make_node_id(uint32_t process_id,
const std::string& host_hash) {
using node_data = node_id::default_data;
if (host_hash.size() != node_data::host_id_size * 2)
return none;
detail::parser::ascii_to_int<16, uint8_t> xvalue;
node_data::host_id_type host_id;
auto in = host_hash.begin();
for (auto& byte : host_id) {
if (!isxdigit(*in))
return none;
auto first_nibble = (xvalue(*in++) << 4);
if (!isxdigit(*in))
return none;
byte = static_cast<uint8_t>(first_nibble | xvalue(*in++));
}
if (!node_data::valid(host_id))
return none;
return make_node_id(process_id, host_id);
}
} // namespace caf
<commit_msg>Fix misaligned pointer use<commit_after>/******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright 2011-2018 Dominik Charousset *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#include "caf/node_id.hpp"
#include <cstdio>
#include <cstring>
#include <iterator>
#include <random>
#include <sstream>
#include "caf/binary_deserializer.hpp"
#include "caf/binary_serializer.hpp"
#include "caf/config.hpp"
#include "caf/deserializer.hpp"
#include "caf/detail/get_mac_addresses.hpp"
#include "caf/detail/get_process_id.hpp"
#include "caf/detail/get_root_uuid.hpp"
#include "caf/detail/parser/ascii_to_int.hpp"
#include "caf/detail/ripemd_160.hpp"
#include "caf/logger.hpp"
#include "caf/make_counted.hpp"
#include "caf/sec.hpp"
#include "caf/serializer.hpp"
#include "caf/string_algorithms.hpp"
namespace caf {
node_id::data::~data() {
// nop
}
node_id::default_data::default_data() : pid_(0) {
memset(host_.data(), 0, host_.size());
}
node_id::default_data::default_data(uint32_t pid, const host_id_type& host)
: pid_(pid), host_(host) {
// nop
}
namespace {
std::atomic<uint8_t> system_id;
} // namespace
node_id node_id::default_data::local(const actor_system_config&) {
CAF_LOG_TRACE("");
auto ifs = detail::get_mac_addresses();
std::vector<std::string> macs;
macs.reserve(ifs.size());
for (auto& i : ifs)
macs.emplace_back(std::move(i.second));
auto seeded_hd_serial_and_mac_addr = join(macs, "") + detail::get_root_uuid();
// By adding 8 random ASCII characters, we make sure to assign a new (random)
// ID to a node every time we start it. Otherwise, we might run into issues
// where a restarted node produces identical actor IDs than the node it
// replaces. Especially when running nodes in a container, because then the
// process ID is most likely the same.
std::random_device rd;
std::minstd_rand gen{rd()};
std::uniform_int_distribution<> dis(33, 126);
for (int i = 0; i < 8; ++i)
seeded_hd_serial_and_mac_addr += static_cast<char>(dis(gen));
// One final tweak: we add another character that makes sure two actor systems
// in the same process won't have the same node ID - even if the user
// manipulates the system to always produce the same seed for its randomness.
auto sys_seed = static_cast<char>(system_id.fetch_add(1) + 33);
seeded_hd_serial_and_mac_addr += sys_seed;
host_id_type hid;
detail::ripemd_160(hid, seeded_hd_serial_and_mac_addr);
return make_node_id(detail::get_process_id(), hid);
}
bool node_id::default_data::valid(const host_id_type& x) noexcept {
auto is_zero = [](uint8_t x) { return x == 0; };
return !std::all_of(x.begin(), x.end(), is_zero);
}
bool node_id::default_data::valid() const noexcept {
return pid_ != 0 && valid(host_);
}
size_t node_id::default_data::hash_code() const noexcept {
// XOR the first few bytes from the node ID and the process ID.
auto x = static_cast<size_t>(pid_);
size_t y;
memcpy(&y, host_.data(), sizeof(size_t));
return x ^ y;
}
atom_value node_id::default_data::implementation_id() const noexcept {
return class_id;
}
int node_id::default_data::compare(const data& other) const noexcept {
if (this == &other)
return 0;
auto other_id = other.implementation_id();
if (class_id != other_id)
return caf::compare(class_id, other_id);
auto& x = static_cast<const default_data&>(other);
if (pid_ != x.pid_)
return pid_ < x.pid_ ? -1 : 1;
return memcmp(host_.data(), x.host_.data(), host_.size());
}
void node_id::default_data::print(std::string& dst) const {
if (!valid()) {
dst += "invalid-node";
return;
}
detail::append_hex(dst, host_);
dst += '#';
dst += std::to_string(pid_);
}
error node_id::default_data::serialize(serializer& sink) const {
return sink(pid_, host_);
}
error node_id::default_data::deserialize(deserializer& source) {
return source(pid_, host_);
}
error_code<sec>
node_id::default_data::serialize(binary_serializer& sink) const {
return sink(pid_, host_);
}
error_code<sec>
node_id::default_data::deserialize(binary_deserializer& source) {
return source(pid_, host_);
}
node_id::uri_data::uri_data(uri value) : value_(std::move(value)) {
// nop
}
bool node_id::uri_data::valid() const noexcept {
return !value_.empty();
}
size_t node_id::uri_data::hash_code() const noexcept {
std::hash<uri> f;
return f(value_);
}
atom_value node_id::uri_data::implementation_id() const noexcept {
return class_id;
}
int node_id::uri_data::compare(const data& other) const noexcept {
if (this == &other)
return 0;
auto other_id = other.implementation_id();
if (class_id != other_id)
return caf::compare(class_id, other_id);
return value_.compare(static_cast<const uri_data&>(other).value_);
}
void node_id::uri_data::print(std::string& dst) const {
if (!valid()) {
dst += "invalid-node";
return;
}
dst += to_string(value_);
}
error node_id::uri_data::serialize(serializer& sink) const {
return sink(value_);
}
error node_id::uri_data::deserialize(deserializer& source) {
return source(value_);
}
error_code<sec> node_id::uri_data::serialize(binary_serializer& sink) const {
return sink(value_);
}
error_code<sec> node_id::uri_data::deserialize(binary_deserializer& source) {
return source(value_);
}
node_id& node_id::operator=(const none_t&) {
data_.reset();
return *this;
}
node_id::node_id(intrusive_ptr<data> data) : data_(std::move(data)) {
// nop
}
node_id::~node_id() {
// nop
}
node_id::operator bool() const {
return static_cast<bool>(data_);
}
int node_id::compare(const node_id& other) const noexcept {
if (this == &other || data_ == other.data_)
return 0;
if (data_ == nullptr)
return other.data_ == nullptr ? 0 : -1;
return other.data_ == nullptr ? 1 : data_->compare(*other.data_);
}
void node_id::swap(node_id& x) {
data_.swap(x.data_);
}
namespace {
template <class Serializer>
auto serialize_data(Serializer& sink, const intrusive_ptr<node_id::data>& ptr) {
if (ptr && ptr->valid()) {
if (auto err = sink(ptr->implementation_id()))
return err;
return ptr->serialize(sink);
}
return sink(atom(""));
}
template <class Deserializer>
auto deserialize_data(Deserializer& source, intrusive_ptr<node_id::data>& ptr) {
using result_type = typename Deserializer::result_type;
auto impl = static_cast<atom_value>(0);
if (auto err = source(impl))
return err;
if (impl == atom("")) {
ptr.reset();
return result_type{};
}
if (impl == node_id::default_data::class_id) {
if (ptr == nullptr
|| ptr->implementation_id() != node_id::default_data::class_id)
ptr = make_counted<node_id::default_data>();
return ptr->deserialize(source);
} else if (impl == node_id::uri_data::class_id) {
if (ptr == nullptr
|| ptr->implementation_id() != node_id::uri_data::class_id)
ptr = make_counted<node_id::uri_data>();
return ptr->deserialize(source);
}
return result_type{sec::unknown_type};
}
} // namespace
error inspect(serializer& sink, node_id& x) {
return serialize_data(sink, x.data_);
}
error inspect(deserializer& source, node_id& x) {
return deserialize_data(source, x.data_);
}
error_code<sec> inspect(binary_serializer& sink, node_id& x) {
return serialize_data(sink, x.data_);
}
error_code<sec> inspect(binary_deserializer& source, node_id& x) {
return deserialize_data(source, x.data_);
}
void append_to_string(std::string& str, const node_id& x) {
if (x != none)
x->print(str);
else
str += "invalid-node";
}
std::string to_string(const node_id& x) {
std::string result;
append_to_string(result, x);
return result;
}
node_id make_node_id(uri from) {
auto ptr = make_counted<node_id::uri_data>(std::move(from));
return node_id{std::move(ptr)};
}
node_id make_node_id(uint32_t process_id,
const node_id::default_data::host_id_type& host_id) {
auto ptr = make_counted<node_id::default_data>(process_id, host_id);
return node_id{std::move(ptr)};
}
optional<node_id> make_node_id(uint32_t process_id,
const std::string& host_hash) {
using node_data = node_id::default_data;
if (host_hash.size() != node_data::host_id_size * 2)
return none;
detail::parser::ascii_to_int<16, uint8_t> xvalue;
node_data::host_id_type host_id;
auto in = host_hash.begin();
for (auto& byte : host_id) {
if (!isxdigit(*in))
return none;
auto first_nibble = (xvalue(*in++) << 4);
if (!isxdigit(*in))
return none;
byte = static_cast<uint8_t>(first_nibble | xvalue(*in++));
}
if (!node_data::valid(host_id))
return none;
return make_node_id(process_id, host_id);
}
} // namespace caf
<|endoftext|> |
<commit_before>/*
* This file is part of the PySide project.
*
* Copyright (C) 2009-2010 Nokia Corporation and/or its subsidiary(-ies).
*
* Contact: PySide team <contact@pyside.org>
*
* 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 "signalmanager.h"
#include "pysidesignal.h"
#include "pysideproperty.h"
#include "pysideproperty_p.h"
#include "pyside.h"
#include <QHash>
#include <QStringList>
#include <QMetaMethod>
#include <autodecref.h>
#include <gilstate.h>
#include <QDebug>
#include <limits>
#include <typeresolver.h>
#include <basewrapper.h>
#include <conversions.h>
#if QSLOT_CODE != 1 || QSIGNAL_CODE != 2
#error QSLOT_CODE and/or QSIGNAL_CODE changed! change the hardcoded stuff to the correct value!
#endif
#define PYSIDE_SLOT '1'
#define PYSIDE_SIGNAL '2'
#include "globalreceiver.h"
#define PYTHON_TYPE "PyObject"
namespace PySide {
static int callMethod(QObject* object, int id, void** args);
PyObjectWrapper::PyObjectWrapper()
:m_me(Py_None)
{
Py_INCREF(m_me);
}
PyObjectWrapper::PyObjectWrapper(PyObject* me)
: m_me(me)
{
Py_INCREF(m_me);
}
PyObjectWrapper::PyObjectWrapper(const PyObjectWrapper &other)
: m_me(other.m_me)
{
Py_INCREF(m_me);
}
PyObjectWrapper::~PyObjectWrapper()
{
Py_DECREF(m_me);
}
PyObjectWrapper::operator PyObject*() const
{
return m_me;
}
};
namespace Shiboken {
template<>
struct Converter<PySide::PyObjectWrapper>
{
static PySide::PyObjectWrapper toCpp(PyObject* obj)
{
return PySide::PyObjectWrapper(obj);
}
static PyObject* toPython(void* obj)
{
return toPython(*reinterpret_cast<PySide::PyObjectWrapper*>(obj));
}
static PyObject* toPython(const PySide::PyObjectWrapper& obj)
{
Py_INCREF((PyObject*)obj);
return obj;
}
};
};
using namespace PySide;
struct SignalManager::SignalManagerPrivate
{
GlobalReceiver m_globalReceiver;
};
static void clearSignalManager()
{
PySide::SignalManager::instance().clear();
}
SignalManager::SignalManager() : m_d(new SignalManagerPrivate)
{
// Register Qt primitive typedefs used on signals.
using namespace Shiboken;
// Register PyObject type to use in queued signal and slot connections
qRegisterMetaType<PyObjectWrapper>(PYTHON_TYPE);
TypeResolver::createValueTypeResolver<PyObjectWrapper>(PYTHON_TYPE);
TypeResolver::createValueTypeResolver<PyObjectWrapper>("object");
TypeResolver::createValueTypeResolver<PyObjectWrapper>("PySide::PyObjectWrapper");
PySide::registerCleanupFunction(clearSignalManager);
}
void SignalManager::clear()
{
delete m_d;
m_d = new SignalManagerPrivate();
m_d.reset();
}
SignalManager::~SignalManager()
{
delete m_d;
}
SignalManager& SignalManager::instance()
{
static SignalManager me;
return me;
}
QObject* SignalManager::globalReceiver()
{
return &m_d->m_globalReceiver;
}
void SignalManager::globalReceiverConnectNotify(QObject* source, int slotIndex)
{
m_d->m_globalReceiver.connectNotify(source, slotIndex);
}
void SignalManager::globalReceiverDisconnectNotify(QObject* source, int slotIndex)
{
m_d->m_globalReceiver.disconnectNotify(source, slotIndex);
}
void SignalManager::addGlobalSlot(const char* slot, PyObject* callback)
{
m_d->m_globalReceiver.addSlot(slot, callback);
}
static bool emitShortCircuitSignal(QObject* source, int signalIndex, PyObject* args)
{
void* signalArgs[2] = {0, args};
QMetaObject::activate(source, signalIndex, signalArgs);
return true;
}
static bool emitNormalSignal(QObject* source, int signalIndex, const char* signal, PyObject* args, const QStringList& argTypes)
{
Shiboken::AutoDecRef sequence(PySequence_Fast(args, 0));
int argsGiven = PySequence_Fast_GET_SIZE(sequence.object());
if (argsGiven > argTypes.count()) {
PyErr_Format(PyExc_TypeError, "%s only accepts %d arguments, %d given!", signal, argTypes.count(), argsGiven);
return false;
}
void** signalArgs = new void*[argsGiven+1];
void** signalValues = new void*[argsGiven];
signalArgs[0] = 0;
int i;
for (i = 0; i < argsGiven; ++i) {
Shiboken::TypeResolver* typeResolver = Shiboken::TypeResolver::get(qPrintable(argTypes[i]));
if (typeResolver) {
typeResolver->toCpp(PySequence_Fast_GET_ITEM(sequence.object(), i), &signalValues[i], true);
if (Shiboken::TypeResolver::getType(qPrintable(argTypes[i])) == Shiboken::TypeResolver::ObjectType)
signalArgs[i+1] = &signalValues[i];
else
signalArgs[i+1] = signalValues[i];
} else {
PyErr_Format(PyExc_TypeError, "Unknown type used to emit a signal: %s", qPrintable(argTypes[i]));
break;
}
}
bool ok = i == argsGiven;
if (ok)
QMetaObject::activate(source, signalIndex, signalArgs);
//cleanup memory
for (int j = 0; j < i; ++j)
Shiboken::TypeResolver::get(qPrintable(argTypes[j]))->deleteObject(signalArgs[j+1]);
delete[] signalArgs;
delete[] signalValues;
return ok;
}
bool SignalManager::emitSignal(QObject* source, const char* signal, PyObject* args)
{
if (!Signal::checkQtSignal(signal))
return false;
signal++;
int signalIndex = source->metaObject()->indexOfSignal(signal);
if (signalIndex != -1) {
bool isShortCircuit;
QStringList argTypes = Signal::getArgsFromSignature(signal, &isShortCircuit);
if (isShortCircuit)
return emitShortCircuitSignal(source, signalIndex, args);
else
return emitNormalSignal(source, signalIndex, signal, args, argTypes);
}
return false;
}
int SignalManager::qt_metacall(QObject* object, QMetaObject::Call call, int id, void** args)
{
const QMetaObject* metaObject = object->metaObject();
PySideProperty* pp = 0;
PyObject* pp_name = 0;
QMetaProperty mp;
Shiboken::TypeResolver* typeResolver = 0;
PyObject* pySelf = 0;
if (call != QMetaObject::InvokeMetaMethod) {
mp = metaObject->property(id);
if (!mp.isValid())
return id - metaObject->methodCount();
Shiboken::GilState gil;
pySelf = Shiboken::BindingManager::instance().retrieveWrapper(object);
Q_ASSERT(pySelf);
pp_name = PyString_FromString(mp.name());
pp = Property::getObject(pySelf, pp_name);
if (!pp) {
qWarning("Invalid property.");
Py_XDECREF(pp_name);
return id - metaObject->methodCount();
}
typeResolver = Shiboken::TypeResolver::get(mp.typeName());
Q_ASSERT(typeResolver);
}
switch(call) {
#ifndef QT_NO_PROPERTIES
case QMetaObject::ReadProperty:
{
Shiboken::GilState gil;
PyObject* value = Property::getValue(pp, pySelf);
if (value) {
typeResolver->toCpp(value, &args[0]);
Py_DECREF(value);
} else if (PyErr_Occurred()) {
PyErr_Print(); // Clear any errors but print them to stderr
}
break;
}
case QMetaObject::WriteProperty:
{
Shiboken::GilState gil;
Shiboken::AutoDecRef value(typeResolver->toPython(args[0]));
Property::setValue(pp, pySelf, value);
break;
}
case QMetaObject::ResetProperty:
{
Shiboken::GilState gil;
Property::reset(pp, pp_name);
break;
}
case QMetaObject::QueryPropertyDesignable:
case QMetaObject::QueryPropertyScriptable:
case QMetaObject::QueryPropertyStored:
case QMetaObject::QueryPropertyEditable:
case QMetaObject::QueryPropertyUser:
break;
#endif
case QMetaObject::InvokeMetaMethod:
id = callMethod(object, id, args);
break;
default:
qWarning("Unsupported meta invocation type.");
}
if (call == QMetaObject::InvokeMetaMethod)
id = id - metaObject->methodCount();
else
id = id - metaObject->propertyCount();
if (pp || pp_name) {
Shiboken::GilState gil;
Py_XDECREF(pp);
Py_XDECREF(pp_name);
}
return id;
}
static int PySide::callMethod(QObject* object, int id, void** args)
{
const QMetaObject* metaObject = object->metaObject();
QMetaMethod method = metaObject->method(id);
if (method.methodType() == QMetaMethod::Signal) {
// emit python signal
QMetaObject::activate(object, id, args);
} else {
// call python slot
Shiboken::GilState gil;
QList<QByteArray> paramTypes = method.parameterTypes();
PyObject* self = Shiboken::BindingManager::instance().retrieveWrapper(object);
PyObject* preparedArgs = NULL;
Py_ssize_t args_size = paramTypes.count();
if (args_size)
preparedArgs = PyTuple_New(args_size);
for (int i = 0, max = paramTypes.count(); i < max; ++i) {
void* data = args[i+1];
const char* dataType = paramTypes[i].constData();
PyObject* arg = Shiboken::TypeResolver::get(dataType)->toPython(data);
PyTuple_SET_ITEM(preparedArgs, i, arg);
}
QString methodName = method.signature();
methodName = methodName.left(methodName.indexOf('('));
Shiboken::AutoDecRef pyMethod(PyObject_GetAttrString(self, qPrintable(methodName)));
if (!pyMethod.isNull()) {
Shiboken::AutoDecRef retval(PyObject_CallObject(pyMethod, preparedArgs));
if (retval.isNull()) {
qWarning() << "Error calling slot" << methodName;
PyErr_Print();
}
} else {
qWarning() << "Dynamic slot" << methodName << "not found!";
}
Py_XDECREF(preparedArgs);
}
return -1;
}
bool SignalManager::registerMetaMethod(QObject* source, const char* signature, QMetaMethod::MethodType type)
{
Q_ASSERT(source);
const QMetaObject* metaObject = source->metaObject();
int methodIndex = metaObject->indexOfMethod(signature);
// Create the dynamic signal is needed
if (methodIndex == -1) {
Shiboken::SbkBaseWrapper* self = (Shiboken::SbkBaseWrapper*) Shiboken::BindingManager::instance().retrieveWrapper(source);
if (!self->containsCppWrapper) {
qWarning() << "Invalid Signal signature:" << signature;
return false;
} else {
PySide::DynamicQMetaObject* dynMetaObj = reinterpret_cast<PySide::DynamicQMetaObject*>(const_cast<QMetaObject*>(metaObject));
if (type == QMetaMethod::Signal)
dynMetaObj->addSignal(signature);
else
dynMetaObj->addSlot(signature);
}
}
return true;
}
bool SignalManager::hasConnectionWith(const QObject *object)
{
return m_d->m_globalReceiver.hasConnectionWith(object);
}
<commit_msg>Fixed invalid call function.<commit_after>/*
* This file is part of the PySide project.
*
* Copyright (C) 2009-2010 Nokia Corporation and/or its subsidiary(-ies).
*
* Contact: PySide team <contact@pyside.org>
*
* 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 "signalmanager.h"
#include "pysidesignal.h"
#include "pysideproperty.h"
#include "pysideproperty_p.h"
#include "pyside.h"
#include <QHash>
#include <QStringList>
#include <QMetaMethod>
#include <autodecref.h>
#include <gilstate.h>
#include <QDebug>
#include <limits>
#include <typeresolver.h>
#include <basewrapper.h>
#include <conversions.h>
#if QSLOT_CODE != 1 || QSIGNAL_CODE != 2
#error QSLOT_CODE and/or QSIGNAL_CODE changed! change the hardcoded stuff to the correct value!
#endif
#define PYSIDE_SLOT '1'
#define PYSIDE_SIGNAL '2'
#include "globalreceiver.h"
#define PYTHON_TYPE "PyObject"
namespace PySide {
static int callMethod(QObject* object, int id, void** args);
PyObjectWrapper::PyObjectWrapper()
:m_me(Py_None)
{
Py_INCREF(m_me);
}
PyObjectWrapper::PyObjectWrapper(PyObject* me)
: m_me(me)
{
Py_INCREF(m_me);
}
PyObjectWrapper::PyObjectWrapper(const PyObjectWrapper &other)
: m_me(other.m_me)
{
Py_INCREF(m_me);
}
PyObjectWrapper::~PyObjectWrapper()
{
Py_DECREF(m_me);
}
PyObjectWrapper::operator PyObject*() const
{
return m_me;
}
};
namespace Shiboken {
template<>
struct Converter<PySide::PyObjectWrapper>
{
static PySide::PyObjectWrapper toCpp(PyObject* obj)
{
return PySide::PyObjectWrapper(obj);
}
static PyObject* toPython(void* obj)
{
return toPython(*reinterpret_cast<PySide::PyObjectWrapper*>(obj));
}
static PyObject* toPython(const PySide::PyObjectWrapper& obj)
{
Py_INCREF((PyObject*)obj);
return obj;
}
};
};
using namespace PySide;
struct SignalManager::SignalManagerPrivate
{
GlobalReceiver m_globalReceiver;
};
static void clearSignalManager()
{
PySide::SignalManager::instance().clear();
}
SignalManager::SignalManager() : m_d(new SignalManagerPrivate)
{
// Register Qt primitive typedefs used on signals.
using namespace Shiboken;
// Register PyObject type to use in queued signal and slot connections
qRegisterMetaType<PyObjectWrapper>(PYTHON_TYPE);
TypeResolver::createValueTypeResolver<PyObjectWrapper>(PYTHON_TYPE);
TypeResolver::createValueTypeResolver<PyObjectWrapper>("object");
TypeResolver::createValueTypeResolver<PyObjectWrapper>("PySide::PyObjectWrapper");
PySide::registerCleanupFunction(clearSignalManager);
}
void SignalManager::clear()
{
delete m_d;
m_d = new SignalManagerPrivate();
}
SignalManager::~SignalManager()
{
delete m_d;
}
SignalManager& SignalManager::instance()
{
static SignalManager me;
return me;
}
QObject* SignalManager::globalReceiver()
{
return &m_d->m_globalReceiver;
}
void SignalManager::globalReceiverConnectNotify(QObject* source, int slotIndex)
{
m_d->m_globalReceiver.connectNotify(source, slotIndex);
}
void SignalManager::globalReceiverDisconnectNotify(QObject* source, int slotIndex)
{
m_d->m_globalReceiver.disconnectNotify(source, slotIndex);
}
void SignalManager::addGlobalSlot(const char* slot, PyObject* callback)
{
m_d->m_globalReceiver.addSlot(slot, callback);
}
static bool emitShortCircuitSignal(QObject* source, int signalIndex, PyObject* args)
{
void* signalArgs[2] = {0, args};
QMetaObject::activate(source, signalIndex, signalArgs);
return true;
}
static bool emitNormalSignal(QObject* source, int signalIndex, const char* signal, PyObject* args, const QStringList& argTypes)
{
Shiboken::AutoDecRef sequence(PySequence_Fast(args, 0));
int argsGiven = PySequence_Fast_GET_SIZE(sequence.object());
if (argsGiven > argTypes.count()) {
PyErr_Format(PyExc_TypeError, "%s only accepts %d arguments, %d given!", signal, argTypes.count(), argsGiven);
return false;
}
void** signalArgs = new void*[argsGiven+1];
void** signalValues = new void*[argsGiven];
signalArgs[0] = 0;
int i;
for (i = 0; i < argsGiven; ++i) {
Shiboken::TypeResolver* typeResolver = Shiboken::TypeResolver::get(qPrintable(argTypes[i]));
if (typeResolver) {
typeResolver->toCpp(PySequence_Fast_GET_ITEM(sequence.object(), i), &signalValues[i], true);
if (Shiboken::TypeResolver::getType(qPrintable(argTypes[i])) == Shiboken::TypeResolver::ObjectType)
signalArgs[i+1] = &signalValues[i];
else
signalArgs[i+1] = signalValues[i];
} else {
PyErr_Format(PyExc_TypeError, "Unknown type used to emit a signal: %s", qPrintable(argTypes[i]));
break;
}
}
bool ok = i == argsGiven;
if (ok)
QMetaObject::activate(source, signalIndex, signalArgs);
//cleanup memory
for (int j = 0; j < i; ++j)
Shiboken::TypeResolver::get(qPrintable(argTypes[j]))->deleteObject(signalArgs[j+1]);
delete[] signalArgs;
delete[] signalValues;
return ok;
}
bool SignalManager::emitSignal(QObject* source, const char* signal, PyObject* args)
{
if (!Signal::checkQtSignal(signal))
return false;
signal++;
int signalIndex = source->metaObject()->indexOfSignal(signal);
if (signalIndex != -1) {
bool isShortCircuit;
QStringList argTypes = Signal::getArgsFromSignature(signal, &isShortCircuit);
if (isShortCircuit)
return emitShortCircuitSignal(source, signalIndex, args);
else
return emitNormalSignal(source, signalIndex, signal, args, argTypes);
}
return false;
}
int SignalManager::qt_metacall(QObject* object, QMetaObject::Call call, int id, void** args)
{
const QMetaObject* metaObject = object->metaObject();
PySideProperty* pp = 0;
PyObject* pp_name = 0;
QMetaProperty mp;
Shiboken::TypeResolver* typeResolver = 0;
PyObject* pySelf = 0;
if (call != QMetaObject::InvokeMetaMethod) {
mp = metaObject->property(id);
if (!mp.isValid())
return id - metaObject->methodCount();
Shiboken::GilState gil;
pySelf = Shiboken::BindingManager::instance().retrieveWrapper(object);
Q_ASSERT(pySelf);
pp_name = PyString_FromString(mp.name());
pp = Property::getObject(pySelf, pp_name);
if (!pp) {
qWarning("Invalid property.");
Py_XDECREF(pp_name);
return id - metaObject->methodCount();
}
typeResolver = Shiboken::TypeResolver::get(mp.typeName());
Q_ASSERT(typeResolver);
}
switch(call) {
#ifndef QT_NO_PROPERTIES
case QMetaObject::ReadProperty:
{
Shiboken::GilState gil;
PyObject* value = Property::getValue(pp, pySelf);
if (value) {
typeResolver->toCpp(value, &args[0]);
Py_DECREF(value);
} else if (PyErr_Occurred()) {
PyErr_Print(); // Clear any errors but print them to stderr
}
break;
}
case QMetaObject::WriteProperty:
{
Shiboken::GilState gil;
Shiboken::AutoDecRef value(typeResolver->toPython(args[0]));
Property::setValue(pp, pySelf, value);
break;
}
case QMetaObject::ResetProperty:
{
Shiboken::GilState gil;
Property::reset(pp, pp_name);
break;
}
case QMetaObject::QueryPropertyDesignable:
case QMetaObject::QueryPropertyScriptable:
case QMetaObject::QueryPropertyStored:
case QMetaObject::QueryPropertyEditable:
case QMetaObject::QueryPropertyUser:
break;
#endif
case QMetaObject::InvokeMetaMethod:
id = callMethod(object, id, args);
break;
default:
qWarning("Unsupported meta invocation type.");
}
if (call == QMetaObject::InvokeMetaMethod)
id = id - metaObject->methodCount();
else
id = id - metaObject->propertyCount();
if (pp || pp_name) {
Shiboken::GilState gil;
Py_XDECREF(pp);
Py_XDECREF(pp_name);
}
return id;
}
static int PySide::callMethod(QObject* object, int id, void** args)
{
const QMetaObject* metaObject = object->metaObject();
QMetaMethod method = metaObject->method(id);
if (method.methodType() == QMetaMethod::Signal) {
// emit python signal
QMetaObject::activate(object, id, args);
} else {
// call python slot
Shiboken::GilState gil;
QList<QByteArray> paramTypes = method.parameterTypes();
PyObject* self = Shiboken::BindingManager::instance().retrieveWrapper(object);
PyObject* preparedArgs = NULL;
Py_ssize_t args_size = paramTypes.count();
if (args_size)
preparedArgs = PyTuple_New(args_size);
for (int i = 0, max = paramTypes.count(); i < max; ++i) {
void* data = args[i+1];
const char* dataType = paramTypes[i].constData();
PyObject* arg = Shiboken::TypeResolver::get(dataType)->toPython(data);
PyTuple_SET_ITEM(preparedArgs, i, arg);
}
QString methodName = method.signature();
methodName = methodName.left(methodName.indexOf('('));
Shiboken::AutoDecRef pyMethod(PyObject_GetAttrString(self, qPrintable(methodName)));
if (!pyMethod.isNull()) {
Shiboken::AutoDecRef retval(PyObject_CallObject(pyMethod, preparedArgs));
if (retval.isNull()) {
qWarning() << "Error calling slot" << methodName;
PyErr_Print();
}
} else {
qWarning() << "Dynamic slot" << methodName << "not found!";
}
Py_XDECREF(preparedArgs);
}
return -1;
}
bool SignalManager::registerMetaMethod(QObject* source, const char* signature, QMetaMethod::MethodType type)
{
Q_ASSERT(source);
const QMetaObject* metaObject = source->metaObject();
int methodIndex = metaObject->indexOfMethod(signature);
// Create the dynamic signal is needed
if (methodIndex == -1) {
Shiboken::SbkBaseWrapper* self = (Shiboken::SbkBaseWrapper*) Shiboken::BindingManager::instance().retrieveWrapper(source);
if (!self->containsCppWrapper) {
qWarning() << "Invalid Signal signature:" << signature;
return false;
} else {
PySide::DynamicQMetaObject* dynMetaObj = reinterpret_cast<PySide::DynamicQMetaObject*>(const_cast<QMetaObject*>(metaObject));
if (type == QMetaMethod::Signal)
dynMetaObj->addSignal(signature);
else
dynMetaObj->addSlot(signature);
}
}
return true;
}
bool SignalManager::hasConnectionWith(const QObject *object)
{
return m_d->m_globalReceiver.hasConnectionWith(object);
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <fstream>
#include "vecrand.hpp"
#include "interaction.hpp"
#include "collection.hpp"
// Some constants
// Note that "flt" is a "floating point number", defaults to "double"
// but can be compiled as "long double" if needed
const flt sigma = 1.0;
const flt sigmal = 1.4;
const flt epsilon = 1.0;
const uint Ns = 40;
const uint Nl = 40;
const flt phi0 = 0.001;
// Some algorithmic constants
const flt dt = 0.1;
// the final pressure
const flt P0 = 1e-8;
// The initial pressure
const flt startP = 1e-4;
// The algorithm works by minimizing H = U(x_i...) + PV w.r.t. x_i and κ=log V.
// The final overlap is thus approximately related to P, and the higher the P, the
// faster it converges.
// In this simulation, we start with a high P, and then relax to lower Ps.
// These are the "quitting" parameters, see below for use
const flt P_frac = 1e-4;
#ifndef LONGFLOAT
const flt force_max = 1e-14;
#else
const flt force_max = 1e-18;
#endif
void writefile(AtomVec& atoms, OriginBox& obox);
int main(){
cout << "Float size: " << sizeof(flt) << " epsilon: " << std::numeric_limits<flt>::epsilon() << "\n";
assert(std::numeric_limits<flt>::epsilon() < force_max*10);
// new random seed each time, for velocities and placement
seed();
// Volume of the spheres
// Each sphere is σ^d * π/(2d), i.e. π σ^2/4 for 2D, π σ^3/6 for 3D
// Total volume of the spheres takes a constant N out front
const flt Vs = (Ns * pow(sigma, NDIM) + Nl * pow(sigmal, NDIM)) * M_PI_2 / NDIM;
// Initial length of the box is [(volume of spheres) / phi0]^(1/d)
const flt L = pow(Vs / phi0, OVERNDIM);
cout << "Using L = " << L << "\n";
// Create the bounding box (sides of length L), and a "vector" of Natoms atoms
boost::shared_ptr<OriginBox> obox(new OriginBox(L));
// Create a vector of the masses of the atoms
// We just use all mass 1, because this is a packing
boost::shared_ptr<AtomVec> atomptr(new AtomVec(Nl + Ns, 1.0));
AtomVec & atoms = *atomptr;
// Harmonic Interaction
// Its called "Repulsion" for historical reasons
// It takes a pointer to the box, a pointer to the atoms, and a "skin depth" for the NeighborList
boost::shared_ptr<NListed<EpsSigExpAtom, RepulsionPair> >
hertzian(new NListed<EpsSigExpAtom, RepulsionPair>(obox, atomptr, 0.1*sigma));
boost::shared_ptr<NeighborList> nl = hertzian->neighbor_list();
// ^ this is the Interaction
// Note that NListed is a class template; its an Interaction that
// takes various structs as template parameters, and turns them into
// a neighbor Interaction
// See interaction.hpp for a whole bunch of them
// Also note that the NeighborList is not the same as the
// "neighborlisted" Interaction; multiple interactions can use the
// same NeighborList
// Now we run through all the atoms, set their positions / velocities,
// and add them to the Repulsion Interaction (i.e., to the neighbor list)
for (uint i=0; i < atoms.size(); i++){
atoms[i].x = obox->rand_loc(); // random location in the box
atoms[i].v = Vec::Zero(); // A zero-vector
atoms[i].f = Vec::Zero();
atoms[i].a = Vec::Zero();
flt sig = i < Ns ? sigma : sigmal;
// Add it to the Repulsion potential
hertzian->add(EpsSigExpAtom(atoms.get_id(i), epsilon, sig, 2));
// ^ exponent for the harmonic Interaction
}
// force an update the NeighborList, so we can get an accurate energy
nl->update_list(true);
cout << "Starting. Neighborlist contains " << nl->numpairs() << " / " <<
(atoms.size()*(atoms.size()-1))/2 << " pairs\n";
//Now we make our "Collection"
CollectionNLCG collec = CollectionNLCG(obox, atomptr, dt, P0);
// This is very important! Otherwise the NeighborList won't update!
collec.add_tracker(nl);
// And add the Interaction
collec.add_interaction(hertzian);
writefile(atoms, *obox);
//Print out total energy, kinetic_energy energy, and potential energy
cout << "H: " << collec.hamiltonian() << " K: " << collec.kinetic_energy()
<< " U: " << hertzian->energy(*obox) << " phi: " << (Vs/obox->V()) << "\n";
// Run the simulation! And every _ steps, write a frame to the .xyz
// file and print out the energies again
uint i = 0;
for(flt curP=startP; curP>P0; curP/=10){
cout << "P: " << curP << "\n";
collec.set_pressure(curP);
while (true) {
for(uint j=0; j<1000; j++){
collec.timestep();
}
i++;
writefile(atoms, *obox);
flt pdiff = collec.pressure() / curP - 1.0;
flt force_err = 0;
for(uint k=0; k<atoms.size(); k++){
flt fmag = atoms[k].f.norm();
if(fmag > force_err) force_err = fmag;
}
cout.precision(sizeof(flt));
cout << i << " H: " << collec.hamiltonian() << " K: " << collec.kinetic_energy()
<< " U: " << hertzian->energy(*obox) << " phi: " << (Vs/obox->V()) << "\n";
cout.precision(6);
cout << " Pdiff: " << pdiff << " force_err: " << force_err << "\n";
if(abs(pdiff) < P_frac and force_err < force_max){
cout << "Done!\n";
break;
}
}
}
};
void writefile(AtomVec& atoms, OriginBox& obox){
// The .xyz format is simple:
// Line 1: [Number of atoms]
// Line 2: [Comment line, whatever you want, left blank here]
// Line 3: [element type, here C for carbon]\t[x]\t[y]\t[z]
// Line 4: [element type, here C for carbon]\t[x]\t[y]\t[z]
// ...
// Line N+1: [element type, here C for carbon]\t[x]\t[y]\t[z]
// Line N+2: [element type, here C for carbon]\t[x]\t[y]\t[z]
// Line N+3: [Number of atoms]
// Line N+4: [Comment line, whatever you want, left blank here]
// Line N+5: [element type, here C for carbon]\t[x]\t[y]\t[z]
// ...
// And so on. each set of N atoms/coordinates corresponds to a "frame",
// which then make a movie. There must be the same N in each frame for VMD.
// Note that if this is compiled as a 2D simulation, it will leave out
// the z coordinate, and VMD can't handle that.
ofstream outf;
outf.open("packing.xyz", ios::out);
outf.precision(24);
outf << atoms.size() << endl;
outf << "L=" << obox.L() << endl; // blank line for comment
for(uint i=0; i<atoms.size(); i++){
if(i < Ns){
outf << "C";
} else {
outf << "O";
}
Vec normloc = obox.diff(Vec::Zero(), atoms[i].x);
for(uint j=0; j<NDIM; j++){
outf << "\t" << normloc[j];
}
outf << endl;
};
// Unnecessary extra:
// Write a "tcl" file with the box boundaries
// the "tcl" file is made specifically for VMD
ofstream pbcfile;
pbcfile.open("packing.tcl", ios::out);
pbcfile << "set cell [pbc set {";
for(uint j=0; j<NDIM; j++){
pbcfile << obox.box_shape()[j] << " ";
}
pbcfile << "} -all];\n";
pbcfile << "pbc box -toggle -center origin -color red;\n";
pbcfile << "set natoms [atomselect 0 \"name C\";];\n"
<< "$natoms set radius " << (sigma/2.0) << ";\n"
<< "set natoms [atomselect 0 \"name O\";];\n"
<< "$natoms set radius " << (sigmal/2.0) << ";\n";
// Now you should be able to run "vmd -e LJatoms-pbc.tcl LJatoms.xyz"
// and it will show you the movie and also the bounding box
// if you have .vmdrc in that same directory, you should also be able
// to toggle the box with the "b" button
};
<commit_msg>Fixed name change in packer<commit_after>#include <iostream>
#include <fstream>
#include "vecrand.hpp"
#include "interaction.hpp"
#include "collection.hpp"
// Some constants
// Note that "flt" is a "floating point number", defaults to "double"
// but can be compiled as "long double" if needed
const flt sigma = 1.0;
const flt sigmal = 1.4;
const flt epsilon = 1.0;
const uint Ns = 40;
const uint Nl = 40;
const flt phi0 = 0.001;
// Some algorithmic constants
const flt dt = 0.1;
// the final pressure
const flt P0 = 1e-8;
// The initial pressure
const flt startP = 1e-4;
// The algorithm works by minimizing H = U(x_i...) + PV w.r.t. x_i and κ=log V.
// The final overlap is thus approximately related to P, and the higher the P, the
// faster it converges.
// In this simulation, we start with a high P, and then relax to lower Ps.
// These are the "quitting" parameters, see below for use
const flt P_frac = 1e-4;
#ifndef LONGFLOAT
const flt force_max = 1e-14;
#else
const flt force_max = 1e-18;
#endif
void writefile(AtomVec& atoms, OriginBox& obox);
int main(){
cout << "Float size: " << sizeof(flt) << " epsilon: " << std::numeric_limits<flt>::epsilon() << "\n";
assert(std::numeric_limits<flt>::epsilon() < force_max*10);
// new random seed each time, for velocities and placement
seed();
// Volume of the spheres
// Each sphere is σ^d * π/(2d), i.e. π σ^2/4 for 2D, π σ^3/6 for 3D
// Total volume of the spheres takes a constant N out front
const flt Vs = (Ns * pow(sigma, NDIM) + Nl * pow(sigmal, NDIM)) * M_PI_2 / NDIM;
// Initial length of the box is [(volume of spheres) / phi0]^(1/d)
const flt L = pow(Vs / phi0, OVERNDIM);
cout << "Using L = " << L << "\n";
// Create the bounding box (sides of length L), and a "vector" of Natoms atoms
boost::shared_ptr<OriginBox> obox(new OriginBox(L));
// Create a vector of the masses of the atoms
// We just use all mass 1, because this is a packing
boost::shared_ptr<AtomVec> atomptr(new AtomVec(Nl + Ns, 1.0));
AtomVec & atoms = *atomptr;
// Harmonic Interaction
// Its called "Repulsion" for historical reasons
// It takes a pointer to the box, a pointer to the atoms, and a "skin depth" for the NeighborList
boost::shared_ptr<NListed<EpsSigExpAtom, RepulsionPair> >
hertzian(new NListed<EpsSigExpAtom, RepulsionPair>(obox, atomptr, 0.1*sigma));
boost::shared_ptr<NeighborList> nl = hertzian->neighbor_list();
// ^ this is the Interaction
// Note that NListed is a class template; its an Interaction that
// takes various structs as template parameters, and turns them into
// a neighbor Interaction
// See interaction.hpp for a whole bunch of them
// Also note that the NeighborList is not the same as the
// "neighborlisted" Interaction; multiple interactions can use the
// same NeighborList
// Now we run through all the atoms, set their positions / velocities,
// and add them to the Repulsion Interaction (i.e., to the neighbor list)
for (uint i=0; i < atoms.size(); i++){
atoms[i].x = obox->rand_loc(); // random location in the box
atoms[i].v = Vec::Zero(); // A zero-vector
atoms[i].f = Vec::Zero();
atoms[i].a = Vec::Zero();
flt sig = i < Ns ? sigma : sigmal;
// Add it to the Repulsion potential
hertzian->add(EpsSigExpAtom(atoms.get_id(i), epsilon, sig, 2));
// ^ exponent for the harmonic Interaction
}
// force an update the NeighborList, so we can get an accurate energy
nl->update_list(true);
cout << "Starting. Neighborlist contains " << nl->numpairs() << " / " <<
(atoms.size()*(atoms.size()-1))/2 << " pairs\n";
//Now we make our "Collection"
CollectionNLCG collec = CollectionNLCG(obox, atomptr, dt, P0);
// This is very important! Otherwise the NeighborList won't update!
collec.add_tracker(nl);
// And add the Interaction
collec.add_interaction(hertzian);
writefile(atoms, *obox);
//Print out total energy, kinetic_energy energy, and potential energy
cout << "H: " << collec.hamiltonian() << " K: " << collec.kinetic_energy()
<< " U: " << hertzian->energy(*obox) << " phi: " << (Vs/obox->V()) << "\n";
// Run the simulation! And every _ steps, write a frame to the .xyz
// file and print out the energies again
uint i = 0;
for(flt curP=startP; curP>P0; curP/=10){
cout << "P: " << curP << "\n";
collec.set_pressure_goal(curP);
while (true) {
for(uint j=0; j<1000; j++){
collec.timestep();
}
i++;
writefile(atoms, *obox);
flt pdiff = collec.pressure() / curP - 1.0;
flt force_err = 0;
for(uint k=0; k<atoms.size(); k++){
flt fmag = atoms[k].f.norm();
if(fmag > force_err) force_err = fmag;
}
cout.precision(sizeof(flt));
cout << i << " H: " << collec.hamiltonian() << " K: " << collec.kinetic_energy()
<< " U: " << hertzian->energy(*obox) << " phi: " << (Vs/obox->V()) << "\n";
cout.precision(6);
cout << " Pdiff: " << pdiff << " force_err: " << force_err << "\n";
if(abs(pdiff) < P_frac and force_err < force_max){
cout << "Done!\n";
break;
}
}
}
};
void writefile(AtomVec& atoms, OriginBox& obox){
// The .xyz format is simple:
// Line 1: [Number of atoms]
// Line 2: [Comment line, whatever you want, left blank here]
// Line 3: [element type, here C for carbon]\t[x]\t[y]\t[z]
// Line 4: [element type, here C for carbon]\t[x]\t[y]\t[z]
// ...
// Line N+1: [element type, here C for carbon]\t[x]\t[y]\t[z]
// Line N+2: [element type, here C for carbon]\t[x]\t[y]\t[z]
// Line N+3: [Number of atoms]
// Line N+4: [Comment line, whatever you want, left blank here]
// Line N+5: [element type, here C for carbon]\t[x]\t[y]\t[z]
// ...
// And so on. each set of N atoms/coordinates corresponds to a "frame",
// which then make a movie. There must be the same N in each frame for VMD.
// Note that if this is compiled as a 2D simulation, it will leave out
// the z coordinate, and VMD can't handle that.
ofstream outf;
outf.open("packing.xyz", ios::out);
outf.precision(24);
outf << atoms.size() << endl;
outf << "L=" << obox.L() << endl; // blank line for comment
for(uint i=0; i<atoms.size(); i++){
if(i < Ns){
outf << "C";
} else {
outf << "O";
}
Vec normloc = obox.diff(Vec::Zero(), atoms[i].x);
for(uint j=0; j<NDIM; j++){
outf << "\t" << normloc[j];
}
outf << endl;
};
// Unnecessary extra:
// Write a "tcl" file with the box boundaries
// the "tcl" file is made specifically for VMD
ofstream pbcfile;
pbcfile.open("packing.tcl", ios::out);
pbcfile << "set cell [pbc set {";
for(uint j=0; j<NDIM; j++){
pbcfile << obox.box_shape()[j] << " ";
}
pbcfile << "} -all];\n";
pbcfile << "pbc box -toggle -center origin -color red;\n";
pbcfile << "set natoms [atomselect 0 \"name C\";];\n"
<< "$natoms set radius " << (sigma/2.0) << ";\n"
<< "set natoms [atomselect 0 \"name O\";];\n"
<< "$natoms set radius " << (sigmal/2.0) << ";\n";
// Now you should be able to run "vmd -e LJatoms-pbc.tcl LJatoms.xyz"
// and it will show you the movie and also the bounding box
// if you have .vmdrc in that same directory, you should also be able
// to toggle the box with the "b" button
};
<|endoftext|> |
<commit_before>/*
* Jamoma 2-Dimensional Matrix Data Class
* Copyright © 2011-2012, Timothy Place & Nathan Wolek
*
* License: This code is licensed under the terms of the "New BSD License"
* http://creativecommons.org/licenses/BSD/
*/
#include "TTMatrix.h"
#include "TTEnvironment.h"
#include "TTBase.h"
#define thisTTClass TTMatrix
#define thisTTClassName "matrix"
#define thisTTClassTags "matrix"
TT_OBJECT_CONSTRUCTOR,
mData(NULL),
mRowCount(1), // initialize to a 1x1 matrix by default (maybe we should be using the args?)
mColumnCount(1), // initialize to a 1x1 matrix by default (maybe we should be using the args?)
mElementCount(1),
mComponentCount(1),
mComponentStride(1),
mDataCount(0),
mType(TT("uint8")),
mTypeSizeInBytes(1),
mDataSize(0),
mDataIsLocallyOwned(YES),
mHeadPtr(NULL),
mTailPtr(NULL)
{
addAttributeWithGetterAndSetter(Dimensions, kTypeUInt32); // mDimensions deprecated, should we delete this too?
// we will keep setDimensions() & getDimensions()
addAttributeWithSetter(RowCount, kTypeUInt32);
addAttributeWithSetter(ColumnCount, kTypeUInt32);
addAttributeWithSetter(Type, kTypeUInt8);
addAttributeWithSetter(ElementCount, kTypeUInt8);
addMessage(clear);
addMessageWithArguments(fill);
addMessageWithArguments(get);
addMessageWithArguments(set);
// TODO: getLockedPointer -- returns a pointer to the data, locks the matrix mutex
// TODO: releaseLockedPointer -- releases the matrix mutex
// TODO: the above two items mean we need a TTMutex member
resize();
}
TTMatrix::~TTMatrix()
{
if (mDataIsLocallyOwned)
delete[] mData; // TODO: only do this if the refcount for the data is down to zero!
}
TTErr TTMatrix::resize()
{
mComponentCount = mRowCount * mColumnCount;
mDataCount = mComponentCount * mElementCount;
mDataSize = mDataCount * mTypeSizeInBytes;
mComponentStride = mTypeSizeInBytes * mElementCount;
if (mDataIsLocallyOwned) {
// TODO: currently, we are not preserving memory when resizing. Should we try to preserve the previous memory contents?
// TODO: thread protection
delete[] mData;
mData = new TTByte[mDataSize];
mHeadPtr = mData;
mTailPtr = mData + mDataSize;
}
if (mDataSize && mData)
{
return kTTErrNone;
} else {
return kTTErrAllocFailed;
}
}
TTBoolean TTMatrix::setRowCountWithoutResize(TTUInt32 aNewRowCount)
{
if (aNewRowCount > 0)
{
mRowCount = aNewRowCount;
return true;
} else {
return false;
}
}
TTBoolean TTMatrix::setColumnCountWithoutResize(TTUInt32 aNewColumnCount)
{
if (aNewColumnCount > 0)
{
mColumnCount = aNewColumnCount;
return true;
} else {
return false;
}
}
TTBoolean TTMatrix::setElementCountWithoutResize(TTUInt8 aNewElementCount)
{
if (aNewElementCount > 0)
{
mElementCount = aNewElementCount;
return true;
} else {
return false;
}
}
TTBoolean TTMatrix::setTypeWithoutResize(TTDataInfoPtr aNewType)
{
if (aNewType->isNumerical)
{
mTypeAsDataInfo = aNewType;
mType = aNewType->name;
mTypeSizeInBytes = (aNewType->bitdepth / 8);
return true;
} else {
return false;
}
}
TTErr TTMatrix::setRowCount(const TTValue& aNewRowCount)
{
TTUInt32 aNewRowCountInt = aNewRowCount;
if (setRowCountWithoutResize(aNewRowCountInt))
{
return resize();
} else {
return kTTErrInvalidValue;
}
}
TTErr TTMatrix::setColumnCount(const TTValue& aNewColumnCount)
{
TTUInt32 aNewColumnCountInt = aNewColumnCount;
if (setColumnCountWithoutResize(aNewColumnCountInt))
{
return resize();
} else {
return kTTErrInvalidValue;
}
}
TTErr TTMatrix::setElementCount(const TTValue& newElementCount)
{
TTUInt8 aNewElementCountInt = newElementCount;
if (setElementCountWithoutResize(aNewElementCountInt))
{
return resize();
} else {
return kTTErrInvalidValue;
}
}
TTErr TTMatrix::setType(const TTValue& aType)
{
TTSymbolPtr aNewTypeName = aType;
TTDataInfoPtr aNewDataType = TTDataInfo::getInfoForType(aNewTypeName); // move into the "withoutResize" method?
if (setTypeWithoutResize(aNewDataType))
{
return resize();
} else {
return kTTErrInvalidValue;
}
}
TTErr TTMatrix::setDimensions(const TTValue& someNewDimensions)
{
TTUInt32 aNewRowCount = 1;
TTUInt32 aNewColumnCount = 1;
TTUInt8 size = someNewDimensions.getSize();
// needed to support old calls with 1 or 2 dimensions
if (size > 0) { someNewDimensions.get(0, aNewRowCount); }
if (size > 1) { someNewDimensions.get(1, aNewColumnCount); }
if (this->setRowCountWithoutResize(aNewRowCount) &&
this->setColumnCountWithoutResize(aNewColumnCount))
{
return resize();
} else {
return kTTErrInvalidValue;
}
}
TTErr TTMatrix::getDimensions(TTValue& returnedDimensions) const
{
returnedDimensions.setSize(2);
returnedDimensions.set(0, mRowCount);
returnedDimensions.set(1, mColumnCount);
return kTTErrNone;
}
TTErr TTMatrix::clear()
{
memset(mData, 0, mDataSize);
return kTTErrNone;
}
TTErr TTMatrix::fill(const TTValue& anInputValue, TTValue &anUnusedOutputValue)
{
TTBytePtr fillValue = new TTByte[mComponentStride];
// TODO: here we have this ugly switch again...
if (mType == TT("uint8"))
anInputValue.getArray((TTUInt8*)fillValue, mElementCount);
else if (mType == TT("int32"))
anInputValue.getArray((TTInt32*)fillValue, mElementCount);
else if (mType == TT("float32"))
anInputValue.getArray((TTFloat32*)fillValue, mElementCount);
else if (mType == TT("float64"))
anInputValue.getArray((TTFloat64*)fillValue, mElementCount);
for (TTUInt32 i=0; i<mDataSize; i += mComponentStride)
memcpy(mData+i, fillValue, mComponentStride);
delete[] fillValue;
return kTTErrNone;
}
/*
To find the index in the matrix:
1D Matrix: index = x
2D Matrix: index = dim_0 y + x
3D Matrix: index = dim_0 dim_1 z + dim_0 y + x
etc.
*/
// args passed-in should be the 2 coordinates
// args returned will be the value(s) at those coordinates
TTErr TTMatrix::get(const TTValue& anInputValue, TTValue &anOutputValue) const
{
TTUInt16 dimensionCount = anInputValue.getSize();
if (dimensionCount != 2) // 2 dimensions only
return kTTErrWrongNumValues;
// TODO: this will be a good place to use the planned where() method
TTUInt32 i, j, index;
anInputValue.get(0, i);
anInputValue.get(1, j);
index = i * mColumnCount + j;
// TODO: there is no bounds checking here
anOutputValue.clear();
// TODO: here we have this ugly switch again...
// Maybe we could just have duplicate pointers of different types in our class, and then we could access them more cleanly?
if (mType == TT("uint8")) {
for (int e=0; e<mElementCount; e++)
anOutputValue.append((TTUInt8*)(mData+(index*mComponentStride+e*mTypeSizeInBytes)));
}
else if (mType == TT("int32")) {
for (int e=0; e<mElementCount; e++)
anOutputValue.append((TTInt32*)(mData+(index*mComponentStride+e*mTypeSizeInBytes)));
}
else if (mType == TT("float32")) {
for (int e=0; e<mElementCount; e++)
anOutputValue.append((TTFloat32*)(mData+(index*mComponentStride+e*mTypeSizeInBytes)));
}
else if (mType == TT("float64")) {
for (int e=0; e<mElementCount; e++)
anOutputValue.append((TTFloat64*)(mData+(index*mComponentStride+e*mTypeSizeInBytes)));
}
return kTTErrNone;
}
/*
template<typename T>
TTErr TTMatrix::get2dWithinBounds(TTRowID i, TTColumnID j, T& data)
{
//TTUInt32 m = mRowCount;
TTUInt32 n = mColumnCount;
i -= 1; // convert to zero-based indices for data access
j -= 1; // convert to zero-based indices for data access
TTUInt32 distanceFromHead = (i*n+j) * mComponentStride;
TTBoolean isInBounds = inBoundsZeroIndex(distanceFromHead);
if (isInBounds)
{
data = *(T*)(mData + distanceFromHead);
return kTTErrNone;
} else {
return kTTErrInvalidValue;
}
}
*/
// args passed-in should be the coordinates plus the value
// therefore anInputValue requires (2 + mElementCount) items
TTErr TTMatrix::set(const TTValue& anInputValue, TTValue &anUnusedOutputValue)
{
TTValue theValue;
TTUInt16 dimensionCount = anInputValue.getSize() - mElementCount;
if (dimensionCount != 2) // 2 dimensions only
return kTTErrWrongNumValues;
theValue.copyFrom(anInputValue, dimensionCount);
// TODO: this will be a good place to use the planned where() method
TTUInt32 i, j, index;
anInputValue.get(0, i);
anInputValue.get(1, j);
index = i * mColumnCount + j;
// TODO: there is no bounds checking here
if (mType == TT("uint8")) {
for (int e=0; e<mElementCount; e++)
anInputValue.get(e+dimensionCount, *(TTUInt8*)(mData+(index*mComponentStride+e*mTypeSizeInBytes)));
}
else if (mType == TT("int32")) {
for (int e=0; e<mElementCount; e++)
anInputValue.get(e+dimensionCount, *(TTInt32*)(mData+(index*mComponentStride+e*mTypeSizeInBytes)));
}
else if (mType == TT("float32")) {
for (int e=0; e<mElementCount; e++)
anInputValue.get(e+dimensionCount, *(TTFloat32*)(mData+(index*mComponentStride+e*mTypeSizeInBytes)));
}
else if (mType == TT("float64")) {
for (int e=0; e<mElementCount; e++)
anInputValue.get(e+dimensionCount, *(TTFloat64*)(mData+(index*mComponentStride+e*mTypeSizeInBytes)));
}
return kTTErrNone;
}
TTBoolean TTMatrix::allAttributesMatch(const TTMatrix& anotherMatrix)
{
// TODO: should/could this be inlined?
if (mTypeAsDataInfo == anotherMatrix.mTypeAsDataInfo &&
mElementCount == anotherMatrix.mElementCount &&
mRowCount == anotherMatrix.mRowCount &&
mColumnCount == anotherMatrix.mColumnCount)
{
return true;
} else {
return false;
}
}
TTErr TTMatrix::copy(const TTMatrix& source, TTMatrix& dest)
{
dest.adaptTo(source);
memcpy(dest.mData, source.mData, source.mDataSize);
return kTTErrNone;
}
TTErr TTMatrix::adaptTo(const TTMatrix& anotherMatrix)
{
// TODO: what should we do if anotherMatrix is not locally owned?
// It would be nice to re-dimension the data, but we can't re-alloc / resize the number of bytes...
// NW: don't understand above comment, previous set attribute methods *were* calling resize()
if (setRowCountWithoutResize(anotherMatrix.mRowCount) &&
setColumnCountWithoutResize(anotherMatrix.mColumnCount) &&
setElementCountWithoutResize(anotherMatrix.mElementCount) &&
setTypeWithoutResize(anotherMatrix.mTypeAsDataInfo))
{
resize();
return kTTErrNone;
} else {
return kTTErrInvalidValue;
}
}
TTErr TTMatrix::iterate(TTMatrix* C, const TTMatrix* A, const TTMatrix* B, TTMatrixIterator iterator)
{
//TTBoolean AmatchesB = A->allAttributesMatch(B);
if (true) {
C->adaptTo(A);
int stride = A->mTypeSizeInBytes;
int size = A->mDataSize;
for (int k=0; k<size; k+=stride)
(*iterator)(C->mData+k, A->mData+k, B->mData+k);
return kTTErrNone;
} else {
return kTTErrGeneric;
}
}
<commit_msg>TTMatrix: adding a few thoughts/notes as TODO comments<commit_after>/*
* Jamoma 2-Dimensional Matrix Data Class
* Copyright © 2011-2012, Timothy Place & Nathan Wolek
*
* License: This code is licensed under the terms of the "New BSD License"
* http://creativecommons.org/licenses/BSD/
*/
#include "TTMatrix.h"
#include "TTEnvironment.h"
#include "TTBase.h"
#define thisTTClass TTMatrix
#define thisTTClassName "matrix"
#define thisTTClassTags "matrix"
TT_OBJECT_CONSTRUCTOR,
mData(NULL),
mRowCount(1), // initialize to a 1x1 matrix by default (maybe we should be using the args?)
mColumnCount(1), // initialize to a 1x1 matrix by default (maybe we should be using the args?)
mElementCount(1),
mComponentCount(1),
mComponentStride(1),
mDataCount(0),
mType(TT("uint8")),
mTypeSizeInBytes(1),
mDataSize(0),
mDataIsLocallyOwned(YES),
mHeadPtr(NULL),
mTailPtr(NULL)
{
addAttributeWithGetterAndSetter(Dimensions, kTypeUInt32); // mDimensions deprecated, should we delete this too?
// we will keep setDimensions() & getDimensions()
addAttributeWithSetter(RowCount, kTypeUInt32);
addAttributeWithSetter(ColumnCount, kTypeUInt32);
addAttributeWithSetter(Type, kTypeUInt8);
addAttributeWithSetter(ElementCount, kTypeUInt8);
addMessage(clear);
addMessageWithArguments(fill);
addMessageWithArguments(get);
addMessageWithArguments(set);
// TODO: getLockedPointer -- returns a pointer to the data, locks the matrix mutex
// TODO: releaseLockedPointer -- releases the matrix mutex
// TODO: the above two items mean we need a TTMutex member
resize();
}
TTMatrix::~TTMatrix()
{
if (mDataIsLocallyOwned)
delete[] mData; // TODO: only do this if the refcount for the data is down to zero!
}
TTErr TTMatrix::resize()
{
mComponentCount = mRowCount * mColumnCount;
mDataCount = mComponentCount * mElementCount;
mDataSize = mDataCount * mTypeSizeInBytes;
mComponentStride = mTypeSizeInBytes * mElementCount;
if (mDataIsLocallyOwned) {
// TODO: currently, we are not preserving memory when resizing. Should we try to preserve the previous memory contents?
// TODO: thread protection
delete[] mData;
mData = new TTByte[mDataSize];
mHeadPtr = mData;
mTailPtr = mData + mDataSize;
}
if (mDataSize && mData)
{
return kTTErrNone;
} else {
return kTTErrAllocFailed;
}
}
TTBoolean TTMatrix::setRowCountWithoutResize(TTUInt32 aNewRowCount)
{
if (aNewRowCount > 0)
{
mRowCount = aNewRowCount;
return true;
} else {
return false;
}
}
TTBoolean TTMatrix::setColumnCountWithoutResize(TTUInt32 aNewColumnCount)
{
if (aNewColumnCount > 0)
{
mColumnCount = aNewColumnCount;
return true;
} else {
return false;
}
}
TTBoolean TTMatrix::setElementCountWithoutResize(TTUInt8 aNewElementCount)
{
if (aNewElementCount > 0)
{
mElementCount = aNewElementCount;
return true;
} else {
return false;
}
}
TTBoolean TTMatrix::setTypeWithoutResize(TTDataInfoPtr aNewType)
{
if (aNewType->isNumerical)
{
mTypeAsDataInfo = aNewType;
mType = aNewType->name;
mTypeSizeInBytes = (aNewType->bitdepth / 8);
return true;
} else {
return false;
}
}
TTErr TTMatrix::setRowCount(const TTValue& aNewRowCount)
{
TTUInt32 aNewRowCountInt = aNewRowCount;
if (setRowCountWithoutResize(aNewRowCountInt))
{
return resize();
} else {
return kTTErrInvalidValue;
}
}
TTErr TTMatrix::setColumnCount(const TTValue& aNewColumnCount)
{
TTUInt32 aNewColumnCountInt = aNewColumnCount;
if (setColumnCountWithoutResize(aNewColumnCountInt))
{
return resize();
} else {
return kTTErrInvalidValue;
}
}
TTErr TTMatrix::setElementCount(const TTValue& newElementCount)
{
TTUInt8 aNewElementCountInt = newElementCount;
if (setElementCountWithoutResize(aNewElementCountInt))
{
return resize();
} else {
return kTTErrInvalidValue;
}
}
TTErr TTMatrix::setType(const TTValue& aType)
{
TTSymbolPtr aNewTypeName = aType;
TTDataInfoPtr aNewDataType = TTDataInfo::getInfoForType(aNewTypeName); // move into the "withoutResize" method?
if (setTypeWithoutResize(aNewDataType))
{
return resize();
} else {
return kTTErrInvalidValue;
}
}
TTErr TTMatrix::setDimensions(const TTValue& someNewDimensions)
{
TTUInt32 aNewRowCount = 1;
TTUInt32 aNewColumnCount = 1;
TTUInt8 size = someNewDimensions.getSize();
// needed to support old calls with 1 or 2 dimensions
if (size > 0) { someNewDimensions.get(0, aNewRowCount); }
if (size > 1) { someNewDimensions.get(1, aNewColumnCount); }
if (this->setRowCountWithoutResize(aNewRowCount) &&
this->setColumnCountWithoutResize(aNewColumnCount))
{
return resize();
} else {
return kTTErrInvalidValue;
}
}
TTErr TTMatrix::getDimensions(TTValue& returnedDimensions) const
{
returnedDimensions.setSize(2);
returnedDimensions.set(0, mRowCount);
returnedDimensions.set(1, mColumnCount);
return kTTErrNone;
}
TTErr TTMatrix::clear()
{
memset(mData, 0, mDataSize);
return kTTErrNone;
}
TTErr TTMatrix::fill(const TTValue& anInputValue, TTValue &anUnusedOutputValue)
{
TTBytePtr fillValue = new TTByte[mComponentStride];
// TODO: here we have this ugly switch again...
if (mType == TT("uint8"))
anInputValue.getArray((TTUInt8*)fillValue, mElementCount);
else if (mType == TT("int32"))
anInputValue.getArray((TTInt32*)fillValue, mElementCount);
else if (mType == TT("float32"))
anInputValue.getArray((TTFloat32*)fillValue, mElementCount);
else if (mType == TT("float64"))
anInputValue.getArray((TTFloat64*)fillValue, mElementCount);
for (TTUInt32 i=0; i<mDataSize; i += mComponentStride)
memcpy(mData+i, fillValue, mComponentStride);
delete[] fillValue;
return kTTErrNone;
}
/*
To find the index in the matrix:
1D Matrix: index = x
2D Matrix: index = dim_0 y + x
3D Matrix: index = dim_0 dim_1 z + dim_0 y + x
etc.
*/
// args passed-in should be the 2 coordinates
// args returned will be the value(s) at those coordinates
TTErr TTMatrix::get(const TTValue& anInputValue, TTValue &anOutputValue) const
{
TTUInt16 dimensionCount = anInputValue.getSize();
if (dimensionCount != 2) // 2 dimensions only
return kTTErrWrongNumValues;
// TODO: this will be a good place to use the planned where() method
TTUInt32 i, j, index;
anInputValue.get(0, i);
anInputValue.get(1, j);
index = i * mColumnCount + j;
// TODO: there is no bounds checking here
anOutputValue.clear();
// TODO: here we have this ugly switch again...
// Maybe we could just have duplicate pointers of different types in our class, and then we could access them more cleanly?
if (mType == TT("uint8")) {
for (int e=0; e<mElementCount; e++)
anOutputValue.append((TTUInt8*)(mData+(index*mComponentStride+e*mTypeSizeInBytes)));
}
else if (mType == TT("int32")) {
for (int e=0; e<mElementCount; e++)
anOutputValue.append((TTInt32*)(mData+(index*mComponentStride+e*mTypeSizeInBytes)));
}
else if (mType == TT("float32")) {
for (int e=0; e<mElementCount; e++)
anOutputValue.append((TTFloat32*)(mData+(index*mComponentStride+e*mTypeSizeInBytes)));
}
else if (mType == TT("float64")) {
for (int e=0; e<mElementCount; e++)
anOutputValue.append((TTFloat64*)(mData+(index*mComponentStride+e*mTypeSizeInBytes)));
}
return kTTErrNone;
}
/*
template<typename T>
TTErr TTMatrix::get2dWithinBounds(TTRowID i, TTColumnID j, T& data)
{
//TTUInt32 m = mRowCount;
TTUInt32 n = mColumnCount;
i -= 1; // convert to zero-based indices for data access
j -= 1; // convert to zero-based indices for data access
TTUInt32 distanceFromHead = (i*n+j) * mComponentStride;
TTBoolean isInBounds = inBoundsZeroIndex(distanceFromHead);
if (isInBounds)
{
data = *(T*)(mData + distanceFromHead);
return kTTErrNone;
} else {
return kTTErrInvalidValue;
}
}
*/
// args passed-in should be the coordinates plus the value
// therefore anInputValue requires (2 + mElementCount) items
TTErr TTMatrix::set(const TTValue& anInputValue, TTValue &anUnusedOutputValue)
{
TTValue theValue;
TTUInt16 dimensionCount = anInputValue.getSize() - mElementCount;
if (dimensionCount != 2) // 2 dimensions only
return kTTErrWrongNumValues;
theValue.copyFrom(anInputValue, dimensionCount);
// TODO: this will be a good place to use the planned where() method
TTUInt32 i, j, index;
anInputValue.get(0, i);
anInputValue.get(1, j);
index = i * mColumnCount + j;
// TODO: there is no bounds checking here
if (mType == TT("uint8")) {
for (int e=0; e<mElementCount; e++)
anInputValue.get(e+dimensionCount, *(TTUInt8*)(mData+(index*mComponentStride+e*mTypeSizeInBytes)));
}
else if (mType == TT("int32")) {
for (int e=0; e<mElementCount; e++)
anInputValue.get(e+dimensionCount, *(TTInt32*)(mData+(index*mComponentStride+e*mTypeSizeInBytes)));
}
else if (mType == TT("float32")) {
for (int e=0; e<mElementCount; e++)
anInputValue.get(e+dimensionCount, *(TTFloat32*)(mData+(index*mComponentStride+e*mTypeSizeInBytes)));
}
else if (mType == TT("float64")) {
for (int e=0; e<mElementCount; e++)
anInputValue.get(e+dimensionCount, *(TTFloat64*)(mData+(index*mComponentStride+e*mTypeSizeInBytes)));
}
return kTTErrNone;
}
TTBoolean TTMatrix::allAttributesMatch(const TTMatrix& anotherMatrix)
{
// TODO: should/could this be inlined?
if (mTypeAsDataInfo == anotherMatrix.mTypeAsDataInfo &&
mElementCount == anotherMatrix.mElementCount &&
mRowCount == anotherMatrix.mRowCount &&
mColumnCount == anotherMatrix.mColumnCount)
{
return true;
} else {
return false;
}
}
TTErr TTMatrix::copy(const TTMatrix& source, TTMatrix& dest)
{
// TODO: could this be rethought as an iterator?
dest.adaptTo(source);
memcpy(dest.mData, source.mData, source.mDataSize);
return kTTErrNone;
}
TTErr TTMatrix::adaptTo(const TTMatrix& anotherMatrix)
{
// TODO: what should we do if anotherMatrix is not locally owned?
// It would be nice to re-dimension the data, but we can't re-alloc / resize the number of bytes...
// NW: don't understand above comment, previous set attribute methods *were* calling resize()
if (setRowCountWithoutResize(anotherMatrix.mRowCount) &&
setColumnCountWithoutResize(anotherMatrix.mColumnCount) &&
setElementCountWithoutResize(anotherMatrix.mElementCount) &&
setTypeWithoutResize(anotherMatrix.mTypeAsDataInfo))
{
resize();
return kTTErrNone;
} else {
return kTTErrInvalidValue;
}
}
TTErr TTMatrix::iterate(TTMatrix* C, const TTMatrix* A, const TTMatrix* B, TTMatrixIterator iterator)
{
// TTBoolean match = A->allAttributesMatch(B);
// TODO: above line fails to build. if working, the returned "match" would be used of if statement that follows.
if (true) {
C->adaptTo(A);
int stride = A->mTypeSizeInBytes;
int size = A->mDataSize;
for (int k=0; k<size; k+=stride)
(*iterator)(C->mData+k, A->mData+k, B->mData+k);
return kTTErrNone;
} else {
return kTTErrGeneric;
}
}
<|endoftext|> |
<commit_before>// bitmessage cracker, build with g++ or MSVS to a shared library, use included python code for usage under bitmessage
#ifdef _WIN32
#include "Winsock.h"
#include "Windows.h"
#define uint64_t unsigned __int64
#else
#include <arpa/inet.h>
#include <pthread.h>
#include <stdint.h>
#endif
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "openssl/sha.h"
#define HASH_SIZE 64
#define BUFLEN 16384
#define ntohll(x) ( ( (uint64_t)(ntohl( (unsigned int)((x << 32) >> 32) )) << 32) | ntohl( ((unsigned int)(x >> 32)) ) )
unsigned long long max_val;
unsigned char *initialHash;
int numthreads = 8;
unsigned long long successval = 0;
#ifdef _WIN32
DWORD WINAPI threadfunc(LPVOID lpParameter) {
DWORD incamt = (DWORD)lpParameter;
#else
void * threadfunc(void* param) {
unsigned int incamt = (unsigned int)param;
#endif
SHA512_CTX sha;
unsigned char buf[HASH_SIZE + sizeof(uint64_t)] = { 0 };
unsigned char output[HASH_SIZE] = { 0 };
memcpy(buf + sizeof(uint64_t), initialHash, HASH_SIZE);
unsigned long long tmpnonce = incamt;
unsigned long long * nonce = (unsigned long long *)buf;
unsigned long long * hash = (unsigned long long *)output;
while (successval == 0) {
tmpnonce += numthreads;
(*nonce) = ntohll(tmpnonce); /* increment nonce */
SHA512_Init(&sha);
SHA512_Update(&sha, buf, HASH_SIZE + sizeof(uint64_t));
SHA512_Final(output, &sha);
SHA512_Init(&sha);
SHA512_Update(&sha, output, HASH_SIZE);
SHA512_Final(output, &sha);
if (ntohll(*hash) < max_val) {
successval = tmpnonce;
}
}
return NULL;
}
extern "C" __declspec(dllexport) unsigned long long BitmessagePOW(unsigned char * starthash, unsigned long long target)
{
successval = 0;
max_val = target;
initialHash = (unsigned char *)starthash;
# ifdef _WIN32
HANDLE* threads = (HANDLE*)calloc(sizeof(HANDLE), numthreads);
# else
pthread_t* threads = calloc(sizeof(pthread_t), numthreads);
# endif
for (int i = 0; i < numthreads; i++) {
# ifdef _WIN32
threads[i] = CreateThread(NULL, 0, threadfunc, (LPVOID)i, 0, NULL);
SetThreadPriority(threads[i], THREAD_PRIORITY_IDLE);
# else
pthread_create(&threads[i], NULL, threadfunc, (void*)i);
# endif
}
# ifdef _WIN32
WaitForMultipleObjects(numthreads, threads, TRUE, INFINITE);
# else
for (int i = 0; i < numthreads; i++) {
pthread_join(threads[i], NULL);
}
# endif
free(threads);
return successval;
}<commit_msg>C PoW updates<commit_after>// bitmessage cracker, build with g++ or MSVS to a shared library, use included python code for usage under bitmessage
#ifdef _WIN32
#include "Winsock.h"
#include "Windows.h"
#define uint64_t unsigned __int64
#else
#include <arpa/inet.h>
#include <pthread.h>
#include <stdint.h>
#endif
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "openssl/sha.h"
#define HASH_SIZE 64
#define BUFLEN 16384
#if defined(__GNUC__)
#define EXPORT __attribute__ ((__visibility__("default")))
#define UINT intptr_t
#elif defined(WIN32)
#define EXPORT __declspec(dllexport)
#define UINT unsigned int
#endif
#define ntohll(x) ( ( (uint64_t)(ntohl( (unsigned int)((x << 32) >> 32) )) << 32) | ntohl( ((unsigned int)(x >> 32)) ) )
unsigned long long max_val;
unsigned char *initialHash;
int numthreads = 8;
unsigned long long successval = 0;
#ifdef _WIN32
DWORD WINAPI threadfunc(LPVOID lpParameter) {
DWORD incamt = (DWORD)lpParameter;
#else
void * threadfunc(void* param) {
UINT incamt = (UINT)param;
#endif
SHA512_CTX sha;
unsigned char buf[HASH_SIZE + sizeof(uint64_t)] = { 0 };
unsigned char output[HASH_SIZE] = { 0 };
memcpy(buf + sizeof(uint64_t), initialHash, HASH_SIZE);
unsigned long long tmpnonce = incamt;
unsigned long long * nonce = (unsigned long long *)buf;
unsigned long long * hash = (unsigned long long *)output;
while (successval == 0) {
tmpnonce += numthreads;
(*nonce) = ntohll(tmpnonce); /* increment nonce */
SHA512_Init(&sha);
SHA512_Update(&sha, buf, HASH_SIZE + sizeof(uint64_t));
SHA512_Final(output, &sha);
SHA512_Init(&sha);
SHA512_Update(&sha, output, HASH_SIZE);
SHA512_Final(output, &sha);
if (ntohll(*hash) < max_val) {
successval = tmpnonce;
}
}
return NULL;
}
extern "C" EXPORT unsigned long long BitmessagePOW(unsigned char * starthash, unsigned long long target)
{
successval = 0;
max_val = target;
initialHash = (unsigned char *)starthash;
# ifdef _WIN32
HANDLE* threads = (HANDLE*)calloc(sizeof(HANDLE), numthreads);
# else
pthread_t* threads = (pthread_t*)calloc(sizeof(pthread_t), numthreads);
struct sched_param schparam;
schparam.sched_priority = 0;
# endif
for (UINT i = 0; i < numthreads; i++) {
# ifdef _WIN32
threads[i] = CreateThread(NULL, 0, threadfunc, (LPVOID)i, 0, NULL);
SetThreadPriority(threads[i], THREAD_PRIORITY_IDLE);
# else
pthread_create(&threads[i], NULL, threadfunc, (void*)i);
pthread_setschedparam(threads[i], SCHED_IDLE, &schparam);
# endif
}
# ifdef _WIN32
WaitForMultipleObjects(numthreads, threads, TRUE, INFINITE);
# else
for (int i = 0; i < numthreads; i++) {
pthread_join(threads[i], NULL);
}
# endif
free(threads);
return successval;
}
<|endoftext|> |
<commit_before><commit_msg>Make setSinkId try to set the sink even if the given new sinkId equals the current sinkId.<commit_after><|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: styledlg.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2005-09-08 21:53:29 $
*
* 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 SC_STYLEDLG_HXX
#define SC_STYLEDLG_HXX
#ifndef _SFX_HXX
#endif
#ifndef _SFX_STYLEDLG_HXX //autogen
#include <sfx2/styledlg.hxx>
#endif
//==================================================================
class SfxStyleSheetBase;
class ScStyleDlg : public SfxStyleDialog
{
public:
ScStyleDlg( Window* pParent,
SfxStyleSheetBase& rStyleBase,
USHORT nRscId );
~ScStyleDlg();
protected:
virtual void PageCreated( USHORT nPageId, SfxTabPage& rTabPage );
virtual const SfxItemSet* GetRefreshedSet();
private:
USHORT nDlgRsc;
};
#endif // SC_STYLEDLG_HXX
<commit_msg>INTEGRATION: CWS changefileheader (1.2.700); FILE MERGED 2008/04/01 15:31:01 thb 1.2.700.2: #i85898# Stripping all external header guards 2008/03/31 17:15:49 rt 1.2.700.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: styledlg.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 SC_STYLEDLG_HXX
#define SC_STYLEDLG_HXX
#ifndef _SFX_HXX
#endif
#include <sfx2/styledlg.hxx>
//==================================================================
class SfxStyleSheetBase;
class ScStyleDlg : public SfxStyleDialog
{
public:
ScStyleDlg( Window* pParent,
SfxStyleSheetBase& rStyleBase,
USHORT nRscId );
~ScStyleDlg();
protected:
virtual void PageCreated( USHORT nPageId, SfxTabPage& rTabPage );
virtual const SfxItemSet* GetRefreshedSet();
private:
USHORT nDlgRsc;
};
#endif // SC_STYLEDLG_HXX
<|endoftext|> |
<commit_before><commit_msg>fixed coherent scattering unit test: but scattering angle accuracy is still less than ideal<commit_after><|endoftext|> |
<commit_before>/*
*
* Copyright 2013 Telefonica Investigacion y Desarrollo, S.A.U
*
* This file is part of Orion Context Broker.
*
* Orion Context Broker 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.
*
* Orion Context Broker 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 Orion Context Broker. If not, see http://www.gnu.org/licenses/.
*
* For those usages not covered by this license please contact with
* iot_support at tid dot es
*
* Author: Fermin Galan
*/
#include "gtest/gtest.h"
#include "mongo/client/dbclient.h"
#include "logMsg/logMsg.h"
#include "logMsg/traceLevels.h"
#include "common/globals.h"
#include "mongoBackend/MongoGlobal.h"
#include "mongoBackend/mongoUnsubscribeContextAvailability.h"
#include "ngsi9/UnsubscribeContextAvailabilityRequest.h"
#include "ngsi9/UnsubscribeContextAvailabilityResponse.h"
#include "unittests/testInit.h"
#include "unittests/commonMocks.h"
/* ****************************************************************************
*
* USING
*/
using mongo::DBClientBase;
using mongo::BSONObj;
using mongo::BSONArray;
using mongo::BSONElement;
using mongo::OID;
using mongo::DBException;
using mongo::BSONObjBuilder;
using ::testing::_;
using ::testing::Throw;
using ::testing::Return;
extern void setMongoConnectionForUnitTest(DBClientBase* _connection);
/* ****************************************************************************
*
* First set of test is related with updating thinks
*
* - subscriptionNotFound
* - unsubscribe
*
* Simulating fails in MongoDB connection.
*
* - MongoDbFindOneFail
* - MongoDbRemoveFail
*
*/
/* ****************************************************************************
*
* prepareDatabase -
*/
static void prepareDatabase(void) {
/* Set database */
setupDatabase();
DBClientBase* connection = getMongoConnection();
BSONObj sub1 = BSON("_id" << OID("51307b66f481db11bf860001") <<
"expiration" << 10000000 <<
"reference" << "http://notify1.me" <<
"entities" << BSON_ARRAY(BSON("id" << "E1" << "type" << "T1" << "isPattern" << "false")) <<
"attrs" << BSONArray());
BSONObj sub2 = BSON("_id" << OID("51307b66f481db11bf860002") <<
"expiration" << 20000000 <<
"reference" << "http://notify2.me" <<
"entities" << BSON_ARRAY(BSON("id" << "E1" << "type" << "T1" << "isPattern" << "false")) <<
"attrs" << BSON_ARRAY("A1" << "A2"));
connection->insert(SUBSCRIBECONTEXTAVAIL_COLL, sub1);
connection->insert(SUBSCRIBECONTEXTAVAIL_COLL, sub2);
}
/* ****************************************************************************
*
* subscriptionNotFound -
*/
TEST(mongoUnsubscribeContextAvailability, subscriptionNotFound)
{
HttpStatusCode ms;
UnsubscribeContextAvailabilityRequest req;
UnsubscribeContextAvailabilityResponse res;
/* Prepare mock */
NotifierMock* notifierMock = new NotifierMock();
EXPECT_CALL(*notifierMock, sendNotifyContextAvailabilityRequest(_,_,_,_,_))
.Times(0);
setNotifier(notifierMock);
/* Forge the request (from "inside" to "outside") */
req.subscriptionId.set("51307b66f481db11bf869999");
/* Prepare database */
prepareDatabase();
/* Invoke the function in mongoBackend library */
ms = mongoUnsubscribeContextAvailability(&req, &res);
/* Check response is as expected */
EXPECT_EQ(SccOk, ms);
EXPECT_EQ("51307b66f481db11bf869999", res.subscriptionId.get());
EXPECT_EQ(SccContextElementNotFound, res.statusCode.code);
EXPECT_EQ("No context element found", res.statusCode.reasonPhrase);
EXPECT_EQ(0, res.statusCode.details.size());
/* Check database (untouched) */
DBClientBase* connection = getMongoConnection();
ASSERT_EQ(2, connection->count(SUBSCRIBECONTEXTAVAIL_COLL, BSONObj()));
/* Release mock */
delete notifierMock;
}
/* ****************************************************************************
*
* unsubscribe -
*/
TEST(mongoUnsubscribeContextAvailability, unsubscribe)
{
HttpStatusCode ms;
UnsubscribeContextAvailabilityRequest req;
UnsubscribeContextAvailabilityResponse res;
/* Prepare mock */
NotifierMock* notifierMock = new NotifierMock();
EXPECT_CALL(*notifierMock, sendNotifyContextAvailabilityRequest(_,_,_,_,_))
.Times(0);
setNotifier(notifierMock);
/* Forge the request (from "inside" to "outside") */
req.subscriptionId.set("51307b66f481db11bf860001");
/* Prepare database */
prepareDatabase();
/* Invoke the function in mongoBackend library */
ms = mongoUnsubscribeContextAvailability(&req, &res);
/* Check response is as expected */
EXPECT_EQ(SccOk, ms);
EXPECT_EQ("51307b66f481db11bf860001", res.subscriptionId.get());
EXPECT_EQ(SccOk, res.statusCode.code);
EXPECT_EQ("OK", res.statusCode.reasonPhrase);
EXPECT_EQ(0, res.statusCode.details.size());
/* Check database (one document, but not the deleted one) */
DBClientBase* connection = getMongoConnection();
ASSERT_EQ(1, connection->count(SUBSCRIBECONTEXTAVAIL_COLL, BSONObj()));
BSONObj sub = connection->findOne(SUBSCRIBECONTEXTAVAIL_COLL, BSON("_id" << OID("51307b66f481db11bf860002")));
EXPECT_EQ("51307b66f481db11bf860002", sub.getField("_id").OID().toString());
/* Release mock */
delete notifierMock;
}
/* ****************************************************************************
*
* MongoDbFindOneFail -
*
*/
TEST(mongoUnsubscribeContextAvailability, MongoDbFindOneFail)
{
HttpStatusCode ms;
UnsubscribeContextAvailabilityRequest req;
UnsubscribeContextAvailabilityResponse res;
/* Prepare mocks */
const DBException e = DBException("boom!!", 33);
DBClientConnectionMock* connectionMock = new DBClientConnectionMock();
ON_CALL(*connectionMock, findOne("utest.casubs",_,_,_))
.WillByDefault(Throw(e));
NotifierMock* notifierMock = new NotifierMock();
EXPECT_CALL(*notifierMock, sendNotifyContextAvailabilityRequest(_,_,_,_,_))
.Times(0);
setNotifier(notifierMock);
/* Forge the request (from "inside" to "outside") */
req.subscriptionId.set("51307b66f481db11bf860001");
/* Set MongoDB connection (prepare database first with the "actual" connection object).
* The "actual" conneciton is preserved for later use */
prepareDatabase();
DBClientBase* connectionDb = getMongoConnection();
setMongoConnectionForUnitTest(connectionMock);
/* Invoke the function in mongoBackend library */
ms = mongoUnsubscribeContextAvailability(&req, &res);
/* Check response is as expected */
EXPECT_EQ(SccOk, ms);
EXPECT_EQ("51307b66f481db11bf860001", res.subscriptionId.get());
EXPECT_EQ(SccReceiverInternalError, res.statusCode.code);
EXPECT_EQ("Internal Server Error", res.statusCode.reasonPhrase);
EXPECT_EQ("Database Error (collection: utest.casubs "
"- findOne(): { _id: ObjectId('51307b66f481db11bf860001') } "
"- exception: boom!!)", res.statusCode.details);
// Sleeping a little to "give mongod time to process its input".
// Without this sleep, this tests fails around 50% of the times (in Ubuntu 13.04)
usleep(1000);
int count = connectionDb->count(SUBSCRIBECONTEXTAVAIL_COLL, BSONObj());
ASSERT_EQ(2, count);
/* Restore real DB connection */
setMongoConnectionForUnitTest(connectionDb);
/* Release mocks */
delete notifierMock;
delete connectionMock;
}
/* ****************************************************************************
*
* MongoDbRemoveFail -
*
*/
TEST(mongoUnsubscribeContextAvailability, MongoDbRemoveFail)
{
HttpStatusCode ms;
UnsubscribeContextAvailabilityRequest req;
UnsubscribeContextAvailabilityResponse res;
/* Prepare mocks */
const DBException e = DBException("boom!!", 33);
BSONObj fakeSub = BSON("_id" << OID("51307b66f481db11bf860001") <<
"expiration" << 10000000 <<
"reference" << "http://notify1.me" <<
"entities" << BSON_ARRAY(BSON("id" << "E1" << "type" << "T1" << "isPattern" << "false")) <<
"attrs" << BSONArray());
DBClientConnectionMock* connectionMock = new DBClientConnectionMock();
ON_CALL(*connectionMock, findOne("utest.casubs",_,_,_))
.WillByDefault(Return(fakeSub));
ON_CALL(*connectionMock, remove("utest.casubs",_,_,_))
.WillByDefault(Throw(e));
NotifierMock* notifierMock = new NotifierMock();
EXPECT_CALL(*notifierMock, sendNotifyContextAvailabilityRequest(_,_,_,_,_))
.Times(0);
setNotifier(notifierMock);
/* Forge the request (from "inside" to "outside") */
req.subscriptionId.set("51307b66f481db11bf860001");
/* Set MongoDB connection (prepare database first with the "actual" connection object).
* The "actual" conneciton is preserved for later use */
prepareDatabase();
DBClientBase* connectionDb = getMongoConnection();
setMongoConnectionForUnitTest(connectionMock);
/* Invoke the function in mongoBackend library */
ms = mongoUnsubscribeContextAvailability(&req, &res);
/* Check response is as expected */
EXPECT_EQ(SccOk, ms);
EXPECT_EQ("51307b66f481db11bf860001", res.subscriptionId.get());
EXPECT_EQ(SccReceiverInternalError, res.statusCode.code);
EXPECT_EQ("Internal Server Error", res.statusCode.reasonPhrase);
EXPECT_EQ("Database Error (collection: utest.casubs - "
"remove(): { _id: ObjectId('51307b66f481db11bf860001') } "
"- exception: boom!!)", res.statusCode.details);
// Sleeping a little to "give mongod time to process its input".
// Without this sleep, this tests fails around 50% of the times (in Ubuntu 13.04)
usleep(1000);
ASSERT_EQ(2, connectionDb->count(SUBSCRIBECONTEXTAVAIL_COLL, BSONObj()));
/* Restore real DB connection */
setMongoConnectionForUnitTest(connectionDb);
/* Release mocks */
delete notifierMock;
delete connectionMock;
}
<commit_msg>Style guide in mongoUnsubscribeContextAvailability_test.cpp<commit_after>/*
*
* Copyright 2013 Telefonica Investigacion y Desarrollo, S.A.U
*
* This file is part of Orion Context Broker.
*
* Orion Context Broker 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.
*
* Orion Context Broker 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 Orion Context Broker. If not, see http://www.gnu.org/licenses/.
*
* For those usages not covered by this license please contact with
* iot_support at tid dot es
*
* Author: Fermin Galan
*/
#include "gtest/gtest.h"
#include "mongo/client/dbclient.h"
#include "logMsg/logMsg.h"
#include "logMsg/traceLevels.h"
#include "common/globals.h"
#include "mongoBackend/MongoGlobal.h"
#include "mongoBackend/mongoUnsubscribeContextAvailability.h"
#include "ngsi9/UnsubscribeContextAvailabilityRequest.h"
#include "ngsi9/UnsubscribeContextAvailabilityResponse.h"
#include "unittests/testInit.h"
#include "unittests/commonMocks.h"
/* ****************************************************************************
*
* USING
*/
using mongo::DBClientBase;
using mongo::BSONObj;
using mongo::BSONArray;
using mongo::BSONElement;
using mongo::OID;
using mongo::DBException;
using mongo::BSONObjBuilder;
using ::testing::_;
using ::testing::Throw;
using ::testing::Return;
extern void setMongoConnectionForUnitTest(DBClientBase* _connection);
/* ****************************************************************************
*
* First set of test is related with updating thinks
*
* - subscriptionNotFound
* - unsubscribe
*
* Simulating fails in MongoDB connection.
*
* - MongoDbFindOneFail
* - MongoDbRemoveFail
*
*/
/* ****************************************************************************
*
* prepareDatabase -
*/
static void prepareDatabase(void)
{
/* Set database */
setupDatabase();
DBClientBase* connection = getMongoConnection();
BSONObj sub1 = BSON("_id" << OID("51307b66f481db11bf860001") <<
"expiration" << 10000000 <<
"reference" << "http://notify1.me" <<
"entities" << BSON_ARRAY(BSON("id" << "E1" << "type" << "T1" << "isPattern" << "false")) <<
"attrs" << BSONArray());
BSONObj sub2 = BSON("_id" << OID("51307b66f481db11bf860002") <<
"expiration" << 20000000 <<
"reference" << "http://notify2.me" <<
"entities" << BSON_ARRAY(BSON("id" << "E1" << "type" << "T1" << "isPattern" << "false")) <<
"attrs" << BSON_ARRAY("A1" << "A2"));
connection->insert(SUBSCRIBECONTEXTAVAIL_COLL, sub1);
connection->insert(SUBSCRIBECONTEXTAVAIL_COLL, sub2);
}
/* ****************************************************************************
*
* subscriptionNotFound -
*/
TEST(mongoUnsubscribeContextAvailability, subscriptionNotFound)
{
HttpStatusCode ms;
UnsubscribeContextAvailabilityRequest req;
UnsubscribeContextAvailabilityResponse res;
/* Prepare mock */
NotifierMock* notifierMock = new NotifierMock();
EXPECT_CALL(*notifierMock, sendNotifyContextAvailabilityRequest(_, _, _, _, _))
.Times(0);
setNotifier(notifierMock);
/* Forge the request (from "inside" to "outside") */
req.subscriptionId.set("51307b66f481db11bf869999");
/* Prepare database */
prepareDatabase();
/* Invoke the function in mongoBackend library */
ms = mongoUnsubscribeContextAvailability(&req, &res);
/* Check response is as expected */
EXPECT_EQ(SccOk, ms);
EXPECT_EQ("51307b66f481db11bf869999", res.subscriptionId.get());
EXPECT_EQ(SccContextElementNotFound, res.statusCode.code);
EXPECT_EQ("No context element found", res.statusCode.reasonPhrase);
EXPECT_EQ(0, res.statusCode.details.size());
/* Check database (untouched) */
DBClientBase* connection = getMongoConnection();
ASSERT_EQ(2, connection->count(SUBSCRIBECONTEXTAVAIL_COLL, BSONObj()));
/* Release mock */
delete notifierMock;
}
/* ****************************************************************************
*
* unsubscribe -
*/
TEST(mongoUnsubscribeContextAvailability, unsubscribe)
{
HttpStatusCode ms;
UnsubscribeContextAvailabilityRequest req;
UnsubscribeContextAvailabilityResponse res;
/* Prepare mock */
NotifierMock* notifierMock = new NotifierMock();
EXPECT_CALL(*notifierMock, sendNotifyContextAvailabilityRequest(_, _, _, _, _))
.Times(0);
setNotifier(notifierMock);
/* Forge the request (from "inside" to "outside") */
req.subscriptionId.set("51307b66f481db11bf860001");
/* Prepare database */
prepareDatabase();
/* Invoke the function in mongoBackend library */
ms = mongoUnsubscribeContextAvailability(&req, &res);
/* Check response is as expected */
EXPECT_EQ(SccOk, ms);
EXPECT_EQ("51307b66f481db11bf860001", res.subscriptionId.get());
EXPECT_EQ(SccOk, res.statusCode.code);
EXPECT_EQ("OK", res.statusCode.reasonPhrase);
EXPECT_EQ(0, res.statusCode.details.size());
/* Check database (one document, but not the deleted one) */
DBClientBase* connection = getMongoConnection();
ASSERT_EQ(1, connection->count(SUBSCRIBECONTEXTAVAIL_COLL, BSONObj()));
BSONObj sub = connection->findOne(SUBSCRIBECONTEXTAVAIL_COLL, BSON("_id" << OID("51307b66f481db11bf860002")));
EXPECT_EQ("51307b66f481db11bf860002", sub.getField("_id").OID().toString());
/* Release mock */
delete notifierMock;
}
/* ****************************************************************************
*
* MongoDbFindOneFail -
*
*/
TEST(mongoUnsubscribeContextAvailability, MongoDbFindOneFail)
{
HttpStatusCode ms;
UnsubscribeContextAvailabilityRequest req;
UnsubscribeContextAvailabilityResponse res;
/* Prepare mocks */
const DBException e = DBException("boom!!", 33);
DBClientConnectionMock* connectionMock = new DBClientConnectionMock();
ON_CALL(*connectionMock, findOne("utest.casubs", _, _, _))
.WillByDefault(Throw(e));
NotifierMock* notifierMock = new NotifierMock();
EXPECT_CALL(*notifierMock, sendNotifyContextAvailabilityRequest(_, _, _, _, _))
.Times(0);
setNotifier(notifierMock);
/* Forge the request (from "inside" to "outside") */
req.subscriptionId.set("51307b66f481db11bf860001");
/* Set MongoDB connection (prepare database first with the "actual" connection object).
* The "actual" conneciton is preserved for later use */
prepareDatabase();
DBClientBase* connectionDb = getMongoConnection();
setMongoConnectionForUnitTest(connectionMock);
/* Invoke the function in mongoBackend library */
ms = mongoUnsubscribeContextAvailability(&req, &res);
/* Check response is as expected */
EXPECT_EQ(SccOk, ms);
EXPECT_EQ("51307b66f481db11bf860001", res.subscriptionId.get());
EXPECT_EQ(SccReceiverInternalError, res.statusCode.code);
EXPECT_EQ("Internal Server Error", res.statusCode.reasonPhrase);
EXPECT_EQ("Database Error (collection: utest.casubs "
"- findOne(): { _id: ObjectId('51307b66f481db11bf860001') } "
"- exception: boom!!)", res.statusCode.details);
// Sleeping a little to "give mongod time to process its input".
// Without this sleep, this tests fails around 50% of the times (in Ubuntu 13.04)
usleep(1000);
int count = connectionDb->count(SUBSCRIBECONTEXTAVAIL_COLL, BSONObj());
ASSERT_EQ(2, count);
/* Restore real DB connection */
setMongoConnectionForUnitTest(connectionDb);
/* Release mocks */
delete notifierMock;
delete connectionMock;
}
/* ****************************************************************************
*
* MongoDbRemoveFail -
*
*/
TEST(mongoUnsubscribeContextAvailability, MongoDbRemoveFail)
{
HttpStatusCode ms;
UnsubscribeContextAvailabilityRequest req;
UnsubscribeContextAvailabilityResponse res;
/* Prepare mocks */
const DBException e = DBException("boom!!", 33);
BSONObj fakeSub = BSON("_id" << OID("51307b66f481db11bf860001") <<
"expiration" << 10000000 <<
"reference" << "http://notify1.me" <<
"entities" << BSON_ARRAY(BSON("id" << "E1" <<
"type" << "T1" <<
"isPattern" << "false")) <<
"attrs" << BSONArray());
DBClientConnectionMock* connectionMock = new DBClientConnectionMock();
ON_CALL(*connectionMock, findOne("utest.casubs", _, _, _))
.WillByDefault(Return(fakeSub));
ON_CALL(*connectionMock, remove("utest.casubs", _, _, _))
.WillByDefault(Throw(e));
NotifierMock* notifierMock = new NotifierMock();
EXPECT_CALL(*notifierMock, sendNotifyContextAvailabilityRequest(_, _, _, _, _))
.Times(0);
setNotifier(notifierMock);
/* Forge the request (from "inside" to "outside") */
req.subscriptionId.set("51307b66f481db11bf860001");
/* Set MongoDB connection (prepare database first with the "actual" connection object).
* The "actual" conneciton is preserved for later use */
prepareDatabase();
DBClientBase* connectionDb = getMongoConnection();
setMongoConnectionForUnitTest(connectionMock);
/* Invoke the function in mongoBackend library */
ms = mongoUnsubscribeContextAvailability(&req, &res);
/* Check response is as expected */
EXPECT_EQ(SccOk, ms);
EXPECT_EQ("51307b66f481db11bf860001", res.subscriptionId.get());
EXPECT_EQ(SccReceiverInternalError, res.statusCode.code);
EXPECT_EQ("Internal Server Error", res.statusCode.reasonPhrase);
EXPECT_EQ("Database Error (collection: utest.casubs - "
"remove(): { _id: ObjectId('51307b66f481db11bf860001') } "
"- exception: boom!!)", res.statusCode.details);
// Sleeping a little to "give mongod time to process its input".
// Without this sleep, this tests fails around 50% of the times (in Ubuntu 13.04)
usleep(1000);
ASSERT_EQ(2, connectionDb->count(SUBSCRIBECONTEXTAVAIL_COLL, BSONObj()));
/* Restore real DB connection */
setMongoConnectionForUnitTest(connectionDb);
/* Release mocks */
delete notifierMock;
delete connectionMock;
}
<|endoftext|> |
<commit_before>#include <../tst_qmimedatabase.h>
#include <QDir>
#include <QFile>
#include <QtTest>
#include <qstandardpaths.h>
#include "../tst_qmimedatabase.cpp"
tst_qmimedatabase::tst_qmimedatabase()
{
qputenv("XDG_DATA_HOME", QByteArray("doesnotexist"));
// Copy SRCDIR "../../../src/mimetypes/mime to a temp dir
// then run update-mime-database
// then set XDG_DATA_DIRS to the TEMP dir
QDir here = QDir::currentPath();
here.mkpath("mime/packages");
QFile xml(SRCDIR "../../../src/mimetypes/mime/packages/freedesktop.org.xml");
const QString tempMime = here.absolutePath() + "/mime";
xml.copy(tempMime + "/packages/freedesktop.org.xml");
const QString umd = QStandardPaths::findExecutable("update-mime-database");
if (umd.isEmpty())
QSKIP("shared-mime-info not found, skipping mime.cache test", SkipAll);
QProcess::execute(umd, QStringList() << tempMime);
QVERIFY(QFile::exists(tempMime + "/mime.cache"));
qputenv("XDG_DATA_DIRS", QFile::encodeName(here.absolutePath()));
}
<commit_msg>silence output from update-mime-database<commit_after>#include <../tst_qmimedatabase.h>
#include <QDir>
#include <QFile>
#include <QtTest>
#include <qstandardpaths.h>
#include "../tst_qmimedatabase.cpp"
tst_qmimedatabase::tst_qmimedatabase()
{
qputenv("XDG_DATA_HOME", QByteArray("doesnotexist"));
// Copy SRCDIR "../../../src/mimetypes/mime to a temp dir
// then run update-mime-database
// then set XDG_DATA_DIRS to the TEMP dir
QDir here = QDir::currentPath();
here.mkpath("mime/packages");
QFile xml(SRCDIR "../../../src/mimetypes/mime/packages/freedesktop.org.xml");
const QString tempMime = here.absolutePath() + "/mime";
xml.copy(tempMime + "/packages/freedesktop.org.xml");
const QString umd = QStandardPaths::findExecutable("update-mime-database");
if (umd.isEmpty())
QSKIP("shared-mime-info not found, skipping mime.cache test", SkipAll);
QProcess proc;
proc.setProcessChannelMode(QProcess::MergedChannels); // silence output
proc.start(umd, QStringList() << tempMime);
proc.waitForFinished();
QVERIFY(QFile::exists(tempMime + "/mime.cache"));
qputenv("XDG_DATA_DIRS", QFile::encodeName(here.absolutePath()));
}
<|endoftext|> |
<commit_before>/*!
@file
@copyright Edouard Alligand and Joel Falcou 2015-2017
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
#ifndef BOOST_BRIGAND_FUNCTIONS_COMPARISON_NOT_EQUAL_TO_HPP
#define BOOST_BRIGAND_FUNCTIONS_COMPARISON_NOT_EQUAL_TO_HPP
#include <brigand/types/bool.hpp>
namespace brigand
{
template <typename A, typename B>
struct not_equal_to : bool_ < (A::value != B::value) > {};
}
#endif
<commit_msg>Delete not_equal_to.hpp<commit_after><|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: TestDiagram.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkBoostDividedEdgeBundling.h"
#include "vtkDataSetAttributes.h"
#include "vtkFloatArray.h"
#include "vtkGraphItem.h"
#include "vtkMutableDirectedGraph.h"
#include "vtkNew.h"
#include "vtkPoints.h"
#include "vtkStringArray.h"
#include "vtkXMLTreeReader.h"
#include "vtkViewTheme.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkContext2D.h"
#include "vtkContextInteractorStyle.h"
#include "vtkContextItem.h"
#include "vtkContextActor.h"
#include "vtkContextScene.h"
#include "vtkContextTransform.h"
#include "vtkNew.h"
#include "vtkRegressionTestImage.h"
//----------------------------------------------------------------------------
void BuildSampleGraph(vtkMutableDirectedGraph* graph)
{
vtkNew<vtkPoints> points;
graph->AddVertex();
points->InsertNextPoint(20, 40, 0);
graph->AddVertex();
points->InsertNextPoint(20, 80, 0);
graph->AddVertex();
points->InsertNextPoint(20, 120, 0);
graph->AddVertex();
points->InsertNextPoint(20, 160, 0);
graph->AddVertex();
points->InsertNextPoint(380, 40, 0);
graph->AddVertex();
points->InsertNextPoint(380, 80, 0);
graph->AddVertex();
points->InsertNextPoint(380, 120, 0);
graph->AddVertex();
points->InsertNextPoint(380, 160, 0);
graph->SetPoints(points.GetPointer());
graph->AddEdge(0, 4);
graph->AddEdge(0, 5);
graph->AddEdge(1, 4);
graph->AddEdge(1, 5);
graph->AddEdge(2, 6);
graph->AddEdge(2, 7);
graph->AddEdge(3, 6);
graph->AddEdge(3, 7);
graph->AddEdge(4, 0);
graph->AddEdge(5, 0);
graph->AddEdge(6, 0);
}
//----------------------------------------------------------------------------
void BuildGraphMLGraph(vtkMutableDirectedGraph* graph, std::string file)
{
vtkNew<vtkXMLTreeReader> reader;
reader->SetFileName(file.c_str());
reader->ReadCharDataOn();
reader->Update();
vtkTree *tree = reader->GetOutput();
vtkStringArray *keyArr = vtkStringArray::SafeDownCast(
tree->GetVertexData()->GetAbstractArray("key"));
vtkStringArray *sourceArr = vtkStringArray::SafeDownCast(
tree->GetVertexData()->GetAbstractArray("source"));
vtkStringArray *targetArr = vtkStringArray::SafeDownCast(
tree->GetVertexData()->GetAbstractArray("target"));
vtkStringArray *contentArr = vtkStringArray::SafeDownCast(
tree->GetVertexData()->GetAbstractArray(".chardata"));
double x = 0.0;
double y = 0.0;
vtkIdType source = 0;
vtkIdType target = 0;
vtkNew<vtkPoints> points;
graph->SetPoints(points.GetPointer());
for (vtkIdType i = 0; i < tree->GetNumberOfVertices(); ++i)
{
vtkStdString k = keyArr->GetValue(i);
if (k == "x")
{
x = vtkVariant(contentArr->GetValue(i)).ToDouble();
}
if (k == "y")
{
y = vtkVariant(contentArr->GetValue(i)).ToDouble();
graph->AddVertex();
points->InsertNextPoint(x, y, 0.0);
}
vtkStdString s = sourceArr->GetValue(i);
if (s != "")
{
source = vtkVariant(s).ToInt();
}
vtkStdString t = targetArr->GetValue(i);
if (t != "")
{
target = vtkVariant(t).ToInt();
graph->AddEdge(source, target);
}
}
}
//----------------------------------------------------------------------------
class vtkBundledGraphItem : public vtkGraphItem
{
public:
static vtkBundledGraphItem *New();
vtkTypeMacro(vtkBundledGraphItem, vtkGraphItem);
protected:
vtkBundledGraphItem() { }
~vtkBundledGraphItem() { }
virtual vtkColor4ub EdgeColor(vtkIdType line, vtkIdType point);
virtual float EdgeWidth(vtkIdType line, vtkIdType point);
};
//----------------------------------------------------------------------------
vtkStandardNewMacro(vtkBundledGraphItem);
//----------------------------------------------------------------------------
vtkColor4ub vtkBundledGraphItem::EdgeColor(vtkIdType edgeIdx, vtkIdType pointIdx)
{
float fraction = static_cast<float>(pointIdx) / (this->NumberOfEdgePoints(edgeIdx) - 1);
return vtkColor4ub(fraction*255, 0, 255 - fraction*255, 255);
}
//----------------------------------------------------------------------------
float vtkBundledGraphItem::EdgeWidth(vtkIdType lineIdx, vtkIdType pointIdx)
{
return 4.0f;
}
//----------------------------------------------------------------------------
int TestBoostDividedEdgeBundling(int argc, char* argv[])
{
vtkNew<vtkMutableDirectedGraph> graph;
vtkNew<vtkBoostDividedEdgeBundling> bundle;
BuildSampleGraph(graph.GetPointer());
//BuildGraphMLGraph(graph.GetPointer(), "airlines_flipped.graphml");
bundle->SetInputData(graph.GetPointer());
bundle->Update();
vtkDirectedGraph *output = bundle->GetOutput();
vtkNew<vtkContextActor> actor;
vtkNew<vtkBundledGraphItem> graphItem;
graphItem->SetGraph(output);
vtkNew<vtkContextTransform> trans;
trans->SetInteractive(true);
trans->AddItem(graphItem.GetPointer());
actor->GetScene()->AddItem(trans.GetPointer());
vtkNew<vtkRenderer> renderer;
renderer->SetBackground(1.0, 1.0, 1.0);
vtkNew<vtkRenderWindow> renderWindow;
renderWindow->SetSize(400, 200);
renderWindow->AddRenderer(renderer.GetPointer());
renderer->AddActor(actor.GetPointer());
vtkNew<vtkContextInteractorStyle> interactorStyle;
interactorStyle->SetScene(actor->GetScene());
vtkNew<vtkRenderWindowInteractor> interactor;
interactor->SetInteractorStyle(interactorStyle.GetPointer());
interactor->SetRenderWindow(renderWindow.GetPointer());
renderWindow->SetMultiSamples(0);
renderWindow->Render();
int retVal = vtkRegressionTestImage(renderWindow.GetPointer());
if (retVal == vtkRegressionTester::DO_INTERACTOR)
{
renderWindow->Render();
interactor->Start();
retVal = vtkRegressionTester::PASSED;
}
return !retVal;
}
<commit_msg>TestBoostDividedEdgeBundling: Include vtkObjectFactory.h<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: TestDiagram.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkBoostDividedEdgeBundling.h"
#include "vtkDataSetAttributes.h"
#include "vtkFloatArray.h"
#include "vtkGraphItem.h"
#include "vtkMutableDirectedGraph.h"
#include "vtkNew.h"
#include "vtkObjectFactory.h"
#include "vtkPoints.h"
#include "vtkStringArray.h"
#include "vtkXMLTreeReader.h"
#include "vtkViewTheme.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkContext2D.h"
#include "vtkContextInteractorStyle.h"
#include "vtkContextItem.h"
#include "vtkContextActor.h"
#include "vtkContextScene.h"
#include "vtkContextTransform.h"
#include "vtkNew.h"
#include "vtkRegressionTestImage.h"
//----------------------------------------------------------------------------
void BuildSampleGraph(vtkMutableDirectedGraph* graph)
{
vtkNew<vtkPoints> points;
graph->AddVertex();
points->InsertNextPoint(20, 40, 0);
graph->AddVertex();
points->InsertNextPoint(20, 80, 0);
graph->AddVertex();
points->InsertNextPoint(20, 120, 0);
graph->AddVertex();
points->InsertNextPoint(20, 160, 0);
graph->AddVertex();
points->InsertNextPoint(380, 40, 0);
graph->AddVertex();
points->InsertNextPoint(380, 80, 0);
graph->AddVertex();
points->InsertNextPoint(380, 120, 0);
graph->AddVertex();
points->InsertNextPoint(380, 160, 0);
graph->SetPoints(points.GetPointer());
graph->AddEdge(0, 4);
graph->AddEdge(0, 5);
graph->AddEdge(1, 4);
graph->AddEdge(1, 5);
graph->AddEdge(2, 6);
graph->AddEdge(2, 7);
graph->AddEdge(3, 6);
graph->AddEdge(3, 7);
graph->AddEdge(4, 0);
graph->AddEdge(5, 0);
graph->AddEdge(6, 0);
}
//----------------------------------------------------------------------------
void BuildGraphMLGraph(vtkMutableDirectedGraph* graph, std::string file)
{
vtkNew<vtkXMLTreeReader> reader;
reader->SetFileName(file.c_str());
reader->ReadCharDataOn();
reader->Update();
vtkTree *tree = reader->GetOutput();
vtkStringArray *keyArr = vtkStringArray::SafeDownCast(
tree->GetVertexData()->GetAbstractArray("key"));
vtkStringArray *sourceArr = vtkStringArray::SafeDownCast(
tree->GetVertexData()->GetAbstractArray("source"));
vtkStringArray *targetArr = vtkStringArray::SafeDownCast(
tree->GetVertexData()->GetAbstractArray("target"));
vtkStringArray *contentArr = vtkStringArray::SafeDownCast(
tree->GetVertexData()->GetAbstractArray(".chardata"));
double x = 0.0;
double y = 0.0;
vtkIdType source = 0;
vtkIdType target = 0;
vtkNew<vtkPoints> points;
graph->SetPoints(points.GetPointer());
for (vtkIdType i = 0; i < tree->GetNumberOfVertices(); ++i)
{
vtkStdString k = keyArr->GetValue(i);
if (k == "x")
{
x = vtkVariant(contentArr->GetValue(i)).ToDouble();
}
if (k == "y")
{
y = vtkVariant(contentArr->GetValue(i)).ToDouble();
graph->AddVertex();
points->InsertNextPoint(x, y, 0.0);
}
vtkStdString s = sourceArr->GetValue(i);
if (s != "")
{
source = vtkVariant(s).ToInt();
}
vtkStdString t = targetArr->GetValue(i);
if (t != "")
{
target = vtkVariant(t).ToInt();
graph->AddEdge(source, target);
}
}
}
//----------------------------------------------------------------------------
class vtkBundledGraphItem : public vtkGraphItem
{
public:
static vtkBundledGraphItem *New();
vtkTypeMacro(vtkBundledGraphItem, vtkGraphItem);
protected:
vtkBundledGraphItem() { }
~vtkBundledGraphItem() { }
virtual vtkColor4ub EdgeColor(vtkIdType line, vtkIdType point);
virtual float EdgeWidth(vtkIdType line, vtkIdType point);
};
//----------------------------------------------------------------------------
vtkStandardNewMacro(vtkBundledGraphItem);
//----------------------------------------------------------------------------
vtkColor4ub vtkBundledGraphItem::EdgeColor(vtkIdType edgeIdx, vtkIdType pointIdx)
{
float fraction = static_cast<float>(pointIdx) / (this->NumberOfEdgePoints(edgeIdx) - 1);
return vtkColor4ub(fraction*255, 0, 255 - fraction*255, 255);
}
//----------------------------------------------------------------------------
float vtkBundledGraphItem::EdgeWidth(vtkIdType lineIdx, vtkIdType pointIdx)
{
return 4.0f;
}
//----------------------------------------------------------------------------
int TestBoostDividedEdgeBundling(int argc, char* argv[])
{
vtkNew<vtkMutableDirectedGraph> graph;
vtkNew<vtkBoostDividedEdgeBundling> bundle;
BuildSampleGraph(graph.GetPointer());
//BuildGraphMLGraph(graph.GetPointer(), "airlines_flipped.graphml");
bundle->SetInputData(graph.GetPointer());
bundle->Update();
vtkDirectedGraph *output = bundle->GetOutput();
vtkNew<vtkContextActor> actor;
vtkNew<vtkBundledGraphItem> graphItem;
graphItem->SetGraph(output);
vtkNew<vtkContextTransform> trans;
trans->SetInteractive(true);
trans->AddItem(graphItem.GetPointer());
actor->GetScene()->AddItem(trans.GetPointer());
vtkNew<vtkRenderer> renderer;
renderer->SetBackground(1.0, 1.0, 1.0);
vtkNew<vtkRenderWindow> renderWindow;
renderWindow->SetSize(400, 200);
renderWindow->AddRenderer(renderer.GetPointer());
renderer->AddActor(actor.GetPointer());
vtkNew<vtkContextInteractorStyle> interactorStyle;
interactorStyle->SetScene(actor->GetScene());
vtkNew<vtkRenderWindowInteractor> interactor;
interactor->SetInteractorStyle(interactorStyle.GetPointer());
interactor->SetRenderWindow(renderWindow.GetPointer());
renderWindow->SetMultiSamples(0);
renderWindow->Render();
int retVal = vtkRegressionTestImage(renderWindow.GetPointer());
if (retVal == vtkRegressionTester::DO_INTERACTOR)
{
renderWindow->Render();
interactor->Start();
retVal = vtkRegressionTester::PASSED;
}
return !retVal;
}
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include "fuscale.hxx"
#include <svx/dialogs.hrc>
#include "app.hrc"
#include "View.hxx"
#include "Window.hxx"
#include "OutlineViewShell.hxx"
#include "drawview.hxx"
#include "drawdoc.hxx"
#include "DrawViewShell.hxx"
#include "ViewShell.hxx"
#include "fuzoom.hxx"
#include <vcl/msgbox.hxx>
#include <svx/svdpagv.hxx>
#include <sfx2/viewfrm.hxx>
#include <sfx2/dispatch.hxx>
#include <svx/zoom_def.hxx>
#include <sfx2/zoomitem.hxx>
#include <sfx2/request.hxx>
#include <svx/svxdlg.hxx>
#include <boost/scoped_ptr.hpp>
namespace sd {
TYPEINIT1( FuScale, FuPoor );
FuScale::FuScale (
ViewShell* pViewSh,
::sd::Window* pWin,
::sd::View* pView,
SdDrawDocument* pDoc,
SfxRequest& rReq)
: FuPoor(pViewSh, pWin, pView, pDoc, rReq)
{
}
rtl::Reference<FuPoor> FuScale::Create( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq )
{
rtl::Reference<FuPoor> xFunc( new FuScale( pViewSh, pWin, pView, pDoc, rReq ) );
xFunc->DoExecute(rReq);
return xFunc;
}
void FuScale::DoExecute( SfxRequest& rReq )
{
sal_Int16 nValue;
const SfxItemSet* pArgs = rReq.GetArgs();
if( !pArgs )
{
SfxItemSet aNewAttr( mpDoc->GetPool(), SID_ATTR_ZOOM, SID_ATTR_ZOOM );
boost::scoped_ptr<SvxZoomItem> pZoomItem;
sal_uInt16 nZoomValues = SVX_ZOOM_ENABLE_ALL;
nValue = (sal_Int16) mpWindow->GetZoom();
// zoom on page size?
if( mpViewShell && mpViewShell->ISA( DrawViewShell ) &&
static_cast<DrawViewShell*>(mpViewShell)->IsZoomOnPage() )
{
pZoomItem.reset(new SvxZoomItem( SVX_ZOOM_WHOLEPAGE, nValue ));
}
else
{
pZoomItem.reset(new SvxZoomItem( SVX_ZOOM_PERCENT, nValue ));
}
// limit range
if( mpViewShell )
{
if( mpViewShell->ISA( DrawViewShell ) )
{
SdrPageView* pPageView = mpView->GetSdrPageView();
if( ( pPageView && pPageView->GetObjList()->GetObjCount() == 0 ) )
// || ( mpView->GetMarkedObjectList().GetMarkCount() == 0 ) )
{
nZoomValues &= ~SVX_ZOOM_ENABLE_OPTIMAL;
}
}
else if( mpViewShell->ISA( OutlineViewShell ) )
{
nZoomValues &= ~SVX_ZOOM_ENABLE_OPTIMAL;
nZoomValues &= ~SVX_ZOOM_ENABLE_WHOLEPAGE;
nZoomValues &= ~SVX_ZOOM_ENABLE_PAGEWIDTH;
}
}
pZoomItem->SetValueSet( nZoomValues );
aNewAttr.Put( *pZoomItem );
boost::scoped_ptr<AbstractSvxZoomDialog> pDlg;
SvxAbstractDialogFactory* pFact = SvxAbstractDialogFactory::Create();
if(pFact)
{
pDlg.reset(pFact->CreateSvxZoomDialog(NULL, aNewAttr));
}
if( pDlg )
{
pDlg->SetLimits( (sal_uInt16)mpWindow->GetMinZoom(), (sal_uInt16)mpWindow->GetMaxZoom() );
sal_uInt16 nResult = pDlg->Execute();
switch( nResult )
{
case RET_CANCEL:
{
rReq.Ignore ();
return; // Cancel
}
default:
{
rReq.Ignore ();
/*
rReq.Done( *( pDlg->GetOutputItemSet() ) );
pArgs = rReq.GetArgs();*/
}
break;
}
const SfxItemSet aArgs (*(pDlg->GetOutputItemSet ()));
pDlg.reset();
switch (((const SvxZoomItem &) aArgs.Get (SID_ATTR_ZOOM)).GetType ())
{
case SVX_ZOOM_PERCENT:
{
nValue = ((const SvxZoomItem &) aArgs.Get (SID_ATTR_ZOOM)).GetValue ();
mpViewShell->SetZoom( nValue );
mpViewShell->GetViewFrame()->GetBindings().Invalidate( SidArrayZoom );
}
break;
case SVX_ZOOM_OPTIMAL:
{
if( mpViewShell->ISA( DrawViewShell ) )
{
// name confusion: SID_SIZE_ALL -> zoom onto all objects
// --> the program offers it as optimal
mpViewShell->GetViewFrame()->GetDispatcher()->Execute( SID_SIZE_ALL, SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD);
}
}
break;
case SVX_ZOOM_PAGEWIDTH:
mpViewShell->GetViewFrame()->GetDispatcher()->Execute( SID_SIZE_PAGE_WIDTH, SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD);
break;
case SVX_ZOOM_WHOLEPAGE:
mpViewShell->GetViewFrame()->GetDispatcher()->Execute(SID_SIZE_PAGE, SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD);
break;
default:
break;
}
}
}
else if(mpViewShell && (pArgs->Count () == 1))
{
SFX_REQUEST_ARG (rReq, pScale, SfxUInt32Item, ID_VAL_ZOOM, false);
mpViewShell->SetZoom (pScale->GetValue ());
mpViewShell->GetViewFrame()->GetBindings().Invalidate( SidArrayZoom );
}
}
} // end of namespace sd
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>coverity#704756 Dereference after null check<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include "fuscale.hxx"
#include <svx/dialogs.hrc>
#include "app.hrc"
#include "View.hxx"
#include "Window.hxx"
#include "OutlineViewShell.hxx"
#include "drawview.hxx"
#include "drawdoc.hxx"
#include "DrawViewShell.hxx"
#include "ViewShell.hxx"
#include "fuzoom.hxx"
#include <vcl/msgbox.hxx>
#include <svx/svdpagv.hxx>
#include <sfx2/viewfrm.hxx>
#include <sfx2/dispatch.hxx>
#include <svx/zoom_def.hxx>
#include <sfx2/zoomitem.hxx>
#include <sfx2/request.hxx>
#include <svx/svxdlg.hxx>
#include <boost/scoped_ptr.hpp>
namespace sd {
TYPEINIT1( FuScale, FuPoor );
FuScale::FuScale (
ViewShell* pViewSh,
::sd::Window* pWin,
::sd::View* pView,
SdDrawDocument* pDoc,
SfxRequest& rReq)
: FuPoor(pViewSh, pWin, pView, pDoc, rReq)
{
}
rtl::Reference<FuPoor> FuScale::Create( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq )
{
rtl::Reference<FuPoor> xFunc( new FuScale( pViewSh, pWin, pView, pDoc, rReq ) );
xFunc->DoExecute(rReq);
return xFunc;
}
void FuScale::DoExecute( SfxRequest& rReq )
{
sal_Int16 nValue;
const SfxItemSet* pArgs = rReq.GetArgs();
if( !pArgs )
{
SfxItemSet aNewAttr( mpDoc->GetPool(), SID_ATTR_ZOOM, SID_ATTR_ZOOM );
boost::scoped_ptr<SvxZoomItem> pZoomItem;
sal_uInt16 nZoomValues = SVX_ZOOM_ENABLE_ALL;
nValue = (sal_Int16) mpWindow->GetZoom();
// zoom on page size?
if( mpViewShell && mpViewShell->ISA( DrawViewShell ) &&
static_cast<DrawViewShell*>(mpViewShell)->IsZoomOnPage() )
{
pZoomItem.reset(new SvxZoomItem( SVX_ZOOM_WHOLEPAGE, nValue ));
}
else
{
pZoomItem.reset(new SvxZoomItem( SVX_ZOOM_PERCENT, nValue ));
}
// limit range
if( mpViewShell )
{
if( mpViewShell->ISA( DrawViewShell ) )
{
SdrPageView* pPageView = mpView->GetSdrPageView();
if( ( pPageView && pPageView->GetObjList()->GetObjCount() == 0 ) )
// || ( mpView->GetMarkedObjectList().GetMarkCount() == 0 ) )
{
nZoomValues &= ~SVX_ZOOM_ENABLE_OPTIMAL;
}
}
else if( mpViewShell->ISA( OutlineViewShell ) )
{
nZoomValues &= ~SVX_ZOOM_ENABLE_OPTIMAL;
nZoomValues &= ~SVX_ZOOM_ENABLE_WHOLEPAGE;
nZoomValues &= ~SVX_ZOOM_ENABLE_PAGEWIDTH;
}
}
pZoomItem->SetValueSet( nZoomValues );
aNewAttr.Put( *pZoomItem );
boost::scoped_ptr<AbstractSvxZoomDialog> pDlg;
SvxAbstractDialogFactory* pFact = SvxAbstractDialogFactory::Create();
if(pFact)
{
pDlg.reset(pFact->CreateSvxZoomDialog(NULL, aNewAttr));
}
if( pDlg )
{
pDlg->SetLimits( (sal_uInt16)mpWindow->GetMinZoom(), (sal_uInt16)mpWindow->GetMaxZoom() );
sal_uInt16 nResult = pDlg->Execute();
switch( nResult )
{
case RET_CANCEL:
{
rReq.Ignore ();
return; // Cancel
}
default:
{
rReq.Ignore ();
}
break;
}
const SfxItemSet aArgs (*(pDlg->GetOutputItemSet ()));
pDlg.reset();
if (!mpViewShell)
return;
switch (((const SvxZoomItem &) aArgs.Get (SID_ATTR_ZOOM)).GetType ())
{
case SVX_ZOOM_PERCENT:
{
nValue = ((const SvxZoomItem &) aArgs.Get (SID_ATTR_ZOOM)).GetValue ();
mpViewShell->SetZoom( nValue );
mpViewShell->GetViewFrame()->GetBindings().Invalidate( SidArrayZoom );
}
break;
case SVX_ZOOM_OPTIMAL:
{
if( mpViewShell->ISA( DrawViewShell ) )
{
// name confusion: SID_SIZE_ALL -> zoom onto all objects
// --> the program offers it as optimal
mpViewShell->GetViewFrame()->GetDispatcher()->Execute( SID_SIZE_ALL, SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD);
}
}
break;
case SVX_ZOOM_PAGEWIDTH:
mpViewShell->GetViewFrame()->GetDispatcher()->Execute( SID_SIZE_PAGE_WIDTH, SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD);
break;
case SVX_ZOOM_WHOLEPAGE:
mpViewShell->GetViewFrame()->GetDispatcher()->Execute(SID_SIZE_PAGE, SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD);
break;
default:
break;
}
}
}
else if(mpViewShell && (pArgs->Count () == 1))
{
SFX_REQUEST_ARG (rReq, pScale, SfxUInt32Item, ID_VAL_ZOOM, false);
mpViewShell->SetZoom (pScale->GetValue ());
mpViewShell->GetViewFrame()->GetBindings().Invalidate( SidArrayZoom );
}
}
} // end of namespace sd
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>/// @file
/// @copyright The code is licensed under the BSD License
/// <http://opensource.org/licenses/BSD-2-Clause>,
/// Copyright (c) 2012-2015 Alexandre Hamez.
/// @author Alexandre Hamez
#pragma once
#include <functional> // reference_wrapper
#include <limits>
#include <numeric> // accumulate
#include <vector>
#include "sdd/order/order_builder.hh"
#include "sdd/order/strategies/force_hyperedge.hh"
#include "sdd/order/strategies/force_hypergraph.hh"
#include "sdd/order/strategies/force_vertex.hh"
namespace sdd { namespace force {
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @brief An implementation of the FORCE ordering strategy
/// @see http://dx.doi.org/10.1145/764808.764839
template <typename C>
class worker
{
private:
using id_type = typename C::Identifier;
using vertex_type = vertex<id_type>;
using hyperedge_type = hyperedge<id_type>;
/// @brief
std::deque<vertex_type>& vertices_;
/// @brief The hyperedges that link together vertices.
std::deque<hyperedge_type>& hyperedges_;
/// @brief Keep all computed total spans for statistics.
std::deque<double> spans_;
/// @brief Reverse order.
bool reverse_;
public:
/// @brief Constructor.
worker(hypergraph<C>& graph, bool reverse = false)
: vertices_(graph.vertices()), hyperedges_(graph.hyperedges()), spans_(), reverse_(reverse)
{}
/// @brief Effectively apply the FORCE ordering strategy.
order_builder<C>
operator()(unsigned int iterations = 200)
{
std::vector<std::reference_wrapper<vertex_type>>
sorted_vertices(vertices_.begin(), vertices_.end());
// Keep a copy of the order with the smallest span.
std::vector<std::reference_wrapper<vertex_type>> best_order(sorted_vertices);
double smallest_span = std::numeric_limits<double>::max();
while (iterations-- != 0)
{
// Compute the new center of gravity for every hyperedge.
for (auto& edge : hyperedges_)
{
edge.compute_center_of_gravity();
}
// Compute the tentative new location of every vertex.
for (auto& vertex : vertices_)
{
if (vertex.hyperedges().empty())
{
continue;
}
vertex.location() = std::accumulate( vertex.hyperedges().cbegin()
, vertex.hyperedges().cend()
, 0
, [](double acc, const hyperedge_type* e)
{return acc + e->center_of_gravity() * e->weight();}
) / vertex.hyperedges().size();
}
// Sort tentative vertex locations.
std::sort( sorted_vertices.begin(), sorted_vertices.end()
, [](vertex_type& lhs, vertex_type& rhs){return lhs.location() < rhs.location();});
// Assign integer indices to the vertices.
unsigned int pos = 0;
std::for_each( sorted_vertices.begin(), sorted_vertices.end()
, [&pos](vertex_type& v){v.location() = pos++;});
const double span = get_total_span();
spans_.push_back(span);
if (span < smallest_span)
{
// We keep the order that minimizes the span.
best_order = sorted_vertices;
}
}
order_builder<C> ob;
if (reverse_)
{
for (auto rcit = best_order.rbegin(); rcit != best_order.rend(); ++rcit)
{
ob.push(rcit->get().id());
}
}
else
{
for (const auto& vertex : best_order)
{
ob.push(vertex.get().id());
}
}
return ob;
}
const std::deque<double>&
spans()
const noexcept
{
return spans_;
}
private:
/// @brief Add the span of all hyperedges.
double
get_total_span()
const noexcept
{
return std::accumulate( hyperedges_.cbegin(), hyperedges_.cend(), 0
, [](double acc, const hyperedge_type& h){return acc + h.span();});
}
};
} // namespace force
/*------------------------------------------------------------------------------------------------*/
} // namespace sdd
<commit_msg>Remove default parameter value for FORCE iterations<commit_after>/// @file
/// @copyright The code is licensed under the BSD License
/// <http://opensource.org/licenses/BSD-2-Clause>,
/// Copyright (c) 2012-2015 Alexandre Hamez.
/// @author Alexandre Hamez
#pragma once
#include <functional> // reference_wrapper
#include <limits>
#include <numeric> // accumulate
#include <vector>
#include "sdd/order/order_builder.hh"
#include "sdd/order/strategies/force_hyperedge.hh"
#include "sdd/order/strategies/force_hypergraph.hh"
#include "sdd/order/strategies/force_vertex.hh"
namespace sdd { namespace force {
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @brief An implementation of the FORCE ordering strategy
/// @see http://dx.doi.org/10.1145/764808.764839
template <typename C>
class worker
{
private:
using id_type = typename C::Identifier;
using vertex_type = vertex<id_type>;
using hyperedge_type = hyperedge<id_type>;
/// @brief
std::deque<vertex_type>& vertices_;
/// @brief The hyperedges that link together vertices.
std::deque<hyperedge_type>& hyperedges_;
/// @brief Keep all computed total spans for statistics.
std::deque<double> spans_;
/// @brief Reverse order.
bool reverse_;
public:
/// @brief Constructor.
worker(hypergraph<C>& graph, bool reverse = false)
: vertices_(graph.vertices()), hyperedges_(graph.hyperedges()), spans_(), reverse_(reverse)
{}
/// @brief Effectively apply the FORCE ordering strategy.
order_builder<C>
operator()(unsigned int iterations)
{
std::vector<std::reference_wrapper<vertex_type>>
sorted_vertices(vertices_.begin(), vertices_.end());
// Keep a copy of the order with the smallest span.
std::vector<std::reference_wrapper<vertex_type>> best_order(sorted_vertices);
double smallest_span = std::numeric_limits<double>::max();
while (iterations-- != 0)
{
// Compute the new center of gravity for every hyperedge.
for (auto& edge : hyperedges_)
{
edge.compute_center_of_gravity();
}
// Compute the tentative new location of every vertex.
for (auto& vertex : vertices_)
{
if (vertex.hyperedges().empty())
{
continue;
}
vertex.location() = std::accumulate( vertex.hyperedges().cbegin()
, vertex.hyperedges().cend()
, 0
, [](double acc, const hyperedge_type* e)
{return acc + e->center_of_gravity() * e->weight();}
) / vertex.hyperedges().size();
}
// Sort tentative vertex locations.
std::sort( sorted_vertices.begin(), sorted_vertices.end()
, [](vertex_type& lhs, vertex_type& rhs){return lhs.location() < rhs.location();});
// Assign integer indices to the vertices.
unsigned int pos = 0;
std::for_each( sorted_vertices.begin(), sorted_vertices.end()
, [&pos](vertex_type& v){v.location() = pos++;});
const double span = get_total_span();
spans_.push_back(span);
if (span < smallest_span)
{
// We keep the order that minimizes the span.
best_order = sorted_vertices;
}
}
order_builder<C> ob;
if (reverse_)
{
for (auto rcit = best_order.rbegin(); rcit != best_order.rend(); ++rcit)
{
ob.push(rcit->get().id());
}
}
else
{
for (const auto& vertex : best_order)
{
ob.push(vertex.get().id());
}
}
return ob;
}
const std::deque<double>&
spans()
const noexcept
{
return spans_;
}
private:
/// @brief Add the span of all hyperedges.
double
get_total_span()
const noexcept
{
return std::accumulate( hyperedges_.cbegin(), hyperedges_.cend(), 0
, [](double acc, const hyperedge_type& h){return acc + h.span();});
}
};
} // namespace force
/*------------------------------------------------------------------------------------------------*/
} // namespace sdd
<|endoftext|> |
<commit_before>/*
* Copyright 2015 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 "webrtc/base/criticalsection.h"
#include "webrtc/base/checks.h"
namespace rtc {
CriticalSection::CriticalSection() {
#if defined(WEBRTC_WIN)
InitializeCriticalSection(&crit_);
#else
pthread_mutexattr_t mutex_attribute;
pthread_mutexattr_init(&mutex_attribute);
pthread_mutexattr_settype(&mutex_attribute, PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(&mutex_, &mutex_attribute);
pthread_mutexattr_destroy(&mutex_attribute);
CS_DEBUG_CODE(thread_ = 0);
CS_DEBUG_CODE(recursion_count_ = 0);
#endif
}
CriticalSection::~CriticalSection() {
#if defined(WEBRTC_WIN)
DeleteCriticalSection(&crit_);
#else
pthread_mutex_destroy(&mutex_);
#endif
}
void CriticalSection::Enter() EXCLUSIVE_LOCK_FUNCTION() {
#if defined(WEBRTC_WIN)
EnterCriticalSection(&crit_);
#else
pthread_mutex_lock(&mutex_);
#if CS_DEBUG_CHECKS
if (!recursion_count_) {
RTC_DCHECK(!thread_);
thread_ = pthread_self();
} else {
RTC_DCHECK(CurrentThreadIsOwner());
}
++recursion_count_;
#endif
#endif
}
bool CriticalSection::TryEnter() EXCLUSIVE_TRYLOCK_FUNCTION(true) {
#if defined(WEBRTC_WIN)
return TryEnterCriticalSection(&crit_) != FALSE;
#else
if (pthread_mutex_trylock(&mutex_) != 0)
return false;
#if CS_DEBUG_CHECKS
if (!recursion_count_) {
RTC_DCHECK(!thread_);
thread_ = pthread_self();
} else {
RTC_DCHECK(CurrentThreadIsOwner());
}
++recursion_count_;
#endif
return true;
#endif
}
void CriticalSection::Leave() UNLOCK_FUNCTION() {
RTC_DCHECK(CurrentThreadIsOwner());
#if defined(WEBRTC_WIN)
LeaveCriticalSection(&crit_);
#else
#if CS_DEBUG_CHECKS
--recursion_count_;
RTC_DCHECK(recursion_count_ >= 0);
if (!recursion_count_)
thread_ = 0;
#endif
pthread_mutex_unlock(&mutex_);
#endif
}
bool CriticalSection::CurrentThreadIsOwner() const {
#if defined(WEBRTC_WIN)
return crit_.OwningThread == reinterpret_cast<HANDLE>(GetCurrentThreadId());
#else
#if CS_DEBUG_CHECKS
return pthread_equal(thread_, pthread_self());
#else
return true;
#endif // CS_DEBUG_CHECKS
#endif
}
bool CriticalSection::IsLocked() const {
#if defined(WEBRTC_WIN)
return crit_.LockCount != -1;
#else
#if CS_DEBUG_CHECKS
return thread_ != 0;
#else
return true;
#endif
#endif
}
CritScope::CritScope(CriticalSection* cs) : cs_(cs) { cs_->Enter(); }
CritScope::~CritScope() { cs_->Leave(); }
TryCritScope::TryCritScope(CriticalSection* cs)
: cs_(cs), locked_(cs->TryEnter()) {
CS_DEBUG_CODE(lock_was_called_ = false);
}
TryCritScope::~TryCritScope() {
CS_DEBUG_CODE(RTC_DCHECK(lock_was_called_));
if (locked_)
cs_->Leave();
}
bool TryCritScope::locked() const {
CS_DEBUG_CODE(lock_was_called_ = true);
return locked_;
}
void GlobalLockPod::Lock() {
#if !defined(WEBRTC_WIN)
const struct timespec ts_null = {0};
#endif
while (AtomicOps::CompareAndSwap(&lock_acquired, 0, 1)) {
#if defined(WEBRTC_WIN)
::Sleep(0);
#else
nanosleep(&ts_null, nullptr);
#endif
}
}
void GlobalLockPod::Unlock() {
int old_value = AtomicOps::CompareAndSwap(&lock_acquired, 1, 0);
RTC_DCHECK_EQ(1, old_value) << "Unlock called without calling Lock first";
}
GlobalLock::GlobalLock() {
lock_acquired = 0;
}
GlobalLockScope::GlobalLockScope(GlobalLockPod* lock)
: lock_(lock) {
lock_->Lock();
}
GlobalLockScope::~GlobalLockScope() {
lock_->Unlock();
}
} // namespace rtc
<commit_msg>Fix VS 2015 warning by adding an additional cast<commit_after>/*
* Copyright 2015 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 "webrtc/base/criticalsection.h"
#include "webrtc/base/checks.h"
namespace rtc {
CriticalSection::CriticalSection() {
#if defined(WEBRTC_WIN)
InitializeCriticalSection(&crit_);
#else
pthread_mutexattr_t mutex_attribute;
pthread_mutexattr_init(&mutex_attribute);
pthread_mutexattr_settype(&mutex_attribute, PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(&mutex_, &mutex_attribute);
pthread_mutexattr_destroy(&mutex_attribute);
CS_DEBUG_CODE(thread_ = 0);
CS_DEBUG_CODE(recursion_count_ = 0);
#endif
}
CriticalSection::~CriticalSection() {
#if defined(WEBRTC_WIN)
DeleteCriticalSection(&crit_);
#else
pthread_mutex_destroy(&mutex_);
#endif
}
void CriticalSection::Enter() EXCLUSIVE_LOCK_FUNCTION() {
#if defined(WEBRTC_WIN)
EnterCriticalSection(&crit_);
#else
pthread_mutex_lock(&mutex_);
#if CS_DEBUG_CHECKS
if (!recursion_count_) {
RTC_DCHECK(!thread_);
thread_ = pthread_self();
} else {
RTC_DCHECK(CurrentThreadIsOwner());
}
++recursion_count_;
#endif
#endif
}
bool CriticalSection::TryEnter() EXCLUSIVE_TRYLOCK_FUNCTION(true) {
#if defined(WEBRTC_WIN)
return TryEnterCriticalSection(&crit_) != FALSE;
#else
if (pthread_mutex_trylock(&mutex_) != 0)
return false;
#if CS_DEBUG_CHECKS
if (!recursion_count_) {
RTC_DCHECK(!thread_);
thread_ = pthread_self();
} else {
RTC_DCHECK(CurrentThreadIsOwner());
}
++recursion_count_;
#endif
return true;
#endif
}
void CriticalSection::Leave() UNLOCK_FUNCTION() {
RTC_DCHECK(CurrentThreadIsOwner());
#if defined(WEBRTC_WIN)
LeaveCriticalSection(&crit_);
#else
#if CS_DEBUG_CHECKS
--recursion_count_;
RTC_DCHECK(recursion_count_ >= 0);
if (!recursion_count_)
thread_ = 0;
#endif
pthread_mutex_unlock(&mutex_);
#endif
}
bool CriticalSection::CurrentThreadIsOwner() const {
#if defined(WEBRTC_WIN)
// OwningThread has type HANDLE but actually contains the Thread ID:
// http://stackoverflow.com/questions/12675301/why-is-the-owningthread-member-of-critical-section-of-type-handle-when-it-is-de
// Converting through size_t avoids the VS 2015 warning C4312: conversion from
// 'type1' to 'type2' of greater size
return crit_.OwningThread ==
reinterpret_cast<HANDLE>(static_cast<size_t>(GetCurrentThreadId()));
#else
#if CS_DEBUG_CHECKS
return pthread_equal(thread_, pthread_self());
#else
return true;
#endif // CS_DEBUG_CHECKS
#endif
}
bool CriticalSection::IsLocked() const {
#if defined(WEBRTC_WIN)
return crit_.LockCount != -1;
#else
#if CS_DEBUG_CHECKS
return thread_ != 0;
#else
return true;
#endif
#endif
}
CritScope::CritScope(CriticalSection* cs) : cs_(cs) { cs_->Enter(); }
CritScope::~CritScope() { cs_->Leave(); }
TryCritScope::TryCritScope(CriticalSection* cs)
: cs_(cs), locked_(cs->TryEnter()) {
CS_DEBUG_CODE(lock_was_called_ = false);
}
TryCritScope::~TryCritScope() {
CS_DEBUG_CODE(RTC_DCHECK(lock_was_called_));
if (locked_)
cs_->Leave();
}
bool TryCritScope::locked() const {
CS_DEBUG_CODE(lock_was_called_ = true);
return locked_;
}
void GlobalLockPod::Lock() {
#if !defined(WEBRTC_WIN)
const struct timespec ts_null = {0};
#endif
while (AtomicOps::CompareAndSwap(&lock_acquired, 0, 1)) {
#if defined(WEBRTC_WIN)
::Sleep(0);
#else
nanosleep(&ts_null, nullptr);
#endif
}
}
void GlobalLockPod::Unlock() {
int old_value = AtomicOps::CompareAndSwap(&lock_acquired, 1, 0);
RTC_DCHECK_EQ(1, old_value) << "Unlock called without calling Lock first";
}
GlobalLock::GlobalLock() {
lock_acquired = 0;
}
GlobalLockScope::GlobalLockScope(GlobalLockPod* lock)
: lock_(lock) {
lock_->Lock();
}
GlobalLockScope::~GlobalLockScope() {
lock_->Unlock();
}
} // namespace rtc
<|endoftext|> |
<commit_before>#pragma once
#include <memory>
#include <type_traits>
namespace cu
{
template <typename T>
std::unique_ptr<std::decay_t<T>> to_unique_ptr( T && x )
{
return std::make_unique<std::decay_t<T>>( std::forward<T>(x) );
}
template <typename T>
std::shared_ptr<std::decay_t<T>> to_shared_ptr( T && x )
{
return std::make_shared<std::decay_t<T>>( std::forward<T>(x) );
}
} // namespace cu
<commit_msg>When cu::to_shared_ptr is passed an std::unique_ptr, then no wrapping takes place, but a rebind.<commit_after>#pragma once
#include "om_cpp_utils/rank.hpp"
#include <memory>
#include <type_traits>
namespace cu
{
template <typename T>
std::unique_ptr<std::decay_t<T>> to_unique_ptr( T && x )
{
return std::make_unique<std::decay_t<T>>( std::forward<T>(x) );
}
namespace detail
{
template <typename T>
struct is_unique_ptr : std::false_type {};
template <typename ...Ts>
struct is_unique_ptr<std::unique_ptr<Ts...> > : std::true_type {};
template <typename T>
auto to_shared_ptr_impl( T && x, Rank<1> )
-> typename
std::enable_if<
is_unique_ptr<typename std::decay<T>::type>::value,
std::shared_ptr<
typename std::decay<decltype(x)>::type
>
>::type
{
return { std::forward<T>(x) };
}
template <typename T>
std::shared_ptr<std::decay_t<T>> to_shared_ptr_impl( T && x, Rank<0> )
{
return std::make_shared<std::decay_t<T>>( std::forward<T>(x) );
}
} // namespace detail
template <typename T>
std::shared_ptr<std::decay_t<T>> to_shared_ptr( T && x )
{
return detail::to_shared_ptr_impl( std::forward<T>(x), Rank<1>() );
}
} // namespace cu
<|endoftext|> |
<commit_before>// @(#)root/cont:$Name: $:$Id: TProcessID.cxx,v 1.8 2001/12/02 15:11:32 brun Exp $
// Author: Rene Brun 28/09/2001
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
//
// TProcessID
//
// A TProcessID identifies a ROOT job in a unique way in time and space.
// The TProcessID title is made of :
// - The process pid
// - The system hostname
// - The system time in clock units
//
// A TProcessID is automatically created by the TROOT constructor.
// When a TFile contains referenced objects (see TRef), the TProcessID
// object is written to the file.
// If a file has been written in multiple sessions (same machine or not),
// a TProcessID is written for each session.
// These objects are used by the class TRef to uniquely identified
// any TObject pointed by a TRef.
//
// When a referenced object is read from a file (its bit kIsReferenced is set),
// this object is entered into the objects table of the corresponding TProcessID.
// Each TFile has a list of TProcessIDs (see TFile::fProcessIDs) also
// accessible via TProcessID::fgPIDs (for all files).
// When this object is deleted, it is removed from the table via the cleanup
// mechanism invoked by the TObject destructor.
//
// Each TProcessID has a table (TObjArray *fObjects) that keeps track
// of all referenced objects. If a referenced object has a fUniqueID set,
// a pointer to this unique object may be found via fObjects->At(fUniqueID).
// In the same way, when a TRef::GetObject is called, GetObject uses
// its own fUniqueID to find the pointer to the referenced object.
// See TProcessID::GetObjectWithID and PutObjectWithID.
//
// When a referenced object is deleted, its slot in fObjects is set to null.
//
//////////////////////////////////////////////////////////////////////////
#include "TProcessID.h"
#include "TROOT.h"
#include "TFile.h"
#include "TUUID.h"
TObjArray *TProcessID::fgPIDs = 0; //pointer to the list of TProcessID
TProcessID *TProcessID::fgPID = 0; //pointer to the TProcessID of the current session
UInt_t TProcessID::fgNumber = 0; //Current referenced object instance count
ClassImp(TProcessID)
//______________________________________________________________________________
TProcessID::TProcessID()
{
fCount = 0;
fObjects = 0;
}
//______________________________________________________________________________
TProcessID::~TProcessID()
{
delete fObjects;
fObjects = 0;
fgPIDs->Remove(this);
}
//______________________________________________________________________________
TProcessID::TProcessID(const TProcessID &ref)
{
// TProcessID copy ctor.
}
//______________________________________________________________________________
TProcessID *TProcessID::AddProcessID()
{
// static function to add a new TProcessID to the list of PIDs
TProcessID *pid = new TProcessID();
if (!fgPIDs) {
fgPID = pid;
fgPIDs = new TObjArray(10);
gROOT->GetListOfCleanups()->Add(fgPIDs);
}
UShort_t apid = fgPIDs->GetEntriesFast();
pid->IncrementCount();
fgPIDs->Add(pid);
char name[20];
sprintf(name,"ProcessID%d",apid);
pid->SetName(name);
TUUID u;
apid = fgPIDs->GetEntriesFast();
pid->SetTitle(u.AsString());
return pid;
}
//______________________________________________________________________________
UInt_t TProcessID::AssignID(TObject *obj)
{
// static function returning the ID assigned to obj
// If the object is not yet referenced, its kIsReferenced bit is set
// and its fUniqueID set to the current number of referenced objects so far.
UInt_t uid = obj->GetUniqueID();
if (obj == fgPID->GetObjectWithID(uid)) return uid;
fgNumber++;
obj->SetBit(kIsReferenced);
uid = fgNumber;
obj->SetUniqueID(uid);
fgPID->PutObjectWithID(obj,uid);
return uid;
}
//______________________________________________________________________________
void TProcessID::Cleanup()
{
// static function (called by TROOT destructor) to delete all TProcessIDs
fgPIDs->Delete();
delete fgPIDs;
}
//______________________________________________________________________________
Int_t TProcessID::DecrementCount()
{
// the reference fCount is used to delete the TProcessID
// in the TFile destructor when fCount = 0
fCount--;
if (fCount < 0) fCount = 0;
return fCount;
}
//______________________________________________________________________________
TProcessID *TProcessID::GetProcessID(UShort_t pid)
{
// static function returning a pointer to TProcessID number pid in fgPIDs
return (TProcessID*)fgPIDs->At(pid);
}
//______________________________________________________________________________
Int_t TProcessID::IncrementCount()
{
if (!fObjects) fObjects = new TObjArray(100);
fCount++;
return fCount;
}
//______________________________________________________________________________
UInt_t TProcessID::GetObjectCount()
{
// Return the current referenced object count
// fgNumber is incremented everytime a new object is referenced
return fgNumber;
}
//______________________________________________________________________________
TObject *TProcessID::GetObjectWithID(UInt_t uid)
{
//returns the TObject with unique identifier uid in the table of objects
//if (!fObjects) fObjects = new TObjArray(100);
if ((Int_t)uid > fObjects->GetSize()) return 0;
return fObjects->UncheckedAt(uid);
}
//______________________________________________________________________________
void TProcessID::PutObjectWithID(TObject *obj, UInt_t uid)
{
//stores the object at the uid th slot in the table of objects
//The object uniqueid is set as well as its kMustCleanup bit
//if (!fObjects) fObjects = new TObjArray(100);
if (uid == 0) uid = obj->GetUniqueID();
fObjects->AddAtAndExpand(obj,uid);
obj->SetBit(kMustCleanup);
}
//______________________________________________________________________________
TProcessID *TProcessID::ReadProcessID(UShort_t pidf, TFile *file)
{
// static function
//The TProcessID with number pidf is read from file.
//If the object is not already entered in the gROOT list, it is added.
if (!file) return 0;
TObjArray *pids = file->GetListOfProcessIDs();
TProcessID *pid = 0;
if (pidf < pids->GetSize()) pid = (TProcessID *)pids->UncheckedAt(pidf);
if (pid) return pid;
//check if fProcessIDs[uid] is set in file
//if not set, read the process uid from file
char pidname[32];
sprintf(pidname,"ProcessID%d",pidf);
pid = (TProcessID *)file->Get(pidname);
if (!pid) {
//file->Error("ReadProcessID","Cannot find %s in file %s",pidname,file->GetName());
return 0;
}
pids->AddAtAndExpand(pid,pidf);
pid->IncrementCount();
//check that a similar pid is not already registered in fgPIDs
TIter next(fgPIDs);
TProcessID *p;
while ((p = (TProcessID*)next())) {
if (!strcmp(p->GetTitle(),pid->GetTitle())) return p;
}
Int_t apid = fgPIDs->GetEntriesFast();
fgPIDs->Add(pid);
pid->SetUniqueID(apid);
return pid;
}
//______________________________________________________________________________
void TProcessID::RecursiveRemove(TObject *obj)
{
// called by the object destructor
// remove reference to obj from the current table if it is referenced
if (!obj->TestBit(kIsReferenced)) return;
UInt_t uid = obj->GetUniqueID();
if (obj == GetObjectWithID(uid)) fObjects->RemoveAt(uid);
}
//______________________________________________________________________________
void TProcessID::SetObjectCount(UInt_t number)
{
// static function to set the current referenced object count
// fgNumber is incremented everytime a new object is referenced
fgNumber = number;
}
//______________________________________________________________________________
UShort_t TProcessID::WriteProcessID(TProcessID *pid, TFile *file)
{
// static function
// Check if the ProcessID pid is already in the file.
// if not, add it and return the index number in the local file list
if (!file) return 0;
TObjArray *pids = file->GetListOfProcessIDs();
Int_t pidf = 0;
if (pid) pidf = pids->IndexOf(pid);
if (pidf < 0) {
file->SetBit(TFile::kHasReferences);
pidf = (UShort_t)pids->GetEntriesFast();
pids->Add(pid);
char name[32];
sprintf(name,"ProcessID%d",pidf);
pid->Write(name);
}
return (UShort_t)pidf;
}
<commit_msg>correct description of what TProcessID's title is made of (a TUUID).<commit_after>// @(#)root/cont:$Name: $:$Id: TProcessID.cxx,v 1.9 2001/12/03 10:29:13 brun Exp $
// Author: Rene Brun 28/09/2001
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
//
// TProcessID
//
// A TProcessID identifies a ROOT job in a unique way in time and space.
// The TProcessID title consists of a TUUID object which provides a globally
// unique identifier (for more see TUUID.h).
//
// A TProcessID is automatically created by the TROOT constructor.
// When a TFile contains referenced objects (see TRef), the TProcessID
// object is written to the file.
// If a file has been written in multiple sessions (same machine or not),
// a TProcessID is written for each session.
// These objects are used by the class TRef to uniquely identified
// any TObject pointed by a TRef.
//
// When a referenced object is read from a file (its bit kIsReferenced is set),
// this object is entered into the objects table of the corresponding TProcessID.
// Each TFile has a list of TProcessIDs (see TFile::fProcessIDs) also
// accessible via TProcessID::fgPIDs (for all files).
// When this object is deleted, it is removed from the table via the cleanup
// mechanism invoked by the TObject destructor.
//
// Each TProcessID has a table (TObjArray *fObjects) that keeps track
// of all referenced objects. If a referenced object has a fUniqueID set,
// a pointer to this unique object may be found via fObjects->At(fUniqueID).
// In the same way, when a TRef::GetObject is called, GetObject uses
// its own fUniqueID to find the pointer to the referenced object.
// See TProcessID::GetObjectWithID and PutObjectWithID.
//
// When a referenced object is deleted, its slot in fObjects is set to null.
//
//////////////////////////////////////////////////////////////////////////
#include "TProcessID.h"
#include "TROOT.h"
#include "TFile.h"
#include "TUUID.h"
TObjArray *TProcessID::fgPIDs = 0; //pointer to the list of TProcessID
TProcessID *TProcessID::fgPID = 0; //pointer to the TProcessID of the current session
UInt_t TProcessID::fgNumber = 0; //Current referenced object instance count
ClassImp(TProcessID)
//______________________________________________________________________________
TProcessID::TProcessID()
{
fCount = 0;
fObjects = 0;
}
//______________________________________________________________________________
TProcessID::~TProcessID()
{
delete fObjects;
fObjects = 0;
fgPIDs->Remove(this);
}
//______________________________________________________________________________
TProcessID::TProcessID(const TProcessID &ref)
{
// TProcessID copy ctor.
}
//______________________________________________________________________________
TProcessID *TProcessID::AddProcessID()
{
// static function to add a new TProcessID to the list of PIDs
TProcessID *pid = new TProcessID();
if (!fgPIDs) {
fgPID = pid;
fgPIDs = new TObjArray(10);
gROOT->GetListOfCleanups()->Add(fgPIDs);
}
UShort_t apid = fgPIDs->GetEntriesFast();
pid->IncrementCount();
fgPIDs->Add(pid);
char name[20];
sprintf(name,"ProcessID%d",apid);
pid->SetName(name);
TUUID u;
apid = fgPIDs->GetEntriesFast();
pid->SetTitle(u.AsString());
return pid;
}
//______________________________________________________________________________
UInt_t TProcessID::AssignID(TObject *obj)
{
// static function returning the ID assigned to obj
// If the object is not yet referenced, its kIsReferenced bit is set
// and its fUniqueID set to the current number of referenced objects so far.
UInt_t uid = obj->GetUniqueID();
if (obj == fgPID->GetObjectWithID(uid)) return uid;
fgNumber++;
obj->SetBit(kIsReferenced);
uid = fgNumber;
obj->SetUniqueID(uid);
fgPID->PutObjectWithID(obj,uid);
return uid;
}
//______________________________________________________________________________
void TProcessID::Cleanup()
{
// static function (called by TROOT destructor) to delete all TProcessIDs
fgPIDs->Delete();
delete fgPIDs;
}
//______________________________________________________________________________
Int_t TProcessID::DecrementCount()
{
// the reference fCount is used to delete the TProcessID
// in the TFile destructor when fCount = 0
fCount--;
if (fCount < 0) fCount = 0;
return fCount;
}
//______________________________________________________________________________
TProcessID *TProcessID::GetProcessID(UShort_t pid)
{
// static function returning a pointer to TProcessID number pid in fgPIDs
return (TProcessID*)fgPIDs->At(pid);
}
//______________________________________________________________________________
Int_t TProcessID::IncrementCount()
{
if (!fObjects) fObjects = new TObjArray(100);
fCount++;
return fCount;
}
//______________________________________________________________________________
UInt_t TProcessID::GetObjectCount()
{
// Return the current referenced object count
// fgNumber is incremented everytime a new object is referenced
return fgNumber;
}
//______________________________________________________________________________
TObject *TProcessID::GetObjectWithID(UInt_t uid)
{
//returns the TObject with unique identifier uid in the table of objects
//if (!fObjects) fObjects = new TObjArray(100);
if ((Int_t)uid > fObjects->GetSize()) return 0;
return fObjects->UncheckedAt(uid);
}
//______________________________________________________________________________
void TProcessID::PutObjectWithID(TObject *obj, UInt_t uid)
{
//stores the object at the uid th slot in the table of objects
//The object uniqueid is set as well as its kMustCleanup bit
//if (!fObjects) fObjects = new TObjArray(100);
if (uid == 0) uid = obj->GetUniqueID();
fObjects->AddAtAndExpand(obj,uid);
obj->SetBit(kMustCleanup);
}
//______________________________________________________________________________
TProcessID *TProcessID::ReadProcessID(UShort_t pidf, TFile *file)
{
// static function
//The TProcessID with number pidf is read from file.
//If the object is not already entered in the gROOT list, it is added.
if (!file) return 0;
TObjArray *pids = file->GetListOfProcessIDs();
TProcessID *pid = 0;
if (pidf < pids->GetSize()) pid = (TProcessID *)pids->UncheckedAt(pidf);
if (pid) return pid;
//check if fProcessIDs[uid] is set in file
//if not set, read the process uid from file
char pidname[32];
sprintf(pidname,"ProcessID%d",pidf);
pid = (TProcessID *)file->Get(pidname);
if (!pid) {
//file->Error("ReadProcessID","Cannot find %s in file %s",pidname,file->GetName());
return 0;
}
pids->AddAtAndExpand(pid,pidf);
pid->IncrementCount();
//check that a similar pid is not already registered in fgPIDs
TIter next(fgPIDs);
TProcessID *p;
while ((p = (TProcessID*)next())) {
if (!strcmp(p->GetTitle(),pid->GetTitle())) return p;
}
Int_t apid = fgPIDs->GetEntriesFast();
fgPIDs->Add(pid);
pid->SetUniqueID(apid);
return pid;
}
//______________________________________________________________________________
void TProcessID::RecursiveRemove(TObject *obj)
{
// called by the object destructor
// remove reference to obj from the current table if it is referenced
if (!obj->TestBit(kIsReferenced)) return;
UInt_t uid = obj->GetUniqueID();
if (obj == GetObjectWithID(uid)) fObjects->RemoveAt(uid);
}
//______________________________________________________________________________
void TProcessID::SetObjectCount(UInt_t number)
{
// static function to set the current referenced object count
// fgNumber is incremented everytime a new object is referenced
fgNumber = number;
}
//______________________________________________________________________________
UShort_t TProcessID::WriteProcessID(TProcessID *pid, TFile *file)
{
// static function
// Check if the ProcessID pid is already in the file.
// if not, add it and return the index number in the local file list
if (!file) return 0;
TObjArray *pids = file->GetListOfProcessIDs();
Int_t pidf = 0;
if (pid) pidf = pids->IndexOf(pid);
if (pidf < 0) {
file->SetBit(TFile::kHasReferences);
pidf = (UShort_t)pids->GetEntriesFast();
pids->Add(pid);
char name[32];
sprintf(name,"ProcessID%d",pidf);
pid->Write(name);
}
return (UShort_t)pidf;
}
<|endoftext|> |
<commit_before><commit_msg>improved comments<commit_after><|endoftext|> |
<commit_before>/*$Id$
*
* This source file is a part of the Berlin Project.
* Copyright (C) 1999 Stefan Seefeld <stefan@berlin-consortium.org>
* http://www.berlin-consortium.org
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 675 Mass Ave, Cambridge,
* MA 02139, USA.
*/
#ifndef _Math_hh
#define _Math_hh
#include <Warsaw/Transform.hh>
#include <algorithm>
#include <cstdlib>
#include <cmath>
namespace Math
{
const double pi = M_PI;
template <class T> inline T min(T a, T b) { return a < b ? a : b;}
template <class T> inline T max(T a, T b) { return a < b ? b : a;}
template <class T> inline T min(T a, T b, const T &c, const T &d) { return min(min(a, b), min(c, d));}
template <class T> inline T max(T a, T b, const T &c, const T &d) { return max(max(a, b), max(c, d));}
inline float abs(float a) { return fabs(a);}
inline double abs(double a) { return fabs(a);}
inline int abs(int a) { return abs(a);}
inline long abs(long a) { return labs(a);}
template <class T> inline int round(T a) { return a > 0 ? static_cast<int>(a + 0.5) : - static_cast<int>(-a + 0.5);}
template <class T> inline bool equal(T a, T b, T e) { return a - b < e && b - a < e;}
//. general orthogonal matrix transformation
//. needs to be refined for perspective trafos
inline Warsaw::Vertex &operator *= (Warsaw::Vertex &v, const Warsaw::Transform::Matrix &m)
{
Warsaw::Coord tx = v.x;
Warsaw::Coord ty = v.y;
v.x = m[0][0] * tx + m[0][1] * ty + m[0][2] * v.z + m[0][3];
v.y = m[1][0] * tx + m[1][1] * ty + m[1][2] * v.z + m[1][3];
v.z = m[2][0] * tx + m[2][1] * ty + m[2][2] * v.z + m[2][3];
return v;
}
};
#endif /* _Math_hh */
<commit_msg>missed config header<commit_after>/*$Id$
*
* This source file is a part of the Berlin Project.
* Copyright (C) 1999 Stefan Seefeld <stefan@berlin-consortium.org>
* http://www.berlin-consortium.org
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 675 Mass Ave, Cambridge,
* MA 02139, USA.
*/
#ifndef _Math_hh
#define _Math_hh
#include <Warsaw/config.hh>
#include <Warsaw/Transform.hh>
#include <algorithm>
#include <cstdlib>
#include <cmath>
namespace Math
{
const double pi = M_PI;
template <class T> inline T min(T a, T b) { return a < b ? a : b;}
template <class T> inline T max(T a, T b) { return a < b ? b : a;}
template <class T> inline T min(T a, T b, const T &c, const T &d) { return min(min(a, b), min(c, d));}
template <class T> inline T max(T a, T b, const T &c, const T &d) { return max(max(a, b), max(c, d));}
inline float abs(float a) { return fabs(a);}
inline double abs(double a) { return fabs(a);}
inline int abs(int a) { return abs(a);}
inline long abs(long a) { return labs(a);}
template <class T> inline int round(T a) { return a > 0 ? static_cast<int>(a + 0.5) : - static_cast<int>(-a + 0.5);}
template <class T> inline bool equal(T a, T b, T e) { return a - b < e && b - a < e;}
//. general orthogonal matrix transformation
//. needs to be refined for perspective trafos
inline Warsaw::Vertex &operator *= (Warsaw::Vertex &v, const Warsaw::Transform::Matrix &m)
{
Warsaw::Coord tx = v.x;
Warsaw::Coord ty = v.y;
v.x = m[0][0] * tx + m[0][1] * ty + m[0][2] * v.z + m[0][3];
v.y = m[1][0] * tx + m[1][1] * ty + m[1][2] * v.z + m[1][3];
v.z = m[2][0] * tx + m[2][1] * ty + m[2][2] * v.z + m[2][3];
return v;
}
};
#endif /* _Math_hh */
<|endoftext|> |
<commit_before>#include "drake/examples/Cars/car_simulation.h"
#include <cstdlib>
#include "drake/examples/Cars/curve2.h"
#include "drake/examples/Cars/gen/euler_floating_joint_state.h"
#include "drake/examples/Cars/gen/simple_car_state.h"
#include "drake/examples/Cars/trajectory_car.h"
using drake::AffineSystem;
using drake::NullVector;
using Eigen::Matrix;
using Eigen::MatrixXd;
using Eigen::VectorXd;
namespace drake {
namespace examples {
namespace cars {
const std::string kDurationFlag = "--duration";
void PrintUsageInstructions(const std::string executable_name) {
std::cout
<< "Usage: " << executable_name
<< " [vehicle model file] [world model files] "
<< kDurationFlag << " [duration in seconds]"
<< std::endl
<< std::endl
<< "Where:" << std::endl
<< " - [vehicle model file] is the path to the URDF or SDF file defining "
<< std::endl
<< " the vehicle model(s) and are thus attached to the world via "
<< std::endl
<< " DrakeJoint::QUATERNION joints."
<< std::endl
<< std::endl
<< " - [world model files] is a space-separated list of paths to URDF or "
<< std::endl
<< " SDF files. This list can be of length zero or more. The models "
<< std::endl
<< " within these files connected to the world via DrakeJoint::FIXED "
<< std::endl
<< " joints."
<< std::endl
<< std::endl
<< " - [duration in seconds] is the number of seconds (floating point) to "
<< std::endl
<< " to run the simulation. This value is in simulation time, which is "
<< std::endl
<< " not necessarily equal to real time."
<< std::endl;
}
std::shared_ptr<RigidBodySystem> CreateRigidBodySystem(int argc,
const char* argv[]) {
if (argc < 2) {
PrintUsageInstructions(argv[0]);
exit(EXIT_FAILURE);
}
// Instantiates a rigid body system.
auto rigid_body_sys = std::allocate_shared<RigidBodySystem>(
Eigen::aligned_allocator<RigidBodySystem>());
// Adds a robot model.
rigid_body_sys->addRobotFromFile(argv[1], DrakeJoint::QUATERNION);
// Adds the environment.
for (int ii = 2; ii < argc; ++ii) {
if (std::string(argv[ii]) != kDurationFlag) {
rigid_body_sys->addRobotFromFile(argv[ii], DrakeJoint::FIXED);
} else {
++ii; // Skips the value immediately after "--duration".
}
}
// Adds a flat terrain if no environment is specified.
if (argc < 3) {
const std::shared_ptr<RigidBodyTree>& tree =
rigid_body_sys->getRigidBodyTree();
AddFlatTerrain(tree);
}
// Sets various simulation parameters.
SetRigidBodySystemParameters(rigid_body_sys.get());
return rigid_body_sys;
}
void SetRigidBodySystemParameters(RigidBodySystem* rigid_body_sys) {
rigid_body_sys->penetration_stiffness = 5000.0;
rigid_body_sys->penetration_damping =
rigid_body_sys->penetration_stiffness / 10.0;
rigid_body_sys->friction_coefficient = 10.0; // essentially infinite friction
}
double ParseDuration(int argc, const char* argv[]) {
for (int ii = 1; ii < argc; ++ii) {
if (std::string(argv[ii]) == kDurationFlag) {
if (++ii == argc) {
PrintUsageInstructions(argv[0]);
throw std::runtime_error(
"ERROR: Command line option \"" + kDurationFlag +
"\" is not followed by a value!");
}
return atof(argv[ii]);
}
}
return std::numeric_limits<double>::infinity();
}
void AddFlatTerrain(const std::shared_ptr<RigidBodyTree>& rigid_body_tree,
double box_size, double box_depth) {
DrakeShapes::Box geom(Eigen::Vector3d(box_size, box_size, box_depth));
Eigen::Isometry3d T_element_to_link = Eigen::Isometry3d::Identity();
T_element_to_link.translation() << 0, 0,
-box_depth / 2; // top of the box is at z=0
RigidBody& world = rigid_body_tree->world();
Eigen::Vector4d color;
color << 0.9297, 0.7930, 0.6758,
1; // was hex2dec({'ee','cb','ad'})'/256 in matlab
world.AddVisualElement(
DrakeShapes::VisualElement(geom, T_element_to_link, color));
rigid_body_tree->addCollisionElement(
RigidBodyCollisionElement(geom, T_element_to_link, &world), world,
"terrain");
rigid_body_tree->updateStaticCollisionElements();
}
std::shared_ptr<CascadeSystem<
Gain<DrivingCommand, PDControlSystem<RigidBodySystem>::InputVector>,
PDControlSystem<RigidBodySystem>>>
CreateVehicleSystem(std::shared_ptr<RigidBodySystem> rigid_body_sys) {
const auto& tree = rigid_body_sys->getRigidBodyTree();
// Sets up PD controllers for throttle and steering.
const double kpSteering = 400, kdSteering = 80, kThrottle = 100;
MatrixXd Kp(getNumInputs(*rigid_body_sys), tree->number_of_positions());
Kp.setZero();
MatrixXd Kd(getNumInputs(*rigid_body_sys), tree->number_of_velocities());
Kd.setZero();
Matrix<double, Eigen::Dynamic, 3> map_driving_cmd_to_x_d(
tree->number_of_positions() + tree->number_of_velocities(), 3);
map_driving_cmd_to_x_d.setZero();
for (int actuator_idx = 0;
actuator_idx < static_cast<int>(tree->actuators.size());
actuator_idx++) {
const std::string& actuator_name = tree->actuators[actuator_idx].name_;
if (actuator_name == "steering") {
// Obtains the rigid body to which the actuator is attached.
const auto& rigid_body = tree->actuators[actuator_idx].body_;
// Sets the steering actuator's Kp gain.
Kp(actuator_idx, rigid_body->get_position_start_index()) = kpSteering;
// Sets the steering actuator's Kd gain.
Kd(actuator_idx, rigid_body->get_velocity_start_index()) = kdSteering;
// Saves the mapping between the driving command and the steering command.
map_driving_cmd_to_x_d(rigid_body->get_position_start_index(),
DrivingCommandIndices::kSteeringAngle) =
1; // steering command
} else if (actuator_name == "right_wheel_joint" ||
actuator_name == "left_wheel_joint") {
// Obtains the rigid body to which the actuator is attached.
const auto& rigid_body = tree->actuators[actuator_idx].body_;
// Sets the throttle Kd gain.
Kd(actuator_idx, rigid_body->get_velocity_start_index()) = kThrottle;
// Saves the mapping between the driving command and the throttle command.
map_driving_cmd_to_x_d(
tree->number_of_positions() + rigid_body->get_velocity_start_index(),
DrivingCommandIndices::kThrottle) = 20;
// Saves the mapping between the driving command and the braking command.
map_driving_cmd_to_x_d(
tree->number_of_positions() + rigid_body->get_velocity_start_index(),
DrivingCommandIndices::kBrake) = -20;
}
}
auto vehicle_with_pd = std::allocate_shared<PDControlSystem<RigidBodySystem>>(
Eigen::aligned_allocator<PDControlSystem<RigidBodySystem>>(),
rigid_body_sys, Kp, Kd);
auto vehicle_sys = cascade(
std::allocate_shared<
Gain<DrivingCommand, PDControlSystem<RigidBodySystem>::InputVector>>(
Eigen::aligned_allocator<Gain<
DrivingCommand, PDControlSystem<RigidBodySystem>::InputVector>>(),
map_driving_cmd_to_x_d),
vehicle_with_pd);
return vehicle_sys;
}
namespace {
// A figure-eight. One loop has a radius of @p radius - @p inset,
// the other loop has a radius of @p radius + @p inset.
Curve2<double> MakeCurve(double radius, double inset) {
// TODO(jwnimmer-tri) This function will be rewritten once we have
// proper splines. Don't try too hard to understand it. Run the
// demo to see it first, and only then try to understand the code.
typedef Curve2<double>::Point2 Point2d;
std::vector<Point2d> waypoints;
// Start (0, +i).
// Straight right to (+r, +i).
// Loop around (+i, +r).
// Straight back to (+i, 0).
waypoints.push_back({0.0, inset});
for (int theta_deg = -90; theta_deg <= 180; ++theta_deg) {
const Point2d center{radius, radius};
const double theta = theta_deg * M_PI / 180.0;
const Point2d direction{std::cos(theta), std::sin(theta)};
waypoints.push_back(center + (direction * (radius - inset)));
}
waypoints.push_back({inset, 0.0});
// Start (+i, 0).
// Straight down to (+i, -r).
// Loop around (-r, +i).
// Straight back to start (implicitly via segment to waypoints[0]).
for (int theta_deg = 0; theta_deg >= -270; --theta_deg) {
const Point2d center{-radius, -radius};
const double theta = theta_deg * M_PI / 180.0;
const Point2d direction{std::cos(theta), std::sin(theta)};
waypoints.push_back(center + (direction * (radius + inset)));
}
// Many copies.
const int kNumCopies = 100;
std::vector<Point2d> looped_waypoints;
for (int copies = 0; copies < kNumCopies; ++copies) {
std::copy(waypoints.begin(), waypoints.end(),
std::back_inserter(looped_waypoints));
}
looped_waypoints.push_back(waypoints.front());
return Curve2<double>(looped_waypoints);
}
} // namespace anonymous
std::shared_ptr<TrajectoryCar> CreateTrajectoryCarSystem(int index) {
// The possible curves to trace (lanes).
const std::vector<Curve2<double>> curves{
MakeCurve(40.0, 0.0), // BR
MakeCurve(40.0, 4.0), // BR
MakeCurve(40.0, 8.0),
};
// Magic car placement to make a good visual demo.
const auto& curve = curves[index % curves.size()];
const double start_time = (index / curves.size()) * 0.8;
const double kSpeed = 8.0;
return std::make_shared<TrajectoryCar>(curve, kSpeed, start_time);
}
std::shared_ptr<AffineSystem<
NullVector, SimpleCarState, EulerFloatingJointState>>
CreateSimpleCarVisualizationAdapter() {
const int insize = SimpleCarState<double>().size();
const int outsize = EulerFloatingJointState<double>().size();
MatrixXd D;
D.setZero(outsize, insize);
D(EulerFloatingJointStateIndices::kX, SimpleCarStateIndices::kX) = 1;
D(EulerFloatingJointStateIndices::kY, SimpleCarStateIndices::kY) = 1;
D(EulerFloatingJointStateIndices::kYaw, SimpleCarStateIndices::kHeading) = 1;
EulerFloatingJointState<double> y0;
return std::make_shared<
AffineSystem<
NullVector,
SimpleCarState,
EulerFloatingJointState>>(
MatrixXd::Zero(0, 0),
MatrixXd::Zero(0, insize),
VectorXd::Zero(0),
MatrixXd::Zero(outsize, 0),
D, toEigen(y0));
}
SimulationOptions GetCarSimulationDefaultOptions() {
SimulationOptions result;
result.initial_step_size = 5e-3;
result.timeout_seconds = std::numeric_limits<double>::infinity();
return result;
}
VectorXd GetInitialState(const RigidBodySystem& rigid_body_sys) {
const auto& tree = rigid_body_sys.getRigidBodyTree();
VectorXd x0 = VectorXd::Zero(rigid_body_sys.getNumStates());
x0.head(tree->number_of_positions()) = tree->getZeroConfiguration();
return x0;
}
} // namespace cars
} // namespace examples
} // namespace drake
<commit_msg>Modified code to break out of for loop as soon as --duration is encountered.<commit_after>#include "drake/examples/Cars/car_simulation.h"
#include <cstdlib>
#include "drake/examples/Cars/curve2.h"
#include "drake/examples/Cars/gen/euler_floating_joint_state.h"
#include "drake/examples/Cars/gen/simple_car_state.h"
#include "drake/examples/Cars/trajectory_car.h"
using drake::AffineSystem;
using drake::NullVector;
using Eigen::Matrix;
using Eigen::MatrixXd;
using Eigen::VectorXd;
namespace drake {
namespace examples {
namespace cars {
const std::string kDurationFlag = "--duration";
void PrintUsageInstructions(const std::string executable_name) {
std::cout
<< "Usage: " << executable_name
<< " [vehicle model file] [world model files] "
<< kDurationFlag << " [duration in seconds]"
<< std::endl
<< std::endl
<< "Where:" << std::endl
<< " - [vehicle model file] is the path to the URDF or SDF file defining "
<< std::endl
<< " the vehicle model(s) and are thus attached to the world via "
<< std::endl
<< " DrakeJoint::QUATERNION joints."
<< std::endl
<< std::endl
<< " - [world model files] is a space-separated list of paths to URDF or "
<< std::endl
<< " SDF files. This list can be of length zero or more. The models "
<< std::endl
<< " within these files connected to the world via DrakeJoint::FIXED "
<< std::endl
<< " joints."
<< std::endl
<< std::endl
<< " - [duration in seconds] is the number of seconds (floating point) to "
<< std::endl
<< " to run the simulation. This value is in simulation time, which is "
<< std::endl
<< " not necessarily equal to real time."
<< std::endl;
}
std::shared_ptr<RigidBodySystem> CreateRigidBodySystem(int argc,
const char* argv[]) {
if (argc < 2) {
PrintUsageInstructions(argv[0]);
exit(EXIT_FAILURE);
}
// Instantiates a rigid body system.
auto rigid_body_sys = std::allocate_shared<RigidBodySystem>(
Eigen::aligned_allocator<RigidBodySystem>());
// Adds a robot model.
rigid_body_sys->addRobotFromFile(argv[1], DrakeJoint::QUATERNION);
// Adds the environment.
for (int ii = 2; ii < argc; ++ii) {
if (std::string(argv[ii]) != kDurationFlag) {
rigid_body_sys->addRobotFromFile(argv[ii], DrakeJoint::FIXED);
} else {
// The duration flag must be the penultimate argument. Thus, we can ignore
// the rest of the arguments and break out of the enclosing for loop.
break;
}
}
// Adds a flat terrain if no environment is specified.
if (argc < 3) {
const std::shared_ptr<RigidBodyTree>& tree =
rigid_body_sys->getRigidBodyTree();
AddFlatTerrain(tree);
}
// Sets various simulation parameters.
SetRigidBodySystemParameters(rigid_body_sys.get());
return rigid_body_sys;
}
void SetRigidBodySystemParameters(RigidBodySystem* rigid_body_sys) {
rigid_body_sys->penetration_stiffness = 5000.0;
rigid_body_sys->penetration_damping =
rigid_body_sys->penetration_stiffness / 10.0;
rigid_body_sys->friction_coefficient = 10.0; // essentially infinite friction
}
double ParseDuration(int argc, const char* argv[]) {
for (int ii = 1; ii < argc; ++ii) {
if (std::string(argv[ii]) == kDurationFlag) {
if (++ii == argc) {
PrintUsageInstructions(argv[0]);
throw std::runtime_error(
"ERROR: Command line option \"" + kDurationFlag +
"\" is not followed by a value!");
}
return atof(argv[ii]);
}
}
return std::numeric_limits<double>::infinity();
}
void AddFlatTerrain(const std::shared_ptr<RigidBodyTree>& rigid_body_tree,
double box_size, double box_depth) {
DrakeShapes::Box geom(Eigen::Vector3d(box_size, box_size, box_depth));
Eigen::Isometry3d T_element_to_link = Eigen::Isometry3d::Identity();
T_element_to_link.translation() << 0, 0,
-box_depth / 2; // top of the box is at z=0
RigidBody& world = rigid_body_tree->world();
Eigen::Vector4d color;
color << 0.9297, 0.7930, 0.6758,
1; // was hex2dec({'ee','cb','ad'})'/256 in matlab
world.AddVisualElement(
DrakeShapes::VisualElement(geom, T_element_to_link, color));
rigid_body_tree->addCollisionElement(
RigidBodyCollisionElement(geom, T_element_to_link, &world), world,
"terrain");
rigid_body_tree->updateStaticCollisionElements();
}
std::shared_ptr<CascadeSystem<
Gain<DrivingCommand, PDControlSystem<RigidBodySystem>::InputVector>,
PDControlSystem<RigidBodySystem>>>
CreateVehicleSystem(std::shared_ptr<RigidBodySystem> rigid_body_sys) {
const auto& tree = rigid_body_sys->getRigidBodyTree();
// Sets up PD controllers for throttle and steering.
const double kpSteering = 400, kdSteering = 80, kThrottle = 100;
MatrixXd Kp(getNumInputs(*rigid_body_sys), tree->number_of_positions());
Kp.setZero();
MatrixXd Kd(getNumInputs(*rigid_body_sys), tree->number_of_velocities());
Kd.setZero();
Matrix<double, Eigen::Dynamic, 3> map_driving_cmd_to_x_d(
tree->number_of_positions() + tree->number_of_velocities(), 3);
map_driving_cmd_to_x_d.setZero();
for (int actuator_idx = 0;
actuator_idx < static_cast<int>(tree->actuators.size());
actuator_idx++) {
const std::string& actuator_name = tree->actuators[actuator_idx].name_;
if (actuator_name == "steering") {
// Obtains the rigid body to which the actuator is attached.
const auto& rigid_body = tree->actuators[actuator_idx].body_;
// Sets the steering actuator's Kp gain.
Kp(actuator_idx, rigid_body->get_position_start_index()) = kpSteering;
// Sets the steering actuator's Kd gain.
Kd(actuator_idx, rigid_body->get_velocity_start_index()) = kdSteering;
// Saves the mapping between the driving command and the steering command.
map_driving_cmd_to_x_d(rigid_body->get_position_start_index(),
DrivingCommandIndices::kSteeringAngle) =
1; // steering command
} else if (actuator_name == "right_wheel_joint" ||
actuator_name == "left_wheel_joint") {
// Obtains the rigid body to which the actuator is attached.
const auto& rigid_body = tree->actuators[actuator_idx].body_;
// Sets the throttle Kd gain.
Kd(actuator_idx, rigid_body->get_velocity_start_index()) = kThrottle;
// Saves the mapping between the driving command and the throttle command.
map_driving_cmd_to_x_d(
tree->number_of_positions() + rigid_body->get_velocity_start_index(),
DrivingCommandIndices::kThrottle) = 20;
// Saves the mapping between the driving command and the braking command.
map_driving_cmd_to_x_d(
tree->number_of_positions() + rigid_body->get_velocity_start_index(),
DrivingCommandIndices::kBrake) = -20;
}
}
auto vehicle_with_pd = std::allocate_shared<PDControlSystem<RigidBodySystem>>(
Eigen::aligned_allocator<PDControlSystem<RigidBodySystem>>(),
rigid_body_sys, Kp, Kd);
auto vehicle_sys = cascade(
std::allocate_shared<
Gain<DrivingCommand, PDControlSystem<RigidBodySystem>::InputVector>>(
Eigen::aligned_allocator<Gain<
DrivingCommand, PDControlSystem<RigidBodySystem>::InputVector>>(),
map_driving_cmd_to_x_d),
vehicle_with_pd);
return vehicle_sys;
}
namespace {
// A figure-eight. One loop has a radius of @p radius - @p inset,
// the other loop has a radius of @p radius + @p inset.
Curve2<double> MakeCurve(double radius, double inset) {
// TODO(jwnimmer-tri) This function will be rewritten once we have
// proper splines. Don't try too hard to understand it. Run the
// demo to see it first, and only then try to understand the code.
typedef Curve2<double>::Point2 Point2d;
std::vector<Point2d> waypoints;
// Start (0, +i).
// Straight right to (+r, +i).
// Loop around (+i, +r).
// Straight back to (+i, 0).
waypoints.push_back({0.0, inset});
for (int theta_deg = -90; theta_deg <= 180; ++theta_deg) {
const Point2d center{radius, radius};
const double theta = theta_deg * M_PI / 180.0;
const Point2d direction{std::cos(theta), std::sin(theta)};
waypoints.push_back(center + (direction * (radius - inset)));
}
waypoints.push_back({inset, 0.0});
// Start (+i, 0).
// Straight down to (+i, -r).
// Loop around (-r, +i).
// Straight back to start (implicitly via segment to waypoints[0]).
for (int theta_deg = 0; theta_deg >= -270; --theta_deg) {
const Point2d center{-radius, -radius};
const double theta = theta_deg * M_PI / 180.0;
const Point2d direction{std::cos(theta), std::sin(theta)};
waypoints.push_back(center + (direction * (radius + inset)));
}
// Many copies.
const int kNumCopies = 100;
std::vector<Point2d> looped_waypoints;
for (int copies = 0; copies < kNumCopies; ++copies) {
std::copy(waypoints.begin(), waypoints.end(),
std::back_inserter(looped_waypoints));
}
looped_waypoints.push_back(waypoints.front());
return Curve2<double>(looped_waypoints);
}
} // namespace anonymous
std::shared_ptr<TrajectoryCar> CreateTrajectoryCarSystem(int index) {
// The possible curves to trace (lanes).
const std::vector<Curve2<double>> curves{
MakeCurve(40.0, 0.0), // BR
MakeCurve(40.0, 4.0), // BR
MakeCurve(40.0, 8.0),
};
// Magic car placement to make a good visual demo.
const auto& curve = curves[index % curves.size()];
const double start_time = (index / curves.size()) * 0.8;
const double kSpeed = 8.0;
return std::make_shared<TrajectoryCar>(curve, kSpeed, start_time);
}
std::shared_ptr<AffineSystem<
NullVector, SimpleCarState, EulerFloatingJointState>>
CreateSimpleCarVisualizationAdapter() {
const int insize = SimpleCarState<double>().size();
const int outsize = EulerFloatingJointState<double>().size();
MatrixXd D;
D.setZero(outsize, insize);
D(EulerFloatingJointStateIndices::kX, SimpleCarStateIndices::kX) = 1;
D(EulerFloatingJointStateIndices::kY, SimpleCarStateIndices::kY) = 1;
D(EulerFloatingJointStateIndices::kYaw, SimpleCarStateIndices::kHeading) = 1;
EulerFloatingJointState<double> y0;
return std::make_shared<
AffineSystem<
NullVector,
SimpleCarState,
EulerFloatingJointState>>(
MatrixXd::Zero(0, 0),
MatrixXd::Zero(0, insize),
VectorXd::Zero(0),
MatrixXd::Zero(outsize, 0),
D, toEigen(y0));
}
SimulationOptions GetCarSimulationDefaultOptions() {
SimulationOptions result;
result.initial_step_size = 5e-3;
result.timeout_seconds = std::numeric_limits<double>::infinity();
return result;
}
VectorXd GetInitialState(const RigidBodySystem& rigid_body_sys) {
const auto& tree = rigid_body_sys.getRigidBodyTree();
VectorXd x0 = VectorXd::Zero(rigid_body_sys.getNumStates());
x0.head(tree->number_of_positions()) = tree->getZeroConfiguration();
return x0;
}
} // namespace cars
} // namespace examples
} // namespace drake
<|endoftext|> |
<commit_before>// Copyright 2012 Cloudera Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "rpc/rpc-trace.h"
#include <boost/bind.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/foreach.hpp>
#include <gutil/strings/substitute.h>
#include "common/logging.h"
#include "util/debug-util.h"
#include "util/time.h"
#include "util/webserver.h"
using namespace impala;
using namespace boost;
using namespace rapidjson;
using namespace std;
using namespace strings;
// Singleton class to keep track of all RpcEventHandlers, and to render them to a
// web-based summary page.
class RpcEventHandlerManager {
public:
// Adds an event handler to the list of those tracked
void RegisterEventHandler(RpcEventHandler* event_handler);
// Produces Json for /rpcz with summary information for all Rpc methods.
// { "servers": [
// .. list of output from RpcEventHandler::ToJson()
// ] }
void JsonCallback(const Webserver::ArgumentMap& args, Document* document);
// Resets method statistics. Takes two optional arguments: 'server' and 'method'. If
// neither are specified, all server statistics are reset. If only the former is
// specified, all statistics for that server are reset. If both arguments are present,
// resets the statistics for a single method only. Produces no JSON output.
void ResetCallback(const Webserver::ArgumentMap& args, Document* document);
private:
// Protects event_handlers_
mutex lock_;
// List of all event handlers in the system - once an event handler is registered, it
// should never be deleted. Event handlers are owned by the TProcessor which calls them,
// which are themselves owned by a ThriftServer. Since we do not terminate ThriftServers
// after they are started, event handlers have a lifetime equivalent to the length of
// the process.
vector<RpcEventHandler*> event_handlers_;
};
// Only instance of RpcEventHandlerManager
scoped_ptr<RpcEventHandlerManager> handler_manager;
void impala::InitRpcEventTracing(Webserver* webserver) {
handler_manager.reset(new RpcEventHandlerManager());
if (webserver != NULL) {
Webserver::UrlCallback json = bind<void>(
mem_fn(&RpcEventHandlerManager::JsonCallback), handler_manager.get(), _1, _2);
webserver->RegisterUrlCallback("/rpcz", "rpcz.tmpl", json);
Webserver::UrlCallback reset = bind<void>(
mem_fn(&RpcEventHandlerManager::ResetCallback), handler_manager.get(), _1, _2);
webserver->RegisterUrlCallback("/rpcz_reset", "", reset, reset);
}
}
void RpcEventHandlerManager::RegisterEventHandler(RpcEventHandler* event_handler) {
DCHECK(event_handler != NULL);
lock_guard<mutex> l(lock_);
event_handlers_.push_back(event_handler);
}
void RpcEventHandlerManager::JsonCallback(const Webserver::ArgumentMap& args,
Document* document) {
lock_guard<mutex> l(lock_);
Value servers(kArrayType);
BOOST_FOREACH(RpcEventHandler* handler, event_handlers_) {
Value server(kObjectType);
handler->ToJson(&server, document);
servers.PushBack(server, document->GetAllocator());
}
document->AddMember("servers", servers, document->GetAllocator());
}
void RpcEventHandlerManager::ResetCallback(const Webserver::ArgumentMap& args,
Document* document) {
Webserver::ArgumentMap::const_iterator server_it = args.find("server");
bool reset_all_servers = (server_it == args.end());
Webserver::ArgumentMap::const_iterator method_it = args.find("method");
bool reset_all_in_server = (method_it == args.end());
lock_guard<mutex> l(lock_);
BOOST_FOREACH(RpcEventHandler* handler, event_handlers_) {
if (reset_all_servers || handler->server_name() == server_it->second) {
if (reset_all_in_server) {
handler->ResetAll();
} else {
handler->Reset(method_it->second);
}
if (!reset_all_servers) return;
}
}
}
void RpcEventHandler::Reset(const string& method_name) {
lock_guard<mutex> l(method_map_lock_);
MethodMap::iterator it = method_map_.find(method_name);
if (it == method_map_.end()) return;
it->second->time_stats->Reset();
it->second->num_in_flight = 0L;
}
void RpcEventHandler::ResetAll() {
lock_guard<mutex> l(method_map_lock_);
BOOST_FOREACH(const MethodMap::value_type& method, method_map_) {
method.second->time_stats->Reset();
method.second->num_in_flight = 0L;
}
}
RpcEventHandler::RpcEventHandler(const string& server_name, MetricGroup* metrics) :
server_name_(server_name), metrics_(metrics) {
if (handler_manager.get() != NULL) handler_manager->RegisterEventHandler(this);
}
void RpcEventHandler::ToJson(Value* server, Document* document) {
lock_guard<mutex> l(method_map_lock_);
Value name(server_name_.c_str(), document->GetAllocator());
server->AddMember("name", name, document->GetAllocator());
Value methods(kArrayType);
BOOST_FOREACH(const MethodMap::value_type& rpc, method_map_) {
Value method(kObjectType);
Value method_name(rpc.first.c_str(), document->GetAllocator());
method.AddMember("name", method_name, document->GetAllocator());
const string& human_readable = rpc.second->time_stats->ToHumanReadable();
Value summary(human_readable.c_str(), document->GetAllocator());
method.AddMember("summary", summary, document->GetAllocator());
method.AddMember("in_flight", rpc.second->num_in_flight, document->GetAllocator());
Value server_name(server_name_.c_str(), document->GetAllocator());
method.AddMember("server_name", server_name, document->GetAllocator());
methods.PushBack(method, document->GetAllocator());
}
server->AddMember("methods", methods, document->GetAllocator());
}
void* RpcEventHandler::getContext(const char* fn_name, void* server_context) {
ThriftServer::ConnectionContext* cnxn_ctx =
reinterpret_cast<ThriftServer::ConnectionContext*>(server_context);
MethodMap::iterator it;
{
lock_guard<mutex> l(method_map_lock_);
it = method_map_.find(fn_name);
if (it == method_map_.end()) {
MethodDescriptor* descriptor = new MethodDescriptor();
descriptor->name = fn_name;
const string& time_metric_name =
Substitute("rpc-method.$0.$1.call_duration", server_name_, descriptor->name);
descriptor->time_stats = metrics_->RegisterMetric(
new StatsMetric<double>(time_metric_name, TUnit::TIME_MS));
it = method_map_.insert(make_pair(descriptor->name, descriptor)).first;
}
}
++(it->second->num_in_flight);
// TODO: Consider pooling these
InvocationContext* ctxt_ptr =
new InvocationContext(MonotonicMillis(), cnxn_ctx, it->second);
VLOG_RPC << "RPC call: " << string(fn_name) << "(from "
<< ctxt_ptr->cnxn_ctx->network_address << ")";
return reinterpret_cast<void*>(ctxt_ptr);
}
void RpcEventHandler::postWrite(void* ctx, const char* fn_name, uint32_t bytes) {
InvocationContext* rpc_ctx = reinterpret_cast<InvocationContext*>(ctx);
int64_t elapsed_time = MonotonicMillis() - rpc_ctx->start_time_ms;
const string& call_name = string(fn_name);
// TODO: bytes is always 0, how come?
VLOG_RPC << "RPC call: " << server_name_ << ":" << call_name << " from "
<< rpc_ctx->cnxn_ctx->network_address << " took "
<< PrettyPrinter::Print(elapsed_time * 1000L * 1000L, TUnit::TIME_NS);
MethodDescriptor* descriptor = rpc_ctx->method_descriptor;
delete rpc_ctx;
--descriptor->num_in_flight;
descriptor->time_stats->Update(elapsed_time);
}
<commit_msg>IMPALA-1848: Fix argument that hides 'rpcz_reset' from nav bar<commit_after>// Copyright 2012 Cloudera Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "rpc/rpc-trace.h"
#include <boost/bind.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/foreach.hpp>
#include <gutil/strings/substitute.h>
#include "common/logging.h"
#include "util/debug-util.h"
#include "util/time.h"
#include "util/webserver.h"
using namespace impala;
using namespace boost;
using namespace rapidjson;
using namespace std;
using namespace strings;
// Singleton class to keep track of all RpcEventHandlers, and to render them to a
// web-based summary page.
class RpcEventHandlerManager {
public:
// Adds an event handler to the list of those tracked
void RegisterEventHandler(RpcEventHandler* event_handler);
// Produces Json for /rpcz with summary information for all Rpc methods.
// { "servers": [
// .. list of output from RpcEventHandler::ToJson()
// ] }
void JsonCallback(const Webserver::ArgumentMap& args, Document* document);
// Resets method statistics. Takes two optional arguments: 'server' and 'method'. If
// neither are specified, all server statistics are reset. If only the former is
// specified, all statistics for that server are reset. If both arguments are present,
// resets the statistics for a single method only. Produces no JSON output.
void ResetCallback(const Webserver::ArgumentMap& args, Document* document);
private:
// Protects event_handlers_
mutex lock_;
// List of all event handlers in the system - once an event handler is registered, it
// should never be deleted. Event handlers are owned by the TProcessor which calls them,
// which are themselves owned by a ThriftServer. Since we do not terminate ThriftServers
// after they are started, event handlers have a lifetime equivalent to the length of
// the process.
vector<RpcEventHandler*> event_handlers_;
};
// Only instance of RpcEventHandlerManager
scoped_ptr<RpcEventHandlerManager> handler_manager;
void impala::InitRpcEventTracing(Webserver* webserver) {
handler_manager.reset(new RpcEventHandlerManager());
if (webserver != NULL) {
Webserver::UrlCallback json = bind<void>(
mem_fn(&RpcEventHandlerManager::JsonCallback), handler_manager.get(), _1, _2);
webserver->RegisterUrlCallback("/rpcz", "rpcz.tmpl", json);
Webserver::UrlCallback reset = bind<void>(
mem_fn(&RpcEventHandlerManager::ResetCallback), handler_manager.get(), _1, _2);
webserver->RegisterUrlCallback("/rpcz_reset", "", reset, false);
}
}
void RpcEventHandlerManager::RegisterEventHandler(RpcEventHandler* event_handler) {
DCHECK(event_handler != NULL);
lock_guard<mutex> l(lock_);
event_handlers_.push_back(event_handler);
}
void RpcEventHandlerManager::JsonCallback(const Webserver::ArgumentMap& args,
Document* document) {
lock_guard<mutex> l(lock_);
Value servers(kArrayType);
BOOST_FOREACH(RpcEventHandler* handler, event_handlers_) {
Value server(kObjectType);
handler->ToJson(&server, document);
servers.PushBack(server, document->GetAllocator());
}
document->AddMember("servers", servers, document->GetAllocator());
}
void RpcEventHandlerManager::ResetCallback(const Webserver::ArgumentMap& args,
Document* document) {
Webserver::ArgumentMap::const_iterator server_it = args.find("server");
bool reset_all_servers = (server_it == args.end());
Webserver::ArgumentMap::const_iterator method_it = args.find("method");
bool reset_all_in_server = (method_it == args.end());
lock_guard<mutex> l(lock_);
BOOST_FOREACH(RpcEventHandler* handler, event_handlers_) {
if (reset_all_servers || handler->server_name() == server_it->second) {
if (reset_all_in_server) {
handler->ResetAll();
} else {
handler->Reset(method_it->second);
}
if (!reset_all_servers) return;
}
}
}
void RpcEventHandler::Reset(const string& method_name) {
lock_guard<mutex> l(method_map_lock_);
MethodMap::iterator it = method_map_.find(method_name);
if (it == method_map_.end()) return;
it->second->time_stats->Reset();
it->second->num_in_flight = 0L;
}
void RpcEventHandler::ResetAll() {
lock_guard<mutex> l(method_map_lock_);
BOOST_FOREACH(const MethodMap::value_type& method, method_map_) {
method.second->time_stats->Reset();
method.second->num_in_flight = 0L;
}
}
RpcEventHandler::RpcEventHandler(const string& server_name, MetricGroup* metrics) :
server_name_(server_name), metrics_(metrics) {
if (handler_manager.get() != NULL) handler_manager->RegisterEventHandler(this);
}
void RpcEventHandler::ToJson(Value* server, Document* document) {
lock_guard<mutex> l(method_map_lock_);
Value name(server_name_.c_str(), document->GetAllocator());
server->AddMember("name", name, document->GetAllocator());
Value methods(kArrayType);
BOOST_FOREACH(const MethodMap::value_type& rpc, method_map_) {
Value method(kObjectType);
Value method_name(rpc.first.c_str(), document->GetAllocator());
method.AddMember("name", method_name, document->GetAllocator());
const string& human_readable = rpc.second->time_stats->ToHumanReadable();
Value summary(human_readable.c_str(), document->GetAllocator());
method.AddMember("summary", summary, document->GetAllocator());
method.AddMember("in_flight", rpc.second->num_in_flight, document->GetAllocator());
Value server_name(server_name_.c_str(), document->GetAllocator());
method.AddMember("server_name", server_name, document->GetAllocator());
methods.PushBack(method, document->GetAllocator());
}
server->AddMember("methods", methods, document->GetAllocator());
}
void* RpcEventHandler::getContext(const char* fn_name, void* server_context) {
ThriftServer::ConnectionContext* cnxn_ctx =
reinterpret_cast<ThriftServer::ConnectionContext*>(server_context);
MethodMap::iterator it;
{
lock_guard<mutex> l(method_map_lock_);
it = method_map_.find(fn_name);
if (it == method_map_.end()) {
MethodDescriptor* descriptor = new MethodDescriptor();
descriptor->name = fn_name;
const string& time_metric_name =
Substitute("rpc-method.$0.$1.call_duration", server_name_, descriptor->name);
descriptor->time_stats = metrics_->RegisterMetric(
new StatsMetric<double>(time_metric_name, TUnit::TIME_MS));
it = method_map_.insert(make_pair(descriptor->name, descriptor)).first;
}
}
++(it->second->num_in_flight);
// TODO: Consider pooling these
InvocationContext* ctxt_ptr =
new InvocationContext(MonotonicMillis(), cnxn_ctx, it->second);
VLOG_RPC << "RPC call: " << string(fn_name) << "(from "
<< ctxt_ptr->cnxn_ctx->network_address << ")";
return reinterpret_cast<void*>(ctxt_ptr);
}
void RpcEventHandler::postWrite(void* ctx, const char* fn_name, uint32_t bytes) {
InvocationContext* rpc_ctx = reinterpret_cast<InvocationContext*>(ctx);
int64_t elapsed_time = MonotonicMillis() - rpc_ctx->start_time_ms;
const string& call_name = string(fn_name);
// TODO: bytes is always 0, how come?
VLOG_RPC << "RPC call: " << server_name_ << ":" << call_name << " from "
<< rpc_ctx->cnxn_ctx->network_address << " took "
<< PrettyPrinter::Print(elapsed_time * 1000L * 1000L, TUnit::TIME_NS);
MethodDescriptor* descriptor = rpc_ctx->method_descriptor;
delete rpc_ctx;
--descriptor->num_in_flight;
descriptor->time_stats->Update(elapsed_time);
}
<|endoftext|> |
<commit_before>
/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkBenchmark.h"
#include "SkBitmap.h"
#include "SkCanvas.h"
#include "SkColorPriv.h"
#include "SkGradientShader.h"
#include "SkPaint.h"
#include "SkShader.h"
#include "SkString.h"
#include "SkUnitMapper.h"
struct GradData {
int fCount;
const SkColor* fColors;
const SkScalar* fPos;
};
static const SkColor gColors[] = {
SK_ColorRED, SK_ColorGREEN, SK_ColorBLUE, SK_ColorWHITE, SK_ColorBLACK
};
static const SkScalar gPos0[] = { 0, SK_Scalar1 };
static const SkScalar gPos1[] = { SK_Scalar1/4, SK_Scalar1*3/4 };
static const SkScalar gPos2[] = {
0, SK_Scalar1/8, SK_Scalar1/2, SK_Scalar1*7/8, SK_Scalar1
};
static const GradData gGradData[] = {
{ 2, gColors, NULL },
{ 2, gColors, gPos0 },
{ 2, gColors, gPos1 },
{ 5, gColors, NULL },
{ 5, gColors, gPos2 }
};
/// Ignores scale
static SkShader* MakeLinear(const SkPoint pts[2], const GradData& data,
SkShader::TileMode tm, SkUnitMapper* mapper,
float scale) {
return SkGradientShader::CreateLinear(pts, data.fColors, data.fPos,
data.fCount, tm, mapper);
}
static SkShader* MakeRadial(const SkPoint pts[2], const GradData& data,
SkShader::TileMode tm, SkUnitMapper* mapper,
float scale) {
SkPoint center;
center.set(SkScalarAve(pts[0].fX, pts[1].fX),
SkScalarAve(pts[0].fY, pts[1].fY));
return SkGradientShader::CreateRadial(center, center.fX * scale,
data.fColors,
data.fPos, data.fCount, tm, mapper);
}
/// Ignores scale
static SkShader* MakeSweep(const SkPoint pts[2], const GradData& data,
SkShader::TileMode tm, SkUnitMapper* mapper,
float scale) {
SkPoint center;
center.set(SkScalarAve(pts[0].fX, pts[1].fX),
SkScalarAve(pts[0].fY, pts[1].fY));
return SkGradientShader::CreateSweep(center.fX, center.fY, data.fColors,
data.fPos, data.fCount, mapper);
}
/// Ignores scale
static SkShader* Make2Radial(const SkPoint pts[2], const GradData& data,
SkShader::TileMode tm, SkUnitMapper* mapper,
float scale) {
SkPoint center0, center1;
center0.set(SkScalarAve(pts[0].fX, pts[1].fX),
SkScalarAve(pts[0].fY, pts[1].fY));
center1.set(SkScalarInterp(pts[0].fX, pts[1].fX, SkIntToScalar(3)/5),
SkScalarInterp(pts[0].fY, pts[1].fY, SkIntToScalar(1)/4));
return SkGradientShader::CreateTwoPointRadial(
center1, (pts[1].fX - pts[0].fX) / 7,
center0, (pts[1].fX - pts[0].fX) / 2,
data.fColors, data.fPos, data.fCount, tm, mapper);
}
typedef SkShader* (*GradMaker)(const SkPoint pts[2], const GradData& data,
SkShader::TileMode tm, SkUnitMapper* mapper,
float scale);
static const struct {
GradMaker fMaker;
const char* fName;
int fRepeat;
} gGrads[] = {
{ MakeLinear, "linear", 15 },
{ MakeRadial, "radial1", 10 },
{ MakeSweep, "sweep", 1 },
{ Make2Radial, "radial2", 5 },
};
enum GradType { // these must match the order in gGrads
kLinear_GradType,
kRadial_GradType,
kSweep_GradType,
kRadial2_GradType
};
enum GeomType {
kRect_GeomType,
kOval_GeomType
};
static const char* tilemodename(SkShader::TileMode tm) {
switch (tm) {
case SkShader::kClamp_TileMode:
return "clamp";
case SkShader::kRepeat_TileMode:
return "repeat";
case SkShader::kMirror_TileMode:
return "mirror";
default:
SkASSERT(!"unknown tilemode");
return "error";
}
}
static const char* geomtypename(GeomType gt) {
switch (gt) {
case kRect_GeomType:
return "rectangle";
case kOval_GeomType:
return "oval";
default:
SkASSERT(!"unknown geometry type");
return "error";
}
}
///////////////////////////////////////////////////////////////////////////////
class GradientBench : public SkBenchmark {
SkString fName;
SkShader* fShader;
int fCount;
enum {
W = 400,
H = 400,
N = 1
};
public:
GradientBench(void* param, GradType gradType,
SkShader::TileMode tm = SkShader::kClamp_TileMode,
GeomType geomType = kRect_GeomType,
float scale = 1.0f)
: INHERITED(param) {
fName.printf("gradient_%s_%s", gGrads[gradType].fName,
tilemodename(tm));
if (geomType != kRect_GeomType) {
fName.append("_");
fName.append(geomtypename(geomType));
}
const SkPoint pts[2] = {
{ 0, 0 },
{ SkIntToScalar(W), SkIntToScalar(H) }
};
fCount = SkBENCHLOOP(N * gGrads[gradType].fRepeat);
fShader = gGrads[gradType].fMaker(pts, gGradData[0], tm, NULL, scale);
fGeomType = geomType;
}
virtual ~GradientBench() {
fShader->unref();
}
protected:
virtual const char* onGetName() {
return fName.c_str();
}
virtual void onDraw(SkCanvas* canvas) {
SkPaint paint;
this->setupPaint(&paint);
paint.setShader(fShader);
SkRect r = { 0, 0, SkIntToScalar(W), SkIntToScalar(H) };
for (int i = 0; i < fCount; i++) {
switch (fGeomType) {
case kRect_GeomType:
canvas->drawRect(r, paint);
break;
case kOval_GeomType:
canvas->drawOval(r, paint);
break;
}
}
}
private:
typedef SkBenchmark INHERITED;
GeomType fGeomType;
};
class Gradient2Bench : public SkBenchmark {
public:
Gradient2Bench(void* param) : INHERITED(param) {}
protected:
virtual const char* onGetName() {
return "gradient_create";
}
virtual void onDraw(SkCanvas* canvas) {
SkPaint paint;
this->setupPaint(&paint);
const SkRect r = { 0, 0, SkIntToScalar(4), SkIntToScalar(4) };
const SkPoint pts[] = {
{ 0, 0 },
{ SkIntToScalar(100), SkIntToScalar(100) },
};
for (int i = 0; i < SkBENCHLOOP(1000); i++) {
const int a = i % 256;
SkColor colors[] = {
SK_ColorBLACK,
SkColorSetARGB(a, a, a, a),
SK_ColorWHITE };
SkShader* s = SkGradientShader::CreateLinear(pts, colors, NULL,
SK_ARRAY_COUNT(colors),
SkShader::kClamp_TileMode);
paint.setShader(s)->unref();
canvas->drawRect(r, paint);
}
}
private:
typedef SkBenchmark INHERITED;
};
static SkBenchmark* Fact0(void* p) { return new GradientBench(p, kLinear_GradType); }
static SkBenchmark* Fact01(void* p) { return new GradientBench(p, kLinear_GradType, SkShader::kMirror_TileMode); }
// Draw a radial gradient of radius 1/2 on a rectangle; half the lines should
// be completely pinned, the other half should pe partially pinned
static SkBenchmark* Fact1(void* p) { return new GradientBench(p, kRadial_GradType, SkShader::kClamp_TileMode, kRect_GeomType, 0.5f); }
// Draw a radial gradient on a circle of equal size; all the lines should
// hit the unpinned fast path (so long as GradientBench.W == H)
static SkBenchmark* Fact1o(void* p) { return new GradientBench(p, kRadial_GradType, SkShader::kClamp_TileMode, kOval_GeomType); }
static SkBenchmark* Fact11(void* p) { return new GradientBench(p, kRadial_GradType, SkShader::kMirror_TileMode); }
static SkBenchmark* Fact2(void* p) { return new GradientBench(p, kSweep_GradType); }
static SkBenchmark* Fact3(void* p) { return new GradientBench(p, kRadial2_GradType); }
static SkBenchmark* Fact31(void* p) { return new GradientBench(p, kRadial2_GradType, SkShader::kMirror_TileMode); }
static SkBenchmark* Fact4(void* p) { return new Gradient2Bench(p); }
static BenchRegistry gReg0(Fact0);
static BenchRegistry gReg01(Fact01);
static BenchRegistry gReg1(Fact1);
static BenchRegistry gReg1o(Fact1o);
static BenchRegistry gReg11(Fact11);
static BenchRegistry gReg2(Fact2);
static BenchRegistry gReg3(Fact3);
static BenchRegistry gReg31(Fact31);
static BenchRegistry gReg4(Fact4);
<commit_msg>add bench for conical Gradient<commit_after>
/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkBenchmark.h"
#include "SkBitmap.h"
#include "SkCanvas.h"
#include "SkColorPriv.h"
#include "SkGradientShader.h"
#include "SkPaint.h"
#include "SkShader.h"
#include "SkString.h"
#include "SkUnitMapper.h"
struct GradData {
int fCount;
const SkColor* fColors;
const SkScalar* fPos;
};
static const SkColor gColors[] = {
SK_ColorRED, SK_ColorGREEN, SK_ColorBLUE, SK_ColorWHITE, SK_ColorBLACK
};
static const SkScalar gPos0[] = { 0, SK_Scalar1 };
static const SkScalar gPos1[] = { SK_Scalar1/4, SK_Scalar1*3/4 };
static const SkScalar gPos2[] = {
0, SK_Scalar1/8, SK_Scalar1/2, SK_Scalar1*7/8, SK_Scalar1
};
static const GradData gGradData[] = {
{ 2, gColors, NULL },
{ 2, gColors, gPos0 },
{ 2, gColors, gPos1 },
{ 5, gColors, NULL },
{ 5, gColors, gPos2 }
};
/// Ignores scale
static SkShader* MakeLinear(const SkPoint pts[2], const GradData& data,
SkShader::TileMode tm, SkUnitMapper* mapper,
float scale) {
return SkGradientShader::CreateLinear(pts, data.fColors, data.fPos,
data.fCount, tm, mapper);
}
static SkShader* MakeRadial(const SkPoint pts[2], const GradData& data,
SkShader::TileMode tm, SkUnitMapper* mapper,
float scale) {
SkPoint center;
center.set(SkScalarAve(pts[0].fX, pts[1].fX),
SkScalarAve(pts[0].fY, pts[1].fY));
return SkGradientShader::CreateRadial(center, center.fX * scale,
data.fColors,
data.fPos, data.fCount, tm, mapper);
}
/// Ignores scale
static SkShader* MakeSweep(const SkPoint pts[2], const GradData& data,
SkShader::TileMode tm, SkUnitMapper* mapper,
float scale) {
SkPoint center;
center.set(SkScalarAve(pts[0].fX, pts[1].fX),
SkScalarAve(pts[0].fY, pts[1].fY));
return SkGradientShader::CreateSweep(center.fX, center.fY, data.fColors,
data.fPos, data.fCount, mapper);
}
/// Ignores scale
static SkShader* Make2Radial(const SkPoint pts[2], const GradData& data,
SkShader::TileMode tm, SkUnitMapper* mapper,
float scale) {
SkPoint center0, center1;
center0.set(SkScalarAve(pts[0].fX, pts[1].fX),
SkScalarAve(pts[0].fY, pts[1].fY));
center1.set(SkScalarInterp(pts[0].fX, pts[1].fX, SkIntToScalar(3)/5),
SkScalarInterp(pts[0].fY, pts[1].fY, SkIntToScalar(1)/4));
return SkGradientShader::CreateTwoPointRadial(
center1, (pts[1].fX - pts[0].fX) / 7,
center0, (pts[1].fX - pts[0].fX) / 2,
data.fColors, data.fPos, data.fCount, tm, mapper);
}
/// Ignores scale
static SkShader* MakeConical(const SkPoint pts[2], const GradData& data,
SkShader::TileMode tm, SkUnitMapper* mapper,
float scale) {
SkPoint center0, center1;
center0.set(SkScalarAve(pts[0].fX, pts[1].fX),
SkScalarAve(pts[0].fY, pts[1].fY));
center1.set(SkScalarInterp(pts[0].fX, pts[1].fX, SkIntToScalar(3)/5),
SkScalarInterp(pts[0].fY, pts[1].fY, SkIntToScalar(1)/4));
return SkGradientShader::CreateTwoPointConical(center1, (pts[1].fX - pts[0].fX) / 7,
center0, (pts[1].fX - pts[0].fX) / 2,
data.fColors, data.fPos, data.fCount, tm, mapper);
}
typedef SkShader* (*GradMaker)(const SkPoint pts[2], const GradData& data,
SkShader::TileMode tm, SkUnitMapper* mapper,
float scale);
static const struct {
GradMaker fMaker;
const char* fName;
int fRepeat;
} gGrads[] = {
{ MakeLinear, "linear", 15 },
{ MakeRadial, "radial1", 10 },
{ MakeSweep, "sweep", 1 },
{ Make2Radial, "radial2", 5 },
{ MakeConical, "conical", 5 },
};
enum GradType { // these must match the order in gGrads
kLinear_GradType,
kRadial_GradType,
kSweep_GradType,
kRadial2_GradType,
kConical_GradType
};
enum GeomType {
kRect_GeomType,
kOval_GeomType
};
static const char* tilemodename(SkShader::TileMode tm) {
switch (tm) {
case SkShader::kClamp_TileMode:
return "clamp";
case SkShader::kRepeat_TileMode:
return "repeat";
case SkShader::kMirror_TileMode:
return "mirror";
default:
SkASSERT(!"unknown tilemode");
return "error";
}
}
static const char* geomtypename(GeomType gt) {
switch (gt) {
case kRect_GeomType:
return "rectangle";
case kOval_GeomType:
return "oval";
default:
SkASSERT(!"unknown geometry type");
return "error";
}
}
///////////////////////////////////////////////////////////////////////////////
class GradientBench : public SkBenchmark {
SkString fName;
SkShader* fShader;
int fCount;
enum {
W = 400,
H = 400,
N = 1
};
public:
GradientBench(void* param, GradType gradType,
SkShader::TileMode tm = SkShader::kClamp_TileMode,
GeomType geomType = kRect_GeomType,
float scale = 1.0f)
: INHERITED(param) {
fName.printf("gradient_%s_%s", gGrads[gradType].fName,
tilemodename(tm));
if (geomType != kRect_GeomType) {
fName.append("_");
fName.append(geomtypename(geomType));
}
const SkPoint pts[2] = {
{ 0, 0 },
{ SkIntToScalar(W), SkIntToScalar(H) }
};
fCount = SkBENCHLOOP(N * gGrads[gradType].fRepeat);
fShader = gGrads[gradType].fMaker(pts, gGradData[0], tm, NULL, scale);
fGeomType = geomType;
}
virtual ~GradientBench() {
fShader->unref();
}
protected:
virtual const char* onGetName() {
return fName.c_str();
}
virtual void onDraw(SkCanvas* canvas) {
SkPaint paint;
this->setupPaint(&paint);
paint.setShader(fShader);
SkRect r = { 0, 0, SkIntToScalar(W), SkIntToScalar(H) };
for (int i = 0; i < fCount; i++) {
switch (fGeomType) {
case kRect_GeomType:
canvas->drawRect(r, paint);
break;
case kOval_GeomType:
canvas->drawOval(r, paint);
break;
}
}
}
private:
typedef SkBenchmark INHERITED;
GeomType fGeomType;
};
class Gradient2Bench : public SkBenchmark {
public:
Gradient2Bench(void* param) : INHERITED(param) {}
protected:
virtual const char* onGetName() {
return "gradient_create";
}
virtual void onDraw(SkCanvas* canvas) {
SkPaint paint;
this->setupPaint(&paint);
const SkRect r = { 0, 0, SkIntToScalar(4), SkIntToScalar(4) };
const SkPoint pts[] = {
{ 0, 0 },
{ SkIntToScalar(100), SkIntToScalar(100) },
};
for (int i = 0; i < SkBENCHLOOP(1000); i++) {
const int a = i % 256;
SkColor colors[] = {
SK_ColorBLACK,
SkColorSetARGB(a, a, a, a),
SK_ColorWHITE };
SkShader* s = SkGradientShader::CreateLinear(pts, colors, NULL,
SK_ARRAY_COUNT(colors),
SkShader::kClamp_TileMode);
paint.setShader(s)->unref();
canvas->drawRect(r, paint);
}
}
private:
typedef SkBenchmark INHERITED;
};
static SkBenchmark* Fact0(void* p) { return new GradientBench(p, kLinear_GradType); }
static SkBenchmark* Fact01(void* p) { return new GradientBench(p, kLinear_GradType, SkShader::kMirror_TileMode); }
// Draw a radial gradient of radius 1/2 on a rectangle; half the lines should
// be completely pinned, the other half should pe partially pinned
static SkBenchmark* Fact1(void* p) { return new GradientBench(p, kRadial_GradType, SkShader::kClamp_TileMode, kRect_GeomType, 0.5f); }
// Draw a radial gradient on a circle of equal size; all the lines should
// hit the unpinned fast path (so long as GradientBench.W == H)
static SkBenchmark* Fact1o(void* p) { return new GradientBench(p, kRadial_GradType, SkShader::kClamp_TileMode, kOval_GeomType); }
static SkBenchmark* Fact11(void* p) { return new GradientBench(p, kRadial_GradType, SkShader::kMirror_TileMode); }
static SkBenchmark* Fact2(void* p) { return new GradientBench(p, kSweep_GradType); }
static SkBenchmark* Fact3(void* p) { return new GradientBench(p, kRadial2_GradType); }
static SkBenchmark* Fact31(void* p) { return new GradientBench(p, kRadial2_GradType, SkShader::kMirror_TileMode); }
static SkBenchmark* Fact5(void* p) { return new GradientBench(p, kConical_GradType); }
static SkBenchmark* Fact4(void* p) { return new Gradient2Bench(p); }
static BenchRegistry gReg0(Fact0);
static BenchRegistry gReg01(Fact01);
static BenchRegistry gReg1(Fact1);
static BenchRegistry gReg1o(Fact1o);
static BenchRegistry gReg11(Fact11);
static BenchRegistry gReg2(Fact2);
static BenchRegistry gReg3(Fact3);
static BenchRegistry gReg31(Fact31);
static BenchRegistry gReg5(Fact5);
static BenchRegistry gReg4(Fact4);
<|endoftext|> |
<commit_before>#ifdef VM_HAS_CSS
#include "mozart.hh"
#include <gtest/gtest.h>
#include "testutils.hh"
using namespace mozart;
class CstTest : public MozartTest {};
TEST_F(CstTest, IntVarLike) {
nativeint x = -5;
UnstableNode xNode = SmallInt::build(vm,x);
EXPECT_TRUE(IntVarLike(xNode).isIntVarLike(vm));
}
TEST_F(CstTest, Creation) {
UnstableNode mx = SmallInt::build(vm,2);
UnstableNode x = CstIntVar::build(vm,mx,mx);
EXPECT_TRUE(IntVarLike(x).isIntVarLike(vm));
}
TEST_F(CstTest, Build) {
Space *currentSpace = vm->getCurrentSpace();
GecodeSpace& cst = currentSpace->getCstSpace();
cst.dumpSpaceInformation();
}
#endif
<commit_msg>Added some tests for the IntVarLike interface<commit_after>#ifdef VM_HAS_CSS
#include "mozart.hh"
#include <climits>
#include <gtest/gtest.h>
#include "testutils.hh"
using namespace mozart;
class CstTest : public MozartTest {};
TEST_F(CstTest, IntVarLike) {
nativeint x = -5;
UnstableNode xNode = SmallInt::build(vm,x);
EXPECT_TRUE(IntVarLike(xNode).isIntVarLike(vm));
// The following test only makes sense in 64 bits architectures
// where a nativeint can store integer bigger than INT_MIN
nativeint out = INT_MIN + 1;
EXPECT_FALSE(CstIntVar::validAsElement(out));
UnstableNode outNode = SmallInt::build(vm,out);
EXPECT_FALSE(IntVarLike(outNode).isIntVarLike(vm));
EXPECT_RAISE(MOZART_STR("IntVarLike"),
CstIntVar::build(vm,outNode,outNode));
}
TEST_F(CstTest, Creation) {
UnstableNode mn = SmallInt::build(vm,2);
UnstableNode mx = SmallInt::build(vm,10);
UnstableNode x = CstIntVar::build(vm,mn,mx);
EXPECT_TRUE(IntVarLike(x).isIntVarLike(vm));
UnstableNode minNode = IntVarLike(x).min(vm);
EXPECT_EQ_INT(2,minNode);
UnstableNode maxNode = IntVarLike(x).max(vm);
EXPECT_EQ_INT(10,maxNode);
}
TEST_F(CstTest, Build) {
Space *currentSpace = vm->getCurrentSpace();
GecodeSpace& cst = currentSpace->getCstSpace();
cst.dumpSpaceInformation();
}
#endif
<|endoftext|> |
<commit_before>// Time: O(n)
// Space: O(n)
class Solution {
public:
/**
* @param expression: a vector of strings;
* @return: an integer
*/
int evaluateExpression(vector<string> &expression) {
if (expression.empty()) {
return 0;
}
vector<string> postfix;
infixToPostfix(expression, postfix);
return evaluatePostfixExpression(postfix);
}
// Evaluate Postfix Expression.
int evaluatePostfixExpression(vector<string> &postfix) {
if (postfix.empty()) {
return 0;
}
stack<string> s;
for (const auto& tok : postfix) {
if (!is_operator(tok)) {
s.emplace(tok);
} else {
int y = stoi(s.top());
s.pop();
int x = stoi(s.top());
s.pop();
if (tok[0] == '+') {
x += y;
} else if (tok[0] == '-') {
x -= y;
} else if (tok[0] == '*') {
x *= y;
} else {
x /= y;
}
s.emplace(to_string(x));
}
}
return stoi(s.top());
}
bool is_operator(const string &op) {
return op.length() == 1 && string("+-*/").find(op) != string::npos;
}
// Convert Infix to Postfix Expression.
void infixToPostfix(vector<string>& infix, vector<string>& postfix) {
stack<string> s;
for (auto tok : infix) {
// Any number would be pushed into stack.
if (atoi(tok.c_str())) {
postfix.emplace_back(tok);
} else if (tok == "(") {
s.emplace(tok);
} else if (tok == ")") {
// Meet ")", then pop until "(".
while (!s.empty()) {
tok = s.top();
s.pop();
if (tok == "(") {
break;
}
postfix.emplace_back(tok);
}
} else {
// Order of tokens in stack should be like "(-*",
// The token will be added in an strictly increasing precedence order.
while (!s.empty() && precedence(tok) <= precedence(s.top())) {
postfix.emplace_back(s.top());
s.pop();
}
s.emplace(tok);
}
}
// Pop the remaining token and add them to the postfix.
while (!s.empty()) {
postfix.emplace_back(s.top());
s.pop();
}
}
int precedence(string x) {
if (x == "(") { // The least precedence.
return 0;
} else if (x == "+" || x == "-") {
return 1;
} else if (x == "*" || x == "/") {
return 2;
}
return 3;
}
};
<commit_msg>Update expression-evaluation.cpp<commit_after>// Time: O(n)
// Space: O(n)
class Solution {
public:
/**
* @param expression: a vector of strings;
* @return: an integer
*/
int evaluateExpression(vector<string> &expression) {
if (expression.empty()) {
return 0;
}
vector<string> postfix;
infixToPostfix(expression, postfix);
return evaluatePostfixExpression(postfix);
}
// Evaluate Postfix Expression.
int evaluatePostfixExpression(vector<string> &postfix) {
if (postfix.empty()) {
return 0;
}
stack<string> s;
for (const auto& tok : postfix) {
if (!is_operator(tok)) {
s.emplace(tok);
} else {
int y = stoi(s.top());
s.pop();
int x = stoi(s.top());
s.pop();
if (tok[0] == '+') {
x += y;
} else if (tok[0] == '-') {
x -= y;
} else if (tok[0] == '*') {
x *= y;
} else {
x /= y;
}
s.emplace(to_string(x));
}
}
return stoi(s.top());
}
bool is_operator(const string &op) {
return op.length() == 1 && string("+-*/").find(op) != string::npos;
}
// Convert Infix to Postfix Expression.
void infixToPostfix(vector<string>& infix, vector<string>& postfix) {
stack<string> s;
for (auto tok : infix) {
// Any number would be pushed into stack.
if (stoi(tok)) {
postfix.emplace_back(tok);
} else if (tok == "(") {
s.emplace(tok);
} else if (tok == ")") {
// Meet ")", then pop until "(".
while (!s.empty()) {
tok = s.top();
s.pop();
if (tok == "(") {
break;
}
postfix.emplace_back(tok);
}
} else {
// Order of tokens in stack should be like "(-*",
// The token will be added in an strictly increasing precedence order.
while (!s.empty() && precedence(tok) <= precedence(s.top())) {
postfix.emplace_back(s.top());
s.pop();
}
s.emplace(tok);
}
}
// Pop the remaining token and add them to the postfix.
while (!s.empty()) {
postfix.emplace_back(s.top());
s.pop();
}
}
int precedence(string x) {
if (x == "(") { // The least precedence.
return 0;
} else if (x == "+" || x == "-") {
return 1;
} else if (x == "*" || x == "/") {
return 2;
}
return 3;
}
};
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2016, Graphics Lab, Georgia Tech Research Corporation
* Copyright (c) 2016, Humanoid Lab, Georgia Tech Research Corporation
* Copyright (c) 2016, Personal Robotics Lab, Carnegie Mellon University
* All rights reserved.
*
* This file is provided under the following "BSD-style" License:
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <gtest/gtest.h>
#include <fcl/distance.h>
#include "dart/dart.hpp"
#include "TestHelpers.hpp"
using namespace dart;
//==============================================================================
void testBasicInterface(const std::shared_ptr<CollisionDetector>& cd,
double tol = 1e-12)
{
if (cd->getType() != collision::FCLCollisionDetector::getStaticType())
{
dtwarn << "Aborting test: distance check is not supported by "
<< cd->getType() << ".\n";
return;
}
auto simpleFrame1 = Eigen::make_aligned_shared<SimpleFrame>(Frame::World());
auto simpleFrame2 = Eigen::make_aligned_shared<SimpleFrame>(Frame::World());
ShapePtr shape1(new EllipsoidShape(Eigen::Vector3d(1.0, 1.0, 1.0)));
ShapePtr shape2(new EllipsoidShape(Eigen::Vector3d(0.5, 0.5, 0.5)));
simpleFrame1->setShape(shape1);
simpleFrame2->setShape(shape2);
auto group1 = cd->createCollisionGroup(simpleFrame1.get());
auto group2 = cd->createCollisionGroup(simpleFrame2.get());
auto group12 = cd->createCollisionGroup(group1.get(), group2.get());
EXPECT_EQ(group1->getNumShapeFrames(), 1u);
EXPECT_EQ(group2->getNumShapeFrames(), 1u);
EXPECT_EQ(group12->getNumShapeFrames(), 2u);
collision::DistanceOption option;
option.enableNearestPoints = true;
EXPECT_TRUE(option.distanceFilter == nullptr);
EXPECT_TRUE(option.enableNearestPoints == true);
collision::DistanceResult result;
EXPECT_TRUE(result.found() == false);
result.clear();
simpleFrame1->setTranslation(Eigen::Vector3d(0.0, 0.0, 0.0));
simpleFrame2->setTranslation(Eigen::Vector3d(0.75, 0.0, 0.0));
group1->distance(group2.get(), option, &result);
EXPECT_DOUBLE_EQ(result.minimumDistance, 0.0);
EXPECT_TRUE(result.shapeFrame1 == simpleFrame1.get()
|| result.shapeFrame1 == simpleFrame2.get());
EXPECT_TRUE(result.shapeFrame2 == simpleFrame1.get()
|| result.shapeFrame2 == simpleFrame2.get());
EXPECT_TRUE(
result.nearestPoint1.isApprox(Eigen::Vector3d(0.5, 0.0, 0.0), tol));
EXPECT_TRUE(
result.nearestPoint2.isApprox(Eigen::Vector3d(0.5, 0.0, 0.0), tol));
EXPECT_TRUE(result.found() == true);
result.clear();
simpleFrame1->setTranslation(Eigen::Vector3d(0.0, 0.0, 0.0));
simpleFrame2->setTranslation(Eigen::Vector3d(0.75, 0.0, 0.0));
group12->distance(option, &result);
EXPECT_DOUBLE_EQ(result.minimumDistance, 0.0);
EXPECT_TRUE(result.shapeFrame1 == simpleFrame1.get()
|| result.shapeFrame1 == simpleFrame2.get());
EXPECT_TRUE(result.shapeFrame2 == simpleFrame1.get()
|| result.shapeFrame2 == simpleFrame2.get());
EXPECT_TRUE(
result.nearestPoint1.isApprox(Eigen::Vector3d(0.5, 0.0, 0.0), tol));
EXPECT_TRUE(
result.nearestPoint2.isApprox(Eigen::Vector3d(0.5, 0.0, 0.0), tol));
EXPECT_TRUE(result.found() == true);
result.clear();
simpleFrame1->setTranslation(Eigen::Vector3d(0.0, 0.0, 0.0));
simpleFrame2->setTranslation(Eigen::Vector3d(0.75, 0.0, 0.0));
cd->distance(group1.get(), group2.get(), option, &result);
EXPECT_DOUBLE_EQ(result.minimumDistance, 0.0);
EXPECT_TRUE(result.shapeFrame1 == simpleFrame1.get()
|| result.shapeFrame1 == simpleFrame2.get());
EXPECT_TRUE(result.shapeFrame2 == simpleFrame1.get()
|| result.shapeFrame2 == simpleFrame2.get());
EXPECT_TRUE(
result.nearestPoint1.isApprox(Eigen::Vector3d(0.5, 0.0, 0.0), tol));
EXPECT_TRUE(
result.nearestPoint2.isApprox(Eigen::Vector3d(0.5, 0.0, 0.0), tol));
EXPECT_TRUE(result.found() == true);
}
//==============================================================================
TEST(Distance, testBasicInterface)
{
auto fcl = FCLCollisionDetector::create();
testBasicInterface(fcl);
#if HAVE_BULLET_COLLISION
auto bullet = BulletCollisionDetector::create();
testBasicInterface(bullet);
#endif
auto dart = DARTCollisionDetector::create();
testBasicInterface(dart);
}
//==============================================================================
void testOptions(const std::shared_ptr<CollisionDetector>& cd,
double tol = 1e-12)
{
if (cd->getType() != collision::FCLCollisionDetector::getStaticType())
{
dtwarn << "Aborting test: distance check is not supported by "
<< cd->getType() << ".\n";
return;
}
auto simpleFrame1 = Eigen::make_aligned_shared<SimpleFrame>(Frame::World());
auto simpleFrame2 = Eigen::make_aligned_shared<SimpleFrame>(Frame::World());
ShapePtr shape1(new EllipsoidShape(Eigen::Vector3d(1.0, 1.0, 1.0)));
ShapePtr shape2(new EllipsoidShape(Eigen::Vector3d(0.5, 0.5, 0.5)));
simpleFrame1->setShape(shape1);
simpleFrame2->setShape(shape2);
auto group1 = cd->createCollisionGroup(simpleFrame1.get());
auto group2 = cd->createCollisionGroup(simpleFrame2.get());
auto group12 = cd->createCollisionGroup(group1.get(), group2.get());
EXPECT_EQ(group1->getNumShapeFrames(), 1u);
EXPECT_EQ(group2->getNumShapeFrames(), 1u);
EXPECT_EQ(group12->getNumShapeFrames(), 2u);
collision::DistanceOption option;
collision::DistanceResult result;
EXPECT_TRUE(option.distanceFilter == nullptr);
EXPECT_TRUE(option.enableNearestPoints == false);
EXPECT_TRUE(result.found() == false);
result.clear();
simpleFrame1->setTranslation(Eigen::Vector3d(0.0, 0.0, 0.0));
simpleFrame2->setTranslation(Eigen::Vector3d(0.75, 0.0, 0.0));
group12->distance(option, &result);
EXPECT_DOUBLE_EQ(result.minimumDistance, 0.0);
EXPECT_TRUE(result.shapeFrame1 == simpleFrame1.get()
|| result.shapeFrame1 == simpleFrame2.get());
EXPECT_TRUE(result.shapeFrame2 == simpleFrame1.get()
|| result.shapeFrame2 == simpleFrame2.get());
EXPECT_EQ(result.nearestPoint1, Eigen::Vector3d::Zero());
EXPECT_EQ(result.nearestPoint2, Eigen::Vector3d::Zero());
EXPECT_TRUE(result.found() == true);
option.enableNearestPoints = true;
result.clear();
simpleFrame1->setTranslation(Eigen::Vector3d(0.0, 0.0, 0.0));
simpleFrame2->setTranslation(Eigen::Vector3d(0.75, 0.0, 0.0));
group12->distance(option, &result);
EXPECT_DOUBLE_EQ(result.minimumDistance, 0.0);
EXPECT_TRUE(result.shapeFrame1 == simpleFrame1.get()
|| result.shapeFrame1 == simpleFrame2.get());
EXPECT_TRUE(result.shapeFrame2 == simpleFrame1.get()
|| result.shapeFrame2 == simpleFrame2.get());
EXPECT_TRUE(
result.nearestPoint1.isApprox(Eigen::Vector3d(0.5, 0.0, 0.0), tol));
EXPECT_TRUE(
result.nearestPoint2.isApprox(Eigen::Vector3d(0.5, 0.0, 0.0), tol));
EXPECT_TRUE(result.found() == true);
option.enableNearestPoints = true;
result.clear();
simpleFrame1->setTranslation(Eigen::Vector3d(0.0, 0.0, 0.0));
simpleFrame2->setTranslation(Eigen::Vector3d(1.0, 0.0, 0.0));
group12->distance(option, &result);
EXPECT_DOUBLE_EQ(result.minimumDistance, 0.25);
EXPECT_TRUE(result.shapeFrame1 == simpleFrame1.get()
|| result.shapeFrame1 == simpleFrame2.get());
EXPECT_TRUE(result.shapeFrame2 == simpleFrame1.get()
|| result.shapeFrame2 == simpleFrame2.get());
EXPECT_TRUE(
result.nearestPoint1.isApprox(Eigen::Vector3d(0.5, 0.0, 0.0), tol)
|| result.nearestPoint1.isApprox(Eigen::Vector3d(0.75, 0.0, 0.0), tol));
EXPECT_TRUE(
result.nearestPoint2.isApprox(Eigen::Vector3d(0.5, 0.0, 0.0), tol)
|| result.nearestPoint2.isApprox(Eigen::Vector3d(0.75, 0.0, 0.0), tol));
EXPECT_TRUE(result.found() == true);
}
//==============================================================================
TEST(Distance, Options)
{
auto fcl = FCLCollisionDetector::create();
testOptions(fcl);
#if HAVE_BULLET_COLLISION
auto bullet = BulletCollisionDetector::create();
testOptions(bullet);
#endif
auto dart = DARTCollisionDetector::create();
testOptions(dart);
}
//==============================================================================
void testSphereSphere(const std::shared_ptr<CollisionDetector>& cd,
double tol = 1e-12)
{
if (cd->getType() != collision::FCLCollisionDetector::getStaticType())
{
dtwarn << "Aborting test: distance check is not supported by "
<< cd->getType() << ".\n";
return;
}
auto simpleFrame1 = Eigen::make_aligned_shared<SimpleFrame>(Frame::World());
auto simpleFrame2 = Eigen::make_aligned_shared<SimpleFrame>(Frame::World());
ShapePtr shape1(new EllipsoidShape(Eigen::Vector3d(1.0, 1.0, 1.0)));
ShapePtr shape2(new EllipsoidShape(Eigen::Vector3d(0.5, 0.5, 0.5)));
simpleFrame1->setShape(shape1);
simpleFrame2->setShape(shape2);
auto group1 = cd->createCollisionGroup(simpleFrame1.get());
auto group2 = cd->createCollisionGroup(simpleFrame2.get());
auto group12 = cd->createCollisionGroup(group1.get(), group2.get());
EXPECT_EQ(group1->getNumShapeFrames(), 1u);
EXPECT_EQ(group2->getNumShapeFrames(), 1u);
EXPECT_EQ(group12->getNumShapeFrames(), 2u);
collision::DistanceOption option;
collision::DistanceResult result;
result.clear();
simpleFrame1->setTranslation(Eigen::Vector3d(0.0, 0.0, 0.0));
simpleFrame2->setTranslation(Eigen::Vector3d(0.75, 0.0, 0.0));
group12->distance(option, &result);
EXPECT_DOUBLE_EQ(result.minimumDistance, 0.0);
EXPECT_TRUE(result.shapeFrame1 == simpleFrame1.get()
|| result.shapeFrame1 == simpleFrame2.get());
EXPECT_TRUE(result.shapeFrame2 == simpleFrame1.get()
|| result.shapeFrame2 == simpleFrame2.get());
EXPECT_EQ(result.nearestPoint1, Eigen::Vector3d::Zero());
EXPECT_EQ(result.nearestPoint2, Eigen::Vector3d::Zero());
result.clear();
simpleFrame1->setTranslation(Eigen::Vector3d(0.0, 0.0, 0.0));
simpleFrame2->setTranslation(Eigen::Vector3d(1.0, 0.0, 0.0));
group12->distance(option, &result);
EXPECT_DOUBLE_EQ(result.minimumDistance, 0.25);
}
//==============================================================================
TEST(Distance, SphereSphere)
{
auto fcl = FCLCollisionDetector::create();
testSphereSphere(fcl);
#if HAVE_BULLET_COLLISION
auto bullet = BulletCollisionDetector::create();
testSphereSphere(bullet);
#endif
auto dart = DARTCollisionDetector::create();
testSphereSphere(dart);
}
//==============================================================================
void testBoxBox(const std::shared_ptr<CollisionDetector>& cd,
double tol = 1e-12)
{
if (cd->getType() != collision::FCLCollisionDetector::getStaticType())
{
dtwarn << "Aborting test: distance check is not supported by "
<< cd->getType() << ".\n";
return;
}
auto simpleFrame1 = Eigen::make_aligned_shared<SimpleFrame>(Frame::World());
auto simpleFrame2 = Eigen::make_aligned_shared<SimpleFrame>(Frame::World());
ShapePtr shape1(new BoxShape(Eigen::Vector3d(1.0, 1.0, 1.0)));
ShapePtr shape2(new BoxShape(Eigen::Vector3d(0.5, 0.5, 0.5)));
simpleFrame1->setShape(shape1);
simpleFrame2->setShape(shape2);
Eigen::Vector3d pos1 = Eigen::Vector3d(0.0, 0.0, 0.0);
Eigen::Vector3d pos2 = Eigen::Vector3d(0.0, 0.0, 0.0);
simpleFrame1->setTranslation(pos1);
simpleFrame2->setTranslation(pos2);
auto group1 = cd->createCollisionGroup(simpleFrame1.get());
auto group2 = cd->createCollisionGroup(simpleFrame2.get());
EXPECT_EQ(group1->getNumShapeFrames(), 1u);
EXPECT_EQ(group2->getNumShapeFrames(), 1u);
collision::DistanceOption option;
collision::DistanceResult result;
// EXPECT_TRUE(group1->distance(group2.get(), option, &result));
Eigen::Vector3d min = Eigen::Vector3d(-0.25, 0.25, 0.0);
Eigen::Vector3d max = Eigen::Vector3d(0.25, 0.5, 0.0);
}
//==============================================================================
TEST(Distance, BoxBox)
{
auto fcl = FCLCollisionDetector::create();
testBoxBox(fcl);
#if HAVE_BULLET_COLLISION
auto bullet = BulletCollisionDetector::create();
testBoxBox(bullet);
#endif
auto dart = DARTCollisionDetector::create();
testBoxBox(dart);
}
//==============================================================================
int main(int argc, char* argv[])
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<commit_msg>Remove incomplete tests<commit_after>/*
* Copyright (c) 2016, Graphics Lab, Georgia Tech Research Corporation
* Copyright (c) 2016, Humanoid Lab, Georgia Tech Research Corporation
* Copyright (c) 2016, Personal Robotics Lab, Carnegie Mellon University
* All rights reserved.
*
* This file is provided under the following "BSD-style" License:
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <gtest/gtest.h>
#include <fcl/distance.h>
#include "dart/dart.hpp"
#include "TestHelpers.hpp"
using namespace dart;
//==============================================================================
void testBasicInterface(const std::shared_ptr<CollisionDetector>& cd,
double tol = 1e-12)
{
if (cd->getType() != collision::FCLCollisionDetector::getStaticType())
{
dtwarn << "Aborting test: distance check is not supported by "
<< cd->getType() << ".\n";
return;
}
auto simpleFrame1 = Eigen::make_aligned_shared<SimpleFrame>(Frame::World());
auto simpleFrame2 = Eigen::make_aligned_shared<SimpleFrame>(Frame::World());
ShapePtr shape1(new EllipsoidShape(Eigen::Vector3d(1.0, 1.0, 1.0)));
ShapePtr shape2(new EllipsoidShape(Eigen::Vector3d(0.5, 0.5, 0.5)));
simpleFrame1->setShape(shape1);
simpleFrame2->setShape(shape2);
auto group1 = cd->createCollisionGroup(simpleFrame1.get());
auto group2 = cd->createCollisionGroup(simpleFrame2.get());
auto group12 = cd->createCollisionGroup(group1.get(), group2.get());
EXPECT_EQ(group1->getNumShapeFrames(), 1u);
EXPECT_EQ(group2->getNumShapeFrames(), 1u);
EXPECT_EQ(group12->getNumShapeFrames(), 2u);
collision::DistanceOption option;
option.enableNearestPoints = true;
EXPECT_TRUE(option.distanceFilter == nullptr);
EXPECT_TRUE(option.enableNearestPoints == true);
collision::DistanceResult result;
EXPECT_TRUE(result.found() == false);
result.clear();
simpleFrame1->setTranslation(Eigen::Vector3d(0.0, 0.0, 0.0));
simpleFrame2->setTranslation(Eigen::Vector3d(0.75, 0.0, 0.0));
group1->distance(group2.get(), option, &result);
EXPECT_DOUBLE_EQ(result.minimumDistance, 0.0);
EXPECT_TRUE(result.shapeFrame1 == simpleFrame1.get()
|| result.shapeFrame1 == simpleFrame2.get());
EXPECT_TRUE(result.shapeFrame2 == simpleFrame1.get()
|| result.shapeFrame2 == simpleFrame2.get());
EXPECT_TRUE(
result.nearestPoint1.isApprox(Eigen::Vector3d(0.5, 0.0, 0.0), tol));
EXPECT_TRUE(
result.nearestPoint2.isApprox(Eigen::Vector3d(0.5, 0.0, 0.0), tol));
EXPECT_TRUE(result.found() == true);
result.clear();
simpleFrame1->setTranslation(Eigen::Vector3d(0.0, 0.0, 0.0));
simpleFrame2->setTranslation(Eigen::Vector3d(0.75, 0.0, 0.0));
group12->distance(option, &result);
EXPECT_DOUBLE_EQ(result.minimumDistance, 0.0);
EXPECT_TRUE(result.shapeFrame1 == simpleFrame1.get()
|| result.shapeFrame1 == simpleFrame2.get());
EXPECT_TRUE(result.shapeFrame2 == simpleFrame1.get()
|| result.shapeFrame2 == simpleFrame2.get());
EXPECT_TRUE(
result.nearestPoint1.isApprox(Eigen::Vector3d(0.5, 0.0, 0.0), tol));
EXPECT_TRUE(
result.nearestPoint2.isApprox(Eigen::Vector3d(0.5, 0.0, 0.0), tol));
EXPECT_TRUE(result.found() == true);
result.clear();
simpleFrame1->setTranslation(Eigen::Vector3d(0.0, 0.0, 0.0));
simpleFrame2->setTranslation(Eigen::Vector3d(0.75, 0.0, 0.0));
cd->distance(group1.get(), group2.get(), option, &result);
EXPECT_DOUBLE_EQ(result.minimumDistance, 0.0);
EXPECT_TRUE(result.shapeFrame1 == simpleFrame1.get()
|| result.shapeFrame1 == simpleFrame2.get());
EXPECT_TRUE(result.shapeFrame2 == simpleFrame1.get()
|| result.shapeFrame2 == simpleFrame2.get());
EXPECT_TRUE(
result.nearestPoint1.isApprox(Eigen::Vector3d(0.5, 0.0, 0.0), tol));
EXPECT_TRUE(
result.nearestPoint2.isApprox(Eigen::Vector3d(0.5, 0.0, 0.0), tol));
EXPECT_TRUE(result.found() == true);
}
//==============================================================================
TEST(Distance, testBasicInterface)
{
auto fcl = FCLCollisionDetector::create();
testBasicInterface(fcl);
#if HAVE_BULLET_COLLISION
auto bullet = BulletCollisionDetector::create();
testBasicInterface(bullet);
#endif
auto dart = DARTCollisionDetector::create();
testBasicInterface(dart);
}
//==============================================================================
void testOptions(const std::shared_ptr<CollisionDetector>& cd,
double tol = 1e-12)
{
if (cd->getType() != collision::FCLCollisionDetector::getStaticType())
{
dtwarn << "Aborting test: distance check is not supported by "
<< cd->getType() << ".\n";
return;
}
auto simpleFrame1 = Eigen::make_aligned_shared<SimpleFrame>(Frame::World());
auto simpleFrame2 = Eigen::make_aligned_shared<SimpleFrame>(Frame::World());
ShapePtr shape1(new EllipsoidShape(Eigen::Vector3d(1.0, 1.0, 1.0)));
ShapePtr shape2(new EllipsoidShape(Eigen::Vector3d(0.5, 0.5, 0.5)));
simpleFrame1->setShape(shape1);
simpleFrame2->setShape(shape2);
auto group1 = cd->createCollisionGroup(simpleFrame1.get());
auto group2 = cd->createCollisionGroup(simpleFrame2.get());
auto group12 = cd->createCollisionGroup(group1.get(), group2.get());
EXPECT_EQ(group1->getNumShapeFrames(), 1u);
EXPECT_EQ(group2->getNumShapeFrames(), 1u);
EXPECT_EQ(group12->getNumShapeFrames(), 2u);
collision::DistanceOption option;
collision::DistanceResult result;
EXPECT_TRUE(option.distanceFilter == nullptr);
EXPECT_TRUE(option.enableNearestPoints == false);
EXPECT_TRUE(result.found() == false);
result.clear();
simpleFrame1->setTranslation(Eigen::Vector3d(0.0, 0.0, 0.0));
simpleFrame2->setTranslation(Eigen::Vector3d(0.75, 0.0, 0.0));
group12->distance(option, &result);
EXPECT_DOUBLE_EQ(result.minimumDistance, 0.0);
EXPECT_TRUE(result.shapeFrame1 == simpleFrame1.get()
|| result.shapeFrame1 == simpleFrame2.get());
EXPECT_TRUE(result.shapeFrame2 == simpleFrame1.get()
|| result.shapeFrame2 == simpleFrame2.get());
EXPECT_EQ(result.nearestPoint1, Eigen::Vector3d::Zero());
EXPECT_EQ(result.nearestPoint2, Eigen::Vector3d::Zero());
EXPECT_TRUE(result.found() == true);
option.enableNearestPoints = true;
result.clear();
simpleFrame1->setTranslation(Eigen::Vector3d(0.0, 0.0, 0.0));
simpleFrame2->setTranslation(Eigen::Vector3d(0.75, 0.0, 0.0));
group12->distance(option, &result);
EXPECT_DOUBLE_EQ(result.minimumDistance, 0.0);
EXPECT_TRUE(result.shapeFrame1 == simpleFrame1.get()
|| result.shapeFrame1 == simpleFrame2.get());
EXPECT_TRUE(result.shapeFrame2 == simpleFrame1.get()
|| result.shapeFrame2 == simpleFrame2.get());
EXPECT_TRUE(
result.nearestPoint1.isApprox(Eigen::Vector3d(0.5, 0.0, 0.0), tol));
EXPECT_TRUE(
result.nearestPoint2.isApprox(Eigen::Vector3d(0.5, 0.0, 0.0), tol));
EXPECT_TRUE(result.found() == true);
option.enableNearestPoints = true;
result.clear();
simpleFrame1->setTranslation(Eigen::Vector3d(0.0, 0.0, 0.0));
simpleFrame2->setTranslation(Eigen::Vector3d(1.0, 0.0, 0.0));
group12->distance(option, &result);
EXPECT_DOUBLE_EQ(result.minimumDistance, 0.25);
EXPECT_TRUE(result.shapeFrame1 == simpleFrame1.get()
|| result.shapeFrame1 == simpleFrame2.get());
EXPECT_TRUE(result.shapeFrame2 == simpleFrame1.get()
|| result.shapeFrame2 == simpleFrame2.get());
EXPECT_TRUE(
result.nearestPoint1.isApprox(Eigen::Vector3d(0.5, 0.0, 0.0), tol)
|| result.nearestPoint1.isApprox(Eigen::Vector3d(0.75, 0.0, 0.0), tol));
EXPECT_TRUE(
result.nearestPoint2.isApprox(Eigen::Vector3d(0.5, 0.0, 0.0), tol)
|| result.nearestPoint2.isApprox(Eigen::Vector3d(0.75, 0.0, 0.0), tol));
EXPECT_TRUE(result.found() == true);
}
//==============================================================================
TEST(Distance, Options)
{
auto fcl = FCLCollisionDetector::create();
testOptions(fcl);
#if HAVE_BULLET_COLLISION
auto bullet = BulletCollisionDetector::create();
testOptions(bullet);
#endif
auto dart = DARTCollisionDetector::create();
testOptions(dart);
}
//==============================================================================
void testSphereSphere(const std::shared_ptr<CollisionDetector>& cd,
double tol = 1e-12)
{
if (cd->getType() != collision::FCLCollisionDetector::getStaticType())
{
dtwarn << "Aborting test: distance check is not supported by "
<< cd->getType() << ".\n";
return;
}
auto simpleFrame1 = Eigen::make_aligned_shared<SimpleFrame>(Frame::World());
auto simpleFrame2 = Eigen::make_aligned_shared<SimpleFrame>(Frame::World());
ShapePtr shape1(new EllipsoidShape(Eigen::Vector3d(1.0, 1.0, 1.0)));
ShapePtr shape2(new EllipsoidShape(Eigen::Vector3d(0.5, 0.5, 0.5)));
simpleFrame1->setShape(shape1);
simpleFrame2->setShape(shape2);
auto group1 = cd->createCollisionGroup(simpleFrame1.get());
auto group2 = cd->createCollisionGroup(simpleFrame2.get());
auto group12 = cd->createCollisionGroup(group1.get(), group2.get());
EXPECT_EQ(group1->getNumShapeFrames(), 1u);
EXPECT_EQ(group2->getNumShapeFrames(), 1u);
EXPECT_EQ(group12->getNumShapeFrames(), 2u);
collision::DistanceOption option;
collision::DistanceResult result;
result.clear();
simpleFrame1->setTranslation(Eigen::Vector3d(0.0, 0.0, 0.0));
simpleFrame2->setTranslation(Eigen::Vector3d(0.75, 0.0, 0.0));
group12->distance(option, &result);
EXPECT_DOUBLE_EQ(result.minimumDistance, 0.0);
EXPECT_TRUE(result.shapeFrame1 == simpleFrame1.get()
|| result.shapeFrame1 == simpleFrame2.get());
EXPECT_TRUE(result.shapeFrame2 == simpleFrame1.get()
|| result.shapeFrame2 == simpleFrame2.get());
EXPECT_TRUE(result.nearestPoint1.isApprox(Eigen::Vector3d::Zero(), tol));
EXPECT_TRUE(result.nearestPoint2.isApprox(Eigen::Vector3d::Zero(), tol));
}
//==============================================================================
TEST(Distance, SphereSphere)
{
auto fcl = FCLCollisionDetector::create();
testSphereSphere(fcl);
#if HAVE_BULLET_COLLISION
auto bullet = BulletCollisionDetector::create();
testSphereSphere(bullet);
#endif
auto dart = DARTCollisionDetector::create();
testSphereSphere(dart);
}
//==============================================================================
int main(int argc, char* argv[])
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<|endoftext|> |
<commit_before>//=============================================================================
// ■ map.cpp
//-----------------------------------------------------------------------------
// 地图类
//=============================================================================
#include "tiled_map.hpp"
#include "glm/gtc/noise.hpp"
namespace VM76 {
DataMap::DataMap(int w, int h, int l) {
constStone = {1, 0};
map = (TileData*) malloc(sizeof(TileData) * w * h * l);
width = w; length = l; height = h;
if (!read_map()) generate_V1();
}
void DataMap::generate_flat() {
for (int x = 0; x < width; x++)
for (int z = 0; z < length; z++)
for (int y = 0; y < height; y++) {
TileData t = map[calcIndex(x,y,z)];
t.tid = (y == 0) ? Grass : Air;
}
}
bool DataMap::read_map() {
log("Reading map");
VBinaryFileReader* fr = new VBinaryFileReader("map.dat");
if (!fr->f) return false;
int map_version = fr->read_i32();
if (fr->read_u8() == 'V' && fr->read_u8() == 'M'
&& fr->read_u8() == '7' && fr->read_u8() == '6') {
log("Map version : %d", map_version);
for (int x = 0; x < width * length * height; x++) {
if (x % (width * length * height / 7) == 0)
log("Map %d%% loaded", 100 * x / (width * length * height));
map[x].tid = fr->read_u8();
map[x].data_flag = fr->read_u8();
}
return true;
} else {
log("Invalid map.dat");
return false;
}
}
void DataMap::save_map() {
VBinaryFileWriter* fw = new VBinaryFileWriter("map.dat");
// 版本号
fw->write_i32(100);
// 文件头标识
fw->write_u8('V');
fw->write_u8('M');
fw->write_u8('7');
fw->write_u8('6');
for (int x = 0; x < width * length * height; x++) {
fw->write_u8(map[x].tid);
fw->write_u8(map[x].data_flag);
}
delete fw;
log("Map saved");
}
void DataMap::generate_V1() {
log("Start generating maps, %d x %d x %d", width, length, height);
for (int i = 0; i < width; i ++) {
if (i % (width / 12) == 0)
log("Generated %d%% (%d / %d)",
(int) (100.0 / width * i),
i * length * height, width * length * height
);
for (int j = 0; j < length; j++) {
glm::vec2 pos = glm::vec2(i, j) * 0.001f;
float hm = glm::perlin(pos);
pos = pos * 1.3f; hm += glm::perlin(pos) * 0.8;
hm = hm * hm;
pos = pos * 1.8f; float n = glm::perlin(pos) * (hm * 0.5 + 0.5);
pos = pos * 1.5f + glm::vec2(0.1f, 0.13f); n += glm::perlin(pos) * 0.85f * (hm * 0.5 + 0.5);
pos = pos * 2.1f + glm::vec2(0.1f, 0.13f); n += sin(glm::perlin(pos) * VMath::PIf * 0.5) * 0.65f * hm;
pos = pos * 2.2f + glm::vec2(0.1f, 0.13f); n += glm::perlin(pos) * 0.35f;
pos = pos * 2.6f + glm::vec2(0.15f, 0.1f); n += glm::perlin(pos) * 0.18f;
pos = pos * 1.9f + glm::vec2(0.2f);
n += sin(glm::perlin(pos) * VMath::PIf * 0.5) * 0.1f;
n = glm::clamp(1.0f / (float) TERRIAN_MAX_HEIGHT, n * 0.5f + 0.5f, 1.0f);
int h = n * TERRIAN_MAX_HEIGHT;
int ho = h;
h = glm::clamp(0, h, height);
for (int y = 0; y < h; y++) {
map[calcIndex(i,y,j)].tid = (y == ho - 1) ? Grass : Stone;
}
for (int y = h; y < height; y++) {
map[calcIndex(i,y,j)].tid = Air;
}
}
}
log("Generated 100%%, Complete");
}
Map::Map(int w, int h, int l, int csize) {
log("Init map with size %d, %d, %d in chunk size %d", w, l, h, csize);
CHUNK_SIZE = csize;
width = w; length = l; height = h;
bw = CHUNK_SIZE * w; bl = CHUNK_SIZE * l; bh = CHUNK_SIZE * h;
chunks = new TiledMap*[w * l * h];
map = new DataMap(bw, bh, bl);
for (int x = 0; x < length; x++) {
log("Baking Chunks: %d%% (%d / %d)",
(int) (100.0 / length * x),
x * width * height, width * length * height
);
for (int z = 0; z < width; z++)
for (int y = 0; y < height; y++) {
int ind = calcChunkIndex(x,y,z);
chunks[ind] = new TiledMap(
CHUNK_SIZE, CHUNK_SIZE, CHUNK_SIZE,
glm::vec3(CHUNK_SIZE * x, CHUNK_SIZE * y, CHUNK_SIZE * z),
map
);
chunks[ind]->bake_tiles();
}
}
log("Baking Chunks: 100%%, map initialized");
}
void Map::place_block(glm::vec3 dir, int tid) {
int cx = (int) dir.x / CHUNK_SIZE;
int cy = (int) dir.y / CHUNK_SIZE;
int cz = (int) dir.z / CHUNK_SIZE;
map->map[map->calcIndex(dir)].tid = tid;
chunks[calcChunkIndex(cx,cy,cz)]->bake_tiles();
}
void Map::render() {
for (int x = 0; x < width * length * height; x++)
chunks[x]->render();
}
Map::~Map() {
for (int x = 0; x < width * length * height; x++) {
VMDE_Dispose(delete, chunks[x]);
}
XE(delete[], chunks);
log("Saving map");
map->save_map();
}
}
<commit_msg>改进地图生成->变成火星地形生成器了<commit_after>//=============================================================================
// ■ map.cpp
//-----------------------------------------------------------------------------
// 地图类
//=============================================================================
#include "tiled_map.hpp"
#include "glm/gtc/noise.hpp"
namespace VM76 {
DataMap::DataMap(int w, int h, int l) {
constStone = {1, 0};
map = (TileData*) malloc(sizeof(TileData) * w * h * l);
width = w; length = l; height = h;
if (!read_map()) generate_V1();
}
void DataMap::generate_flat() {
for (int x = 0; x < width; x++)
for (int z = 0; z < length; z++)
for (int y = 0; y < height; y++) {
TileData t = map[calcIndex(x,y,z)];
t.tid = (y == 0) ? Grass : Air;
}
}
bool DataMap::read_map() {
log("Reading map");
VBinaryFileReader* fr = new VBinaryFileReader("map.dat");
if (!fr->f) return false;
int map_version = fr->read_i32();
if (fr->read_u8() == 'V' && fr->read_u8() == 'M'
&& fr->read_u8() == '7' && fr->read_u8() == '6') {
log("Map version : %d", map_version);
for (int x = 0; x < width * length * height; x++) {
if (x % (width * length * height / 7) == 0)
log("Map %d%% loaded", 100 * x / (width * length * height));
map[x].tid = fr->read_u8();
map[x].data_flag = fr->read_u8();
}
return true;
} else {
log("Invalid map.dat");
return false;
}
}
void DataMap::save_map() {
VBinaryFileWriter* fw = new VBinaryFileWriter("map.dat");
// 版本号
fw->write_i32(100);
// 文件头标识
fw->write_u8('V');
fw->write_u8('M');
fw->write_u8('7');
fw->write_u8('6');
for (int x = 0; x < width * length * height; x++) {
fw->write_u8(map[x].tid);
fw->write_u8(map[x].data_flag);
}
delete fw;
log("Map saved");
}
void DataMap::generate_V1() {
log("Start generating maps, %d x %d x %d", width, length, height);
const glm::mat2 rotate2D = glm::mat2(1.3623, 1.7531, -1.7131, 1.4623);
for (int i = 0; i < width; i ++) {
if (i % (width / 12) == 0)
log("Generated %d%% (%d / %d)",
(int) (100.0 / width * i),
i * length * height, width * length * height
);
for (int j = 0; j < length; j++) {
glm::vec2 pos = glm::vec2(i, j) * 0.00001f;
float ww = glm::perlin(pos * 0.1f) + glm::perlin(-pos * 0.1f);
ww = ww * ww * 0.5f + 0.5f;
ww *= 2.0f;
float w = 1.0;
float n = .0f;
for (int i = 0; i < 5; i++) {
glm::vec2 xp = pos + ww * w * glm::perlin(pos);
glm::vec2 wv = 1.0f - glm::abs(glm::sin(xp));
glm::vec2 swv = glm::abs(glm::cos(xp));
wv = glm::mix(wv, swv, wv);
n += glm::pow(1.0 - glm::pow(wv.x * wv.y, 0.75), 2.0 * w);
w *= 0.85f;
pos = rotate2D * pos * 3.2f;
pos -= glm::vec2(0.4f, 0.8f) * (float) i;
}
pos = glm::vec2(i, j) * -0.00001f; w = 1.0;
for (int i = 0; i < 3; i++) {
n += w * glm::simplex(pos);
w *= -0.65f;
pos = rotate2D * pos * 3.2f;
}
n *= 0.5f;
n = glm::pow(n, 1.0 + ww);
n = glm::clamp(n * 0.7f + 0.2f, 1.0f / (float) TERRIAN_MAX_HEIGHT, 1.0f);
int h = n * TERRIAN_MAX_HEIGHT;
int ho = h;
h = glm::clamp(0, h, height);
for (int y = 0; y < h; y++) {
map[calcIndex(i,y,j)].tid = (y == ho - 1) ? Grass : Stone;
}
for (int y = h; y < height; y++) {
map[calcIndex(i,y,j)].tid = Air;
}
}
}
log("Generated 100%%, Complete");
}
Map::Map(int w, int h, int l, int csize) {
log("Init map with size %d, %d, %d in chunk size %d", w, l, h, csize);
CHUNK_SIZE = csize;
width = w; length = l; height = h;
bw = CHUNK_SIZE * w; bl = CHUNK_SIZE * l; bh = CHUNK_SIZE * h;
chunks = new TiledMap*[w * l * h];
map = new DataMap(bw, bh, bl);
for (int x = 0; x < length; x++) {
log("Baking Chunks: %d%% (%d / %d)",
(int) (100.0 / length * x),
x * width * height, width * length * height
);
for (int z = 0; z < width; z++)
for (int y = 0; y < height; y++) {
int ind = calcChunkIndex(x,y,z);
chunks[ind] = new TiledMap(
CHUNK_SIZE, CHUNK_SIZE, CHUNK_SIZE,
glm::vec3(CHUNK_SIZE * x, CHUNK_SIZE * y, CHUNK_SIZE * z),
map
);
chunks[ind]->bake_tiles();
}
}
log("Baking Chunks: 100%%, map initialized");
}
void Map::place_block(glm::vec3 dir, int tid) {
int cx = (int) dir.x / CHUNK_SIZE;
int cy = (int) dir.y / CHUNK_SIZE;
int cz = (int) dir.z / CHUNK_SIZE;
map->map[map->calcIndex(dir)].tid = tid;
chunks[calcChunkIndex(cx,cy,cz)]->bake_tiles();
}
void Map::render() {
for (int x = 0; x < width * length * height; x++)
chunks[x]->render();
}
Map::~Map() {
for (int x = 0; x < width * length * height; x++) {
VMDE_Dispose(delete, chunks[x]);
}
XE(delete[], chunks);
log("Saving map");
map->save_map();
}
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkPipelineGraphSource.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkAbstractArray.h"
#include "vtkAlgorithmOutput.h"
#include "vtkAnnotationLink.h"
#include "vtkArrayData.h"
#include "vtkCollection.h"
#include "vtkDataRepresentation.h"
#include "vtkDataSetAttributes.h"
#include "vtkEdgeListIterator.h"
#include "vtkGraph.h"
#include "vtkGraph.h"
#include "vtkInformation.h"
#include "vtkMutableDirectedGraph.h"
#include "vtkObjectFactory.h"
#include "vtkPipelineGraphSource.h"
#include "vtkSmartPointer.h"
#include "vtkStringArray.h"
#include "vtkTable.h"
#include "vtkTree.h"
#include "vtkVariantArray.h"
#include "vtkView.h"
#include <boost/algorithm/string.hpp>
#include <vtksys/stl/map>
#include <vtksys/stl/stack>
#include <vtksys/ios/sstream>
using vtksys_stl::map;
using vtksys_stl::stack;
using vtksys_ios::ostringstream;
#define VTK_CREATE(type, name) \
vtkSmartPointer<type> name = vtkSmartPointer<type>::New()
vtkCxxRevisionMacro(vtkPipelineGraphSource, "1.2");
vtkStandardNewMacro(vtkPipelineGraphSource);
// ----------------------------------------------------------------------
vtkPipelineGraphSource::vtkPipelineGraphSource()
{
this->SetNumberOfInputPorts(0);
this->SetNumberOfOutputPorts(1);
this->Sinks = vtkCollection::New();
}
// ----------------------------------------------------------------------
vtkPipelineGraphSource::~vtkPipelineGraphSource()
{
if (this->Sinks)
{
this->Sinks->Delete();
this->Sinks = NULL;
}
}
// ----------------------------------------------------------------------
void vtkPipelineGraphSource::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
}
// ----------------------------------------------------------------------
void vtkPipelineGraphSource::AddSink(vtkObject* sink)
{
if (sink != NULL && !this->Sinks->IsItemPresent(sink))
{
this->Sinks->AddItem(sink);
this->Modified();
}
}
void vtkPipelineGraphSource::RemoveSink(vtkObject* sink)
{
if (sink != NULL && this->Sinks->IsItemPresent(sink))
{
this->Sinks->RemoveItem(sink);
this->Modified();
}
}
// ----------------------------------------------------------------------
static void InsertObject(
vtkObject* object,
map<vtkObject*, vtkIdType>& object_map,
vtkMutableDirectedGraph* builder,
vtkStringArray* vertex_class_name_array,
vtkVariantArray* vertex_object_array,
vtkStringArray* edge_class_name_array,
vtkVariantArray* edge_object_array)
{
if(!object)
return;
if(object_map.count(object))
return;
// Insert pipeline algorithms ...
if(vtkAlgorithm* const algorithm = vtkAlgorithm::SafeDownCast(object))
{
object_map[algorithm] = builder->AddVertex();
vertex_class_name_array->InsertNextValue(algorithm->GetClassName());
vertex_object_array->InsertNextValue(algorithm);
// Recursively insert algorithm inputs ...
for(int i = 0; i != algorithm->GetNumberOfInputPorts(); ++i)
{
for(int j = 0; j != algorithm->GetNumberOfInputConnections(i); ++j)
{
vtkAlgorithm* const input_algorithm = algorithm->GetInputConnection(i, j)->GetProducer();
InsertObject(input_algorithm, object_map, builder, vertex_class_name_array, vertex_object_array, edge_class_name_array, edge_object_array);
builder->AddEdge(object_map[input_algorithm], object_map[algorithm]);
vtkDataObject* input_data = input_algorithm->GetOutputDataObject(algorithm->GetInputConnection(i, j)->GetIndex());
edge_class_name_array->InsertNextValue(input_data ? input_data->GetClassName() : "");
edge_object_array->InsertNextValue(input_data);
}
}
// Special-case: if this is a representation, insert its annotation link ...
if(vtkDataRepresentation* const data_representation = vtkDataRepresentation::SafeDownCast(algorithm))
{
if(vtkAnnotationLink* const annotation_link = data_representation->GetAnnotationLink())
{
InsertObject(annotation_link, object_map, builder, vertex_class_name_array, vertex_object_array, edge_class_name_array, edge_object_array);
builder->AddEdge(object_map[annotation_link], object_map[algorithm]);
edge_class_name_array->InsertNextValue("vtkAnnotationLayers");
edge_object_array->InsertNextValue(annotation_link->GetOutput());
}
}
}
// Insert pipeline views ...
else if(vtkView* const view = vtkView::SafeDownCast(object))
{
object_map[view] = builder->AddVertex();
vertex_class_name_array->InsertNextValue(view->GetClassName());
vertex_object_array->InsertNextValue(view);
// Recursively insert view inputs ...
for(int i = 0; i != view->GetNumberOfRepresentations(); ++i)
{
vtkDataRepresentation* const input_representation = view->GetRepresentation(i);
InsertObject(input_representation, object_map, builder, vertex_class_name_array, vertex_object_array, edge_class_name_array, edge_object_array);
builder->AddEdge(object_map[input_representation], object_map[view]);
edge_class_name_array->InsertNextValue("");
edge_object_array->InsertNextValue(0);
}
}
}
int vtkPipelineGraphSource::RequestData(
vtkInformation*,
vtkInformationVector**,
vtkInformationVector* outputVector)
{
// Setup the graph data structure ...
VTK_CREATE(vtkMutableDirectedGraph, builder);
vtkStringArray* vertex_class_name_array = vtkStringArray::New();
vertex_class_name_array->SetName("class_name");
builder->GetVertexData()->AddArray(vertex_class_name_array);
vertex_class_name_array->Delete();
vtkVariantArray* vertex_object_array = vtkVariantArray::New();
vertex_object_array->SetName("object");
builder->GetVertexData()->AddArray(vertex_object_array);
vertex_object_array->Delete();
vtkStringArray* edge_class_name_array = vtkStringArray::New();
edge_class_name_array->SetName("class_name");
builder->GetEdgeData()->AddArray(edge_class_name_array);
edge_class_name_array->Delete();
vtkVariantArray* edge_object_array = vtkVariantArray::New();
edge_object_array->SetName("object");
builder->GetEdgeData()->AddArray(edge_object_array);
edge_object_array->Delete();
// Recursively insert pipeline components into the graph ...
map<vtkObject*, vtkIdType> object_map;
for(vtkIdType i = 0; i != this->Sinks->GetNumberOfItems(); ++i)
{
InsertObject(this->Sinks->GetItemAsObject(i), object_map, builder, vertex_class_name_array, vertex_object_array, edge_class_name_array, edge_object_array);
}
// Finish creating the output graph ...
vtkDirectedGraph* const output_graph = vtkDirectedGraph::GetData(outputVector);
if(!output_graph->CheckedShallowCopy(builder))
{
vtkErrorMacro(<<"Invalid graph structure");
return 0;
}
return 1;
}
void vtkPipelineGraphSource::PipelineToDot(vtkAlgorithm* sink, ostream& output, const vtkStdString& graph_name)
{
vtkSmartPointer<vtkCollection> sinks = vtkSmartPointer<vtkCollection>::New();
sinks->AddItem(sink);
PipelineToDot(sinks, output, graph_name);
}
void vtkPipelineGraphSource::PipelineToDot(vtkCollection* sinks, ostream& output, const vtkStdString& graph_name)
{
// Create a graph representation of the pipeline ...
vtkSmartPointer<vtkPipelineGraphSource> pipeline = vtkSmartPointer<vtkPipelineGraphSource>::New();
for(vtkIdType i = 0; i != sinks->GetNumberOfItems(); ++i)
{
pipeline->AddSink(sinks->GetItemAsObject(i));
}
pipeline->Update();
vtkGraph* const pipeline_graph = pipeline->GetOutput();
vtkAbstractArray* const vertex_object_array = pipeline_graph->GetVertexData()->GetAbstractArray("object");
vtkAbstractArray* const edge_object_array = pipeline_graph->GetEdgeData()->GetAbstractArray("object");
output << "digraph \"" << graph_name << "\"\n";
output << "{\n";
// Do some standard formatting ...
output << " node [ fontname=\"helvetica\" fontsize=\"10\" shape=\"record\" style=\"filled\" ]\n";
output << " edge [ fontname=\"helvetica\" fontsize=\"9\" ]\n\n";
// Write-out vertices ...
for(vtkIdType i = 0; i != pipeline_graph->GetNumberOfVertices(); ++i)
{
vtkObjectBase* const object = vertex_object_array->GetVariantValue(i).ToVTKObject();
vtkstd::stringstream buffer;
object->PrintSelf(buffer, vtkIndent());
vtkstd::string line;
vtkstd::string object_state;
for(vtkstd::getline(buffer, line); buffer; vtkstd::getline(buffer, line))
{
boost::algorithm::replace_all(line, "\"", "'");
boost::algorithm::replace_all(line, "\r", "");
boost::algorithm::replace_all(line, "\n", "");
if(0 == line.find("Debug:"))
continue;
if(0 == line.find("Modified Time:"))
continue;
if(0 == line.find("Reference Count:"))
continue;
if(0 == line.find("Registered Events:"))
continue;
if(0 == line.find("Executive:"))
continue;
if(0 == line.find("ErrorCode:"))
continue;
if(0 == line.find("Information:"))
continue;
if(0 == line.find("AbortExecute:"))
continue;
if(0 == line.find("Progress:"))
continue;
if(0 == line.find("Progress Text:"))
continue;
if(0 == line.find(" "))
continue;
object_state += line + "\\n";
}
vtkstd::string fillcolor = "#ccffcc";
if(vtkView::SafeDownCast(object))
{
fillcolor = "#ffffcc";
}
else if(vtkAnnotationLink::SafeDownCast(object))
{
fillcolor = "#ccccff";
}
output << " " << "node_" << object << " [ fillcolor=\"" << fillcolor << "\" label=\"{" << object->GetClassName() << "|" << object_state << "}\" vtk_class_name=\"" << object->GetClassName() << "\" ]\n";
}
// Write-out edges ...
vtkSmartPointer<vtkEdgeListIterator> edges = vtkSmartPointer<vtkEdgeListIterator>::New();
edges->SetGraph(pipeline_graph);
while(edges->HasNext())
{
vtkEdgeType edge = edges->Next();
vtkObjectBase* const source = vertex_object_array->GetVariantValue(edge.Source).ToVTKObject();
vtkObjectBase* const target = vertex_object_array->GetVariantValue(edge.Target).ToVTKObject();
vtkObjectBase* const object = edge_object_array->GetVariantValue(edge.Id).ToVTKObject();
vtkstd::string color = "black";
if(vtkTree::SafeDownCast(object))
{
color = "#00bb00";
}
else if(vtkTable::SafeDownCast(object))
{
color = "blue";
}
else if(vtkArrayData* const array_data = vtkArrayData::SafeDownCast(object))
{
if(array_data->GetNumberOfArrays())
{
color = "";
for(vtkIdType i = 0; i != array_data->GetNumberOfArrays(); ++i)
{
if(i)
color += ":";
if(array_data->GetArray(i)->IsDense())
color += "purple";
else
color += "red";
}
}
}
else if(vtkGraph::SafeDownCast(object))
{
color = "#cc6600";
}
output << " " << "node_" << source << " -> " << "node_" << target << " [ color=\"" << color << "\" fontcolor=\"" << color << "\" label=\"" << (object ? object->GetClassName() : "") << "\" ]\n";
}
output << "}\n";
}
<commit_msg>ENH: vtkPipelineGraphSource produces GraphViz output with input and output ports labelled.<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkPipelineGraphSource.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkAbstractArray.h"
#include "vtkAlgorithmOutput.h"
#include "vtkAnnotationLink.h"
#include "vtkArrayData.h"
#include "vtkCollection.h"
#include "vtkDataRepresentation.h"
#include "vtkDataSetAttributes.h"
#include "vtkEdgeListIterator.h"
#include "vtkGraph.h"
#include "vtkGraph.h"
#include "vtkInformation.h"
#include "vtkMutableDirectedGraph.h"
#include "vtkObjectFactory.h"
#include "vtkPipelineGraphSource.h"
#include "vtkSmartPointer.h"
#include "vtkStringArray.h"
#include "vtkTable.h"
#include "vtkTree.h"
#include "vtkVariantArray.h"
#include "vtkView.h"
#include <boost/algorithm/string.hpp>
#include <vtksys/stl/map>
#include <vtksys/stl/stack>
#include <vtksys/ios/sstream>
using vtksys_stl::map;
using vtksys_stl::stack;
using vtksys_ios::ostringstream;
#define VTK_CREATE(type, name) \
vtkSmartPointer<type> name = vtkSmartPointer<type>::New()
vtkCxxRevisionMacro(vtkPipelineGraphSource, "1.3");
vtkStandardNewMacro(vtkPipelineGraphSource);
// ----------------------------------------------------------------------
vtkPipelineGraphSource::vtkPipelineGraphSource()
{
this->SetNumberOfInputPorts(0);
this->SetNumberOfOutputPorts(1);
this->Sinks = vtkCollection::New();
}
// ----------------------------------------------------------------------
vtkPipelineGraphSource::~vtkPipelineGraphSource()
{
if (this->Sinks)
{
this->Sinks->Delete();
this->Sinks = NULL;
}
}
// ----------------------------------------------------------------------
void vtkPipelineGraphSource::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
}
// ----------------------------------------------------------------------
void vtkPipelineGraphSource::AddSink(vtkObject* sink)
{
if (sink != NULL && !this->Sinks->IsItemPresent(sink))
{
this->Sinks->AddItem(sink);
this->Modified();
}
}
void vtkPipelineGraphSource::RemoveSink(vtkObject* sink)
{
if (sink != NULL && this->Sinks->IsItemPresent(sink))
{
this->Sinks->RemoveItem(sink);
this->Modified();
}
}
// ----------------------------------------------------------------------
static void InsertObject(
vtkObject* object,
map<vtkObject*, vtkIdType>& object_map,
vtkMutableDirectedGraph* builder,
vtkStringArray* vertex_class_name_array,
vtkVariantArray* vertex_object_array,
vtkStringArray* edge_output_port_array,
vtkStringArray* edge_input_port_array,
vtkStringArray* edge_class_name_array,
vtkVariantArray* edge_object_array)
{
if(!object)
return;
if(object_map.count(object))
return;
// Insert pipeline algorithms ...
if(vtkAlgorithm* const algorithm = vtkAlgorithm::SafeDownCast(object))
{
object_map[algorithm] = builder->AddVertex();
vertex_class_name_array->InsertNextValue(algorithm->GetClassName());
vertex_object_array->InsertNextValue(algorithm);
// Recursively insert algorithm inputs ...
for(int i = 0; i != algorithm->GetNumberOfInputPorts(); ++i)
{
for(int j = 0; j != algorithm->GetNumberOfInputConnections(i); ++j)
{
vtkAlgorithm* const input_algorithm = algorithm->GetInputConnection(i, j)->GetProducer();
InsertObject(input_algorithm, object_map, builder, vertex_class_name_array, vertex_object_array, edge_output_port_array, edge_input_port_array, edge_class_name_array, edge_object_array);
builder->AddEdge(object_map[input_algorithm], object_map[algorithm]);
vtkDataObject* input_data = input_algorithm->GetOutputDataObject(algorithm->GetInputConnection(i, j)->GetIndex());
edge_output_port_array->InsertNextValue(vtkVariant(algorithm->GetInputConnection(i, j)->GetIndex()).ToString());
edge_input_port_array->InsertNextValue(vtkVariant(i).ToString());
edge_class_name_array->InsertNextValue(input_data ? input_data->GetClassName() : "");
edge_object_array->InsertNextValue(input_data);
}
}
// Special-case: if this is a representation, insert its annotation link ...
if(vtkDataRepresentation* const data_representation = vtkDataRepresentation::SafeDownCast(algorithm))
{
if(vtkAnnotationLink* const annotation_link = data_representation->GetAnnotationLink())
{
InsertObject(annotation_link, object_map, builder, vertex_class_name_array, vertex_object_array, edge_output_port_array, edge_input_port_array, edge_class_name_array, edge_object_array);
builder->AddEdge(object_map[annotation_link], object_map[algorithm]);
edge_output_port_array->InsertNextValue("");
edge_input_port_array->InsertNextValue("");
edge_class_name_array->InsertNextValue("vtkAnnotationLayers");
edge_object_array->InsertNextValue(annotation_link->GetOutput());
}
}
}
// Insert pipeline views ...
else if(vtkView* const view = vtkView::SafeDownCast(object))
{
object_map[view] = builder->AddVertex();
vertex_class_name_array->InsertNextValue(view->GetClassName());
vertex_object_array->InsertNextValue(view);
// Recursively insert view inputs ...
for(int i = 0; i != view->GetNumberOfRepresentations(); ++i)
{
vtkDataRepresentation* const input_representation = view->GetRepresentation(i);
InsertObject(input_representation, object_map, builder, vertex_class_name_array, vertex_object_array, edge_output_port_array, edge_input_port_array, edge_class_name_array, edge_object_array);
builder->AddEdge(object_map[input_representation], object_map[view]);
edge_output_port_array->InsertNextValue("");
edge_input_port_array->InsertNextValue(vtkVariant(i).ToString());
edge_class_name_array->InsertNextValue("");
edge_object_array->InsertNextValue(0);
}
}
}
int vtkPipelineGraphSource::RequestData(
vtkInformation*,
vtkInformationVector**,
vtkInformationVector* outputVector)
{
// Setup the graph data structure ...
VTK_CREATE(vtkMutableDirectedGraph, builder);
vtkStringArray* vertex_class_name_array = vtkStringArray::New();
vertex_class_name_array->SetName("class_name");
builder->GetVertexData()->AddArray(vertex_class_name_array);
vertex_class_name_array->Delete();
vtkVariantArray* vertex_object_array = vtkVariantArray::New();
vertex_object_array->SetName("object");
builder->GetVertexData()->AddArray(vertex_object_array);
vertex_object_array->Delete();
vtkStringArray* edge_output_port_array = vtkStringArray::New();
edge_output_port_array->SetName("output_port");
builder->GetEdgeData()->AddArray(edge_output_port_array);
edge_output_port_array->Delete();
vtkStringArray* edge_input_port_array = vtkStringArray::New();
edge_input_port_array->SetName("input_port");
builder->GetEdgeData()->AddArray(edge_input_port_array);
edge_input_port_array->Delete();
vtkStringArray* edge_class_name_array = vtkStringArray::New();
edge_class_name_array->SetName("class_name");
builder->GetEdgeData()->AddArray(edge_class_name_array);
edge_class_name_array->Delete();
vtkVariantArray* edge_object_array = vtkVariantArray::New();
edge_object_array->SetName("object");
builder->GetEdgeData()->AddArray(edge_object_array);
edge_object_array->Delete();
// Recursively insert pipeline components into the graph ...
map<vtkObject*, vtkIdType> object_map;
for(vtkIdType i = 0; i != this->Sinks->GetNumberOfItems(); ++i)
{
InsertObject(this->Sinks->GetItemAsObject(i), object_map, builder, vertex_class_name_array, vertex_object_array, edge_output_port_array, edge_input_port_array, edge_class_name_array, edge_object_array);
}
// Finish creating the output graph ...
vtkDirectedGraph* const output_graph = vtkDirectedGraph::GetData(outputVector);
if(!output_graph->CheckedShallowCopy(builder))
{
vtkErrorMacro(<<"Invalid graph structure");
return 0;
}
return 1;
}
void vtkPipelineGraphSource::PipelineToDot(vtkAlgorithm* sink, ostream& output, const vtkStdString& graph_name)
{
vtkSmartPointer<vtkCollection> sinks = vtkSmartPointer<vtkCollection>::New();
sinks->AddItem(sink);
PipelineToDot(sinks, output, graph_name);
}
void vtkPipelineGraphSource::PipelineToDot(vtkCollection* sinks, ostream& output, const vtkStdString& graph_name)
{
// Create a graph representation of the pipeline ...
vtkSmartPointer<vtkPipelineGraphSource> pipeline = vtkSmartPointer<vtkPipelineGraphSource>::New();
for(vtkIdType i = 0; i != sinks->GetNumberOfItems(); ++i)
{
pipeline->AddSink(sinks->GetItemAsObject(i));
}
pipeline->Update();
vtkGraph* const pipeline_graph = pipeline->GetOutput();
vtkAbstractArray* const vertex_object_array = pipeline_graph->GetVertexData()->GetAbstractArray("object");
vtkAbstractArray* const edge_output_port_array = pipeline_graph->GetEdgeData()->GetAbstractArray("output_port");
vtkAbstractArray* const edge_input_port_array = pipeline_graph->GetEdgeData()->GetAbstractArray("input_port");
vtkAbstractArray* const edge_object_array = pipeline_graph->GetEdgeData()->GetAbstractArray("object");
output << "digraph \"" << graph_name << "\"\n";
output << "{\n";
// Do some standard formatting ...
output << " node [ fontname=\"helvetica\" fontsize=\"10\" shape=\"record\" style=\"filled\" ]\n";
output << " edge [ fontname=\"helvetica\" fontsize=\"9\" ]\n\n";
// Write-out vertices ...
for(vtkIdType i = 0; i != pipeline_graph->GetNumberOfVertices(); ++i)
{
vtkObjectBase* const object = vertex_object_array->GetVariantValue(i).ToVTKObject();
vtkstd::stringstream buffer;
object->PrintSelf(buffer, vtkIndent());
vtkstd::string line;
vtkstd::string object_state;
for(vtkstd::getline(buffer, line); buffer; vtkstd::getline(buffer, line))
{
boost::algorithm::replace_all(line, "\"", "'");
boost::algorithm::replace_all(line, "\r", "");
boost::algorithm::replace_all(line, "\n", "");
if(0 == line.find("Debug:"))
continue;
if(0 == line.find("Modified Time:"))
continue;
if(0 == line.find("Reference Count:"))
continue;
if(0 == line.find("Registered Events:"))
continue;
if(0 == line.find("Executive:"))
continue;
if(0 == line.find("ErrorCode:"))
continue;
if(0 == line.find("Information:"))
continue;
if(0 == line.find("AbortExecute:"))
continue;
if(0 == line.find("Progress:"))
continue;
if(0 == line.find("Progress Text:"))
continue;
if(0 == line.find(" "))
continue;
object_state += line + "\\n";
}
vtkstd::string fillcolor = "#ccffcc";
if(vtkView::SafeDownCast(object))
{
fillcolor = "#ffffcc";
}
else if(vtkAnnotationLink::SafeDownCast(object))
{
fillcolor = "#ccccff";
}
output << " " << "node_" << object << " [ fillcolor=\"" << fillcolor << "\" label=\"{" << object->GetClassName() << "|" << object_state << "}\" vtk_class_name=\"" << object->GetClassName() << "\" ]\n";
}
// Write-out edges ...
vtkSmartPointer<vtkEdgeListIterator> edges = vtkSmartPointer<vtkEdgeListIterator>::New();
edges->SetGraph(pipeline_graph);
while(edges->HasNext())
{
vtkEdgeType edge = edges->Next();
vtkObjectBase* const source = vertex_object_array->GetVariantValue(edge.Source).ToVTKObject();
vtkObjectBase* const target = vertex_object_array->GetVariantValue(edge.Target).ToVTKObject();
const vtkStdString output_port = edge_output_port_array->GetVariantValue(edge.Id).ToString();
const vtkStdString input_port = edge_input_port_array->GetVariantValue(edge.Id).ToString();
vtkObjectBase* const object = edge_object_array->GetVariantValue(edge.Id).ToVTKObject();
vtkstd::string color = "black";
if(vtkTree::SafeDownCast(object))
{
color = "#00bb00";
}
else if(vtkTable::SafeDownCast(object))
{
color = "blue";
}
else if(vtkArrayData* const array_data = vtkArrayData::SafeDownCast(object))
{
if(array_data->GetNumberOfArrays())
{
color = "";
for(vtkIdType i = 0; i != array_data->GetNumberOfArrays(); ++i)
{
if(i)
color += ":";
if(array_data->GetArray(i)->IsDense())
color += "purple";
else
color += "red";
}
}
}
else if(vtkGraph::SafeDownCast(object))
{
color = "#cc6600";
}
output << " " << "node_" << source << " -> " << "node_" << target;
output << " [";
output << " color=\"" << color << "\" fontcolor=\"" << color << "\"";
output << " label=\"" << (object ? object->GetClassName() : "") << "\"";
output << " headlabel=\"" << input_port << "\"";
output << " taillabel=\"" << output_port << "\"";
output << " ]\n";
}
output << "}\n";
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <vector>
#include <Eigen/Dense>
#include "roadnet.hpp"
int main()
{
Eigen::Vector3d transform( 1.0, 0.0, 1.6 );
RoadNetwork rd( 2.0, transform, 2, 3 );
std::cout << rd << std::endl;
double x, y;
rd.map_point( 0, 0, x, y );
std::cout << "(0, 0) -> (" << x << ", " << y << ")" << std::endl;
rd.map_point( 1, 2, x, y );
std::cout << "(1, 2) -> (" << x << ", " << y << ")" << std::endl;
for (size_t idx = 0; idx < rd.number_of_segments(); idx++)
std::cout << rd.mapped_segment( idx ).transpose() << std::endl;
return 0;
}
<commit_msg>RND JSON to stdout, otherwise to stderr in helloroadnet<commit_after>#include <iostream>
#include <vector>
#include <Eigen/Dense>
#include "roadnet.hpp"
int main()
{
Eigen::Vector3d transform( 1.0, 0.0, 1.6 );
RoadNetwork rd( 2.0, transform, 2, 3 );
std::cout << rd << std::endl;
double x, y;
rd.map_point( 0, 0, x, y );
std::cerr << "(0, 0) -> (" << x << ", " << y << ")" << std::endl;
rd.map_point( 1, 2, x, y );
std::cerr << "(1, 2) -> (" << x << ", " << y << ")" << std::endl;
for (size_t idx = 0; idx < rd.number_of_segments(); idx++)
std::cerr << rd.mapped_segment( idx ).transpose() << std::endl;
return 0;
}
<|endoftext|> |
<commit_before>#ifndef AB_ASSERT_HPP_
#define AB_ASSERT_HPP_
#include <Ab/Config.hpp>
#include <Ab/CppUtilities.hpp>
#include <cstdio>
#include <cstdlib>
#include <fmt/core.h>
#include <iostream>
#include <sstream>
namespace Ab {
/// Crash the process. This call should be catchable by a native debugger.
///
[[noreturn]] inline void trap() { __builtin_trap(); }
/// Designate a statement as unreachable. It is undefined behaviour to execute
/// this statement.
///
[[noreturn]] inline void unreachable() { __builtin_unreachable(); }
/// Output an error message to stderr and trap.
/// Message format:
/// ```
/// <file>:<line>: <message>
/// in: <function>
/// note: <note>
/// ```
///
[[noreturn]] inline void
fail(const char* location, const char* function, const char* message, const char* note) {
std::stringstream str;
str << location << ": Error: " << message << std::endl;
str << "\tin: " << function << std::endl;
if (note != nullptr) {
str << "\tnote: " << note << std::endl;
}
std::cerr << str.str() << std::endl;
trap();
}
/// Check condition, fail if false.
///
inline void
check(bool value, const char* location, const char* function, const char* message,
const char* note) {
if (!value) {
fail(location, function, message, note);
}
}
} // namespace Ab
/// Assert that x is true.
///
#define AB_ASSERT(x) \
::Ab::check((x), AB_LOCATION_STR(), AB_FUNCTION_STR(), "Assertion Failed", AB_STRINGIFY(x))
/// Assert that x is true. Report with message on failure.
///
#define AB_ASSERT_MSG(x, message) \
::Ab::check((x), AB_LOCATION_STR(), AB_FUNCTION_STR(), (message), AB_STRINGIFY(x))
/// Unconditional crash. No-return.
///
#define AB_ASSERT_UNREACHABLE() \
::Ab::fail(AB_LOCATION_STR(), AB_FUNCTION_STR(), "Unreachable statement reached", nullptr)
/// Unconditional crash with message. No-return.
///
#define AB_ASSERT_UNREACHABLE_MSG(message) \
::Ab::fail(AB_LOCATION_STR(), AB_FUNCTION_STR(), (message), nullptr)
/// Unconditional crash. No-return.
///
#define AB_ASSERT_UNIMPLEMENTED() \
::Ab::fail(AB_LOCATION_STR(), AB_FUNCTION_STR(), "Unimplemented function called", nullptr)
#endif // AB_ASSERT_HPP_
<commit_msg>Clean up UNREACHABLE and trap<commit_after>#ifndef AB_ASSERT_HPP_
#define AB_ASSERT_HPP_
#include <Ab/Config.hpp>
#include <Ab/CppUtilities.hpp>
#include <cstdio>
#include <cstdlib>
#include <fmt/core.h>
#include <iostream>
#include <sstream>
namespace Ab {
/// Crash the process. This call should result in a process signal that can be caught by a native
/// debugger.
///
[[noreturn]] inline void trap() noexcept { __builtin_trap(); }
/// Output an error message to stderr and trap.
/// Message format:
/// ```
/// <file>:<line>: <message>
/// in: <function>
/// note: <note>
/// ```
///
[[noreturn]] inline void
fail(const char* location, const char* function, const char* message, const char* note) {
std::stringstream str;
str << location << ": Error: " << message << std::endl;
str << "\tin: " << function << std::endl;
if (note != nullptr) {
str << "\tnote: " << note << std::endl;
}
std::cerr << str.str() << std::endl;
trap();
}
/// Check condition, fail if false.
///
inline void
check(bool value, const char* location, const char* function, const char* message,
const char* note) {
if (!value) {
fail(location, function, message, note);
}
}
} // namespace Ab
/// Designate a statement as unreachable. This pseudo-function acts as a hint to the compiler
/// that a point in the program cannot be reached. It is undefined behaviour to execute this
/// function. If you just want to trigger a crash, use AB_ASSERT_UNREACHABLE instead.
///
#define AB_UNREACHABLE() __builtin_unreachable();
/// Assert that x is true.
///
#define AB_ASSERT(x) \
::Ab::check((x), AB_LOCATION_STR(), AB_FUNCTION_STR(), "Assertion Failed", AB_STRINGIFY(x))
/// Assert that x is true. Report with message on failure.
///
#define AB_ASSERT_MSG(x, message) \
::Ab::check((x), AB_LOCATION_STR(), AB_FUNCTION_STR(), (message), AB_STRINGIFY(x))
/// Unconditional crash. No-return.
///
#define AB_ASSERT_UNREACHABLE() \
::Ab::fail(AB_LOCATION_STR(), AB_FUNCTION_STR(), "Unreachable statement reached", nullptr)
/// Unconditional crash with message. No-return.
///
#define AB_ASSERT_UNREACHABLE_MSG(message) \
::Ab::fail(AB_LOCATION_STR(), AB_FUNCTION_STR(), (message), nullptr)
/// Unconditional crash. No-return.
///
#define AB_ASSERT_UNIMPLEMENTED() \
::Ab::fail(AB_LOCATION_STR(), AB_FUNCTION_STR(), "Unimplemented function called", nullptr)
#endif // AB_ASSERT_HPP_
<|endoftext|> |
<commit_before>//@author A0097630B
#include "stdafx.h"
#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/format.hpp>
#include <boost/lexical_cast.hpp>
#include "add_query.h"
namespace {
/// The format for displaying an ADD_QUERY
const boost::wformat STRING_FORMAT(L"%1% (deadline %2%, %3% priority, %4% "
L"subtasks, %5% dependents)");
} // namespace
namespace You {
namespace NLP {
std::wostream& operator<<(std::wostream& s, const ADD_QUERY& q) {
return s << (boost::wformat(STRING_FORMAT) % q.description % (
q.deadline ?
boost::lexical_cast<std::wstring>(q.deadline.get()) : L"none"
) % (
q.priority == TaskPriority::HIGH ? L"high" : L"normal"
) % (
q.subtasks.size()
) % (
q.dependent ? 1 : 0
));
}
bool ADD_QUERY::operator==(const ADD_QUERY& rhs) const {
return description == rhs.description &&
priority == rhs.priority &&
deadline == rhs.deadline &&
subtasks.size() == rhs.subtasks.size() &&
std::equal(begin(subtasks), end(subtasks), begin(rhs.subtasks)) &&
dependent == rhs.dependent;
}
std::wstring ToString(const ADD_QUERY& q) {
return boost::lexical_cast<std::wstring>(q);
}
} // namespace NLP
} // namespace You
<commit_msg>Fix equality comparison for dependents.<commit_after>//@author A0097630B
#include "stdafx.h"
#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/format.hpp>
#include <boost/lexical_cast.hpp>
#include "add_query.h"
namespace {
/// The format for displaying an ADD_QUERY
const boost::wformat STRING_FORMAT(L"%1% (deadline %2%, %3% priority, %4% "
L"subtasks, %5% dependents)");
} // namespace
namespace You {
namespace NLP {
std::wostream& operator<<(std::wostream& s, const ADD_QUERY& q) {
return s << (boost::wformat(STRING_FORMAT) % q.description % (
q.deadline ?
boost::lexical_cast<std::wstring>(q.deadline.get()) : L"none"
) % (
q.priority == TaskPriority::HIGH ? L"high" : L"normal"
) % (
q.subtasks.size()
) % (
q.dependent ? 1 : 0
));
}
bool ADD_QUERY::operator==(const ADD_QUERY& rhs) const {
return description == rhs.description &&
priority == rhs.priority &&
deadline == rhs.deadline &&
subtasks.size() == rhs.subtasks.size() &&
std::equal(begin(subtasks), end(subtasks), begin(rhs.subtasks)) &&
(
(!dependent && !rhs.dependent) || (
dependent && rhs.dependent &&
*dependent.get() == *rhs.dependent.get()));
}
std::wstring ToString(const ADD_QUERY& q) {
return boost::lexical_cast<std::wstring>(q);
}
} // namespace NLP
} // namespace You
<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#include <iostream>
#include <fstream>
#include <stdexcept>
#include <mapnik/geom_util.hpp>
// boost
#include <boost/algorithm/string.hpp>
#include <boost/filesystem/operations.hpp>
#include "shape_featureset.hpp"
#include "shape_index_featureset.hpp"
#include "shape.hpp"
DATASOURCE_PLUGIN(shape_datasource)
using mapnik::String;
using mapnik::Double;
using mapnik::Integer;
using mapnik::datasource_exception;
using mapnik::filter_in_box;
using mapnik::filter_at_point;
using mapnik::attribute_descriptor;
shape_datasource::shape_datasource(const parameters ¶ms)
: datasource (params),
type_(datasource::Vector),
file_length_(0),
indexed_(false),
desc_(*params.get<std::string>("type"), *params.get<std::string>("encoding","utf-8"))
{
boost::optional<std::string> file = params.get<std::string>("file");
if (!file) throw datasource_exception("missing <file> parameter");
boost::optional<std::string> base = params.get<std::string>("base");
if (base)
shape_name_ = *base + "/" + *file;
else
shape_name_ = *file;
boost::algorithm::ireplace_last(shape_name_,".shp","");
if (!boost::filesystem::exists(shape_name_ + ".shp")) throw datasource_exception(shape_name_ + " does not exist");
try
{
shape_io shape(shape_name_);
init(shape);
for (int i=0;i<shape.dbf().num_fields();++i)
{
field_descriptor const& fd=shape.dbf().descriptor(i);
std::string fld_name=fd.name_;
switch (fd.type_)
{
case 'C':
case 'D':
case 'M':
case 'L':
desc_.add_descriptor(attribute_descriptor(fld_name, String));
break;
case 'N':
case 'F':
{
if (fd.dec_>0)
{
desc_.add_descriptor(attribute_descriptor(fld_name,Double,false,8));
}
else
{
desc_.add_descriptor(attribute_descriptor(fld_name,Integer,false,4));
}
break;
}
default:
#ifdef MAPNIK_DEBUG
std::clog << "unknown type "<<fd.type_<<"\n";
#endif
break;
}
}
}
catch (datasource_exception& ex)
{
std::clog<<ex.what()<<std::endl;
throw;
}
catch (...)
{
std::clog << " got exception ... \n";
throw;
}
}
shape_datasource::~shape_datasource() {}
const std::string shape_datasource::name_="shape";
void shape_datasource::init(shape_io& shape)
{
//first read header from *.shp
int file_code=shape.shp().read_xdr_integer();
if (file_code!=9994)
{
//invalid
throw datasource_exception("wrong file code");
}
shape.shp().skip(5*4);
file_length_=shape.shp().read_xdr_integer();
int version=shape.shp().read_ndr_integer();
if (version!=1000)
{
//invalid version number
throw datasource_exception("invalid version number");
}
#ifdef MAPNIK_DEBUG
int shape_type = shape.shp().read_ndr_integer();
#else
shape.shp().skip(4);
#endif
shape.shp().read_envelope(extent_);
shape.shp().skip(4*8);
// check if we have an index file around
std::string index_name(shape_name_+".index");
std::ifstream file(index_name.c_str(),std::ios::in | std::ios::binary);
if (file)
{
indexed_=true;
file.close();
}
#ifdef MAPNIK_DEBUG
std::clog << extent_ << std::endl;
std::clog << "file_length=" << file_length_ << std::endl;
std::clog << "shape_type=" << shape_type << std::endl;
#endif
}
int shape_datasource::type() const
{
return type_;
}
layer_descriptor shape_datasource::get_descriptor() const
{
return desc_;
}
std::string shape_datasource::name()
{
return name_;
}
featureset_ptr shape_datasource::features(const query& q) const
{
filter_in_box filter(q.get_bbox());
if (indexed_)
{
return featureset_ptr
(new shape_index_featureset<filter_in_box>(filter,
shape_name_,
q.property_names(),
desc_.get_encoding()));
}
else
{
return featureset_ptr
(new shape_featureset<filter_in_box>(filter,
shape_name_,
q.property_names(),
desc_.get_encoding(),
file_length_));
}
}
featureset_ptr shape_datasource::features_at_point(coord2d const& pt) const
{
filter_at_point filter(pt);
// collect all attribute names
std::vector<attribute_descriptor> const& desc_vector = desc_.get_descriptors();
std::vector<attribute_descriptor>::const_iterator itr = desc_vector.begin();
std::vector<attribute_descriptor>::const_iterator end = desc_vector.end();
std::set<std::string> names;
while (itr != end)
{
names.insert(itr->get_name());
++itr;
}
if (indexed_)
{
return featureset_ptr
(new shape_index_featureset<filter_at_point>(filter,
shape_name_,
names,
desc_.get_encoding()));
}
else
{
return featureset_ptr
(new shape_featureset<filter_at_point>(filter,
shape_name_,
names,
desc_.get_encoding(),
file_length_));
}
}
Envelope<double> shape_datasource::envelope() const
{
return extent_;
}
<commit_msg>shape input: use more flexible (boost::filesystem) method of stripping ext names<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#include <iostream>
#include <fstream>
#include <stdexcept>
#include <mapnik/geom_util.hpp>
// boost
#include <boost/algorithm/string.hpp>
#include <boost/filesystem/operations.hpp>
#include "shape_featureset.hpp"
#include "shape_index_featureset.hpp"
#include "shape.hpp"
DATASOURCE_PLUGIN(shape_datasource)
using mapnik::String;
using mapnik::Double;
using mapnik::Integer;
using mapnik::datasource_exception;
using mapnik::filter_in_box;
using mapnik::filter_at_point;
using mapnik::attribute_descriptor;
shape_datasource::shape_datasource(const parameters ¶ms)
: datasource (params),
type_(datasource::Vector),
file_length_(0),
indexed_(false),
desc_(*params.get<std::string>("type"), *params.get<std::string>("encoding","utf-8"))
{
boost::optional<std::string> file = params.get<std::string>("file");
if (!file) throw datasource_exception("missing <file> parameter");
boost::optional<std::string> base = params.get<std::string>("base");
if (base)
shape_name_ = *base + "/" + *file;
else
shape_name_ = *file;
boost::filesystem::path path(shape_name_);
path.replace_extension("");
shape_name_ = path.string();
if (!boost::filesystem::exists(shape_name_ + ".shp")) throw datasource_exception(shape_name_ + ".shp does not exist");
try
{
shape_io shape(shape_name_);
init(shape);
for (int i=0;i<shape.dbf().num_fields();++i)
{
field_descriptor const& fd=shape.dbf().descriptor(i);
std::string fld_name=fd.name_;
switch (fd.type_)
{
case 'C':
case 'D':
case 'M':
case 'L':
desc_.add_descriptor(attribute_descriptor(fld_name, String));
break;
case 'N':
case 'F':
{
if (fd.dec_>0)
{
desc_.add_descriptor(attribute_descriptor(fld_name,Double,false,8));
}
else
{
desc_.add_descriptor(attribute_descriptor(fld_name,Integer,false,4));
}
break;
}
default:
#ifdef MAPNIK_DEBUG
std::clog << "unknown type "<<fd.type_<<"\n";
#endif
break;
}
}
}
catch (datasource_exception& ex)
{
std::clog<<ex.what()<<std::endl;
throw;
}
catch (...)
{
std::clog << " got exception ... \n";
throw;
}
}
shape_datasource::~shape_datasource() {}
const std::string shape_datasource::name_="shape";
void shape_datasource::init(shape_io& shape)
{
//first read header from *.shp
int file_code=shape.shp().read_xdr_integer();
if (file_code!=9994)
{
//invalid
throw datasource_exception("wrong file code");
}
shape.shp().skip(5*4);
file_length_=shape.shp().read_xdr_integer();
int version=shape.shp().read_ndr_integer();
if (version!=1000)
{
//invalid version number
throw datasource_exception("invalid version number");
}
#ifdef MAPNIK_DEBUG
int shape_type = shape.shp().read_ndr_integer();
#else
shape.shp().skip(4);
#endif
shape.shp().read_envelope(extent_);
shape.shp().skip(4*8);
// check if we have an index file around
std::string index_name(shape_name_+".index");
std::ifstream file(index_name.c_str(),std::ios::in | std::ios::binary);
if (file)
{
indexed_=true;
file.close();
}
#ifdef MAPNIK_DEBUG
std::clog << extent_ << std::endl;
std::clog << "file_length=" << file_length_ << std::endl;
std::clog << "shape_type=" << shape_type << std::endl;
#endif
}
int shape_datasource::type() const
{
return type_;
}
layer_descriptor shape_datasource::get_descriptor() const
{
return desc_;
}
std::string shape_datasource::name()
{
return name_;
}
featureset_ptr shape_datasource::features(const query& q) const
{
filter_in_box filter(q.get_bbox());
if (indexed_)
{
return featureset_ptr
(new shape_index_featureset<filter_in_box>(filter,
shape_name_,
q.property_names(),
desc_.get_encoding()));
}
else
{
return featureset_ptr
(new shape_featureset<filter_in_box>(filter,
shape_name_,
q.property_names(),
desc_.get_encoding(),
file_length_));
}
}
featureset_ptr shape_datasource::features_at_point(coord2d const& pt) const
{
filter_at_point filter(pt);
// collect all attribute names
std::vector<attribute_descriptor> const& desc_vector = desc_.get_descriptors();
std::vector<attribute_descriptor>::const_iterator itr = desc_vector.begin();
std::vector<attribute_descriptor>::const_iterator end = desc_vector.end();
std::set<std::string> names;
while (itr != end)
{
names.insert(itr->get_name());
++itr;
}
if (indexed_)
{
return featureset_ptr
(new shape_index_featureset<filter_at_point>(filter,
shape_name_,
names,
desc_.get_encoding()));
}
else
{
return featureset_ptr
(new shape_featureset<filter_at_point>(filter,
shape_name_,
names,
desc_.get_encoding(),
file_length_));
}
}
Envelope<double> shape_datasource::envelope() const
{
return extent_;
}
<|endoftext|> |
<commit_before>/*
* _____ ___ ___ |
* | _ |___ ___ _ _|_ |_ | | C/C++ framework for 32-bit AVRs
* | | -_| _| | |_ | _| |
* |__|__|___|_| |_ |___|___| | https://github.com/aery32
* |___| |
*
* Copyright (c) 2012-2013, Muiku Oy
* All rights reserved.
*
* LICENSE
*
* New BSD License, see the LICENSE.txt bundled with this package. If you did
* not receive a copy of the license and are unable to obtain it through the
* world-wide-web, please send an email to contact@muiku.com so we can send
* you a copy.
*/
#include <cmath>
#include <cctype>
extern "C" {
#include <ieeefp.h>
}
#include "aery32/string.h"
static const char lookup[10] = {'0','1','2','3','4','5','6','7','8','9'};
char *aery::utoa(unsigned int number, char *buffer, size_t *n)
{
uint8_t i = 0, k = 0;
char t;
if (number == 0)
buffer[i++] = '0';
while (number > 0) {
buffer[i++] = lookup[number % 10];
number = number / 10;
}
buffer[i--] = '\0';
/* swap the numbers since they are in reverse order */
while (k < i) {
t = buffer[k];
buffer[k++] = buffer[i];
buffer[i--] = t;
}
if (n != NULL) *n = k+i+1;
return buffer;
}
char *aery::itoa(int number, char *buffer, size_t *n)
{
if (number < 0) {
buffer[0] = '-';
aery::utoa((unsigned int) (-1 * number), &buffer[1], n);
if (n != NULL)
*n += 1;
return buffer;
}
return aery::utoa((unsigned int) number, buffer, n);
}
/* TODO: Fix rounding */
char *aery::dtoa(double number, uint8_t precision, char *buffer, size_t *n)
{
size_t n2 = 0;
double ip, fp; /* integer and fractional parts */
if (isnan(number)) {
if (n != NULL) *n = 3;
return strcpy(buffer, "NaN");
}
if (isinf(number)) {
if (n != NULL) *n = 3;
return strcpy(buffer, "Inf");
}
if ((fp = modf(number, &ip)) < 0)
fp *= -1;
/* write the integer part and the dot into the buffer */
aery::itoa((int) ip, buffer, &n2);
buffer[n2++] = '.';
/* write the fractional part into the buffer */
if (precision > 8)
precision = 8;
while (precision--) {
fp *= 10;
aery::utoa((unsigned int) fp, buffer + n2++);
fp = fp - (unsigned int) fp;
}
if (n != NULL) *n = n2;
return buffer;
}
int aery::nputs(const char *buffer, size_t n, int (*_putchar)(int))
{
int i = 0, rv;
for (; (*(buffer+i) && n > 0); i++, n--) {
if ((rv = _putchar(*(buffer+i))) < 0)
return rv;
}
return i;
}
int aery::line_to_argv(char *line, char *argv[])
{
unsigned int i = 0, j = 0;
begin:
while (line[i] && isspace(line[i])) i++;
argv[j++] = &line[i];
while (line[i] && !isspace(line[i])) i++;
if (line[i] == '\0') goto end;
line[i++] = '\0'; goto begin;
end:
return j;
}<commit_msg>Slight tweaks to make string.cpp portable.<commit_after>/*
* _____ ___ ___ |
* | _ |___ ___ _ _|_ |_ | | C/C++ framework for 32-bit AVRs
* | | -_| _| | |_ | _| |
* |__|__|___|_| |_ |___|___| | https://github.com/aery32
* |___| |
*
* Copyright (c) 2012-2013, Muiku Oy
* All rights reserved.
*
* LICENSE
*
* New BSD License, see the LICENSE.txt bundled with this package. If you did
* not receive a copy of the license and are unable to obtain it through the
* world-wide-web, please send an email to contact@muiku.com so we can send
* you a copy.
*/
#include <cmath>
#include <cctype>
#include "aery32/string.h"
static const char lookup[10] = {'0','1','2','3','4','5','6','7','8','9'};
char *aery::utoa(unsigned int number, char *buffer, size_t *n)
{
uint8_t i = 0, k = 0;
char t;
if (number == 0)
buffer[i++] = '0';
while (number > 0) {
buffer[i++] = lookup[number % 10];
number = number / 10;
}
buffer[i--] = '\0';
/* swap the numbers since they are in reverse order */
while (k < i) {
t = buffer[k];
buffer[k++] = buffer[i];
buffer[i--] = t;
}
if (n != NULL) *n = k+i+1;
return buffer;
}
char *aery::itoa(int number, char *buffer, size_t *n)
{
if (number < 0) {
buffer[0] = '-';
aery::utoa((unsigned int) (-1 * number), &buffer[1], n);
if (n != NULL)
*n += 1;
return buffer;
}
return aery::utoa((unsigned int) number, buffer, n);
}
/* TODO: Fix rounding */
char *aery::dtoa(double number, uint8_t precision, char *buffer, size_t *n)
{
size_t n2 = 0;
double ip, fp; /* integer and fractional parts */
if (std::isnan(number)) {
if (n != NULL) *n = 3;
return strcpy(buffer, "NaN");
}
if (std::isinf(number)) {
if (n != NULL) *n = 3;
return strcpy(buffer, "Inf");
}
if ((fp = modf(number, &ip)) < 0)
fp *= -1;
/* write the integer part and the dot into the buffer */
aery::itoa((int) ip, buffer, &n2);
buffer[n2++] = '.';
/* write the fractional part into the buffer */
if (precision > 8)
precision = 8;
while (precision--) {
fp *= 10;
aery::utoa((unsigned int) fp, buffer + n2++);
fp = fp - (unsigned int) fp;
}
if (n != NULL) *n = n2;
return buffer;
}
int aery::nputs(const char *buffer, size_t n, int (*_putchar)(int))
{
int i = 0, rv;
for (; (*(buffer+i) && n > 0); i++, n--) {
if ((rv = _putchar(*(buffer+i))) < 0)
return rv;
}
return i;
}
int aery::line_to_argv(char *line, char *argv[])
{
unsigned int i = 0, j = 0;
begin:
while (line[i] && isspace(line[i])) i++;
argv[j++] = &line[i];
while (line[i] && !isspace(line[i])) i++;
if (line[i] == '\0') goto end;
line[i++] = '\0'; goto begin;
end:
return j;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: aqua_clipboard.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-08 18:08:25 $
*
* 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 _AQUA_CLIPBOARD_HXX_
#define _AQUA_CLIPBOARD_HXX_
#ifndef _RTL_USTRING_
#include <rtl/ustring>
#endif
#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif
#ifndef _CPPUHELPER_COMPBASE3_HXX_
#include <cppuhelper/compbase3.hxx>
#endif
#ifndef _COM_SUN_STAR_DATATRANSFER_XTRANSFERABLE_HPP_
#include <com/sun/star/datatransfer/XTransferable.hpp>
#endif
#ifndef _COM_SUN_STAR_DATATRANSFER_CLIPBOARD_XCLIPBOARDEX_HPP_
#include <com/sun/star/datatransfer/clipboard/XClipboardEx.hpp>
#endif
#ifndef _COM_SUN_STAR_DATATRANSFER_CLIPBOARD_XCLIPBOARDOWNER_HPP_
#include <com/sun/star/datatransfer/clipboard/XClipboardOwner.hpp>
#endif
#ifndef _COM_SUN_STAR_DATATRANSFER_CLIPBOARD_XCLIPBOARDLISTENER_HPP_
#include <com/sun/star/datatransfer/clipboard/XClipboardListener.hpp>
#endif
#ifndef _COM_SUN_STAR_DATATRANSFER_CLIPBOARD_XCLIPBOARDNOTIFIER_HPP_
#include <com/sun/star/datatransfer/clipboard/XClipboardNotifier.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
// the service names
#define AQUA_CLIPBOARD_SERVICE_NAME "com.sun.star.datatransfer.clipboard.SystemClipboard"
// the implementation names
#define AQUA_CLIPBOARD_IMPL_NAME "com.sun.star.datatransfer.clipboard.AquaClipboard"
// the registry key names
#define AQUA_CLIPBOARD_REGKEY_NAME "/com.sun.star.datatransfer.clipboard.AquaClipboard/UNO/SERVICES/com.sun.star.datatransfer.clipboard.SystemClipboard"
namespace aqua {
class AquaClipboard :
public cppu::WeakComponentImplHelper3< ::com::sun::star::datatransfer::clipboard::XClipboardEx, ::com::sun::star::datatransfer::clipboard::XClipboardNotifier, ::com::sun::star::lang::XServiceInfo >
{
public:
AquaClipboard();
virtual ::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::XTransferable > SAL_CALL getContents()
throw( ::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL setContents( const ::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::XTransferable >& xTransferable, const ::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::clipboard::XClipboardOwner >& xClipboardOwner )
throw( ::com::sun::star::uno::RuntimeException );
virtual ::rtl::OUString SAL_CALL getName()
throw( ::com::sun::star::uno::RuntimeException );
virtual sal_Int8 SAL_CALL getRenderingCapabilities()
throw( ::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL addClipboardListener( const ::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::clipboard::XClipboardListener >& listener )
throw( ::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL removeClipboardListener( const ::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::clipboard::XClipboardListener >& listener )
throw( ::com::sun::star::uno::RuntimeException );
virtual ::rtl::OUString SAL_CALL getImplementationName()
throw(::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName )
throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames()
throw(::com::sun::star::uno::RuntimeException);
private:
::osl::Mutex m_aMutex;
::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::XTransferable > m_aTransferable;
};
} // namespace aqua
#endif
<commit_msg>INTEGRATION: CWS warnings01 (1.4.4); FILE MERGED 2006/03/09 20:31:40 pl 1.4.4.1: #i55991# removed warnings for windows platform<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: aqua_clipboard.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: hr $ $Date: 2006-06-20 05:58:48 $
*
* 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 _AQUA_CLIPBOARD_HXX_
#define _AQUA_CLIPBOARD_HXX_
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif
#ifndef _CPPUHELPER_COMPBASE3_HXX_
#include <cppuhelper/compbase3.hxx>
#endif
#ifndef _COM_SUN_STAR_DATATRANSFER_XTRANSFERABLE_HPP_
#include <com/sun/star/datatransfer/XTransferable.hpp>
#endif
#ifndef _COM_SUN_STAR_DATATRANSFER_CLIPBOARD_XCLIPBOARDEX_HPP_
#include <com/sun/star/datatransfer/clipboard/XClipboardEx.hpp>
#endif
#ifndef _COM_SUN_STAR_DATATRANSFER_CLIPBOARD_XCLIPBOARDOWNER_HPP_
#include <com/sun/star/datatransfer/clipboard/XClipboardOwner.hpp>
#endif
#ifndef _COM_SUN_STAR_DATATRANSFER_CLIPBOARD_XCLIPBOARDLISTENER_HPP_
#include <com/sun/star/datatransfer/clipboard/XClipboardListener.hpp>
#endif
#ifndef _COM_SUN_STAR_DATATRANSFER_CLIPBOARD_XCLIPBOARDNOTIFIER_HPP_
#include <com/sun/star/datatransfer/clipboard/XClipboardNotifier.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
// the service names
#define AQUA_CLIPBOARD_SERVICE_NAME "com.sun.star.datatransfer.clipboard.SystemClipboard"
// the implementation names
#define AQUA_CLIPBOARD_IMPL_NAME "com.sun.star.datatransfer.clipboard.AquaClipboard"
// the registry key names
#define AQUA_CLIPBOARD_REGKEY_NAME "/com.sun.star.datatransfer.clipboard.AquaClipboard/UNO/SERVICES/com.sun.star.datatransfer.clipboard.SystemClipboard"
namespace aqua {
class AquaClipboard :
public cppu::WeakComponentImplHelper3< ::com::sun::star::datatransfer::clipboard::XClipboardEx, ::com::sun::star::datatransfer::clipboard::XClipboardNotifier, ::com::sun::star::lang::XServiceInfo >
{
public:
AquaClipboard();
virtual ::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::XTransferable > SAL_CALL getContents()
throw( ::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL setContents( const ::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::XTransferable >& xTransferable, const ::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::clipboard::XClipboardOwner >& xClipboardOwner )
throw( ::com::sun::star::uno::RuntimeException );
virtual ::rtl::OUString SAL_CALL getName()
throw( ::com::sun::star::uno::RuntimeException );
virtual sal_Int8 SAL_CALL getRenderingCapabilities()
throw( ::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL addClipboardListener( const ::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::clipboard::XClipboardListener >& listener )
throw( ::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL removeClipboardListener( const ::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::clipboard::XClipboardListener >& listener )
throw( ::com::sun::star::uno::RuntimeException );
virtual ::rtl::OUString SAL_CALL getImplementationName()
throw(::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName )
throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames()
throw(::com::sun::star::uno::RuntimeException);
private:
::osl::Mutex m_aMutex;
::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::XTransferable > m_aTransferable;
};
} // namespace aqua
#endif
<|endoftext|> |
<commit_before>// This file is part of the dune-pymor project:
// https://github.com/pyMor/dune-pymor
// Copyright Holders: Felix Albrecht, Stephan Rave
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_PYMOR_LA_CONTAINER_INTERFACES_HH
#define DUNE_PYMOR_LA_CONTAINER_INTERFACES_HH
#include <utility>
#include <vector>
#include <string>
#include <type_traits>
#include <dune/common/float_cmp.hh>
#include <dune/pymor/common/crtp.hh>
#include <dune/pymor/common/exceptions.hh>
//#include <dune/pymor/functionals/interfaces.hh>
namespace Dune {
namespace Pymor {
namespace LA {
class ContainerInterfacePybindgen {};
template< class Traits >
class ContainerInterface
: public CRTPInterface< ContainerInterface< Traits >, Traits >
, public ContainerInterfacePybindgen
{
typedef CRTPInterface< ContainerInterface< Traits >, Traits > CRTP;
typedef ContainerInterface< Traits > ThisType;
public:
typedef typename Traits::derived_type derived_type;
typedef typename Traits::ScalarType ScalarType;
/**
* \brief Creates a (deep) copy of the underlying resource
* \return A new container
*/
derived_type copy() const
{
CHECK_INTERFACE_IMPLEMENTATION(CRTP::as_imp(*this).copy());
return CRTP::as_imp(*this).copy();
}
/**
* \brief BLAS SCAL operation (in-place sclar multiplication).
* \param alpha The scalar coefficient with which each element of the container is multiplied.
*/
void scal(const ScalarType& alpha)
{
CHECK_AND_CALL_INTERFACE_IMPLEMENTATION(CRTP::as_imp(*this).scal(alpha));
}
/**
* \brief BLAS AXPY operation.
* \param alpha The scalar coefficient with which each element of the container is multiplied
* \param xx Container that is to be elementwise added.
*/
void axpy(const ScalarType& alpha, const derived_type& xx)
{
CHECK_AND_CALL_INTERFACE_IMPLEMENTATION(CRTP::as_imp(*this).axpy(alpha, xx));
}
void axpy(const ScalarType& alpha, const ThisType& xx)
{
CHECK_AND_CALL_INTERFACE_IMPLEMENTATION(CRTP::as_imp(*this).axpy(alpha, CRTP::as_imp(xx)));
}
bool has_equal_shape(const derived_type& other) const
{
CHECK_INTERFACE_IMPLEMENTATION(CRTP::as_imp(*this).has_equal_shape(other));
return CRTP::as_imp(*this).has_equal_shape(other);
}
}; // class ContainerInterface
class VectorInterfacePybindgen {};
template< class Traits >
class VectorInterface
: public ContainerInterface< Traits >
, public VectorInterfacePybindgen
{
typedef CRTPInterface< ContainerInterface< Traits >, Traits > CRTP;
typedef VectorInterface< Traits > ThisType;
public:
typedef typename Traits::derived_type derived_type;
typedef typename Traits::ScalarType ScalarType;
/**
* \brief The dimension of the vector.
* \return The dimension of the vector.
*/
unsigned int dim() const
{
CHECK_INTERFACE_IMPLEMENTATION(CRTP::as_imp(*this).dim());
return CRTP::as_imp(*this).dim();
}
/**
* \brief Check vectors for equality.
* Equality of two vectors is defined as in Dune::FloatCmp componentwise.
* \param other A vector of same dimension to compare with.
* \param epsilon See Dune::FloatCmp.
* \return Truth value of the comparison.
*/
bool almost_equal(const derived_type& other,
const ScalarType epsilon = Dune::FloatCmp::DefaultEpsilon< ScalarType >::value()) const
throw (Exception::sizes_do_not_match, Exception::you_have_to_implement_this)
{
CHECK_INTERFACE_IMPLEMENTATION(CRTP::as_imp(*this).almost_equal(other, epsilon));
return CRTP::as_imp(*this).almost_equal(other, epsilon);
}
bool almost_equal(const ThisType& other,
const ScalarType epsilon = Dune::FloatCmp::DefaultEpsilon< ScalarType >::value()) const
throw (Exception::sizes_do_not_match, Exception::you_have_to_implement_this)
{
CHECK_INTERFACE_IMPLEMENTATION(CRTP::as_imp(*this).almost_equal(CRTP::as_imp(other), epsilon));
return CRTP::as_imp(*this).almost_equal(CRTP::as_imp(other), epsilon);
}
/**
* \brief Computes the scalar products between two vectors.
* \param other The second factor.
* \return The scalar product.
*/
ScalarType dot(const derived_type& other) const
throw (Exception::sizes_do_not_match, Exception::you_have_to_implement_this)
{
CHECK_INTERFACE_IMPLEMENTATION(CRTP::as_imp(*this).dot(other));
return CRTP::as_imp(*this).dot(other);
}
ScalarType dot(const ThisType& other) const
throw (Exception::sizes_do_not_match, Exception::you_have_to_implement_this)
{
CHECK_INTERFACE_IMPLEMENTATION(CRTP::as_imp(*this).dot(CRTP::as_imp(other)));
return CRTP::as_imp(*this).dot(CRTP::as_imp(other));
}
/**
* \brief The l1-norm of the vector.
* \return The l1-norm of the vector.
*/
ScalarType l1_norm() const
{
CHECK_INTERFACE_IMPLEMENTATION(CRTP::as_imp(*this).l1_norm());
return CRTP::as_imp(*this).l1_norm();
}
/**
* \brief The l2-norm of the vector.
* \return The l2-norm of the vector.
*/
ScalarType l2_norm() const
{
CHECK_INTERFACE_IMPLEMENTATION(CRTP::as_imp(*this).l2_norm());
return CRTP::as_imp(*this).l2_norm();
}
/**
* \brief The l-infintiy-norm of the vector.
* \return The l-infintiy-norm of the vector.
*/
ScalarType sup_norm() const
{
CHECK_INTERFACE_IMPLEMENTATION(CRTP::as_imp(*this).sup_norm());
return CRTP::as_imp(*this).sup_norm();
}
/**
* \brief Extract components of the vector.
* \param component_indices Indices of the vector components that are to be returned.
* \return A std::vector< ScalarType > `result` such that `result[i]` is the `component_indices[i]`-th
component of the vector.
*/
std::vector< ScalarType > components(const std::vector< int >& component_indices) const
throw (Exception::sizes_do_not_match, Exception::index_out_of_range)
{
CHECK_INTERFACE_IMPLEMENTATION(CRTP::as_imp(*this).components(component_indices));
return CRTP::as_imp(*this).components(component_indices);
}
/**
* \brief The maximum absolute value of the vector.
* \return A std::vector< ScalarType > result, where int(result[0]) is the index at which the maximum is attained and
* result[1] is the absolute maximum value.
*/
std::vector< ScalarType > amax() const
{
CHECK_INTERFACE_IMPLEMENTATION(CRTP::as_imp(*this).amax());
return CRTP::as_imp(*this).amax();
}
/**
* \brief Adds two vectors.
* \param other The right summand.
* \param result Vector to write the result of this + other to
*/
void add(const derived_type& other, derived_type& result) const throw (Exception::sizes_do_not_match)
{
CHECK_AND_CALL_INTERFACE_IMPLEMENTATION(CRTP::as_imp(*this).add(other, result));
}
void add(const ThisType& other, ThisType& result) const throw (Exception::sizes_do_not_match)
{
CHECK_AND_CALL_INTERFACE_IMPLEMENTATION(CRTP::as_imp(*this).add(CRTP::as_imp(other), CRTP::as_imp(result)));
}
/**
* \brief Adds two vectors.
* \param other The right summand.
* \param
* \return The sum of this and other.
*/
derived_type add(const derived_type& other) const throw (Exception::sizes_do_not_match)
{
derived_type result = this->copy();
result.iadd(other);
return result;
}
derived_type add(const ThisType& other) const throw (Exception::sizes_do_not_match)
{
derived_type result = this->copy();
result.iadd(other);
return result;
}
/**
* \brief Inplace variant of add().
* \param other The right summand.
*/
void iadd(const derived_type& other) throw (Exception::sizes_do_not_match)
{
CHECK_AND_CALL_INTERFACE_IMPLEMENTATION(CRTP::as_imp(*this).iadd(other));
}
void iadd(const ThisType& other) throw (Exception::sizes_do_not_match)
{
CHECK_AND_CALL_INTERFACE_IMPLEMENTATION(CRTP::as_imp(*this).iadd(CRTP::as_imp(other)));
}
/**
* \brief Subtracts two vectors.
* \param other The subtrahend.
* \param result The vectror to write the difference between this and other to.
*/
void sub(const derived_type& other, derived_type& result) const throw (Exception::sizes_do_not_match)
{
CHECK_AND_CALL_INTERFACE_IMPLEMENTATION(CRTP::as_imp(*this).sub(other, result));
}
void sub(const ThisType& other, ThisType& result) const throw (Exception::sizes_do_not_match)
{
CHECK_AND_CALL_INTERFACE_IMPLEMENTATION(CRTP::as_imp(*this).sub(CRTP::as_imp(other), CRTP::as_imp(result)));
}
/**
* \brief Subtracts two vectors.
* \param other The subtrahend.
* \return The difference between this and other.
*/
derived_type sub(const derived_type& other) const throw (Exception::sizes_do_not_match)
{
derived_type result = this->copy();
result.isub(other);
return result;
}
derived_type sub(const ThisType& other) const throw (Exception::sizes_do_not_match)
{
derived_type result = this->copy();
result.isub(other);
return result;
}
/**
* \brief Inplace variant of sub().
* \param other The subtrahend.
*/
void isub(const derived_type& other) throw (Exception::sizes_do_not_match)
{
CHECK_AND_CALL_INTERFACE_IMPLEMENTATION(CRTP::as_imp(*this).isub(other));
}
void isub(const ThisType& other) throw (Exception::sizes_do_not_match)
{
CHECK_AND_CALL_INTERFACE_IMPLEMENTATION(CRTP::as_imp(*this).isub(CRTP::as_imp(other)));
}
// virtual bool linear() const;
// virtual unsigned int dim_source() const;
// virtual std::string type_source() const;
// virtual double apply(const LA::VectorInterface& source,
// const Parameter /*mu*/ = Parameter()) const throw (Exception::types_are_not_compatible,
// Exception::you_have_to_implement_this,
// Exception::sizes_do_not_match,
// Exception::wrong_parameter_type,
// Exception::requirements_not_met,
// Exception::linear_solver_failed,
// Exception::this_does_not_make_any_sense);
}; // class VectorInterface
template< class Traits >
class MatrixInterface
: public ContainerInterface< Traits >
{
typedef CRTPInterface< ContainerInterface< Traits >, Traits > CRTP;
typedef MatrixInterface< Traits > ThisType;
public:
typedef typename Traits::derived_type derived_type;
typedef typename Traits::ScalarType ScalarType;
unsigned int dim_source() const
{
CHECK_INTERFACE_IMPLEMENTATION(CRTP::as_imp(*this).dim_source());
return CRTP::as_imp(*this).dim_source();
}
unsigned int dim_range() const
{
CHECK_INTERFACE_IMPLEMENTATION(CRTP::as_imp(*this).dim_range());
return CRTP::as_imp(*this).dim_range();
}
}; // class MatrixInterface
} // namespace LA
} // namespace Pymor
} // namespace Dune
#endif // DUNE_PYMOR_LA_CONTAINER_INTERFACES_HH
<commit_msg>[la.container.interfaces] added ProvidesContainer interface<commit_after>// This file is part of the dune-pymor project:
// https://github.com/pyMor/dune-pymor
// Copyright Holders: Felix Albrecht, Stephan Rave
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_PYMOR_LA_CONTAINER_INTERFACES_HH
#define DUNE_PYMOR_LA_CONTAINER_INTERFACES_HH
#include <utility>
#include <vector>
#include <string>
#include <type_traits>
#include <dune/common/float_cmp.hh>
#include <dune/pymor/common/crtp.hh>
#include <dune/pymor/common/exceptions.hh>
//#include <dune/pymor/functionals/interfaces.hh>
namespace Dune {
namespace Pymor {
namespace LA {
class ContainerInterfacePybindgen {};
template< class Traits >
class ContainerInterface
: public CRTPInterface< ContainerInterface< Traits >, Traits >
, public ContainerInterfacePybindgen
{
typedef CRTPInterface< ContainerInterface< Traits >, Traits > CRTP;
typedef ContainerInterface< Traits > ThisType;
public:
typedef typename Traits::derived_type derived_type;
typedef typename Traits::ScalarType ScalarType;
/**
* \brief Creates a (deep) copy of the underlying resource
* \return A new container
*/
derived_type copy() const
{
CHECK_INTERFACE_IMPLEMENTATION(CRTP::as_imp(*this).copy());
return CRTP::as_imp(*this).copy();
}
/**
* \brief BLAS SCAL operation (in-place sclar multiplication).
* \param alpha The scalar coefficient with which each element of the container is multiplied.
*/
void scal(const ScalarType& alpha)
{
CHECK_AND_CALL_INTERFACE_IMPLEMENTATION(CRTP::as_imp(*this).scal(alpha));
}
/**
* \brief BLAS AXPY operation.
* \param alpha The scalar coefficient with which each element of the container is multiplied
* \param xx Container that is to be elementwise added.
*/
void axpy(const ScalarType& alpha, const derived_type& xx)
{
CHECK_AND_CALL_INTERFACE_IMPLEMENTATION(CRTP::as_imp(*this).axpy(alpha, xx));
}
void axpy(const ScalarType& alpha, const ThisType& xx)
{
CHECK_AND_CALL_INTERFACE_IMPLEMENTATION(CRTP::as_imp(*this).axpy(alpha, CRTP::as_imp(xx)));
}
bool has_equal_shape(const derived_type& other) const
{
CHECK_INTERFACE_IMPLEMENTATION(CRTP::as_imp(*this).has_equal_shape(other));
return CRTP::as_imp(*this).has_equal_shape(other);
}
}; // class ContainerInterface
template< class Traits >
class ProvidesContainer
: CRTPInterface< ProvidesContainer< Traits >, Traits >
{
typedef CRTPInterface< ProvidesContainer< Traits >, Traits > CRTP;
public:
typedef typename Traits::ContainerType ContainerType;
std::shared_ptr< const ContainerType > container() const
{
CHECK_INTERFACE_IMPLEMENTATION(CRTP::as_imp(*this).container());
return CRTP::as_imp(*this).container();
}
}; // class ProvidesContainer
class VectorInterfacePybindgen {};
template< class Traits >
class VectorInterface
: public ContainerInterface< Traits >
, public VectorInterfacePybindgen
{
typedef CRTPInterface< ContainerInterface< Traits >, Traits > CRTP;
typedef VectorInterface< Traits > ThisType;
public:
typedef typename Traits::derived_type derived_type;
typedef typename Traits::ScalarType ScalarType;
/**
* \brief The dimension of the vector.
* \return The dimension of the vector.
*/
unsigned int dim() const
{
CHECK_INTERFACE_IMPLEMENTATION(CRTP::as_imp(*this).dim());
return CRTP::as_imp(*this).dim();
}
/**
* \brief Check vectors for equality.
* Equality of two vectors is defined as in Dune::FloatCmp componentwise.
* \param other A vector of same dimension to compare with.
* \param epsilon See Dune::FloatCmp.
* \return Truth value of the comparison.
*/
bool almost_equal(const derived_type& other,
const ScalarType epsilon = Dune::FloatCmp::DefaultEpsilon< ScalarType >::value()) const
throw (Exception::sizes_do_not_match, Exception::you_have_to_implement_this)
{
CHECK_INTERFACE_IMPLEMENTATION(CRTP::as_imp(*this).almost_equal(other, epsilon));
return CRTP::as_imp(*this).almost_equal(other, epsilon);
}
bool almost_equal(const ThisType& other,
const ScalarType epsilon = Dune::FloatCmp::DefaultEpsilon< ScalarType >::value()) const
throw (Exception::sizes_do_not_match, Exception::you_have_to_implement_this)
{
CHECK_INTERFACE_IMPLEMENTATION(CRTP::as_imp(*this).almost_equal(CRTP::as_imp(other), epsilon));
return CRTP::as_imp(*this).almost_equal(CRTP::as_imp(other), epsilon);
}
/**
* \brief Computes the scalar products between two vectors.
* \param other The second factor.
* \return The scalar product.
*/
ScalarType dot(const derived_type& other) const
throw (Exception::sizes_do_not_match, Exception::you_have_to_implement_this)
{
CHECK_INTERFACE_IMPLEMENTATION(CRTP::as_imp(*this).dot(other));
return CRTP::as_imp(*this).dot(other);
}
ScalarType dot(const ThisType& other) const
throw (Exception::sizes_do_not_match, Exception::you_have_to_implement_this)
{
CHECK_INTERFACE_IMPLEMENTATION(CRTP::as_imp(*this).dot(CRTP::as_imp(other)));
return CRTP::as_imp(*this).dot(CRTP::as_imp(other));
}
/**
* \brief The l1-norm of the vector.
* \return The l1-norm of the vector.
*/
ScalarType l1_norm() const
{
CHECK_INTERFACE_IMPLEMENTATION(CRTP::as_imp(*this).l1_norm());
return CRTP::as_imp(*this).l1_norm();
}
/**
* \brief The l2-norm of the vector.
* \return The l2-norm of the vector.
*/
ScalarType l2_norm() const
{
CHECK_INTERFACE_IMPLEMENTATION(CRTP::as_imp(*this).l2_norm());
return CRTP::as_imp(*this).l2_norm();
}
/**
* \brief The l-infintiy-norm of the vector.
* \return The l-infintiy-norm of the vector.
*/
ScalarType sup_norm() const
{
CHECK_INTERFACE_IMPLEMENTATION(CRTP::as_imp(*this).sup_norm());
return CRTP::as_imp(*this).sup_norm();
}
/**
* \brief Extract components of the vector.
* \param component_indices Indices of the vector components that are to be returned.
* \return A std::vector< ScalarType > `result` such that `result[i]` is the `component_indices[i]`-th
component of the vector.
*/
std::vector< ScalarType > components(const std::vector< int >& component_indices) const
throw (Exception::sizes_do_not_match, Exception::index_out_of_range)
{
CHECK_INTERFACE_IMPLEMENTATION(CRTP::as_imp(*this).components(component_indices));
return CRTP::as_imp(*this).components(component_indices);
}
/**
* \brief The maximum absolute value of the vector.
* \return A std::vector< ScalarType > result, where int(result[0]) is the index at which the maximum is attained and
* result[1] is the absolute maximum value.
*/
std::vector< ScalarType > amax() const
{
CHECK_INTERFACE_IMPLEMENTATION(CRTP::as_imp(*this).amax());
return CRTP::as_imp(*this).amax();
}
/**
* \brief Adds two vectors.
* \param other The right summand.
* \param result Vector to write the result of this + other to
*/
void add(const derived_type& other, derived_type& result) const throw (Exception::sizes_do_not_match)
{
CHECK_AND_CALL_INTERFACE_IMPLEMENTATION(CRTP::as_imp(*this).add(other, result));
}
void add(const ThisType& other, ThisType& result) const throw (Exception::sizes_do_not_match)
{
CHECK_AND_CALL_INTERFACE_IMPLEMENTATION(CRTP::as_imp(*this).add(CRTP::as_imp(other), CRTP::as_imp(result)));
}
/**
* \brief Adds two vectors.
* \param other The right summand.
* \param
* \return The sum of this and other.
*/
derived_type add(const derived_type& other) const throw (Exception::sizes_do_not_match)
{
derived_type result = this->copy();
result.iadd(other);
return result;
}
derived_type add(const ThisType& other) const throw (Exception::sizes_do_not_match)
{
derived_type result = this->copy();
result.iadd(other);
return result;
}
/**
* \brief Inplace variant of add().
* \param other The right summand.
*/
void iadd(const derived_type& other) throw (Exception::sizes_do_not_match)
{
CHECK_AND_CALL_INTERFACE_IMPLEMENTATION(CRTP::as_imp(*this).iadd(other));
}
void iadd(const ThisType& other) throw (Exception::sizes_do_not_match)
{
CHECK_AND_CALL_INTERFACE_IMPLEMENTATION(CRTP::as_imp(*this).iadd(CRTP::as_imp(other)));
}
/**
* \brief Subtracts two vectors.
* \param other The subtrahend.
* \param result The vectror to write the difference between this and other to.
*/
void sub(const derived_type& other, derived_type& result) const throw (Exception::sizes_do_not_match)
{
CHECK_AND_CALL_INTERFACE_IMPLEMENTATION(CRTP::as_imp(*this).sub(other, result));
}
void sub(const ThisType& other, ThisType& result) const throw (Exception::sizes_do_not_match)
{
CHECK_AND_CALL_INTERFACE_IMPLEMENTATION(CRTP::as_imp(*this).sub(CRTP::as_imp(other), CRTP::as_imp(result)));
}
/**
* \brief Subtracts two vectors.
* \param other The subtrahend.
* \return The difference between this and other.
*/
derived_type sub(const derived_type& other) const throw (Exception::sizes_do_not_match)
{
derived_type result = this->copy();
result.isub(other);
return result;
}
derived_type sub(const ThisType& other) const throw (Exception::sizes_do_not_match)
{
derived_type result = this->copy();
result.isub(other);
return result;
}
/**
* \brief Inplace variant of sub().
* \param other The subtrahend.
*/
void isub(const derived_type& other) throw (Exception::sizes_do_not_match)
{
CHECK_AND_CALL_INTERFACE_IMPLEMENTATION(CRTP::as_imp(*this).isub(other));
}
void isub(const ThisType& other) throw (Exception::sizes_do_not_match)
{
CHECK_AND_CALL_INTERFACE_IMPLEMENTATION(CRTP::as_imp(*this).isub(CRTP::as_imp(other)));
}
// virtual bool linear() const;
// virtual unsigned int dim_source() const;
// virtual std::string type_source() const;
// virtual double apply(const LA::VectorInterface& source,
// const Parameter /*mu*/ = Parameter()) const throw (Exception::types_are_not_compatible,
// Exception::you_have_to_implement_this,
// Exception::sizes_do_not_match,
// Exception::wrong_parameter_type,
// Exception::requirements_not_met,
// Exception::linear_solver_failed,
// Exception::this_does_not_make_any_sense);
}; // class VectorInterface
template< class Traits >
class MatrixInterface
: public ContainerInterface< Traits >
{
typedef CRTPInterface< ContainerInterface< Traits >, Traits > CRTP;
typedef MatrixInterface< Traits > ThisType;
public:
typedef typename Traits::derived_type derived_type;
typedef typename Traits::ScalarType ScalarType;
unsigned int dim_source() const
{
CHECK_INTERFACE_IMPLEMENTATION(CRTP::as_imp(*this).dim_source());
return CRTP::as_imp(*this).dim_source();
}
unsigned int dim_range() const
{
CHECK_INTERFACE_IMPLEMENTATION(CRTP::as_imp(*this).dim_range());
return CRTP::as_imp(*this).dim_range();
}
}; // class MatrixInterface
} // namespace LA
} // namespace Pymor
} // namespace Dune
#endif // DUNE_PYMOR_LA_CONTAINER_INTERFACES_HH
<|endoftext|> |
<commit_before>// the general scene file loading handler
#include <OpenSG/OSGSceneFileHandler.h>
#include <OpenSG/OSGVerifyGraphOp.h>
#include <OpenSG/OSGModelRequest.h>
#include <iostream>
OSG_USING_NAMESPACE
OSG_BEGIN_NAMESPACE
ModelRequest::ModelRequest()
: mParent(NullFC)
, mModel (NullFC)
{;}
ModelRequest::~ModelRequest()
{;}
std::string ModelRequest::getDescription()
{
return std::string("ModelRequest: ") + mFilename;
}
void ModelRequest::execute()
{
std::cout << "ModelRequest: loading model: " << mFilename << std::endl;
mModel = OSG::NodeRefPtr(OSG::SceneFileHandler::the()->read(mFilename.c_str()));
#if 1
VerifyGraphOp* vop = new VerifyGraphOp;
vop->setRepair(true);
vop->setVerbose(true);
NodePtr node(mModel);
vop->traverse(node);
delete vop;
#endif
}
void ModelRequest::sync()
{
if (mParent != NullFC && mModel != NullFC)
{
std::cout << "ModelRequest: adding model to scene: " << mFilename << std::endl;
mParent->addChild(mModel);
}
mCompleted = true;
}
OSG_END_NAMESPACE
<commit_msg>!= NullFC test<commit_after>// the general scene file loading handler
#include <OpenSG/OSGSceneFileHandler.h>
#include <OpenSG/OSGVerifyGraphOp.h>
#include <OpenSG/OSGModelRequest.h>
#include <iostream>
OSG_USING_NAMESPACE
OSG_BEGIN_NAMESPACE
ModelRequest::ModelRequest()
: mParent(NullFC)
, mModel (NullFC)
{;}
ModelRequest::~ModelRequest()
{;}
std::string ModelRequest::getDescription()
{
return std::string("ModelRequest: ") + mFilename;
}
void ModelRequest::execute()
{
std::cout << "ModelRequest: loading model: " << mFilename << std::endl;
mModel = OSG::NodeRefPtr(OSG::SceneFileHandler::the()->read(mFilename.c_str()));
#if 1
VerifyGraphOp* vop = new VerifyGraphOp;
vop->setRepair(true);
vop->setVerbose(true);
NodePtr node(mModel);
vop->traverse(node);
delete vop;
#endif
}
void ModelRequest::sync()
{
if (mParent && mModel)
{
std::cout << "ModelRequest: adding model to scene: " << mFilename << std::endl;
mParent->addChild(mModel);
}
mCompleted = true;
}
OSG_END_NAMESPACE
<|endoftext|> |
<commit_before>#include "bufferAgent.h"
using boost::shared_ptr;
using boost::thread;
using boost::bind;
using std::string;
namespace veil {
namespace helpers {
BufferAgent::BufferAgent(write_fun w, read_fun r)
: m_agentActive(false),
doWrite(w),
doRead(r)
{
agentStart();
}
BufferAgent::~BufferAgent()
{
agentStop();
}
int BufferAgent::onOpen(std::string path, ffi_type ffi)
{
unique_lock guard(m_loopMutex);
m_cacheMap.erase(ffi->fh);
buffer_ptr lCache(new LockableCache());
lCache->fileName = path;
lCache->buffer = newFileCache();
lCache->ffi = *ffi;
m_cacheMap[ffi->fh] = lCache;
return 0;
}
int BufferAgent::onWrite(std::string path, const std::string &buf, size_t size, off_t offset, ffi_type ffi)
{
unique_lock guard(m_loopMutex);
buffer_ptr wrapper = m_cacheMap[ffi->fh];
guard.unlock();
unique_lock buff_guard(wrapper->mutex);
while(wrapper->buffer->byteSize() > 1024 * 1024 * 10) {
guard.lock();
m_jobQueue.push_front(ffi->fh);
m_loopCond.notify_all();
guard.unlock();
wrapper->cond.wait(buff_guard);
}
wrapper->buffer->writeData(offset, buf);
guard.lock();
m_jobQueue.push_back(ffi->fh);
return size;
}
int BufferAgent::onRead(std::string path, std::string &buf, size_t size, off_t offset, ffi_type ffi)
{
boost::unique_lock<boost::recursive_mutex> guard(m_loopMutex);
return EOPNOTSUPP;
}
int BufferAgent::onFlush(std::string path, ffi_type ffi)
{
unique_lock guard(m_loopMutex);
buffer_ptr wrapper = m_cacheMap[ffi->fh];
guard.unlock();
unique_lock buff_guard(wrapper->mutex);
while(wrapper->buffer->blockCount() > 0)
{
block_ptr block = wrapper->buffer->removeOldestBlock();
int res = doWrite(wrapper->fileName, block->data, block->data.size(), block->offset, &wrapper->ffi);
if(res < 0)
{
while(wrapper->buffer->blockCount() > 0)
{
(void) wrapper->buffer->removeOldestBlock();
}
return res;
}
}
guard.lock();
m_jobQueue.remove(ffi->fh);
return 0;
}
int BufferAgent::onRelease(std::string path, ffi_type ffi)
{
boost::unique_lock<boost::recursive_mutex> guard(m_loopMutex);
m_cacheMap.erase(ffi->fh);
return 0;
}
void BufferAgent::agentStart(int worker_count)
{
m_workers.clear();
m_agentActive = true;
while(worker_count--)
{
m_workers.push_back(shared_ptr<thread>(new thread(bind(&BufferAgent::workerLoop, this))));
}
}
void BufferAgent::agentStop()
{
m_agentActive = false;
m_loopCond.notify_all();
while(m_workers.size() > 0)
{
m_workers.back()->join();
m_workers.pop_back();
}
}
void BufferAgent::workerLoop()
{
unique_lock guard(m_loopMutex);
while(m_agentActive)
{
while(m_jobQueue.empty() && m_agentActive)
m_loopCond.wait(guard);
if(!m_agentActive)
return;
fd_type file = m_jobQueue.front();
buffer_ptr wrapper = m_cacheMap[file];
m_jobQueue.pop_front();
m_loopCond.notify_all();
if(!wrapper)
continue;
{
guard.unlock();
unique_lock buff_guard(wrapper->mutex);
block_ptr block = wrapper->buffer->removeOldestBlock();
if(block)
{
int res = doWrite(wrapper->fileName, block->data, block->data.size(), block->offset, &wrapper->ffi);
wrapper->cond.notify_all();
}
buff_guard.unlock();
guard.lock();
if(wrapper->buffer->blockCount() > 0)
{
m_jobQueue.push_back(file);
}
}
}
}
boost::shared_ptr<FileCache> BufferAgent::newFileCache()
{
return boost::shared_ptr<FileCache>(new FileCache(500 * 1024));
}
} // namespace helpers
} // namespace veil
<commit_msg>VFS-292: debug<commit_after>#include "bufferAgent.h"
using boost::shared_ptr;
using boost::thread;
using boost::bind;
using std::string;
namespace veil {
namespace helpers {
BufferAgent::BufferAgent(write_fun w, read_fun r)
: m_agentActive(false),
doWrite(w),
doRead(r)
{
agentStart();
}
BufferAgent::~BufferAgent()
{
agentStop();
}
int BufferAgent::onOpen(std::string path, ffi_type ffi)
{
unique_lock guard(m_loopMutex);
m_cacheMap.erase(ffi->fh);
buffer_ptr lCache(new LockableCache());
lCache->fileName = path;
lCache->buffer = newFileCache();
lCache->ffi = *ffi;
m_cacheMap[ffi->fh] = lCache;
return 0;
}
int BufferAgent::onWrite(std::string path, const std::string &buf, size_t size, off_t offset, ffi_type ffi)
{
unique_lock guard(m_loopMutex);
buffer_ptr wrapper = m_cacheMap[ffi->fh];
guard.unlock();
unique_lock buff_guard(wrapper->mutex);
while(wrapper->buffer->byteSize() > 1024 * 1024 * 10) {
guard.lock();
m_jobQueue.push_front(ffi->fh);
m_loopCond.notify_all();
guard.unlock();
wrapper->cond.wait(buff_guard);
}
wrapper->buffer->writeData(offset, buf);
guard.lock();
m_jobQueue.push_back(ffi->fh);
m_loopCond.notify_all();
return size;
}
int BufferAgent::onRead(std::string path, std::string &buf, size_t size, off_t offset, ffi_type ffi)
{
boost::unique_lock<boost::recursive_mutex> guard(m_loopMutex);
return EOPNOTSUPP;
}
int BufferAgent::onFlush(std::string path, ffi_type ffi)
{
unique_lock guard(m_loopMutex);
buffer_ptr wrapper = m_cacheMap[ffi->fh];
guard.unlock();
unique_lock buff_guard(wrapper->mutex);
while(wrapper->buffer->blockCount() > 0)
{
block_ptr block = wrapper->buffer->removeOldestBlock();
int res = doWrite(wrapper->fileName, block->data, block->data.size(), block->offset, &wrapper->ffi);
if(res < 0)
{
while(wrapper->buffer->blockCount() > 0)
{
(void) wrapper->buffer->removeOldestBlock();
}
return res;
}
}
guard.lock();
m_jobQueue.remove(ffi->fh);
return 0;
}
int BufferAgent::onRelease(std::string path, ffi_type ffi)
{
boost::unique_lock<boost::recursive_mutex> guard(m_loopMutex);
m_cacheMap.erase(ffi->fh);
return 0;
}
void BufferAgent::agentStart(int worker_count)
{
m_workers.clear();
m_agentActive = true;
while(worker_count--)
{
m_workers.push_back(shared_ptr<thread>(new thread(bind(&BufferAgent::workerLoop, this))));
}
}
void BufferAgent::agentStop()
{
m_agentActive = false;
m_loopCond.notify_all();
while(m_workers.size() > 0)
{
m_workers.back()->join();
m_workers.pop_back();
}
}
void BufferAgent::workerLoop()
{
unique_lock guard(m_loopMutex);
while(m_agentActive)
{
while(m_jobQueue.empty() && m_agentActive)
m_loopCond.wait(guard);
if(!m_agentActive)
return;
fd_type file = m_jobQueue.front();
buffer_ptr wrapper = m_cacheMap[file];
m_jobQueue.pop_front();
m_loopCond.notify_all();
if(!wrapper)
continue;
{
guard.unlock();
unique_lock buff_guard(wrapper->mutex);
block_ptr block = wrapper->buffer->removeOldestBlock();
if(block)
{
int res = doWrite(wrapper->fileName, block->data, block->data.size(), block->offset, &wrapper->ffi);
wrapper->cond.notify_all();
}
buff_guard.unlock();
guard.lock();
if(wrapper->buffer->blockCount() > 0)
{
m_jobQueue.push_back(file);
}
}
}
}
boost::shared_ptr<FileCache> BufferAgent::newFileCache()
{
return boost::shared_ptr<FileCache>(new FileCache(500 * 1024));
}
} // namespace helpers
} // namespace veil
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.